<template>
  <el-select :disabled="this.complaint_id === undefined ? false : true" @change="onSelectChange" v-model="customer" filterable remote
             :remote-method="getCustomerSelectFn" :placeholder="$t('请选择客户编号')">
    <el-option v-for="item in getCustomerList" :label="item.number" :value="Number(item.id)" :data="item.name" :key="item.id"></el-option>
  </el-select>
</template>

<script>
import {getCustomerList, getCustomerSelect} from "@/api/ecw/customer";

export default {
  props:{
    complaint_id: Number,
   value:{
     type:Number,
     default:undefined,
   },
  },
  name: "customerSelectByNumber",
  mounted() {
    console.log(this.complaint_id);
    this.getCustomerSelectFn();
    this.$nextTick(()=>{
      this.customer = this.value;
      if(!(this.customerList.some(i => i.id === this.value)) && this.value !== undefined){
        getCustomerList({ids:this.value}).then(r => {
          this.recommended = r.data;
        })
      }
    });
    this.initializeCustomer();
  },
  computed:{
    getCustomerList(){
      let index = this.customerList.findIndex(
        item => item.id === this.recommended[0]?.id
      )
       if(index > -1) return this.customerList
        else return [...this.customerList,...this.recommended]
    }
  },
  data(){
    return {
      customer:'',
      customerList:[],
      recommended:[],
    }
  },
  methods:{

    getCustomerSelectFn(val){
      getCustomerSelect({pageNo:1,pageSize:100,customerNumber:val}).then(r => {
        this.customerList = r.data.list;
      })
    },
    onSelectChange(selectedId) {
      const selectedItem = this.customerList.find(
        (item) => Number(item.id) === selectedId
      );
      this.customer = selectedId; // 记录选中的客户ID
      if (selectedItem) {
        this.$emit("input", { id: selectedId, name: selectedItem.name }); // 返回id和name
      }
    },
    // 初始化时根据传入的 value 请求客户信息
    initializeCustomer() {
      console.log('value:' + this.value)
      console.log('complaint_id:' + this.complaint_id)
      console.log(this.complaint_id !== undefined ? true : false)
      if (this.value !== undefined) {

        getCustomerList({ ids: this.value }).then((r) => {
          const customerData = r.data?.[0];
          // if (customerData) {
          //   this.customer = customerData.id;
          //   this.$emit("input", { id: customerData.id, name: customerData.name + ':select'}); // 返回初始化值
          // }
        });
      }
    },
  },
  watch:{
    value(val){
      this.customer = val;
      this.initializeCustomer(); // 监听传入值的变化
      if(!(this.customerList.some(i => i.id === val)) && val !== undefined){
        getCustomerList({ids:val}).then(r => {
          this.recommended = r.data;
        })
      }
    }
  }
}
</script>

<style scoped>

</style>
