<template>
  <div>
    <el-row class="mb20">
      <div style="font-size: large;font-weight: 520;margin-top: 15px;margin-bottom: 15px;color:#606266" v-if="showTitle">
        <span>{{subTitle}}</span>
      </div>
      <el-button v-if="showAdd && outerType != 4" type="primary" :disabled="addDisabled" @click="add">{{ addLabel }}</el-button>
      <slot :outerType="outerType" :type="type" name="operation"></slot>
    </el-row>
    <el-table :max-height="maxHeight" ref="table"
              :data="records != null && records.length === 0 ? records : records.filter(data=>data.operationFlag!==3)"
              v-loading="loading"
              row-key="id" @select="handleSelect"
              @select-all="handleSelectAll" @selection-change="handleSelectionChange" :span-method="spanMethod"
              class="page-table" stripe :border="border"
              :header-cell-style="{...headerStyle,'background-color': '#F3F4FB'}">
      <slot name="default" :outerType="outerType" :operationType="type" :list="records"></slot>
      <Column label="操作" v-if="showHandle && (outerType != 4 || showWatch)" :minWidth="100" fixed="right" align="center">
        <template #default="{ row,index }">
          <slot name="firstOperation" :row="row" :index="index" :outerType="outerType" :type="type"/>
          <el-link v-if="showWatch" type="primary" @click="watchColumn(row,index)">{{ watchLinkLabel }}</el-link>
          <slot name="secondOperation" :row="row" :index="index" :outerType="outerType" :type="type"/>
          <el-link v-if="showEdit && outerType != 4" type="primary" @click="editColumn(row,index)">{{ editLinkLabel }}</el-link>
          <slot name="thirdOperation" :row="row" :index="index" :outerType="outerType" :type="type"/>
          <el-link v-if="showDelete && outerType != 4" type="danger" @click="deleteColumn(row,index)">{{ deleteLinkLabel }}</el-link>
          <slot name="fourthOperation" :row="row" :index="index" :outerType="outerType" :type="type"/>
        </template>
      </Column>
    </el-table>
    <el-dialog :title="dtlTitle" ref="dialog" :visible.sync="visible" @closed="closeForm" :width="dtlDialogWidth"
               append-to-body :close-on-click-modal="false" :destroy-on-close="true" >
      <template #default v-if="visible">
        <Form v-if="visible" ref="form" :value="form" :disabled="type === 3 || outerType === 4" v-loading="loading"
              :labelWidth="labelWidth" :rules="rules">
          <slot name="form" :type="type" :outerType="outerType" :tableIndex="tableIndex" :form="form"
                :disabled="type === 3"/>
        </Form>
        <slot v-if="visible" name="other" :type="type" :outerType="outerType" :otherData="otherData" :form="form"
              :disabled="type === 3"/>
      </template>
      <slot v-if="visible" name="otherContent" ref="otherContent" :type="type" :outerType="outerType" :form="form"
            :disabled="type === 3"/>
      <template #footer>
        <FooterButton :showConfirm="type!== 3 && outerType !== 4" :showSaveDraft="false" :showSubmit="false" @confirm="dtlConfirm"
                      @cancel="closeForm"/>
      </template>
    </el-dialog>
    <slot name="dialogOthers" :form="form"></slot>
  </div>
</template>

<script>

import Column from "@/components/element/table/Column";
import Form from '@/components/element/form/Form.vue'
import FooterButton from '@/components/element/footerButton.vue'
import {findIndex} from "../../../utils";

/**
 * 列表组件
 */
