<template>
  <view class="change-service-container">
    <view :style="{ paddingTop: top + 'px', height: localHeight + 'px' }" class="change-service-header">
      <view class="back-btn" @tap="goBack">
        <uni-icons color="#333" size="28" type="left"></uni-icons>
      </view>
      <view class="page-title">选择客服</view>
      <view class="empty-header"></view>
    </view>

    <!-- 客服列表 -->
    <view class="service-list">
      <view v-if="isLoading" class="loading">加载中...</view>
      <view v-else-if="serviceList.length === 0" class="empty-service">暂无客服</view>
      <view v-else>
        <view v-for="service in serviceList" :key="service.id">
          <view class="service-item" @tap="confirmChange(service)">
            <image :src="service.employee_image" class="service-avatar" mode="aspectFill"></image>
            <view class="service-info">
              <text class="service-name">{{ service.employee_name }}</text>
              <text class="service-desc">{{ service.expertise || '专业客服为您服务' }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { menuButtonInfo, picUrl, request } from '@/utils'
import { apiArr } from '@/api/customerService'

export default {
  data(){
    return {
      localHeight: '',
      top: '',
      // 客服列表
      serviceList: [],
      // 是否加载中
      isLoading: false,
      // 当前选中的客服ID
      selectedServiceId: ''
    }
  },
  onLoad(options){
    const meun = menuButtonInfo()
    this.top = meun.top
    this.localHeight = meun.height
    // 从选项中获取当前选中的客服ID（如果有）
    if (options.currentMchId) {
      this.selectedServiceId = options.currentMchId
    }

    // 加载客服列表
    this.loadServiceList()
  },
  methods: {
    // 加载客服列表
    async loadServiceList(){
      try {
        this.isLoading = true

        request(apiArr.csGetMchContactList, 'POST', {
          mch_id: uni.getStorageSync('merchantInfo').id
        }).then((res) => {
          if (res.rows && res.rows.length > 0) {
            res.rows.map(item => {
              item.employee_image = picUrl + item.employee_image
            })
            this.serviceList = res.rows
          } else {
            console.log('没有获取到客服列表数据')
          }
        })
      } catch (error) {
        console.error('加载客服列表失败', error)
      } finally {
        this.isLoading = false
      }
    },

    // 选择客服
    selectService(service){
      this.selectedServiceId = service.mchId
    },

    // 确认切换客服
    confirmChange(item){
      if (!item) {
        uni.showToast({
          title: '请选择客服',
          icon: 'none'
        })
        return
      }
      // 存储当前聊天对象的信息
      // uni.setStorageSync('currentChatTarget', item);
      item.type = 1
      // 跳转到聊天页面
      uni.navigateTo({
        url: '/packages/customerService/index/index?item=' + JSON.stringify(item)
      })
    },

    // 返回上一页
    goBack(){
      uni.navigateBack()
    }
  }
}
</script>

<style>
@import url("./index.css");
</style>