<!--客户详情-->
<template>
  <view class="assemble">
    <view class="main_box">
      <view style="height: 20rpx;background: #29D3B4;"></view>

      <view class="count_section">
        <view class="main">
          <view class="course_box">
            <view class="course_box_top">
              <view class="course_box_top_top">
                <image class="pic" :src="$util.img('/uniapp_src/static/images/index/myk.png')"></image>
                <view class="name">{{ safeGet(clientInfo, 'customerResource.name', '未知客户') }}</view>
              </view>
              <view class="course_box_top_below">
                <view class="course_box_top_below-left">
                  <view>{{ $util.formatToDateTime((safeGet(clientInfo, 'customerResource.updated_at', '')),'m-d H:i') }} 跟进</view>

                  <view style="display: flex;align-items: center;">
                    <view style="padding-left: 30rpx;">
                      <image v-if="safeGet(clientInfo, 'customerResource.initial_intent') == 'high'"
                             :src="$util.img('/uniapp_src/static/images/index/lvs.png')" class="drop-image-x"></image>
                      <image v-else-if="safeGet(clientInfo, 'customerResource.initial_intent') == 'medium'"
                             :src="$util.img('/uniapp_src/static/images/index/intention2.png')" class="drop-image-x"></image>
                      <image
                          v-else
                          :src="$util.img('/uniapp_src/static/images/index/intention1.png')"
                          class="drop-image-x">
                      </image>
                    </view>
                  </view>

                </view>
                <view class="course_box_top_below-right">
                  <!-- 操作按钮 -->
                  <view class="action-buttons">
                    <view class="btn-item" @click="handleMakeCall">
                      <image class="btn-icon" :src="$util.img('/uniapp_src/static/images/index/phone.png')"></image>
                    </view>
                    <view class="btn-item" @click="handleSendMessage" v-if="safeGet(clientInfo, 'customerResource.member_id')">
                      <image class="btn-icon" :src="$util.img('/uniapp_src/static/images/index/message.png')"></image>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view class="course_box_centre"></view>
            <view class="course_box_below">
              <view :class="{'selected-text': switch_tags_type === 1, 'text': switch_tags_type !== 1}"
                    @click="switch_tags(1)">基本资料
              </view>
              <view :class="{'selected-text': switch_tags_type === 2, 'text': switch_tags_type !== 2}"
                    @click="switch_tags(2)">课程信息
              </view>
              <view :class="{'selected-text': switch_tags_type === 3, 'text': switch_tags_type !== 3}"
                    @click="switch_tags(3)">通话记录
              </view>
            </view>
          </view>
        </view>
        <view class="bg_box bg_top"></view>
        <view class="bg_box bg_bottom"></view>
      </view>

<!--      基本资料-->
      <view class="basic-information" v-if="switch_tags_type == 1">
        <view class="basic-message">基本信息</view>
        <view class="basic-message-div">
          <view class="basic-message-div-txt">
            <view>来源渠道</view>
            <view>{{safeGet(clientInfo, 'customerResource.source_channel_name', '未知渠道')}}</view>
          </view>
          <view class="basic-message-div-txt">
            <view>来源</view>
            <view>{{safeGet(clientInfo, 'customerResource.source_name', '未知来源')}}</view>
          </view>
          <view class="basic-message-div-txt">
            <view>顾问</view>
            <view>{{safeGet(clientInfo, 'customerResource.consultant_name', '未知顾问')}}</view>
          </view>
          <view class="basic-message-div-txt">
            <view>学生姓名</view>
            <view>{{safeGet(clientInfo, 'customerResource.name', '未知学生')}}</view>
          </view>
          <view class="basic-message-div-txt">
            <view>性别</view>
            <view>{{safeGet(clientInfo, 'customerResource.gender_name', '未知性别')}}</view>
          </view>
        </view>

        <view class="basic-message">附加信息</view>
        <view class="basic-message-div">
          <view class="basic-message-div-txt" @click="openViewOrder()">
            <view>已成交次数</view>
            <view>{{safeGet(clientInfo, 'customerResource.cj_count', 0)}}次</view>
          </view>
          <view class="basic-message-div-txt">
            <view>体验课程</view>
            <view>{{safeGet(clientInfo, 'customerResource.trial_class_count', 0)}}次</view>
          </view>
        </view>
        <view style="height: 200rpx;"></view>
      </view>

<!--      课程信息-->
      <view class="course-info" v-if="switch_tags_type == 2">
        <view v-if="courseInfo && courseInfo.length > 0">
          <view v-for="(course, index) in courseInfo" :key="index" class="course-item" @click="openCourseEditDialog(course)">
            <view class="course-header">
              <view class="course-title">{{ course.course_name || '未知课程' }}</view>
              <view class="course-status" :class="'status-' + (course.status || 'default')">
                {{ course.status === 'active' ? '进行中' : course.status === 'expired' ? '已过期' : course.status === 'completed' ? '已完成' : '未知状态' }}
              </view>
            </view>
            
            <view class="course-progress">
              <view class="progress-bar">
                <view class="progress-fill" :style="{width: ((course.total_count > 0 ? Math.round((course.used_count / course.total_count) * 100) : 0)) + '%'}"></view>
              </view>
              <view class="progress-text">{{ course.used_count || 0 }}/{{ course.total_count || 0 }}节</view>
            </view>
            
            <view class="course-details">
              <view class="detail-row">
                <view class="detail-label">剩余课时：</view>
                <view class="detail-value">{{ (course.total_count || 0) - (course.used_count || 0) }}节</view>
              </view>
              <view class="detail-row">
                <view class="detail-label">有效期至：</view>
                <view class="detail-value">{{ $util.formatToDateTime(course.expiry_date, 'Y-m-d') || '无限期' }}</view>
              </view>
              <view class="detail-row">
                <view class="detail-label">请假次数：</view>
                <view class="detail-value">{{ course.leave_count || 0 }}次</view>
              </view>
              <view class="detail-row">
                <view class="detail-label">主教练：</view>
                <view class="detail-value">{{ course.main_coach_name || '未分配' }}</view>
              </view>
              <view class="detail-row">
                <view class="detail-label">教务：</view>
                <view class="detail-value">{{ course.education_name || '未分配' }}</view>
              </view>
              <view class="detail-row">
                <view class="detail-label">助教：</view>
                <view class="detail-value">{{ course.assistant_names || '无' }}</view>
              </view>
            </view>
            
            <view class="course-actions">
              <view class="action-btn">点击修改教练配置</view>
            </view>
          </view>
        </view>
        <view v-else class="empty-course">
          <image src="/static/images/empty.png" mode="aspectFit" class="empty-img"></image>
          <text class="empty-text">暂无课程信息</text>
        </view>
        <view style="height: 200rpx;"></view>
      </view>

