<template>
  <div class="data-table" :style="{ marginTop: marginTop,width: tableWidth ? tableWidth : '100%',height:tableHeight ? tableHeight : '100%',padding:isAuto ? '':'24px' }">
    <div v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" class="data-table-content">
      <div class="flex">
        <div class="manageTitle">{{ pageTitle }}</div>
        <div>
          <auth-button :auth="btnAddObj" />
          <auth-button :auth="btnQueryObj" />
        </div>
      </div>
      <template v-if="tableData.length || tableCols.length">
        <div style="height: calc(100% - 40px);">
          <el-table v-el-table-infinite-scroll="load" :data="filteredTableData" :summary-method="getSummaries" :span-method="tableSpanMethod" stripe :show-summary="showSummary" border @cell-click="cellClick" :cell-class-name="cellClass" ref="table" :height="tableHeight ? tableHeight : minHeight - 8 + 'vh'" class="table infinite-list" style=" overflow: auto" :style="{width: tableWidth ? tableWidth : '100%'}" @select="selectHandler">
            <el-table-column v-for="(item, index) in tableColsCopy" :key="index" :prop="item.columncode" :label="item.columnname" :show-overflow-tooltip="showOverflowTooltip" :formatter="formatter">
              <template #header>
                <el-tooltip :content="item.columndescribe || item.columnLabel" placement="top">
                  <TableHeaderCell :label="item.columnname" :filter-options="tableDataFilters[item.columncode]" :filter-values.sync="filterValues[item.columncode]" :sortable="item.enablesort" :sort-rule.sync="tableDataSortRules[item.columncode]" />
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column v-if="authBtns.length" label="操作" :width="fixedWidth">
              <template slot-scope="scope">
                <div class="hd-td">
                  <el-scrollbar style="height: 100%">
                    <auth-button v-for="(item,index) in authBtns" :key="index" :auth="item" :row="scope.row" />
                  </el-scrollbar>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template v-else>
        <NoData image-width="auto" image-height="auto" />
      </template>
    </div>
    <div class="data-table-dialog">
      <!--新增/编辑-->
      <Dialog :dialog-title="tableTitle" :dialogSize="width" :dialog-drawer="flag" @handleClose="eledite" @handleSubmit="handleOk">
        <el-form ref="ruleForm" :model="tableForm" :label-width="labelWidth">
          <el-row :gutter="20">
            <el-col v-for="(item, index) in formItem" :key="index" :span="rows">
              <el-form-item :label="item.columnname">
                <template v-if="
                        item.dropdownlist ||
                        item.dropdownlist == 0
                      ">
                  <el-select class="input-shadow" size="small" filterable default-first-option style="width: 100%" v-model="tableForm[item.columncode]" @change="changeSelect(item.columncode, item)" placeholder="请选择" clearable @clear="tableForm[item.columncode] = ''">
                    <el-option v-for="item in tableOptions[item.columncode]" :key="item.v ? item.v : item.planDepartureApt" :label="item.k ? item.k : item.planDepartureApt" :value="
                            item.setlabel === 'positionDescribe'
                              ? item.v
                              : item.v != undefined
                              ? item.v
                              : item.planDepartureApt
                          ">
                    </el-option>
                  </el-select>
                </template>
                <template v-else-if="fromDataType(item.dataType) == 'text'||fromDataType(item.dataType) == 'VARCHAR'">
                  <el-input size="small" :rows="1" type="textarea" @change="inputChangeHandler(item.columncode)" v-model="tableForm[item.columncode]"></el-input>
                </template>
                <template v-else-if="fromDataType(item.dataType) == 'date'">
                  <el-date-picker class="datetimes" value-format="yyyy-MM-dd" v-model="tableForm[item.columncode]" type="date" placeholder="选择日期" @change="inputChangeHandler(item.columncode)">
                  </el-date-picker>
                </template>
                <template v-else-if="fromDataType(item.dataType) == 'datetime'">
                  <el-date-picker class="datetimes" value-format="yyyy-MM-dd HH:mm:ss" v-model="tableForm[item.columncode]" type="datetime" placeholder="选择日期时间" @change="inputChangeHandler(item.columncode)">
                  </el-date-picker>
                </template>
                <template v-else-if="fromDataType(item.dataType) == 'INT' || fromDataType(item.dataType) == 'tinyint'">
                  <el-input size="small" v-model.number="tableForm[item.columncode]" onkeyup="value=value.replace(/[^1-9]/g,'')" @change="inputChangeHandler(item.columncode)"></el-input>
                </template>
                <template v-else>
                  <el-input size="small" v-model="tableForm[item.columncode]" @change="inputChangeHandler(item.columncode)"></el-input>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </Dialog>
      <!--删除-->
      <Dialog dialog-title="删除" :dialog-drawer="rmFlag" @handleClose="rmFlag = false" @handleSubmit="tableRemove">
        <div class="content del-content">
          <span class="el-icon-error error r10"></span>您是否确认删除<span class="error l10">{{ rmTitle }}</span>
          ？
        </div>
      </Dialog>
      <!--高级查询-->
      <Dialog dialog-title="高级查询" dialogSize="600px" :dialog-drawer="advancedDrawer" @handleClose="advancedDrawer = false" @handleSubmit="advancedTable('advancedDialogForm')">
        <AdvancedQuery ref="advancedDialogForm" @getAdvancedQueryData="getAdvancedQueryData" />
        <template slot="d_foot">
          <el-button size="small" @click="queryCollect('advancedDialogForm')" type="primary">收藏</el-button>
        </template>
      </Dialog>
    </div>
  </div>