export default {
  name: "SubTable",
  components: {Column, Form, FooterButton},
  props: {
    subTitle:{
      type: String,
      default:''
    },
    //列表查询参数
    query: {
      type: Object
    },
    //是否开始首次查询
    firstSearchFlag: {
      type: Boolean,
      default: true
    },
    showPageFlag: {
      type: Boolean,
      default: false
    },
    //0默认 1新增 2修改 3删除 4查看
    outerType: {
      type: Number,
      require: true,
      default: 0
    },
    //各自业务表--业务id的字段名 用于前端判断数据来源
    fieldName: {
      type: String,
      default: "id",
    },
    //不能重复的参数名
    compareParam: {
      type: String,
      default: null,
    },
    // [0] : 新增标题 [1] 编辑标题 [2]: 详情标题
    dtlTitleList: {
      type: Array,
      default: () => []
    },
    title: {
      type: String,
      default: ''
    },
    dtlDialogWidth: {
      type: String,
      default: "60%"
    },
    labelWidth: {
      type: String,
      default: "100px",
    },
    //是否展示新增
    showAdd: {
      type: Boolean,
      default: true
    },
    //是否展示编辑
    showEdit: {
      type: Boolean,
      default: true
    },
    //是否展示删除
    showDelete: {
      type: Boolean,
      default: true
    },
    showWatch: {
      type: Boolean,
      default: true
    },
    //是否展示操作
    showHandle: {
      type: Boolean,
      default: true
    },
    //新增禁用
    addDisabled: {
      type: Boolean,
      default: false
    },
    maxHeight: {
      type: String,
      default: "600px"
    },
    //边框
    border: {
      type: Boolean,
      default: false
    },
    spanMethod: {
      type: Function,
      default: () => {
      }
    },
    disabled: {
      type: Boolean,
      default: false
    },
    //查看按钮名称
    watchLinkLabel: {
      type: String,
      default: "查看"
    },
    //编辑按钮名称
    editLinkLabel: {
      type: String,
      default: "修改"
    },
    //删除按钮名称
    deleteLinkLabel: {
      type: String,
      default: "删除"
    },
    dtlRecord: {
      type: Array,
      default: () => [],
    },
    //是否自动关闭
    autoClose: {
      type: Boolean,
      default: true
    },
    deleteText: {
      type: String,
      default: "是否删除"
    },
    deleteTitle: {
      type: String,
      default: "提示"
    },
    shadow: {
      type: String,
      default: "never"
    },
    cardStyle: {
      type: String,
      default: ""
    },
    //自定义 Form校验
    rules: {
      type: Array,
      default: () => {}
    },
    headerStyle: {
      type: String,
      default: () => {}
    },
    //取消默认form确定事件
    cancelDefaultDtlConfirm: {
      type: Boolean,
      default: false
    },
    defaultData:{
      type: Array,
      default: () => []
    },
    showTitle:{
      type: Boolean,
      default: false
    },
    addLabel:{
      type: String,
      default: '新增'
    }
  },
  data() {
    return {
      records: [],
      visible: false,
      type: 3,
      form: {},
      searchParams: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
      dtlTitle: "",
      //数据在records中的索引
      index: null,
      //数据展示在table中的索引
      tableIndex: 0,
      loading: false,
      otherData: [],
      //多字段不重复校验 true不通过  false通过
      checkFlag: false,
      checkMessage: '数据重复',
      deleteFlag: false,
      deleteMessage: '禁止删除'
    };
  },
  created() {

  },
  mounted() {
    this.initData()
  },
  watch: {},
  methods: {
    initData(){
      if(this.defaultData && this.defaultData.length > 0){
        this.records = [...this.defaultData]
      }else{
        this.clearRecords()
      }
    },
    add() {
      this.$emit('add')
      this.type = 1
      this.dtlTitle = !!this.title ? ('新增' + this.title) : this.dtlTitleList[0];
      this.visible = true
    },
    addRow(rows,fieldName) {
      let arr = rows.map(item => item[fieldName])
      if(this.records.some(record => record.operationFlag != 3 && arr.includes(record[fieldName]) )){
        this.$message.error("请勿重复添加数据")
        return;
      }
      if (rows && rows.length && rows.length > 0) {
        rows.forEach(row => {
          this.$set(row, 'operationFlag', 1)
        })
        this.records = this.records.concat(rows)
      } else if (rows) {
        this.$set(rows, 'operationFlag',1)
        this.records.push(rows)
      }
    },
    clearRecords() {
      this.records = []
    },
    addRowAfterClear(rows) {
      if (this.records && this.records.length > 0) {
        if (this.outerType !== 0) {
          //主表非新增
          let temp = []
          this.records.forEach(record => {
            //如果是后台来的数据置flag
            if (record[this.fieldName] !== undefined && record[this.fieldName] !== null) {
              this.$set(record, 'operationFlag', 2)
              temp.push(record)
            }
          })
          this.records = JSON.parse(JSON.stringify(temp))

        } else {
          //主表新增 直接删除records数据
          this.records = []
        }
      }
      if (rows && rows.length && rows.length > 0) {
        rows.forEach(row => {
          this.$set(row, 'operationFlag', 0)
        })
        this.records = this.records.concat(rows)
      } else if (rows) {
        this.$set(rows, 'operationFlag', 0)
        this.records.push(rows)
      }
    },
    async watchColumn(row, index) {
      this.tableIndex = index
      await this.$emit('watchColumn', {row: {...row}, index: index, tableIndex: this.tableIndex})
      this.type = 0;
      this.dtlTitle = !!this.title ? (this.title + '详情') : this.dtlTitleList[2];
      this.visible = true
      this.form = {...row}
    },
    async editColumn(row, index) {
      this.tableIndex = index
      await this.$emit('editColumn', {row: {...row}, index: index, tableIndex: this.tableIndex})
      this.type = 2;
      //编辑  form标题
      this.dtlTitle = !!this.title ? ('修改' + this.title) : this.dtlTitleList[1];
      this.resetForm('form')
      this.form = JSON.parse(JSON.stringify(row))
      this.index = findIndex(this.records, index,row,this.compareParam)
      this.visible = true
    },
    async deleteColumn(row, index) {
      this.index = findIndex(this.records, index,row,this.compareParam)
      let text = this.deleteText + ''
      let title = this.deleteTitle + ''
      await this.$confirm(text, title,{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        type: 'warning'
      });
      await this.$emit("deleteCheck", {records: this.records, form: row, index: index})
      if (this.deleteFlag) {
        this.$message.error(this.deleteMessage + '')
        this.deleteFlag = false;
        return;
      }
      if (row[this.fieldName] === undefined) {
        //前端数据
        this.records.splice(this.index, 1);
      } else {
        //后端数据
        this.$set(row, 'operationFlag', 3);
      }
      this.records = JSON.parse(JSON.stringify(this.records))
      this.$emit('deleteColumn', {records: [...this.records], index: index, row: row})
    },
    //明细确定
    async dtlConfirm() {
      //表单校验
      await this.$refs.form.validate()
      //自定义校验 手动在此处修改 checkFlag
      await this.$emit("customCheck", {records: this.records, form: this.form})
      //修改表单数据的事件 可在此处操作表单数据
      await this.$emit("editAddForm")
      let flag = !!this.checkFlag
      if (this.compareParam != null) {
        //判断除当前修改数据之外的有效数据
        flag = this.records.filter((record, index) => {
          return record.operationFlag !== 3 && record[this.compareParam] !== undefined && record[this.compareParam] === this.form[this.compareParam] && this.index !== index
        }).length >= 1
      }
      flag = flag || !!this.checkFlag
      if (flag) {
        //数据不重复校验
        this.$message.error(this.checkMessage + '')
        this.checkFlag = false
        return;
      }
      //取消默认的明细确定
      if (this.cancelDefaultDtlConfirm) {
        //自定义 明细确定添加数据到records
        await this.$emit('customDtlConfirmAddRows', {records: this.records, form: this.form})
        return;
      }
      this.otherData = []
      //默认
      if (this.outerType === 0) {
        //新增
        if (this.type === 1) {
          this.$set(this.form, 'operationFlag', 1)
          this.records.push({...this.form})
          this.index = this.records.filter(it => it.operationFlag !== '3').length - 1;
        }
        //修改
        else if (this.type === 2) {
          this.$set(this.form, 'operationFlag', 2)
          this.records[this.index] = {...this.form};
          this.records = JSON.parse(JSON.stringify(this.records));
        }
      } else if (this.outerType === 1) {
        if (this.type === 1) {
          this.$set(this.form, 'operationFlag', 1)
          this.records.push({...this.form})
          this.index = this.records.filter(it => it.operationFlag !== '3').length - 1;
        } else if (this.type === 2) {
          //后台来的数据编辑后标记为编辑  前端的数据编辑后标记为新增
          if (this.form[this.fieldName] !== undefined && this.form[this.fieldName] !== null && this.form[this.fieldName] !== "") {
            this.$set(this.form, 'operationFlag', 2)
            this.records[this.index] = {...this.form};
            this.records = JSON.parse(JSON.stringify(this.records));
          } else {
            this.$set(this.form, 'operationFlag', 1)
            this.records[this.index] = {...this.form};
            this.records = JSON.parse(JSON.stringify(this.records));
          }
        }
      }
      //禁止在此处修改数据
      this.$emit('dtlConfirm', {records: [...this.records], form: {...this.form}, index: this.index});
      if (this.autoClose) {
        this.closeForm();
      }
    },
    //保存草稿
    saveDraft() {
      this.$emit("saveDraft", this.records);
    },
    //提交
    submit() {
      this.$emit("submit", this.records);
    },
    //取消
    cancel() {
      this.$emit("cancel");
    },
    closeForm() {
      this.form = {};
      this.loading = false;
      this.visible = false;
      this.$emit('closeForm')
    },
    //获取表格数据
    async getList() {
      //预留分页方法
    },
    handleSelect(val) {
      this.$emit('handleSelect', val)
    },
    handleSelectAll(val) {
      this.$emit('handleSelectAll', val)
    },
    handleSelectionChange(val) {
      this.$emit('handleSelectionChange', val)
    },
    //关闭弹框
    close() {
      this.visible = false;
      this.form = {};
      this.baseInfo = {
        records: [],
      };
    },

  },
};
</script>

<style>
</style>
