<template>
  <div class="card-container">

    <el-row>
      <CustomButton type="primary" label="common.addRow" @handleClick="addRow" v-if="showAdd" icon="el-icon-plus"/>
      <CustomButton type="danger" label="relatedCase.deleteRow" @handleClick="deleteMore" v-if="showDelete" icon="el-icon-delete"/>
      <slot name="operations"/>
    </el-row>
    <CustomForm :value="dtlForm" :disabled="disabled" ref="dtlForm" class="editTableForm">
      <el-table :max-height="maxHeight" ref="table"
                :data="records "
                v-loading="loading" row-key="id" @selection-change="handleSelectionChange" :span-method="spanMethod"
                :class="binClass(showAdd)"  :border="border"
                :header-cell-style="{ ...headerStyle, 'background-color': '#F3F4FB' }">
        <slot name="default" class="formTable" :list="records" :disablde="disabled"></slot>
      </el-table>
    </CustomForm>

  </div>
</template>

<script>

import {isBlank} from "@/utils/common";
import CustomButton from "../CustomButton.vue";
import CustomForm from "../CustomForm/CustomForm.vue";

export default {
  name: "EditTable",
  props: {
    topRightTotalShowFlag: {
      type: Boolean,
      default: false
    },
    list: {
      type: Function
    },
    spanMethod: {
      type: Function,
      default: () => {
      }
    },
    formatter: {
      type: Function,
      default: (obj) => obj
    },
    defaultParams: {
      type: Object,
      default: () => {
      }
    },
    stripe: {
      type: Boolean,
      default: true
    },
    border: {
      type: Boolean,
      default: false
    },
    showPage: {
      type: Boolean,
      default: true
    },
    showAdd: {
      type: Boolean,
      default: true
    },
    showSearch: {
      type: Boolean,
      default: true
    },
    showBatchAdd: {
      type: Boolean,
      default: true
    },
    showDelete: {
      type: Boolean,
      default: true
    },
    //最大高度
    maxHeight: {
      type: Number,
      default: 500
    },
    defaultSort: {
      type: Object,
      default: () => {
      }
    },
    //各自业务表--业务id的字段名 用于前端判断数据来源
    fieldName: {
      type: String,
      default: "id",
    },
    headerStyle: {
      type: Object,
      default: () => {
      }
    },
    // 新增时，需要额外的参数属性
    addRowObject: {
      type: Object,
      default: () => {
      }
    },
    batchAddTitle: {
      type: String,
      default: "批量新增",
    },
    dialogAddTitle: {
      type: String,
      default: "明细选择"
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    dialogList: {
      type: Function
    },
    dialogAdd: {
      type: Boolean,
      default: false
    },
    selectedData: {
      type: Array,
      default: () => []
    },
    //设置按钮的span
    buttonSpan: {
      type: Number,
      default: 6
    },
    buttonOffSet: {
      type: Number,
      default: 0
    },
    //设置按钮的左边距
    marginLeftValue: {
      type: Number,
      default: 22
    },
    dialogDefaultParam: {
      type: Object,
      default: () => {
      }
    },
    /**
     * 为处理 搜索条件非 表单内 的定制参数
     * */
    dialogDefaultSearch: {
      type: Boolean,
      default: true
    },
    /**
     * 是否默认添加一行
     * */
    defaultAddRow: {
      type: Boolean,
      default: false
    },
    checkField: {
      type: String,
      default: null
    },
    checkFieldFunction: {
      type: Function
    },
    tableRowClassName: {
      type: Function
    },
    checkBeforeAddRow: {
      type: Function,
      default: () => true
    },
    skipRules: {
      type: Boolean,
      default: false
    },
    handleAddOpenFunciton: {
      type: Function
    },
    onlyOne: {
      type: Boolean,
      default: false
    },
    selectedTableHeight: {
      type: Number,
      default: 200
    },
    selectTableHeight: {
      type: Number,
      default: 240
    },
    /**
     *  弹框 在重置之后，是否需要清空table的值
     * */
    clearDialogTableFlag: {
      type: Boolean,
      default: false
    }
  },
  components: {CustomForm, CustomButton},
  data() {
    return {
      searchParams: {
        total: 0,
        pageNumber: 1,
        pageSize: 10,
      },
      records: [],
      loading: false,
      selections: [],
      selectedIndexs: [],
      addInfo: {},
      dtlForm: {},
      dtlFormRules: {},
      dialogSearchForm: {
        ...this.dialogDefaultParam
      },
      searchFormData: {},
      deleteItemIds: [],
    };
  },
  computed: {
    qurable() {
      return typeof this.list === 'function'
    },
  },
  watch: {
    records: {
      handler: function (val, oldVal) {
        this.initDataIndex();
        // this.batchInitFormProp();
      },
      immediate: true
    },
    dialogDefaultParam: {
      handler: function (val) {

      }
    },

  },

  methods: {
    handleSelectionChange(val) {
      this.selectedIndexs = val.map((item) => item.index);
      this.$emit('handleSelectionChange', val)
    },
    //sortChange
    sortChange({column, prop, order}) {
      this.$emit('sortChange', {column, prop, order})
    },
    async validateTable() {
      if (this.records.length === 0) {
        this.$message.error("至少保存一条明细！")
        return new Promise((resolve, reject) => {
          reject('fail')
        })
      }
      if (this.checkFieldFunction) {
        let {flag, message} = await this.checkFieldFunction
        if (!flag) {
          this.$message.error(message)
          return new Promise((resolve, reject) => {
            reject('fail')
          })
        }
      }
      return await this.$refs.dtlForm.validate();
    },

    async getList() {
      this.loading = true
      let {total, pageNumber, pageSize} = this.searchParams;
      let searchParams = {
        total: total,
        pageNum: pageNumber,
        pageSize: pageSize,
        ...this.defaultParams
      }
      if (this.list) {
        try {
          const {rows, total} = await this.list(searchParams)
          this.records = this.formatter(rows, searchParams)
          this.searchParams.total = total
          this.$emit('search', searchParams)
        } finally {
          this.loading = false
        }
      } else {
        this.loading = false
      }
    },
    binClass(val) {
      if (val) {
        return 'page-table'
      } else {
        return 'page-table2'
      }
    },


    addRow() {
      if (this.onlyOne && this.records) {
        var filter = this.records.filter(item => item.operationFlag != 2);
        if (filter && filter.length === 1) {
          this.$message.error('只能添加一条明细')
          return
        }
      }

      if (this.dialogAdd) {
        // 添加打开弹窗前对参数的校验
        if (this.checkBeforeAddRow && !this.checkBeforeAddRow()) {
          return
        }
        if (this.handleAddOpenFunciton) {
          this.handleAddOpenFunciton();
        }
        this.$refs.addDialog.open();
        if (!this.showSearch) {
          this.$nextTick(() => this.$refs.table.getList())
        }
      } else {
        let row = {}
        if (this.addRowObject) {
          row = {...this.addRowObject}
        }
        this.records.push({...row, operationFlag: 0});
        this.records = JSON.parse(JSON.stringify(this.records));
      }
    },
    /**
     * 批量新增后 初始化表单内校验规则
     *
     * */
    batchInitFormProp(length) {
      return
      if (!this.$refs.table) return;
      let arrLength = isBlank(length) ? this.records.length : length;
      this.dtlForm = {}
      this.dtlFormRules = {}
      for (let i = 0; i < arrLength; i++) {
        let column = this.$refs.table.$children.filter(v => !isBlank(v.prop));
        let {index, operationFlag} = this.records[i];
        if (operationFlag === 2) {
          continue;
        }
        if (!isBlank(index)) {
          column.forEach(item => {
            this.$set(this.dtlForm, (item.prop + "" + (index)), this.records[index][item.prop]);
            if (item.required) {
              this.$set(this.dtlFormRules, (item.prop + "" + index),
                [{
                  required: true,
                  trigger: 'change',
                  message: item.label + "不能为空",
                  validator: this.valueRequired,
                  index: index
                }])
            }
            if (item.validateFunction) {
              this.$set(this.dtlFormRules, (item.prop + "" + index),
                [{trigger: 'change', validator: item.validateFunction}])
            }
          })
        }
      }
    },
    deleteMore() {
      if (this.selectedIndexs.length === 0) {
        this.$message.error('请至少选择一条数据')
      } else {
        // records 为el-table源数据;
        let index = [];
        for (let i = this.records.length - 1; i >= 0; i--) {
          if (this.selectedIndexs.some(item => item == i)) {
            if (!isBlank(this.records[i][this.fieldName])) {
              this.deleteItemIds.push(this.records[i][this.fieldName]);
            }
            this.records.splice(i, 1);
            index.push(i);
          }
        }
        this.records = JSON.parse(JSON.stringify(this.records))
        this.$emit("deleteMore", {records:this.records,indexs: index,deleteItemIds: this.deleteItemIds})
      }
    },
    /**
     * 通过此方法 存储index
     **/
    initDataIndex() {
      let records = this.records.filter(v => v.operationFlag !== 2);
      if (records != null && records.length > 0) {
        for (let i = 0; i < this.records.length; i++) {
          this.$set(this.records[i], 'index', i)
        }
      }
    },
    valueRequired(rule, value, callback) {
      let {index} = rule;
      let item = this.records[index];
      let formValue = this.dtlForm[rule.field];
      if (item.operationFlag === 2) {
        callback()
      } else if (!isBlank(formValue)) {
        callback()
      } else {
        callback(new Error(rule.message))
      }

    },

  },
  created() {

  },
  mounted() {
    // 列表每次新增或删除都要初始化校验
    let size = 0
    this.$watch(() => this.records, val => {
      if (val && val.length !== size) {
        this.initDataIndex();
        size = val.length
      }
    }, {immediate: true})
    this.$nextTick(() => this.$refs.dtlForm.clearValidate())

    if (this.defaultAddRow) {
      this.addRow();
    }
  },


}


</script>

<style scoped>

::v-deep .el-table-column--selection .cell {
  padding-left: 10px;
  padding-right: 10px;
}

::v-deep .el-dialog__body {
  padding-top: 6px !important;
  padding-bottom: 16px !important;
}

::v-deep .page-table {
  margin-top: 16px !important;
}

::v-deep .searchClass2 {
  margin-right: 0px;
}

::v-deep .mb20 {
  margin-bottom: 0px !important;
}

::v-deep .header {
  margin-bottom: 0px !important;
}


::v-deep .editTableForm .el-form-item {
  margin-bottom: 0 !important;
}

.el-table .frozen-row {
  background-color: #F7DEDF;

}

::v-deep .el-dialog .el-dialog__header .el-dialog__title {
  color: #ffffff !important;
}

::v-deep .el-dialog__header {
  background-color: #304156;
}

.el-table .warning-row {
  background-color: #FBF2E4;

}

</style>