</template>

<script>
import Dialog from "@/components/PublicPageDialog";
import NoData from "@/components/nodata";
import AuthButton from './components/authButton.vue';
import { getAuthData } from "@/utils/validate";
import { Query, newData, modifyData, moveData, abnormalDataRecovery } from "@/api/webApi";
import TableHeaderCell from '@/components/TableHeaderCell/index.vue';
import AdvancedQuery from '@/components/AdvancedQuery'
export default {
  name: "DataTable",
  props: {
    // dataContent: {
    //   type: Object,
    //   default: () => ({}),
    // },
    //弹框宽度
    width: {
      type: String,
      default: "630px",
    },
    //弹框是否显示在body上
    isBody: {
      type: Boolean,
      default: false,
    },
    //弹框表单-行数
    rows: {
      type: Number,
      default: 24,
    },
    //弹框-表单文字宽度
    labelWidth: {
      type: String,
      default: "120px",
    },
    minHeight: {
      type: Number,
      default: 89,
    },
    // 是否显示合计行
    showSummary: {
      type: Boolean,
      default: false,
    },
    marginTop: {
      type: String,
      default: "0px",
    },
    // 不换行，溢出隐藏
    showOverflowTooltip: {
      type: Boolean,
      default: true,
    },
    //操作列宽度
    fixedWidth: {
      type: String,
      default: "180px",
    },
  },
  components: { Dialog, NoData, AdvancedQuery, AuthButton, TableHeaderCell },
  data () {
    return {
      pageTitle: '',
      asShow: true,
      loading: false,
      flag: false,
      serviceId: null,
      rmFlag: false,
      rowTitle: "",
      page: 0,
      pageSize: 20,
      noMore: false,
      tableCols: [], //表头数据
      tableData: [], //表格数据
      tableColsCopy: [], //表头数据缓存
      formItem: [], //表头数据缓存
      tableDataFilters: {}, //表头-下拉数据
      filterValues: {}, //表头-下拉-选中数据
      tableDataCopy: [], //缓存table数据
      tableGroups: [], //表格分组数据
      colShowFilter: "", //表头-下拉-箭头
      spanArr: [], //表格分组数据缓存
      pos: 0, //表格分组计数
      tableTitle: "新增", //弹框标题
      tableType: "add", //弹框类型=新增/编辑
      tableForm: {}, //弹框表单
      rmTitle: "", //弹框-删除-标题
      tableObj: {}, //增/删/改数据缓存
      tableOptions: {}, //弹框-下来数据缓存
      tableArrs: [], //重组table-表头下拉
      proAll: false, //重组时-所有请求是否都完成
      roles: JSON.parse(sessionStorage.getItem("userAuthList")) ?? [],
      tableOptionscp: {},
      tabledatacopy: {},
      queryId: '',
      tableOther: {},
      tableHeight: '',
      tableWidth: '',
      btnQueryObj: {},
      btnAddObj: {},
      btnEditObj: {},
      btnDelObj: {},
      btnRecordObj: {},
      isAuto: false,
      dialogFlag: false,
      authBtns: [],
      authBtnCol: [],
      authBtnColName: [],
      urlParams: {},
      authId: '',
      tableDataSortRules: {},
      tableKey: '',
      dataContent: {},
      advancedDrawer: false,
      selectOptions: [],
    };
  },
  computed: {
    dataTableContentStyle () {
      const style = {};
      if (this.minHeight) {
        style["min-height"] = this.minHeight;
      }
      if (this.tableHeight) {
        style["height"] = this.tableHeight;
      }
      return style;
    },
    //设置表头-下拉-箭头样式
    arrowClass () {
      return function (prop) {
        let classString = "";
        if (this.colShowFilter === prop) {
          return "arrow-active";
        }
        if (
          Object.entries(this.tableDataFilters).find(
            ([key, arr]) => this.filterValues[prop]
          )
        ) {
          classString += "arrow-blue";
        }
        return classString;
      };
    },
    //设置新增修改表单类型
    fromDataType () {
      return function (type) {
        if (type) {
          return type.replace(/\([^\)]*\)/g, "");
        }
      }
    },

    //设置表头-下拉-选中数据
    filteredTableData () {
      const filtered = this.tableData.filter(item => {
        let flag = true
        Object.entries(this.filterValues).forEach(([key, arr]) => {
          if (arr.length && !arr.includes(String(item[key]))) {
            flag = false
          }
        })
        return flag
      })
      const sortRules = Object.entries(this.tableDataSortRules).reduce(
        (pre, [key, value]) => {
          if (value) {
            pre[0].push(key)
            value = value === 'ascending' ? 'asc' : 'desc'
            pre[1].push(value)
          }
          return pre
        },
        [[], []]
      )
      return this._.orderBy(filtered, sortRules[0], sortRules[1])
    },
  },
  mounted () {
    const { query } = this.$route
    const { title, auth_id } = this.$route.meta
    const { arrs } = getAuthData(auth_id)
    const table = arrs.filter(item => item.pagetype == 3)
    const btnArr = arrs.filter(item => item.pagetype == 4)
    if (btnArr && btnArr.length) {
      btnArr.forEach(item => {
        this.autoBtnObj(item)
      })
    }


    this.urlParams = query
    if (table && table.length) {
      const obj = table[0]
      const { arrs } = getAuthData(obj.pageconfigurationid)
      this.isAuto = true
      this.tableOther = obj
      this.pageTitle = obj.pagename;
      this.authId = obj.pageconfigurationid
      this.queryId = obj.serviceid;
      this.authBtns = arrs.filter(item => item.superiorid == this.authId && item.pagetype == 4)
      this.authBtnCol = arrs.filter(item => Number(item.servicetype) == 6)
      if (this.authBtnCol.length) {
        this.authBtnCol.forEach(item => {
          this.authBtnColName.push(item.relation_data)
        })
      }
      if (this.authBtns && this.authBtns.length) {
        this.authBtns.forEach(item => {
          this.autoBtnObj(item)
        })
      }
      this.getColumnData(obj.pagecode);
    } else {
      this.pageTitle = title;
      // if (auth_id) {
      //   this.queryId = serviceid;
      //   this.authId = pageconfigurationid
      // this.getColumnData(auth_id);
      // }
    }
  },
  updated () {
    if (Object.keys(this.tableOther).length) {
      this.tableHeight = this.tableOther.table_height
      this.tableWidth = `${this.tableOther.table_width}`.includes('%') ? this.tableOther.table_width + 'px' : this.tableOther.table_width + 'px'
    }
    this.$refs["table"]?.doLayout();
    // this.$refs['table'].style.width = this.tableOther.table_width
  },
  methods: {
    //获取表头数据
    async getColumnData (pagecode) {
      try {
        const { code, returnData } = await Query({
          "serviceid": 3,
          "datacontent": {
            "filter": {
              "pagecode": pagecode
            }
          },
          "event": "0"
        });
        if (code == 0) {
          if (returnData && returnData.length) {
            const titleColumn = returnData.find(
              (item) => item.isdisplay != 0
            );
            const columncode = returnData.find(
              (item) => item.isprimarykey == 1
            );
            if (columncode && Object.keys(columncode).length) {
              this.tableKey = columncode['columncode']
            }
            if (titleColumn) {
              this.rowTitle = titleColumn.columnname;
            }
            this.$store.dispatch('auth/changeAuthMsg', returnData)
            this.tableCols = returnData;
            this.setTableCols();
            this.initTableData();
            if (Object.keys(this.urlParams).length) {
              this.getQuery(this.queryId, this.urlParams);
            } else {
              this.getQuery(this.queryId);
            }
          }
        } else {
          this.$message.error("获取表头数据失败");
        }
      } catch (error) {
        console.log(error)
      }
    },
    setTableCols () {
      this.tableCols.forEach(({ columncode, enablefilter, enablesort }) => {
        if (enablefilter) {
          this.$set(this.tableDataFilters, columncode, [])
          this.$set(this.filterValues, columncode, [])
        }
        if (enablesort) {
          this.$set(this.tableDataSortRules, columncode, '')
        }
      })
    },
    autoBtnObj (item) {
      switch (item.servicetype) {
        case '1':
          this.btnQueryObj = item
          break;
        case '2':
          this.btnAddObj = item
          break;
        case '3':
          if (item.openmode != "1") {
            this.btnEditObj = item
          }
          else {
            this.btnRecordObj = item
          }
          break;
        case '4':
          this.btnDelObj = item
          break;
        default:
          break;
      }
    },
    autoBtnClick (id, url) {
      switch (id) {
        case '1':
          this.$message.warning('平铺功能开发中')
          break;
        case '2':
          this.$router.push(url)
          break;
        default:
          break;
      }
    },
    handleQuery () {
      const { openmode, pageroute } = this.btnQueryObj
      if (!openmode) return
      if (openmode != 3) this.advancedDrawer = true // this.autoBtnClick(openmode, pageroute)
      this.dialogFlag = true
    },
    eledite () {
      this.flag = false;
      // const arrbegin = _.cloneDeep(this.tableOptionscp);
      // this.tableOptions = arrbegin;
    },
    load () {
      if (!this.isTree) {
        if (this.noMore || this.loading) {
          return;
        }
        if (Object.keys(this.urlParams).length) {
          this.getQuery(this.queryId, this.urlParams);
        } else {
          this.getQuery(this.queryId);
        }
      }
    },
    resetTable () {
      this.dataContent = {}
      this.page = 0;
      this.noMore = false;
      this.tableData = [];
    },
    changeSelect (data, name) {
      if (this.tableForm[data] === "") {
        this.tableForm[data] = null;
      }
      this.tableForm[this.tableOptions[data][0].setvalue] =
        this.tableForm[data];
      const arrbegin = _.cloneDeep(this.tabledatacopy);
      if (this.tableForm.beginNode) {
        this.tableOptions.beginPosition = arrbegin.beginPosition.filter(
          (i) => i.nodeCode === this.tableForm.beginNode
        );
        arrbegin.beginPosition.forEach((element) => {
          if (element.v === this.tableForm.beginPosition) {
            if (element.nodeCode !== this.tableForm.beginNode) {
              this.tableForm.beginPosition = "";
            }
          }
        });
        // let arr = [];
        // this.tableOptions.beginPosition.forEach((element) => {
        //   arr.push(element.nodeCode);
        // });
        // if (
        //   !arr.includes(this.tableForm.beginPosition) &&
        //   this.tableForm.beginNode
        // ) {
        //   this.tableForm.beginPosition = null;
        // }
        this.asShow = false;
        this.asShow = true;
      }
      if (this.tableForm.beginPosition && !this.tableForm.beginNode) {
        arrbegin.beginPosition.forEach((element) => {
          if (this.tableForm.beginPosition === element.v) {
            this.tableForm.beginNode = element.nodeCode;
          }
        });
      }
      if (this.tableForm.endNode) {
        this.tableOptions.endPosition = arrbegin.endPosition.filter(
          (i) => i.nodeCode === this.tableForm.endNode
        );
        arrbegin.endPosition.forEach((element) => {
          if (element.v === this.tableForm.endPosition) {
            if (element.nodeCode !== this.tableForm.endNode) {
              this.tableForm.endPosition = "";
            }
          }
        });
        this.asShow = false;
        this.asShow = true;
      }
      if (this.tableForm.endPosition && !this.tableForm.endNode) {
        arrbegin.endPosition.forEach((element) => {
          if (this.tableForm.endPosition === element.v) {
            this.tableForm.endNode = element.nodeCode;
          }
        });
      }
    },
    inputChangeHandler (data) {
      if (this.tableForm[data] === "") {
        this.tableForm[data] = null;
      }
    },
    //获取高级查询条件
    getColData (val) {
      const arr = [...val]
      if (arr && arr.length) {
        arr.forEach(item => {
          item.value = item.value.replace(/\s*/g, "")
        })
      }
      this.resetTable()
      this.dataContent = { "filter": arr }
      this.getQuery(this.queryId);
    },
    //获取表格数据
    async getQuery (id, datacontent = this.dataContent) {
      datacontent = {
        "filter": {
          1: 1
        }
      }
      try {
        this.loading = true;
        const { code, returnData } = await Query({
          serviceid: id,
          datacontent,
          event: '0'
        });
        if (code == 0) {
          if (returnData.length === 0) {
            this.page--;
            this.noMore = true;
            this.loading = false;
          }
          this.tableData.push(...returnData);
          // this.tableCols = columnset;
          this.serviceId = id;
          setTimeout(() => {
            this.initTableData();
            this.loading = false;
          }, 100);
        } else {
          this.page--;
          this.loading = false;
          this.$message.error("获取表格数据失败");
        }
      } catch (error) {
        this.page--;
        this.loading = false;
      }
    },
    formatChange (data, event, key) {
      const datas = []
      const flag = Array.isArray(data)
      if (flag) {
        for (let i = 0; i < data.length; i++) {
          let obj = {}
          if (event == 1) {
            obj.value = data[i]
          } else if (event == 2) {
            obj.value = data[i]
            obj.filter = {}
            if (Array.isArray(key)) {
              const keys = []
              const vals = []
              obj.filter = []
              for (let j = 0; j < key.length; j++) {
                const dep = key[i]
                keys.push(Object.keys(dep))
                vals.push(Object.values(dep))
              }
              // const nobj = {
              //   "left": "(",
              //   "column": `${keys[i]}`,
              //   "comparator": "=",
              //   "value": `${vals[i]}`,
              //   "right": ")",
              //   "connector": "and"
              // }

              obj.filter.push(nobj)
              if (obj.value.hasOwnProperty(keys[i])) {
                delete obj.value[keys[i]]
              }
            } else {
              obj.filter[key] = data[i][key]
              if (obj.value[key]) {
                delete obj.value[key]
              }
            }
          } else {
            obj = data[i]
          }
          datas.push(obj)
        }
      } else {
        let obj = {}
        obj.filter = {}
        if (event == 1) {
          obj.value = data
        } else if (event == 2) {
          obj.value = data
          obj.filter[key] = obj.value[key]
          if (obj.value[key]) {
            delete obj.value[key]
          }
        } else {
          obj = data
        }
        datas.push(obj)
      }
      return datas
    },
    //表格-增/删/改
    async generalDataReception (event, data, key) {
      try {
        const params = {
          serviceid: this.queryId,
          datacontent: this.formatChange(data, event, key),
          event: `${event}`,
        };
        const { code } =
          event == 1
            ? await newData(params)
            : event == 2
              ? await modifyData(params)
              : await moveData(params);
        if (code == 0) {
          this.$message.success("操作成功");
          this.flag = false;
          this.rmFlag = false;
          this.tableObj = {};
          this.tableForm = {};
          this.resetTable();
          this.load();
          // this.$router.go(0);
        } else {
          this.$message.error("操作失败");
          this.flag = false;
          this.rmFlag = false;
          this.tableObj = {};
          this.tableForm = {};
        }
      } catch (error) {
        this.flag = false;
        this.rmFlag = false;
        this.tableObj = {};
        this.tableForm = {};
      }
    },
    // 表格勾选
    toggleRowSelection (row, isSelected) {
      this.$refs["table"].toggleRowSelection(row, isSelected);
    },
    // 表格初始勾选
    selectTableRows (tableData, selectFlagName) {
      tableData.forEach((row) => {
        this.$refs["table"].toggleRowSelection(row, !!row[selectFlagName]);
      });
      this.$emit("selectionAll", this.$refs.table.selection);
    },
    //初始化表格
    initTableData () {
      this.tableColsCopy = this.tableCols.filter((item) => item.isdisplay == 2);
      this.tableColsCopy = _.orderBy(this.tableColsCopy, ['displaynumber'], ['asc']);
      this.formItem = this.tableCols.filter((item) => item.isdisplay == 2 || item.isdisplay == 3);
      this.formItem = _.orderBy(this.formItem, ['displaynumber'], ['asc']);
      this.tableDataCopy = _.cloneDeep(this.tableData);
      const datas = _.cloneDeep(this.tableColsCopy);
      // const reqUts = [];
      datas.forEach(async (item) => {
        if (item.needGroup) {
          this.tableGroups.push(item.columncode);
        }
        if (item.listqueryTemplateID || item.listqueryTemplateID == 0) {
          this.tableArrs.push(item.columncode);
          // const reqUt = this.getSelectData(item.listqueryTemplateID)
          // reqUts.push(reqUt)
          if (!this.tableOptions[item.columncode]) {
            //开始位置beginPosition 结束位置endPosition (区分开始结束位置必须传null)
            if (
              item.columncode == "alarmSceneId"
            ) {
              this.tableOptions[item.columncode] = await this.getSelectData(
                item.listqueryTemplateID,
                this.urlParams,
                true
              );
            } else {
              this.tableOptions[item.columncode] = await this.getSelectData(
                item.listqueryTemplateID
              );
            }
            this.tabledatacopy[item.columncode] = _.cloneDeep(
              this.tableOptions[item.columncode]
            );
          }
        }
      });
      const dats = this.setTableFilters(this.tableData, this.tableDataFilters)
      this.tableDataFilters = _.cloneDeep(dats)
      // this.selectTableRows(this.tableData, "DeployID");
      this.tableGroup(this.tableData)
      // this.getSelectDataAll(reqUts)
    },
    setTableFilters (tableData, filters) {
      const tempSets = {}
      Object.keys(filters).forEach(key => {
        tempSets[key] = new Set()
      })
      tableData.forEach(item => {
        Object.keys(tempSets).forEach(key => {
          ; (item[key] ?? '') !== '' && tempSets[key].add(String(item[key]))
        })
      })
      Object.keys(tempSets).forEach(key => {
        filters[key] = _.orderBy(
          [...tempSets[key]].map(value => ({
            text: value,
            value,
          })),
          o => o.value
        )
      })
      return filters
    },
    //获取所有获取弹框-下拉数据-请求状态
    getSelectDataAll (reqUts) {
      Promise.all(reqUts)
        .then((res) => {
          this.proAll = true;
        })
        .catch((err) => {
          this.proAll = false;
        });
    },
    //获取弹框-下拉数据
    async getSelectData (id, name = [], flag = false) {
      // name ? [name] : name === null ? [null]: [],
      const { code, returnData } = await Query({
        serviceId: id,
        dataContent: name,
        event: '0'
      });
      if (code == 0) {
        const datas = [...returnData]
        if (datas && datas.length) {
          const datasObj = datas[0]
          const arrs = []
          if (flag) {
            for (const key in datasObj) {
              const obj = {
                v: datasObj[key],
                k: datasObj[key]
              }
              arrs.push(obj)
            }
          } else {
            for (const key in datasObj) {
              const obj = {
                k: datasObj[key],
                v: key
              }
              arrs.push(obj)
            }
          }
          return arrs
        } else {
          return []
        }
      } else {
        return [];
      }
    },
    //重组table-显示名称
    setTable () {
      this.tableArrs.forEach((item) => {
        this.tableOptions[item].forEach((p) => {
          this.tableDataCopy.forEach((msg) => {
            if (msg[item] == p.v) {
              msg[item] = p.k;
            }
          });
          this.tableDataFilters[item].forEach((cap) => {
            if (cap.value == p.v) {
              cap.text = p.k;
              cap.value = p.k;
            }
          });
        });
      });
      this.tableData = this.tableDataCopy;
    },
    //分组
    tableGroup (tableData) {
      const spanArr = [];
      let pos = 0;
      let ifYj = this.tableGroups[0];
      for (let i = 0; i < tableData.length; i++) {
        if (i === 0) {
          spanArr.push(1);
        } else {
          if (tableData[i][ifYj] === tableData[i - 1][ifYj]) {
            spanArr[pos] += 1;
            spanArr.push(0);
          } else {
            spanArr.push(1);
            pos = i;
          }
        }
      }
      this.spanArr = spanArr;
      this.pos = pos;
    },
    popoverShowHandler (prop) {
      this.colShowFilter = prop;
    },
    popoverHideHandler () {
      this.colShowFilter = "";
    },
    //分组
    tableSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (this.tableGroups.includes(column["property"])) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },
    //合计
    getSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        this.tableColsCopy.forEach((p) => {
          if (column.property == p.columnName && p.needCount) {
            const values = data.map((item) => Number(item[column.property]));
            if (!values.every((value) => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0);
              sums[index] += "";
            }
          }
        });
      });
      return sums;
    },
    //弹框-确定
    handleOk () {
      this.submitClickHandler();
    },
    //滚动
    tableLoad () { },
    //表格-新增
    handleAdd () {
      const { openmode, pageroute } = this.btnAddObj
      if (openmode) {
        if (openmode != 2) {
          this.autoBtnClick(openmode, pageroute)
        } else {
          this.flag = true;
          this.tableType = "add";
          this.tableTitle = "新增";
          this.tableForm = {};
        }
      }
    },
    //表格-编辑
    async handleEdit (row) {
      const { openmode, pageroute } = this.btnEditObj
      if (openmode) {
        if (openmode != 2) {
          this.autoBtnClick(openmode, pageroute)
        } else {
          this.flag = true;
          this.tableType = "edit";
          this.tableTitle = "编辑";
          this.tableForm = _.cloneDeep(row);
        }
      }
    },
    //表格-其他类型按钮操作
    handleOther (row, auth) {
      const { openmode, pageroute } = auth
      if (openmode) {
        if (openmode != 2) {
          this.autoBtnClick(openmode, pageroute)
        } else {
          console.log(row)
        }
      }
    },
    //表格-数据恢复
    async handleRecord (row) {
      const { openmode, pageroute } = this.btnRecordObj
      const params = {
        "serviceId": row.serviceId,
        "dataObjectId": row.dataObjectId
      }
      const { code } = await abnormalDataRecovery(params)
    },

    // 新增/编辑-确认
    submitClickHandler () {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (this.tableType == "add") {
            if (this.$route.path == '/alarmstrategySetting') {
              const newObj = Object.assign(this.tableForm, this.urlParams)
              this.generalDataReception(1, newObj);
            } else {
              this.generalDataReception(1, this.tableForm);
            }
          } else {
            this.generalDataReception(2, this.tableForm, this.tableKey);
          }
        } else {
          return false;
        }
      });
    },
    //表格-删除
    handleRemove (row) {
      const { openmode, pageroute } = this.btnDelObj
      if (openmode) {
        if (openmode != 2) {
          this.autoBtnClick(openmode, pageroute)
        } else {
          this.rmFlag = true;
          this.rmTitle = row[this.rowTitle];
          this.tableObj = row;
        }
      }
    },
    //表格-删除-确认
    tableRemove () {
      this.generalDataReception(3, this.tableObj);
    },

    // 表格-选中行
    selectHandler (selection, row) {
      this.$emit("selection-change", selection, row);
    },
    // 表格-查询模板预览
    handlePreview (row) {
      this.$emit("preview", row);
    },
    //高级查询关闭
    dialogHide () {
      this.dialogFlag = false
    },
    //表格-单元格点击
    cellClick (row, column) {
      const dataBtns = this.authBtnCol
      if (dataBtns && dataBtns.length) {
        const clickBtn = dataBtns.filter(item => item.relation_data == column.property)[0]
        if (clickBtn) {
          const { openmode, pageroute, pass_parameters } = clickBtn
          if (openmode == 2) {
            if (pass_parameters) {
              const query = pass_parameters.split(',')
              const obj = {}
              query.forEach(item => {
                obj[item] = row[item]
              })
              this.$router.push({
                path: pageroute,
                query: obj
              })
            } else {
              this.autoBtnClick(openmode, pageroute)
            }
          }
        }
      }
    },
    //表格-设置单元格样式
    cellClass ({ row, column, rowIndex, columnIndex }) {
      if (this.authBtnColName.includes(column.property)) {
        return 'is-click-btn'
      }
    },
    formatter (row, column, cellValue, index) {
      const sameColumn = this.tableCols.find(col => col.columnName === column.property)
      if (sameColumn && this.fromDataType(sameColumn.dataType) === 'datetime') {
        return (cellValue ?? '').replace('T', ' ')
      }
      return cellValue
    },
    //高级查询
    advancedTable (refName) {
      this.$refs[refName].advancedQueryHandler()
    },
    getAdvancedQueryData (dataRules) {
      console.log(dataRules)
    },
    //收藏
    queryCollect (refName) {
      this.$refs[refName].advancedQueryCollect()
    }
  },
};
</script>

<style lang="scss" scoped>
@import "./css/index.scss";
</style>