<!--      跟进记录-->
      <view class="follow-records" v-if="switch_tags_type == 4">
        <view v-for="(v,k) in followList" :key="k">
          <view class="basic-message">{{$util.formatToDateTime(v.follow_up_time,'m-d')}}</view>
          <view class="follow-records-list">
            <view style="display: flex;justify-content: space-between;padding: 16rpx 16rpx 16rpx 60rpx;">
              <view>{{v.student_name}}</view>
              <view>跟进({{v.student_phone}})</view>
            </view>
            <view style="padding: 16rpx 16rpx 16rpx 60rpx;">{{v.follow_up_content}}</view>
            <view style="padding: 16rpx 16rpx 16rpx 60rpx;">{{v.follow_up_time}}</view>
          </view>
        </view>
        <view style="height: 200rpx;"></view>
      </view>

<!--      通话记录-->
      <view class="call-log" v-if="switch_tags_type == 3">
        <view class="call-record-wrapper" v-for="(v,k) in listCallUp" :key="k">
          <view class="call-record-item">
            <view class="call-record-header">
              <view class="call-name">{{v.name}}</view>
              <view class="call-time">{{v.create_time}}</view>
            </view>
            <view class="call-record-content">
              <view class="call-detail">
                <text class="call-label">呼叫时间：</text>
                <text>{{v.created_at}}</text>
              </view>
              <button 
                type="primary" 
                size="mini" 
                class="remark-btn"
                @click="openAddRemark(v)">
                添加备注
              </button>
            </view>
            <view class="call-remark">
              <text class="call-label">呼叫备注：</text>
              <text class="call-remark-content">{{v.remarks || '无'}}</text>
            </view>
          </view>
        </view>
        <view style="height: 200rpx;"></view>
      </view>

<!--      底部按钮组-->
      <view class="bottom-label">
        <view @click="openViewEditClues()">编辑详情</view>
        <view @click="openViewEditClassLog()">课程安排</view>
        <view @click="openViewEditCluesLog()">修改记录</view>
        <view @click="openViewOrder()">订单列表</view>
      </view>
      
      <!-- 添加备注弹窗 -->
      <uni-popup ref="remarkPopup" type="dialog">
        <uni-popup-dialog 
          :title="currentRecord ? `添加备注 (${currentRecord.name || '未知'})` : '添加备注'" 
          :before-close="true" 
          @confirm="confirmRemark" 
          @close="closeRemark">
          <view class="remark-textarea-container">
            <textarea 
              class="remark-textarea"
              v-model="remark_content" 
              placeholder="请输入备注内容"
              maxlength="200"
            ></textarea>
            <text class="remark-count">{{remark_content.length}}/200</text>
          </view>
        </uni-popup-dialog>
      </uni-popup>
      
      <!-- 教练配置编辑弹窗 -->
      <uni-popup ref="courseEditPopup" type="center">
        <view class="popup-container">
          <view class="popup-header">
            <view class="popup-title">修改教练配置</view>
            <view class="popup-close" @click="closeCourseEdit">✕</view>
          </view>
          <view class="course-edit-container">
            <view class="edit-section">
              <view class="section-title">主教练（单选）</view>
              <view class="coach-list">
                <view 
                  v-for="coach in coachList" 
                  :key="coach.id"
                  class="coach-item"
                  :class="{selected: selectedMainCoach === coach.id}"
                  @click="selectMainCoach(coach.id)">
                  <view class="coach-name">{{ coach.name }}</view>
                  <view class="coach-check" v-if="selectedMainCoach === coach.id">✓</view>
                </view>
              </view>
            </view>
            
            <view class="edit-section">
              <view class="section-title">教务（单选）</view>
              <view class="coach-list">
                <view 
                  v-for="education in educationList" 
                  :key="education.id"
                  class="coach-item"
                  :class="{selected: selectedEducation === education.id}"
                  @click="selectEducation(education.id)">
                  <view class="coach-name">{{ education.name }}</view>
                  <view class="coach-check" v-if="selectedEducation === education.id">✓</view>
                </view>
              </view>
            </view>
            
            <view class="edit-section">
              <view class="section-title">助教（多选）</view>
              <view class="coach-list">
                <view 
                  v-for="assistant in assistantList" 
                  :key="assistant.id"
                  class="coach-item"
                  :class="{selected: selectedAssistants.includes(assistant.id)}"
                  @click="toggleAssistant(assistant.id)">
                  <view class="coach-name">{{ assistant.name }}</view>
                  <view class="coach-check" v-if="selectedAssistants.includes(assistant.id)">✓</view>
                </view>
              </view>
            </view>
          </view>
          <view class="popup-footer">
            <view class="popup-btn cancel-btn" @click="closeCourseEdit">取消</view>
            <view class="popup-btn confirm-btn" @click="confirmCourseEdit">确认</view>
          </view>
        </view>
      </uni-popup>
    </view>
  </view>
