<template>
  <el-table-column :label="label" :prop="prop" :min-width="minWidth">
    <template #header="{row,$index}">
      <slot name="header">
        <span style="color: red" v-if="required">*</span>
        <span>{{ label }}</span>
      </slot>
    </template>
    <template #default="{row,$index}">
      <el-form-item :prop="`${prop}${$index}`" :rules="required?  [{
                  required,
                  trigger: 'change',
                  message: label + '不能为空',
                  validator: (rule, value, callback) => valueRequired(rule, value, callback, row)
        }]:[]">
<!--刘总说不要 这个tip         -->
<!--        <el-tooltip :content="returnContent(row)" effect="light">
        </el-tooltip>-->
          <el-select ref="remoteSelect"
                     @change="val => handleChange(val,row,$index)"
                     @clear="val=>handleClear(val,row,$index)"
                     v-model="row[prop]"
                     remote
                     :remote-method="remote"
                     :multiple="multiple"
                     :multiple-limit="multipleLimit"
                     collapse-tags
                     :clearable="clearable"
                     filterable
                     :disabled="disabled || columnDisabledFunction(row,$index)"
                     :allow-create="allowCreate"
                     size="small"
          >
            <el-option
              v-for="item in data"
              :value="item[`${valueProp}`]"
              :label="item[`${labelProp}`]"
              :title="item[`${labelProp}`]"
            />
          </el-select>

      </el-form-item>
    </template>
  </el-table-column>
</template>

<script>

import {escapePercent, isBlank} from "@/utils/common";
import yid from "yid";


export default {
  name: "RemoteSelectColumn",
  props: {
    label: {
      type: String,
      default: "",
    },
    prop: {
      type: String,
    },
    minWidth: {
      type: Number,
      default: 150,
    },
    disableFunction: {
      type: Function,
      default: (row) => !row
    },
    multiple: {
      type: Boolean,
      default: false
    },
    multipleLimit: {
      type: Number,
      default: 10
    },
    valueProp: {
      type: String,
      default: 'value'
    },
    labelProp: {
      type: String,
      default: 'label'
    },
    span: {
      type: Number,
      default: 8
    },
    allowCreate: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    required: {
      type: Boolean,
      default: false
    },
    validateMsg: {
      type: String,
    },
    /**
     * 是否需要同步存储 label值
     * 存储label 字段名
     * */
    setLabelProp: {
      type: String,
      default: ""
    },
    /**
     * 存储label  在下拉款中item的字段名
     *
     * */
    setLabelValueProp: {
      type: String,
      default: ""
    },
    /**
     * 远程搜索方法
     *
     * */
    remoteMethod: {
      type: Function
    },
    /**
     * 输入值查询参数
     * */
    queryLabel: {
      type: String,
    },
    /**
     * 额外查询参数
     * */
    queryParam: {
      type: Object,
      default: () => {
      }
    },
    firstSelect: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      cellRow: {},
      data: [],
      param: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      }
    }
  },
  computed: {
    returnContent() {
      return function (row) {
        if (!this.data || this.data.length === 0) {
          return row[this.prop]
        }
        let item = this.data.find(it => it[this.valueProp] == row[this.prop]);
        if (this.data && this.data.length > 0) {
          return !isBlank(item) ? item[this.labelProp] : "";
        }
      }
    }
  },
  methods: {
    yid,
    columnDisabledFunction(row, $index) {
      return this.disableFunction(row, $index);
    },
    handleChange(cellValue, row, index) {
      let res = null
      this.data.some((item) => {
        if (item[this.valueProp] === cellValue) {
          res = item
          this.$set(this.cellRow, this.prop, cellValue);
          this.$set(this.$parent.$parent.model, (this.prop + `${index}`), cellValue);
          this.$set(row, this.prop, cellValue)
          let operationFlag = isBlank(row.id) ? '1' : '2'
          this.$set(row, 'operationFlag', operationFlag)
          if (!isBlank(this.setLabelProp)) {
            this.$set(row, this.setLabelProp, item[this.setLabelValueProp]);
          }
        }
      })
      this.$emit('change', {val: res, row: row, index: index})
    },
    handleClear(cellValue, row, index) {
      this.$set(this.cellRow, this.prop, "");
      this.$set(this.$parent.$parent.model, (this.prop + `${index}`), "");
      this.$set(row, this.prop, "")
      if (!isBlank(this.setLabelProp)) {
        this.$set(row, this.setLabelProp, "");
      }
      this.$emit('clear',row,index)
    },
    async remote(query) {
      let param = {
        ...this.param,
        ...this.queryParam,
      }
      let label = !isBlank(this.queryLabel) ? this.queryLabel : this.prop
      this.$set(param, label, query)
      this.$set(this.param, label, query)
      // const {code, rows, total} = await this.remoteMethod(param);
      // if (code === 200) {
      //   //2023-11-21 解决，重复输入同一个字符，导致数组重复,输入字符查询，每次都是覆盖；
      //   this.data.push(...rows);
      //   this.param.total = total
      // }
      const res = await this.remoteMethod(param);
      if (!isBlank(res)) {
        this.data = res
      }

    },
    async focus(val) {
      if (this.firstSelect) {
        let row = {...this.queryParam}
        row = escapePercent(row);
        let param = {
          ...this.param,
          ...row,
        }
        let label = !isBlank(this.queryLabel) ? this.queryLabel : this.prop
        this.$set(param, label)
        // const {code, rows, total} = await this.remoteMethod(param);
        // if (code === 200) {
        //   //2023-11-21 解决，重复输入同一个字符，导致数组重复,输入字符查询，每次都是覆盖；
        //   this.data.push(...rows);
        //   this.param.total = total
        // }
        const res = await this.remoteMethod(param);
        if (!isBlank(res)) {
          this.data = res
        }
      }
    },
    async loadMore(val) {
      let {pageNum, pageSize, total} = this.param
      let currentTotal = Number(pageNum) * Number(pageSize);
      let flag = currentTotal >= total;
      if (!flag) {
        this.param.pageNum++;
        await this.queryMethod(val);
      }
    },
    async queryMethod(query) {
      let param = {
        ...this.param,
        ...this.queryParam,
      }
      // const {code, rows, total} = await this.remoteMethod(param);
      // if (code === 200) {
      //   //2023-11-21 解决，重复输入同一个字符，导致数组重复,输入字符查询，每次都是覆盖；
      //   this.data.push(...rows);
      //   this.param.total = total
      // }
      const res = await this.remoteMethod(param);
      if (!isBlank(res)) {
        this.data = res
      }


    },


    valueRequired(rule, value, callback, item) {
      let formValue = item[this.prop];
     if (!isBlank(formValue)) {
        callback()
      } else {
        callback(new Error(rule.message))
      }
    },


  }
};
</script>


<style scoped>
.msg__error {
  color: #ff4949;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  margin: 0;
}
</style>
