<template>
  <el-drawer title="转接客服" size="400px" :visible="visible" direction="rtl" :before-close="onClose">
    <div class="change-customer">
      <div class="select-customer">
        <el-select v-model="selectedCustomer" placeholder="请选择要转接的客服" style="width: 100%; margin-bottom: 20px;">
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.nickName"
            :value="item.id">
          </el-option>
        </el-select>
        
        <el-button 
          type="primary" 
          @click="transfer" 
          :disabled="!selectedCustomer"
          style="width: 100%;">
          转接
        </el-button>
      </div>
      
      <div class="transfer-info" v-if="currentUserInfo">
        <h4>当前对话信息：</h4>
        <p>当前用户：{{ currentUserInfo.nickName }}</p>
        <p>用户ID：{{ currentUserInfo.id }}</p>
      </div>
    </div>
  </el-drawer>
</template>

<script>
export default {
  name: 'ChangeCustomer',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    // 当前对话的目标用户ID
    targetUserId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      customerList: [],
      selectedCustomer: null,
      currentUserInfo: null
    }
  },
  methods: {
    onClose() {
      this.selectedCustomer = null;
      this.$emit('close');
    },
    
    loadCustomers() {
      this.$http({
        url: '/user/getEnableChangeCustomer',
        method: 'post'
      }).then(customers => {
        this.customerList = customers;
      }).catch(error => {
        this.$message.error('获取客服列表失败');
        console.error(error);
      });
    },
    
    transfer() {
      if (!this.selectedCustomer) {
        this.$message.warning('请选择要转接的客服');
        return;
      }

      const params = {
        targetId: this.selectedCustomer,
        userId: this.targetUserId
      };

      this.$http({
        url: '/user/changeCustomer',
        method: 'post',
        data: params
      }).then(res => {
        this.$message.success('转接成功');
        this.$emit('transfer-success');
        this.onClose();
      }).catch(error => {
        this.$message.error('转接失败');
        console.error(error);
      });
    },
    
    open(targetUserId) {
      this.currentUserInfo = { id: targetUserId };
      this.loadCustomers();
    }
  },
  
  watch: {
    visible(newVal) {
      if (newVal) {
        this.loadCustomers();
      } else {
        this.selectedCustomer = null;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.change-customer {
  padding: 20px;

  .select-customer {
    margin-bottom: 30px;
  }

  .transfer-info {
    h4 {
      margin-top: 0;
      color: #333;
    }
    
    p {
      margin: 10px 0;
      color: #666;
    }
  }
}
</style>