</template>

<script>
	import apiRoute from '@/api/apiRoute.js';
	import marketApi from '@/api/market.js';

	export default {
		components: {
			// 导入组件
			uniPopup: () => import('@/components/uni-popup/uni-popup.vue'),
			uniPopupDialog: () => import('@/components/uni-popup/uni-popup-dialog.vue'),
		},
		data() {
			return {
				switch_tags_type: 1,
				select_type: 1,

        resource_sharing_id:'',//共享资源表id
        clientInfo:{
				  id:'',//共享资源id
          resource_id:'',//客户资源id
          customerResource:{},//客户资源信息
          sixSpeed:{},//六要素信息
        },//共享资源详情

        //跟进记录列表
        followList:[],
        //通话记录列表
        listCallUp:[],

        //当前登录的员工信息
        userInfo:{},
        
        // 备注相关
        remark_content: '',
        // 当前选中的通话记录
        currentRecord: null,
        
        // 课程信息相关
        courseInfo: [], // 课程信息列表
        currentCourse: null, // 当前选中的课程
        
        // 教练配置相关
        coachList: [], // 主教练列表
        educationList: [], // 教务列表
        assistantList: [], // 助教列表
        
        // 选中的配置
        selectedMainCoach: null, // 选中的主教练ID
        selectedEducation: null, // 选中的教务ID
        selectedAssistants: [], // 选中的助教ID数组
			}
		},
    onLoad(options) {
      console.log('onLoad - 接收到参数:', options);
      
      // 检查options是否存在且包含resource_sharing_id
      if (!options || !options.resource_sharing_id) {
        console.error('onLoad - 缺少必要参数resource_sharing_id');
        uni.showToast({
          title: '缺少必要参数',
          icon: 'none'
        });
        
        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
        return;
      }
      
      this.resource_sharing_id = options.resource_sharing_id//共享资源表id
      console.log('onLoad - 设置 resource_sharing_id:', this.resource_sharing_id);
    },
    onShow(){
      console.log('onShow - 开始初始化');
      this.init()
    },
		methods: {
		  async init(){
		    console.log('init - 开始初始化流程');
		    
		    // 预加载常用字典数据
		    try {
		      console.log('init - 开始预加载字典数据');
		      const dictPromises = [
		        this.$util.getDict('SourceChannel'), // 来源渠道
		        this.$util.getDict('source'), // 来源
		        this.$util.getDict('preliminarycustomerintention'), // 客户初步意向度
		        this.$util.getDict('kh_status'), // 客户状态
		      ];
		      
		      // 使用Promise.all并行加载字典，但设置超时处理
		      const timeoutPromise = new Promise((_, reject) => 
		        setTimeout(() => reject(new Error('字典加载超时')), 5000)
		      );
		      
		      await Promise.race([
		        Promise.all(dictPromises),
		        timeoutPromise
		      ]).catch(err => {
		        console.warn('字典加载异常或超时，继续执行流程:', err);
		      });
		      
		      console.log('init - 字典数据预加载完成或已超时');
		    } catch (error) {
		      console.warn('init - 字典数据预加载失败，继续执行流程:', error);
		    }
		    
		    // 恢复为串行请求处理，确保数据依赖关系正确
		    try {
		      // 先获取客户详情，因为其他操作可能依赖于客户详情
		      console.log('init - 开始获取客户详情');
		      await this.getInfo();
		      console.log('init - 客户详情获取完成');
		      
		      // 获取员工信息、通话记录和教练列表可以并行
		      console.log('init - 开始获取员工信息、通话记录和教练列表');
		      await Promise.all([
		        this.getUserInfo(),
		        this.getListCallUp(),
		        this.getPersonnelList()
		      ]);
		      console.log('init - 员工信息、通话记录和教练列表获取完成');
		    } catch (error) {
		      console.error('init - 数据加载出错:', error);
		    }
      },

      //获取当前登录的员工信息
      async getUserInfo(){
        console.log('getUserInfo - 开始获取员工信息');
        try {
          let res = await apiRoute.getPersonnelInfo({})
          if (res.code != 1) {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
            return false;
          }
  
          this.userInfo = res.data
          console.log('getUserInfo - 员工信息获取成功');
          return true;
        } catch (error) {
          console.error('getUserInfo - 获取员工信息失败:', error);
          return false;
        }
      },

      //获取客户详情
		  async getInfo(){
		    console.log('getInfo - 开始获取客户详情, resource_sharing_id:', this.resource_sharing_id);
		    try {
		      // 检查resource_sharing_id是否存在
		      if (!this.resource_sharing_id) {
		        console.error('getInfo - resource_sharing_id为空，无法获取客户详情');
		        uni.showToast({
		          title: '缺少必要参数',
		          icon: 'none'
		        });
		        return false;
		      }
		      
		      let data = {
            resource_sharing_id:this.resource_sharing_id//共享资源表id
          }
          console.log('getInfo - 发起请求:', data);
          let res = await apiRoute.xs_resourceSharingInfo(data)
          console.log('getInfo - 请求响应:', res);
          if(res.code != 1){
            console.error('getInfo - 请求失败:', res.msg);
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
            return false;
          }
          this.clientInfo = res.data
          console.log('getInfo - 客户详情数据:', this.clientInfo);
          console.log('getInfo - 客户详情获取完成');
          return true;
		    } catch (error) {
		      console.error('getInfo - 获取客户详情失败:', error);
		      return false;
		    }
      },

      //获取跟进记录
      async getFollowList(){
        let data = {
          sales_id:this.resource_sharing_id//
        }
        let res = await marketApi.followList(data)
        if(res.code != 1){
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
          return
        }
        this.followList = res.data
      },

      //获取通话记录
      async getListCallUp(){
        console.log('getListCallUp - 开始获取通话记录');
        try {
          // 检查resource_sharing_id是否存在
          if (!this.resource_sharing_id) {
            console.error('getListCallUp - resource_sharing_id为空，无法获取通话记录');
            return false;
          }
          
          let data = {
            sales_id:this.resource_sharing_id//
          }
          let res = await apiRoute.listCallUp(data)
          if(res.code != 1){
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
            return false;
          }
          this.listCallUp = res.data
          console.log('getListCallUp - 通话记录获取成功');
          return true;
        } catch (error) {
          console.error('getListCallUp - 获取通话记录失败:', error);
          return false;
        }
      },

      //跳转页面-编辑客户详情
      openViewEditClues(){
        // 检查resource_sharing_id是否存在
        if (!this.resource_sharing_id) {
          console.error('openViewEditClues - resource_sharing_id为空，无法跳转');
          uni.showToast({
            title: '缺少必要参数',
            icon: 'none'
          });
          return;
        }
        
		    let resource_sharing_id = this.resource_sharing_id//共享资源表id
        this.$navigateTo({
          url: `/pages/market/clue/edit_clues?resource_sharing_id=${resource_sharing_id}`
        })
      },

      //跳转页面-客户信息修改记录
      openViewEditCluesLog() {
        // 检查clientInfo.resource_id是否存在
        const resource_id = this.safeGet(this.clientInfo, 'resource_id');
        if (!resource_id) {
          console.error('openViewEditCluesLog - resource_id为空，无法跳转');
          uni.showToast({
            title: '缺少必要参数',
            icon: 'none'
          });
          return;
        }
        
        this.$navigateTo({
          url: `/pages/market/clue/edit_clues_log?resource_id=${resource_id}`
        })
      },

      //跳转页面-订单列表
      openViewOrder() {
        // 检查必要参数是否存在
        const resource_id = this.safeGet(this.clientInfo, 'resource_id');
        if (!resource_id) {
          console.error('openViewOrder - resource_id为空，无法跳转');
          uni.showToast({
            title: '缺少必要参数',
            icon: 'none'
          });
          return;
        }
        
        let resource_name = this.safeGet(this.clientInfo, 'customerResource.name', '')//客户资源id姓名
        let staff_id = this.safeGet(this.userInfo, 'id', '')//员工id
        let staff_id_name = this.safeGet(this.userInfo, 'name', '')//员工姓名

        this.$navigateTo({
          url: `/pages/market/clue/order_list?resource_id=${resource_id}&resource_name=${resource_name}&staff_id=${staff_id}&staff_id_name=${staff_id_name}`
        })
      },

      //跳转页面-课程安排
      openViewEditClassLog() {
        let resource_id = this.clientInfo.resource_id//客户资源id
        let resource_name = this.clientInfo.customerResource.name || ''//客户资源id姓名

        let staff_id = this.userInfo.id//员工id
        let staff_id_name = this.userInfo.name || ''//员工姓名

        this.$navigateTo({
          url: `/pages/market/clue/class_arrangement?resource_id=${resource_id}&resource_name=${resource_name}&staff_id=${staff_id}&staff_id_name=${staff_id_name}`
        })
      },

      //跳转页面-转接跟进任务
      openViewNewTask() {
        this.$navigateTo({
          url: `/pages/market/clue/new_task`
        })
      },

      //拨打电话
      async callTel(tel) {
        let param = {
					staff_id: this.userInfo.id, //员工id
					resource_id: this.clientInfo.resource_id, //资源ID
					resource_type: '', //资源类型（如设备、文件、系统等）
					communication_type: 'phone', //沟通类型: phone-电话, email-邮件, meeting-会议, other-其他
					communication_result: 'success', //沟通结果: success-成功, failure-失败, pending-待定
					remarks: null, //备注
					tag: null, //标签
				}

				let res = await apiRoute.xs_communicationRecordsAdd(param) //添加通过记录
				if (res.code != 1) {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
					return
				}

				uni.makePhoneCall({
					phoneNumber: tel
				})
      },

      // 打开添加备注弹窗
      openAddRemark(record) {
        this.remark_content = '';
        this.currentRecord = record;
        this.$refs.remarkPopup.open();
      },
      
      // 确认添加备注
      async confirmRemark() {
        if (!this.remark_content.trim()) {
          uni.showToast({
            title: '请输入备注内容',
            icon: 'none'
          });
          return;
        }
        
        try {
          uni.showLoading({
            title: '提交中...',
            mask: true
          });
          
          const params = {
            staff_id: this.userInfo.id, // 员工id
            resource_id: this.clientInfo.resource_id, // 资源ID
            resource_type: '', // 资源类型
            communication_type: 'note', // 沟通类型: phone-电话, note-备注
            communication_result: 'success', // 沟通结果
            remarks: this.remark_content, // 备注内容
            tag: null // 标签
          };
          
          // 如果是针对特定通话记录的备注，添加关联ID
          if (this.currentRecord && this.currentRecord.id) {
            params.related_record_id = this.currentRecord.id; // 关联的通话记录ID
            console.log('添加备注到通话记录:', this.currentRecord);
          }
          
          const res = await apiRoute.xs_communicationRecordsAdd(params);
          
          if (res.code !== 1) {
            uni.showToast({
              title: res.msg || '添加备注失败',
              icon: 'none'
            });
            return;
          }
          
          uni.showToast({
            title: '添加备注成功',
            icon: 'success'
          });
          
          // 刷新通话记录列表
          this.getListCallUp();
          
        } catch (error) {
          console.error('添加备注失败:', error);
          uni.showToast({
            title: '添加备注失败，请重试',
            icon: 'none'
          });
        } finally {
          uni.hideLoading();
          this.$refs.remarkPopup.close();
        }
      },
      
      // 关闭备注弹窗
      closeRemark() {
        this.$refs.remarkPopup.close();
      },

      // 拨打电话按钮点击
      handleMakeCall() {
        if (!this.clientInfo.customerResource.phone_number) {
          uni.showToast({
            title: '电话号码为空',
            icon: 'none'
          });
          return;
        }
        this.callTel(this.clientInfo.customerResource.phone_number);
      },

      // 发送消息按钮点击
      handleSendMessage() {
        if (!this.clientInfo.customerResource.member_id) {
          uni.showToast({
            title: '该客户未注册账号，无法发送消息',
            icon: 'none'
          });
          return;
        }
        
        let member_id = this.clientInfo.customerResource.member_id;
        let member_name = this.clientInfo.customerResource.name || '';
        
        this.$navigateTo({
          url: `/pages/market/clue/chat?member_id=${member_id}&member_name=${member_name}`
        });
      },

			//切换标签
			async switch_tags(type){
				this.switch_tags_type = type
				// 当切换到课程信息时，获取课程数据
				if (type === 2) {
					await this.getCourseInfo();
				}
			},
			getSelect(type){
				this.select_type = type
			},

      // 获取课程信息
      async getCourseInfo() {
        try {
          if (!this.clientInfo.resource_id) {
            console.error('getCourseInfo - resource_id为空，无法获取课程信息');
            return false;
          }
          
          // 使用新的学生课程信息接口
          const params = {
            resource_id: this.clientInfo.resource_id,
            member_id: this.clientInfo.customerResource.member_id || ''
          };
          
          // 调用新的API获取课程信息
          try {
            const res = await apiRoute.getStudentCourseInfo(params);
            if (res.code === 1 && res.data) {
              this.courseInfo = res.data;
              console.log('getCourseInfo - 课程信息获取成功:', this.courseInfo);
              return true;
            } else {
              console.warn('API返回错误:', res.msg);
              throw new Error(res.msg);
            }
          } catch (apiError) {
            console.warn('使用API获取课程信息失败，使用模拟数据:', apiError);
            // 如果API调用失败，使用模拟数据进行演示
            this.courseInfo = this.getMockCourseData();
            console.log('getCourseInfo - 使用模拟课程数据');
            return true;
          }
        } catch (error) {
          console.error('getCourseInfo - 获取课程信息异常:', error);
          // 降级到模拟数据
          this.courseInfo = this.getMockCourseData();
          return false;
        }
      },
      
      // 格式化课程数据
      formatCourseData(rawData) {
        if (!Array.isArray(rawData)) {
          return [];
        }
        
        return rawData.map(item => ({
          id: item.id || Math.random(),
          course_name: item.course_name || '未知课程',
          total_count: item.total_count || 0,
          used_count: item.used_count || 0,
          leave_count: item.leave_count || 0,
          expiry_date: item.expiry_date || '',
          status: item.status || 'active',
          main_coach_id: item.main_coach_id || null,
          main_coach_name: item.main_coach_name || '未分配',
          education_id: item.education_id || null,
          education_name: item.education_name || '未分配',
          assistant_ids: item.assistant_ids || '',
          assistant_names: item.assistant_names || '无'
        }));
      },
      
      // 获取模拟课程数据（用于演示）
      getMockCourseData() {
        return [
          {
            id: 1,
            course_name: '篮球基础课程',
            total_count: 20,
            used_count: 8,
            leave_count: 2,
            expiry_date: '2024-12-31',
            status: 'active',
            main_coach_id: 1,
            main_coach_name: '张教练',
            education_id: 2,
            education_name: '李教务',
            assistant_ids: '3,4',
            assistant_names: '王助教, 赵助教'
          },
          {
            id: 2,
            course_name: '足球进阶训练',
            total_count: 15,
            used_count: 15,
            leave_count: 1,
            expiry_date: '2024-10-31',
            status: 'completed',
            main_coach_id: 5,
            main_coach_name: '陈教练',
            education_id: 2,
            education_name: '李教务',
            assistant_ids: '6',
            assistant_names: '孙助教'
          }
        ];
      },
      
      // 获取人员列表（教练、教务、助教）
      async getPersonnelList() {
        try {
          // 使用新的获取人员列表API
          try {
            const res = await apiRoute.getPersonnelList();
            if (res.code === 1 && res.data) {
              const personnel = res.data || [];
              
              // 按角色分类人员 - 根据实际数据结构调整
              this.coachList = personnel.filter(p => p.role_name === '教练' || p.role_type === 'coach' || p.role_name === '教师');
              this.educationList = personnel.filter(p => p.role_name === '教务' || p.role_type === 'education');  
              this.assistantList = personnel.filter(p => p.role_name === '助教' || p.role_type === 'assistant');
              
              console.log('getPersonnelList - 人员列表获取成功');
              console.log('教练列表:', this.coachList);
              console.log('教务列表:', this.educationList);
              console.log('助教列表:', this.assistantList);
              return true;
            } else {
              console.warn('API返回错误:', res.msg);
              throw new Error(res.msg);
            }
          } catch (apiError) {
            console.warn('使用API获取人员列表失败，使用模拟数据:', apiError);
            
            // 如果API调用失败，使用模拟数据
            this.coachList = this.getMockCoachList();
            this.educationList = this.getMockEducationList();
            this.assistantList = this.getMockAssistantList();
            
            console.log('getPersonnelList - 使用模拟人员数据');
            return true;
          }
        } catch (error) {
          console.error('getPersonnelList - 获取人员列表异常:', error);
          // 降级到模拟数据
          this.coachList = this.getMockCoachList();
          this.educationList = this.getMockEducationList();
          this.assistantList = this.getMockAssistantList();
          return false;
        }
      },
      
      // 获取模拟教练数据
      getMockCoachList() {
        return [
          { id: 1, name: '张教练' },
          { id: 5, name: '陈教练' },
          { id: 7, name: '刘教练' }
        ];
      },
      
      // 获取模拟教务数据
      getMockEducationList() {
        return [
          { id: 2, name: '李教务' },
          { id: 8, name: '周教务' }
        ];
      },
      
      // 获取模拟助教数据
      getMockAssistantList() {
        return [
          { id: 3, name: '王助教' },
          { id: 4, name: '赵助教' },
          { id: 6, name: '孙助教' },
          { id: 9, name: '钱助教' }
        ];
      },
      
      // 打开课程编辑弹窗
      openCourseEditDialog(course) {
        this.currentCourse = course;
        
        // 设置当前选中的配置
        this.selectedMainCoach = course.main_coach_id;
        this.selectedEducation = course.education_id;
        this.selectedAssistants = course.assistant_ids ? course.assistant_ids.split(',').map(Number) : [];
        
        this.$refs.courseEditPopup.open();
      },
      
      // 选择主教练
      selectMainCoach(coachId) {
        this.selectedMainCoach = coachId;
      },
      
      // 选择教务
      selectEducation(educationId) {
        this.selectedEducation = educationId;
      },
      
      // 切换助教选择
      toggleAssistant(assistantId) {
        const index = this.selectedAssistants.indexOf(assistantId);
        if (index > -1) {
          this.selectedAssistants.splice(index, 1);
        } else {
          this.selectedAssistants.push(assistantId);
        }
      },
      
      // 确认修改教练配置
      async confirmCourseEdit() {
        try {
          uni.showLoading({
            title: '保存中...',
            mask: true
          });
          
          const params = {
            student_course_id: this.currentCourse.id,
            main_coach_id: this.selectedMainCoach,
            education_id: this.selectedEducation,
            assistant_ids: this.selectedAssistants.join(',')
          };
          
          console.log('准备保存教练配置:', params);
          
          try {
            // 调用真实的API接口
            const res = await apiRoute.updateStudentCoursePersonnel(params);
            if (res.code === 1) {
              uni.showToast({
                title: '修改成功',
                icon: 'success'
              });
              
              // 刷新课程信息
              await this.getCourseInfo();
              
            } else {
              uni.showToast({
                title: res.msg || '修改失败',
                icon: 'none'
              });
              return;
            }
          } catch (apiError) {
            console.warn('API调用失败，使用本地更新:', apiError);
            
            // API调用失败时的降级处理：更新本地数据
            const courseIndex = this.courseInfo.findIndex(c => c.id === this.currentCourse.id);
            if (courseIndex > -1) {
              // 更新主教练
              const mainCoach = this.coachList.find(c => c.id === this.selectedMainCoach);
              if (mainCoach) {
                this.courseInfo[courseIndex].main_coach_id = this.selectedMainCoach;
                this.courseInfo[courseIndex].main_coach_name = mainCoach.name;
              }
              
              // 更新教务
              const education = this.educationList.find(e => e.id === this.selectedEducation);
              if (education) {
                this.courseInfo[courseIndex].education_id = this.selectedEducation;
                this.courseInfo[courseIndex].education_name = education.name;
              }
              
              // 更新助教
              const assistantNames = this.selectedAssistants.map(id => {
                const assistant = this.assistantList.find(a => a.id === id);
                return assistant ? assistant.name : '';
              }).filter(name => name).join(', ');
              
              this.courseInfo[courseIndex].assistant_ids = this.selectedAssistants.join(',');
              this.courseInfo[courseIndex].assistant_names = assistantNames || '无';
            }
            
            uni.showToast({
              title: '修改成功（本地）',
              icon: 'success'
            });
          }
          
        } catch (error) {
          console.error('confirmCourseEdit - 修改教练配置失败:', error);
          uni.showToast({
            title: '修改失败，请重试',
            icon: 'none'
          });
        } finally {
          uni.hideLoading();
          this.$refs.courseEditPopup.close();
        }
      },
      
      // 关闭课程编辑弹窗
      closeCourseEdit() {
        this.$refs.courseEditPopup.close();
      },
      

      // 安全访问对象属性的方法
      safeGet(obj, path, defaultValue = '') {
        if (!obj) return defaultValue;
        const keys = path.split('.');
        let result = obj;
        for (const key of keys) {
          if (result === null || result === undefined || !result.hasOwnProperty(key)) {
            return defaultValue;
          }
          result = result[key];
        }
        return result || defaultValue;
      },
		}
	}
