<template>
  <p-table-edit-pro
    class="white"
    ref="easyTable"
    :rowSelectType="rowSelectType"
    dragle
    auto-width
    size="small"
    :bordered="true"
    :pagination="false"
    :rowKey="rowKey"
    :editor-row-table="!isView"
    :data-source="data"
    :columns="aColumns"
    :rowSelectFixed="true"
    :selectedRowKeys="selectedRowKeys"
    :loading="loading"
    :scroll="scroll"
    :getCheckboxProps="getCheckboxProps"
    @search="clickRow"
    @clickRow="clickRowFun"
    @dblclickRow="dblclickRowFun"
    @colChange="colChange"
    @selectChange="handleSelectChange"
  >
    <template slot="operation" slot-scope="text, record">
      <span
        v-for="item of operations"
        :key="item.title"
        v-show="item.show ? item.show(record) : true"
        class="btn"
        @click.stop="item.click(record)"
      >
        {{ item.title }}
      </span>
    </template>

    <template
      v-if="scopedSlots[0] && scopedSlots[0].type === 'autoComplete'"
      v-slot:[scopedSlots[0].slot]="text, record"
    >
      <a-auto-complete
        :value="text"
        :dataSource="scopedSlotsExtendData[scopedSlots[0].slot]"
        :filterOption="(inputValue, option) => option.key.indexOf(inputValue) > -1"
        @change="(value) => handleAutoComplete(scopedSlots[0].slot, record, value)"
        @select="(value) => handleColSelect(scopedSlots[0].slot, record, value)"
      />
    </template>

    <template
      v-if="scopedSlots[1] && scopedSlots[1].type === 'autoComplete'"
      v-slot:[scopedSlots[1].slot]="text, record"
    >
      <a-auto-complete
        :value="text"
        :dataSource="scopedSlotsExtendData[scopedSlots[1].slot]"
        :filterOption="(inputValue, option) => option.key.indexOf(inputValue) > -1"
        @change="(value) => handleAutoComplete(scopedSlots[1].slot, record, value)"
        @select="(value) => handleColSelect(scopedSlots[1].slot, record, value)"
      />
    </template>

    <template
      v-if="scopedSlots[2] && scopedSlots[2].type === 'autoComplete'"
      v-slot:[scopedSlots[2].slot]="text, record"
    >
      <a-auto-complete
        :value="text"
        :dataSource="scopedSlotsExtendData[scopedSlots[2].slot]"
        :filterOption="(inputValue, option) => option.key.indexOf(inputValue) > -1"
        @change="(value) => handleAutoComplete(scopedSlots[2].slot, record, value)"
        @select="(value) => handleColSelect(scopedSlots[2].slot, record, value)"
      />
    </template>

    <template
      v-if="scopedSlots[3] && scopedSlots[3].type === 'autoComplete'"
      v-slot:[scopedSlots[3].slot]="text, record"
    >
      <a-auto-complete
        :value="text"
        :dataSource="scopedSlotsExtendData[scopedSlots[3].slot]"
        :filterOption="(inputValue, option) => option.key.indexOf(inputValue) > -1"
        @change="(value) => handleAutoComplete(scopedSlots[3].slot, record, value)"
        @select="(value) => handleColSelect(scopedSlots[3].slot, record, value)"
      />
    </template>

    <template
      v-if="scopedSlots[4] && scopedSlots[4].type === 'autoComplete'"
      v-slot:[scopedSlots[4].slot]="text, record"
    >
      <a-auto-complete
        :value="text"
        :dataSource="scopedSlotsExtendData[scopedSlots[4].slot]"
        :filterOption="(inputValue, option) => option.key.indexOf(inputValue) > -1"
        @change="(value) => handleAutoComplete(scopedSlots[4].slot, record, value)"
        @select="(value) => handleColSelect(scopedSlots[4].slot, record, value)"
      />
    </template>

    <template
      v-if="scopedSlots[5] && scopedSlots[5].type === 'autoComplete'"
      v-slot:[scopedSlots[5].slot]="text, record"
    >
      <a-auto-complete
        :value="text"
        :dataSource="scopedSlotsExtendData[scopedSlots[5].slot]"
        :filterOption="(inputValue, option) => option.key.indexOf(inputValue) > -1"
        @change="(value) => handleAutoComplete(scopedSlots[5].slot, record, value)"
        @select="(value) => handleColSelect(scopedSlots[5].slot, record, value)"
      />
    </template>
  </p-table-edit-pro>
</template>

<script>
import { AutoComplete } from 'ant-design-vue'
import clonedeep from 'lodash.clonedeep'

export default {
  components: {
    'a-auto-complete': AutoComplete,
  },
  props: {
    isView: {
      type: Boolean,
      default: false,
    },
    columns: {
      type: Array,
    },
    rowKey: {
      type: String,
    },
    rowSelectType: {
      type: Number,
      default: 2,
    },
    colChange: {
      type: Function,
    },
    colSelect: {
      type: Function,
    },
    operations: {
      type: Array,
    },
    onClick: {
      type: Function,
      default: null,
    },
    onDblClick: {
      type: Function,
      default: null,
    },
    onSelectRow: {
      type: Function,
      default: null,
    },
    getCheckboxProps: {
      type: Function,
      default: null,
    },
  },

  data() {
    return {
      aColumns: null,
      loading: false,
      data: [],
      clickRowRecord: {},
      selectedRowKeys: [],
      remoteParams: {},
      scroll: null,
      clickTest: null,
      scopedSlots: [],
      scopedSlotsExtendData: {},
    }
  },

  watch: {
    columns: {
      handler(val) {
        let cls = clonedeep(val)
        if (this.isView) {
          cls.pop()
        }
        if (Array.isArray(this.operations) && this.operations.length > 0) {
          cls.push({
            title: '操作',
            key: 'operation',
            fixed: 'right',
            width: 100,
            scopedSlots: { customRender: 'operation' },
          })
        }
        let x = 0
        let w = 100
        let scopedSlots = []
        cls.forEach((tt) => {
          if (tt.hidden) {
            return
          }
          if (tt.cusType && tt.scopedSlots && tt.scopedSlots.customRender != 'operation') {
            scopedSlots.push({ type: tt.cusType, slot: tt.scopedSlots.customRender })
            if (tt.cusType == 'autoComplete') {
              this.scopedSlotsExtendData = { ...this.scopedSlotsExtendData, [tt.scopedSlots.customRender]: [] }
            }
          }
          if (tt.width) w = parseInt(tt.width)
          else w = 100
          x += w
        })
        this.scroll = { x: x }
        this.aColumns = cls
        this.scopedSlots = scopedSlots
      },
      immediate: true,
    },
  },

  methods: {
    setItems(items) {
      if (!items && !Array.isArray(items)) {
        return
      }
      let trans = this.columns.filter((t) => t.transValues)
      let a = null
      this.data = items.map((t) => {
        a = { ...t }
        trans.forEach((tt) => {
          if (tt.type === 'switch') {
            a[tt.key] = a[tt.key] == tt.transValues[0] ? true : false
          }
        })
        this.columns.forEach((col) => {
          if (Reflect.has(a, col.key)) return
          a[col.key] = null
        })
        return a
      })
    },
    clickRow(selectedRowKeys, record) {
      // 获取当前编辑行数据
    },
    clickRowFun(selectedRowKeys, record, data) {
      // 点击当前行
      // debugger
      // this.$refs.easyTable.getCurrentRow()
      this.clickRowRecord = record
      this.clickTest = data
      if (this.onClick) {
        this.onClick(selectedRowKeys, record, data)
      }
    },
    dblclickRowFun(selectedRowKeys, record, data) {
      // 点击当前行
      if (this.onDblClick) {
        this.onDblClick(selectedRowKeys, record, data)
      }
    },
    sss() {
      this.$refs.easyTable.getCurrentRow()
    },
    addItem() {
      let item = {}
      this.columns.forEach((tt) => {
        if (tt.hidden) item[tt.key] = 'aaa' + Math.floor(Math.random() * 1000)
        else {
          if (tt.type == 'switch') {
            item[tt.key] = tt.value
          }
          if (tt.type == 'select') {
            item[tt.key] = null
          } else {
            item[tt.key] = ''
          }
        }
      })
      this.data.push(item)
    },

    delItems() {
      // 删除附表所有信息
      this.data = []
      this.selectedRowKeys = []
    },

    delSelectedItems() {
      let list = this.data.filter((t) => !this.selectedRowKeys.some((k) => t[this.rowKey] == k))
      this.data = list
      this.selectedRowKeys = []
    },

    validateFields(fn) {
      fn(null, this.getListData())
    },

    getListData(isSelected) {
      let rowKey = this.columns[0].key
      let trans = this.columns.filter((t) => t.transValues)
      let a = null
      let isSuccess = true
      this.$refs.easyTable.validateFields(
        isSelected ? this.selectedRowKeys : null,
        function (error, values, selectData) {
          if (error) {
            isSuccess = false
            return
          }
        }
      )
      if (!isSuccess) {
        return false
      }
      let list = this.data
      // 过滤勾选项
      // console.log('this.selectedRowKeys', rowKey, list)
      if (isSelected) {
        list = list.filter((tt) => this.selectedRowKeys.some((k) => tt[this.rowKey] == k))
      }
      return list.map((t) => {
        a = { ...t }
        if (typeof a[rowKey] === 'string' && a[rowKey].indexOf('aaa') === 0) {
          a[rowKey] = null
        }
        trans.forEach((tt) => {
          if (tt.type === 'switch') {
            a[tt.key] = a[tt.key] ? tt.transValues[0] : tt.transValues[1]
          }
        })
        Object.keys(a).forEach((k) => {
          if (!this.columns.some((c) => c.key === k || c.dataIndex === k)) {
            delete a[k]
          }
        })
        return a
      })
    },

    handleSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      if (this.onSelectRow) {
        this.onSelectRow(selectedRowKeys, selectedRows)
      }
      // console.log(selectedRowKeys, selectedRows, '555555555555');
    },

    // 处理auto complete
    handleAutoComplete(name, record, value) {
      let index = this.data.findIndex((t) => t == record)
      // console.log(index,name, value, this.data,this.data[index][name])
      this.data.splice(index, 1, { ...this.data[index], [name]: value })
      // this.data[index][name] = value
      // this.data[index] = {
      //   ...this.data[index],
      //   [name]: value
      // };
      let p = {
        record: record,
        name: name,
        value: value,
        index: index,
      }
      this.colChange(p)
    },

    handleColSelect(name, record, value) {
      let index = this.data.findIndex((t) => t[this.rowKey] == record[this.rowKey])
      // console.log(name, record, value, index)
      this.data[index][name] = value
      let p = {
        record: record,
        name: name,
        value: value,
        index: index,
      }
      if (this.colSelect) {
        this.colSelect(p)
      }
    },
    getOption(inputValue, option) {
      // (inputValue, option)=>option.text.indexOf(inputValue) > -1
      // console.log(inputValue, option.key, '321');
    },
  },
}
</script>

<style scoped>
.rightItem {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}
.extra-text {
  float: left;
  font-size: 14px;
  color: #333;
}
.extra-text > span {
  display: inline-block;
  margin-right: 30px;
  line-height: 30px;
}
.btn {
  color: #2b80ff;
  margin-right: 10px;
  cursor: pointer;
}
.btn:hover {
  text-decoration: underline;
}
.white tr > td {
  background-color: #fff;
}
</style>
<style>
.white  .title-required{
  color: rgb(241, 16, 16);
}
</style>