</script>

<style lang="less" scoped>
	.assemble {
		width: 100%;
		height: 100vh;
		overflow: auto;
		background-color: #292929;
	}

	.main_box {
		background: #292929;
		min-height: 28vh;
	}

	// 操作按钮样式
	.action-buttons {
		display: flex;
		align-items: center;
		
		.btn-item {
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-left: 20rpx;
			
			.btn-icon {
				width: 40rpx;
				height: 40rpx;
			}
		}
	}

	//统计信息
	.count_section {
		width: 100%;
		position: relative;

		.main {
			width: 100%;
			position: absolute;
			z-index: 2;
			padding: 0rpx 24rpx;
			display: flex;
			justify-content: center;

			.course_box {
				padding: 26rpx 22rpx 0 22rpx;
				width: 95%;
				height: 250rpx;
				border-radius: 20rpx;
				background-color: #fff;
			}
		}

		.bg_top {
			height: 180rpx;
			background-color: #29D3B4;
		}

		.bg_bottom {
			height: 80rpx;
			background-color: #292929;
		}
	}
	.course_box_top{
		width: 100%;
		height: 60%;
	}
	.course_box_centre{
		margin: auto;
		width: 95%;
		height: 4rpx;
		background: #F5F5F8;
	}
	.course_box_below{
		width: 100%;
		height: 40%;
		display: flex;
		justify-content: space-between;
	}
	.course_box_top_top {
		display: flex;
		align-items: center;
		gap: 20rpx;
	
		.pic {
			width: 44rpx;
			height: 44rpx;
			border-radius: 50%;
		}
	
		.name {
			color: #333333;
			font-size: 28rpx;
		}
	}
	.course_box_top_below{
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	.course_box_top_below-left{
		display: flex;
		align-items: center;
		padding-top: 16rpx;
		font-size: 24rpx;
	}
	.drop-image-x {
		width: 20rpx;
		height: 20rpx;
	}
	.title-x {
		font-size: 28rpx;
		color: #333333;
		padding-left: 10rpx;
	}
	.course_box_top_below-right{
		padding-top: 16rpx;
		font-size: 24rpx;
		display: flex;
		align-items: center;
	}
	.drop-image-star {
		width: 40rpx;
		height: 40rpx;
	}
	.selected-text{
		color: #1CD188;
		display: flex;
		align-items: center;
	}
	.text{
		color: #333333;
		display: flex;
		align-items: center;
	}
	.basic-message{
		color: #fff;
		padding: 16rpx 60rpx;
		display: flex;
		justify-content: space-between;
	}
	.basic-message-div{
		width: 92%;
		margin: auto;
		background: #555555;
		border-radius: 16rpx;
		padding: 16rpx 0;
	}
	.basic-message-div-txt{
		display: flex;
		justify-content: space-between;
		color: #FFFFFF;
		padding: 14rpx 30rpx;
	}
	.bottom-label{
		width: 100%;
		height: 150rpx;
		background: #fff;
		position: fixed;
		bottom: 0;
		left: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 30rpx;
	}
	
	// 备注文本框样式
	.remark-textarea-container {
		width: 100%;
		position: relative;
		padding: 10rpx 0;
	}
	
	.remark-textarea {
		width: 100%;
		height: 200rpx;
		border: 1px solid #ddd;
		border-radius: 8rpx;
		padding: 20rpx;
		font-size: 28rpx;
		background-color: #f8f8f8;
		box-sizing: border-box;
	}
	
	.remark-count {
		position: absolute;
		bottom: 20rpx;
		right: 20rpx;
		font-size: 24rpx;
		color: #999;
	}
	
	// 备注按钮样式
	.remark-btn {
		background-color: #29D3B4 !important; 
		color: white !important; 
		margin: 0 !important; 
		padding: 0 20rpx !important; 
		height: 60rpx !important; 
		line-height: 60rpx !important;
		font-size: 24rpx !important;
		border-radius: 30rpx !important;
	}
	.follow-records-list{
		width: 92%;
		background: #434544;
		border-radius: 16rpx;
		margin: auto;
		padding: 16rpx;
		color: #fff;
		position: relative;
	}
	.same-community{
		width: 120rpx;
		background: #3d4a55;
		color: #1e62a9;
		position: absolute;
		top: 0;
		right: 0;
		padding: 8rpx 16rpx;
		text-align: center;
		border-radius: 40rpx 70rpx 70rpx 12rpx;
	}
	.coeducation{
		width: 120rpx;
		background: #3d4a55;
		color: #2e9380;
		position: absolute;
		top: 0;
		right: 0;
		padding: 8rpx 16rpx;
		text-align: center;
		border-radius: 40rpx 70rpx 70rpx 12rpx;
	}
	.same-community{
		width: 120rpx;
		background: #40504c;
		color: #1e62a9;
		position: absolute;
		top: 0;
		right: 0;
		padding: 8rpx 16rpx;
		text-align: center;
		border-radius: 40rpx 70rpx 70rpx 12rpx;
	}
	.search{
		width: 92%;
		margin: auto;
		display: flex;
		margin-top: 20rpx;
	}
	.selected{
		background: #294e48;
		border-radius: 16rpx;
		padding: 12rpx 8rpx;
		text-align: center;
		color: #29d3b4;
		margin-left: 5rpx;
	}
	.not-selected{
		margin-left: 5rpx;
		background: #ffffff;
		border: 4rpx #959595 solid;
		border-radius: 16rpx;
		padding: 12rpx 8rpx;
		text-align: center;
	}
	.call-record-item {
		width: 100%;
		background: #434544;
		border-radius: 16rpx;
		margin: auto;
		padding: 16rpx;
		color: #fff;
		position: relative;
	}
	.call-record-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.call-name {
		font-size: 28rpx;
		font-weight: bold;
	}
	.call-time {
		font-size: 24rpx;
		color: #999;
	}
	.call-record-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.call-detail {
		display: flex;
		align-items: center;
	}
	.call-label {
		font-size: 24rpx;
		color: #999;
		margin-right: 10rpx;
	}
	.call-remark {
		margin-top: 10rpx;
	}
	.call-remark-content {
		font-size: 24rpx;
		color: #fff;
	}
	
	// 通话记录样式
	.call-log {
		width: 100%;
		padding: 0 20rpx;
		box-sizing: border-box;
	}
	
	.call-record-wrapper {
		margin-bottom: 20rpx;
	}
	
	.call-record-item {
		width: 100%;
		background: #3D3D3D;
		border-radius: 16rpx;
		padding: 20rpx;
		color: #fff;
		box-sizing: border-box;
	}
	
	.call-record-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 15rpx;
		border-bottom: 1px solid #4A4A4A;
		padding-bottom: 10rpx;
	}
	
	.call-name {
		font-size: 28rpx;
		font-weight: bold;
		color: #fff;
	}
	
	.call-time {
		font-size: 24rpx;
		color: #999;
	}
	
	.call-record-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10rpx;
	}
	
	.call-detail {
		display: flex;
		align-items: center;
	}
	
	.call-label {
		font-size: 24rpx;
		color: #999;
		margin-right: 10rpx;
	}
	
	.call-remark {
		margin-top: 10rpx;
		padding-top: 10rpx;
		border-top: 1px solid #4A4A4A;
	}
	
	.call-remark-content {
		font-size: 24rpx;
		color: #fff;
		word-break: break-all;
		display: inline-block;
		width: 90%;
		vertical-align: top;
	}
	
	// 课程信息样式
	.course-info {
		padding: 20rpx;
	}
	
	.course-item {
		background: #3D3D3D;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		color: #fff;
	}
	
	.course-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		padding-bottom: 15rpx;
		border-bottom: 1px solid #4A4A4A;
	}
	
	.course-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #fff;
	}
	
	.course-status {
		padding: 8rpx 16rpx;
		border-radius: 12rpx;
		font-size: 24rpx;
		color: #fff;
	}
	
	.status-active {
		background: #29d3b4;
	}
	
	.status-expired {
		background: #ff6b6b;
	}
	
	.status-completed {
		background: #999;
	}
	
	.status-default {
		background: #666;
	}
	
	.course-progress {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}
	
	.progress-bar {
		flex: 1;
		height: 12rpx;
		background: #555;
		border-radius: 6rpx;
		overflow: hidden;
		margin-right: 20rpx;
	}
	
	.progress-fill {
		height: 100%;
		background: linear-gradient(to right, #29d3b4, #1ea08e);
		border-radius: 6rpx;
		transition: width 0.3s ease;
	}
	
	.progress-text {
		font-size: 26rpx;
		color: #29d3b4;
		min-width: 120rpx;
		text-align: right;
	}
	
	.course-details {
		margin-bottom: 20rpx;
	}
	
	.detail-row {
		display: flex;
		justify-content: space-between;
		margin-bottom: 15rpx;
		font-size: 28rpx;
	}
	
	.detail-label {
		color: #999;
	}
	
	.detail-value {
		color: #fff;
	}
	
	.course-actions {
		text-align: center;
		padding-top: 15rpx;
		border-top: 1px solid #4A4A4A;
	}
	
	.action-btn {
		color: #29d3b4;
		font-size: 28rpx;
	}
	
	.empty-course {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}
	
	.empty-img {
		width: 200rpx;
		height: 200rpx;
		opacity: 0.5;
		margin-bottom: 30rpx;
	}
	
	.empty-text {
		color: #999;
		font-size: 28rpx;
	}
	
	// 教练配置编辑弹窗样式
	.popup-container {
		width: 90vw;
		max-width: 600rpx;
		background: #fff;
		border-radius: 20rpx;
		box-shadow: 0 10rpx 40rpx rgba(0, 0, 0, 0.3);
		overflow: hidden;
	}
	
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 40rpx;
		background: #29d3b4;
		color: #fff;
	}
	
	.popup-title {
		font-size: 36rpx;
		font-weight: bold;
	}
	
	.popup-close {
		font-size: 40rpx;
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.2);
	}
	
	.popup-footer {
		display: flex;
		border-top: 1px solid #eee;
	}
	
	.popup-btn {
		flex: 1;
		padding: 30rpx;
		text-align: center;
		font-size: 32rpx;
		font-weight: bold;
	}
	
	.cancel-btn {
		color: #666;
		border-right: 1px solid #eee;
	}
	
	.confirm-btn {
		color: #29d3b4;
	}
	
	.popup-btn:active {
		background: #f5f5f5;
	}
	
	.course-edit-container {
		width: 100%;
		max-height: 60vh;
		overflow-y: auto;
		padding: 30rpx 20rpx;
		box-sizing: border-box;
	}
	
	.edit-section {
		margin-bottom: 40rpx;
		width: 100%;
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		padding-bottom: 15rpx;
		border-bottom: 2px solid #29d3b4;
	}
	
	.coach-list {
		width: 100%;
		max-height: 300rpx;
		overflow-y: auto;
		border: 1px solid #eee;
		border-radius: 12rpx;
		background: #fff;
	}
	
	.coach-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 30rpx;
		border-bottom: 1px solid #f0f0f0;
		background: #fff;
		transition: all 0.3s ease;
		min-height: 80rpx;
		box-sizing: border-box;
	}
	
	.coach-item:last-child {
		border-bottom: none;
	}
	
	.coach-item.selected {
		background: #f0f9ff;
		border-left: 4rpx solid #29d3b4;
	}
	
	.coach-item:active {
		background: #f5f5f5;
	}
	
	.coach-name {
		font-size: 30rpx;
		color: #333;
		flex: 1;
	}
	
	.coach-check {
		color: #29d3b4;
		font-size: 36rpx;
		font-weight: bold;
		width: 40rpx;
		text-align: center;
	}
</style>