<template>
  <div class="TablePage">
    <PublicPageHeader class="TablePage_header" :page-title="pageTitle">
      <AuthButton :auth="pageAuthBtnAdd" />
      <AuthButton :auth="pageAuthBtnQuery" />
    </PublicPageHeader>
    <div class="TablePage_content">
      <PublicPageTable :loading="loading" :table-cols="tableCols" :table-btns="authBtns" :data="tableData" :header-cell-class-name="headerCellClass" :row-class-name="rowClass" :cell-class-name="cellClass" :formatter="tableFormatter" show-summary @mounted="tableMountedHandler" @load="load" @cell-click="cellClickHandler" @handleEdit="handleEdit" @handleOther="handleOther" @handleRemove="handleRemove" />
    </div>
    <div class="TablePage_dialog">
      <!--新增/编辑-->
      <PublicPageDialog :dialog-title="tableTitle" dialogSize="630px" :dialog-drawer="flag" @handleClose="submitClickClose('ruleForm')" @handleSubmit="submitClickHandler">
        <el-form ref="ruleForm" :model="tableForm" :label-width="labelWidth">
          <el-row :gutter="20">
            <el-col v-for="(item, index) in formItem" :key="index" :span="24">
              <el-form-item :rules="fromDataReq(item)" :prop="item.columncode" :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" @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>
      </PublicPageDialog>
      <!--删除-->
      <PublicPageDialog 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>
      </PublicPageDialog>
      <!--高级查询-->
      <PublicPageDialog 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>
      </PublicPageDialog>
    </div>
  </div>
</template>

<script>
import PublicPageHeader from '@/components/PublicPageHeader'
import PublicPageTable from '@/components/SimpleTable'
import PublicPageDialog from '@/components/PublicPageDialog'
import AdvancedQuery from '@/components/AdvancedQuery'
import AuthButton from '@/components/AuthButton'
import { mapGetters } from 'vuex'
import { Query, newData, modifyData, moveData, abnormalDataRecovery } from "@/api/webApi"

export default {
  name: 'TablePage',
  components: { PublicPageHeader, PublicPageTable, PublicPageDialog, AdvancedQuery, AuthButton },
  data () {
    return {
      page: 0, //当前table页面
      noMore: false, //当前table是否加载到最后开关
      loading: false, //页面加载
      advancedDrawer: false, //高级查询弹框开关
      dialogFlag: false,
      pageTitle: '', //页面名称
      tableCols: [], //表头数据
      tableData: [], //表格数据
      tableBtns: [], //表格按钮权限
      authBtns: [], //表格里面的操作按钮
      dataContent: {}, //表格查询数据
      pageServiceId: null, //表格serviceid
      formItem: null, //弹框表单渲染数据
      flag: false, //弹框表单开关
      tableType: "add", //弹框表单弹框类型
      tableTitle: "新增", //弹框表单标题
      tableForm: {}, //弹框表单数据
      rmFlag: false, //删除弹框开关
      rmTitle: '', //删除弹框标题
      tableObj: {}, //删除数据
      tableOptions: [], //表单数据下拉
      labelWidth: '120px', //表单文字距离
      fromDataReqCatch: [], //表单规则缓存
    }
  },
  computed: {
    ...mapGetters(['authArrs']),
    pageAuthBtnQuery () {
      return this.tableBtns.filter(item => item.servicetype == 1)[0]
    },
    pageAuthBtnAdd () {
      return this.tableBtns.filter(item => item.servicetype == 2)[0]
    },
    pageAuthBtnEdit () {
      return this.tableBtns.filter(item => item.servicetype == 3)[0]
    },
    pageAuthBtnDel () {
      return this.tableBtns.filter(item => item.servicetype == 4)[0]
    },
    pageAuthBtnOther () {
      return this.tableBtns.filter(item => item.servicetype == 5)[0]
    },
    //设置新增修改表单类型
    fromDataType () {
      return function (type) {
        if (type) {
          return type.replace(/\([^\)]*\)/g, "");
        }
      }
    },
    //设置新增修改表单必填类型
    fromDataReq () {
      return function (item) {
        const { dropdownlist, datatype, columnname, isrequired, formatrule } = item
        const itemType = datatype.replace(/\([^\)]*\)/g, "")
        const itemReq = isrequired ? true : false
        const itemRule = formatrule ? true : false
        if (dropdownlist || dropdownlist == 0) return [{ required: itemReq, message: `${columnname}不能为空`, trigger: 'change' }]
        else if (itemType == 'date' || itemType == 'datetime') return [{ required: itemReq, type: 'date', message: `${columnname}不能为空`, trigger: 'change' }]
        else
          if (itemReq && !itemRule) return [{ required: itemReq, message: `${columnname}不能为空`, trigger: 'blur' }]
        return [{ required: itemReq, message: `${columnname}不能为空`, trigger: 'blur' }, { pattern: new RegExp(formatrule), message: `请输入合法的${columnname}规则`, trigger: 'blur' }]

      }
    },
  },
  mounted () {
    this.pageInit()
  },
  methods: {
    //页面初始化
    pageInit () {
      //获取页面配置
      const { pagecode, qid, auth_id } = this.$route.meta
      //获取页面权限类型组件  pagetype 1模块  2页面  3按钮 4表格 5树形  6弹窗
      const pageAuths = this.authArrs
      if (!pageAuths.length) return
      //获取当前页面权限类型
      const pageAuthArrs = pageAuths.filter(item => item['superiorid'] == auth_id)
      if (!pageAuthArrs.length) return
      //获取table权限
      const pageAuthtables = pageAuthArrs.filter(item => item.pagetype == 3)
      if (pageAuthtables?.length) this.getPageTableSetting(pageAuths, pageAuthtables)
      //获取按钮权限
      const pageAuthbtns = pageAuthArrs.filter(item => item.pagetype == 4)
      if (pageAuthbtns?.length) this.getPageBtnSetting(pageAuthbtns)
    },
    //根据页面table设置数据
    getPageTableSetting (pageAuths, pageAuthtables) {
      const authTableObj = pageAuthtables[0]
      //获取当前页面table的配置
      const { pagename, pageconfigurationid, serviceid, pagecode } = authTableObj
      //获取当前页面table的按钮权限
      const currPageBtns = pageAuths.filter(item => item['superiorid'] == pageconfigurationid)
      if (currPageBtns?.length) this.tableBtns.push(...currPageBtns)
      this.authBtns = pageAuths.filter(item => item.superiorid == pageconfigurationid && item.pagetype == 4)
      this.pageServiceId = serviceid;
      this.pageTitle = pagename
      this.getColumnData(pagecode)
    },
    //根据页面按钮设置数据
    getPageBtnSetting (pageAuthbtns) {
      this.tableBtns.push(...pageAuthbtns)
    },
    //获取表头数据
    async getColumnData (pagecode) {
      try {
        const { code, returnData } = await Query({
          serviceid: '3',
          datacontent: { filter: { pagecode } },
          event: "0"
        });
        if (code == 0) {
          if (returnData?.length) {
            this.$store.dispatch('auth/changeAuthMsg', returnData)
            const tableColsCopy = _.cloneDeep(returnData).filter((item) => item.isdisplay == 2);
            const tableColsCopyOrder = _.orderBy(tableColsCopy, ['displaynumber'], ['asc']);
            this.formItem = _.cloneDeep(returnData).filter((item) => item.isdisplay == 2 || item.isdisplay == 3);
            this.formItem = _.orderBy(this.formItem, ['displaynumber'], ['asc']);
            this.tableCols = tableColsCopyOrder;
          }
        } else {
          this.$message.error("获取表头数据失败");
        }
      } catch (error) {
        console.log(error)
      }
    },
    //获取表单下拉数据
    changeSelect (code, item) { },
    inputChangeHandler (data) {
      if (!this.tableForm[data]) this.tableForm[data] = null
    },
    //表单-新增
    handleAdd () {
      const { openmode, pageroute } = this.pageAuthBtnAdd
      if (!openmode) return
      if (openmode != 2) this.autoBtnClick(openmode, pageroute)
      this.flag = true;
      this.tableType = "add";
      this.tableTitle = "新增";
      this.tableForm = {};
    },
    //表格-编辑
    handleEdit (row) {
      const { openmode, pageroute } = this.pageAuthBtnEdit
      if (!openmode) return
      if (openmode != 2) this.autoBtnClick(openmode, pageroute)
      this.flag = true;
      this.tableType = "edit";
      this.tableTitle = "编辑";
      this.tableForm = _.cloneDeep(row);
    },
    //表格-其他类型按钮操作
    handleOther (row, auth) {
      const { openmode, pageroute } = this.pageAuthBtnOther
      if (!openmode) return
      if (openmode != 2) this.autoBtnClick(openmode, pageroute)
    },
    //表格-删除
    handleRemove (row) {
      const { openmode, pageroute } = this.pageAuthBtnDel
      if (!openmode) return
      if (openmode != 2) this.autoBtnClick(openmode, pageroute)
      this.rmFlag = true;
      this.rmTitle = row[this.rowTitle];
      this.tableObj = row;
    },
    //表格-删除-确认
    tableRemove () {
      this.generalDataReception(3, this.tableObj);
    },
    // 新增/编辑-取消
    submitClickClose (formName) {
      this.flag = false
      this.$refs[formName].resetFields()
    },
    // 新增/编辑-确认
    submitClickHandler () {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.tableType == "add" ? this.generalDataReception(1, this.tableForm) : this.generalDataReception(2, this.tableForm)
        } else {
          return 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))
              }
              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.pageServiceId,
          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 = {};
      }
    },
    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.pageAuthBtnQuery
      if (!openmode) return
      if (openmode != 3) this.advancedDrawer = true // this.autoBtnClick(openmode, pageroute)
      this.dialogFlag = true
    },
    //高级查询-确定
    advancedTable (refName) {
      this.$refs[refName].advancedQueryHandler()
    },
    //高级查询-确定-数据
    getAdvancedQueryData (dataRules) {
      console.log(dataRules)
    },
    //高级查询-收藏
    queryCollect (refName) {
      this.$refs[refName].advancedQueryCollect()
    },
    // 给表头单元格加上 ascending 或 descending 使用 element 自带的排序箭头变色
    headerCellClass () {
      return function ({ row, column, rowIndex, columnIndex }) {
        const classes = []
        const rule = this.tableDataSortRules[column.property]
        if (rule) {
          classes.push(rule)
        }
        return classes.join(' ')
      }
    },
    //添加-表格-行样式
    rowClass () {
      return function ({ row, rowIndex }) {
        const classes = []
        if (row.deleted === 'DEL') {
          classes.push('bgl-deleted')
        }
        return classes.join(' ')
      }
    },
    //添加-表格-单元格样式
    cellClass () {
      return function ({ row, column, rowIndex, columnIndex }) {
        const classes = []
        if (
          [
            'flightNO',
            // 'passengerName',
            'bagSN',
            'U_Device_ID',
            'preFlightNO',
            'transferFlightNO',
          ].includes(column.property) &&
          row[column.property] &&
          row[column.property] !== 'FBULK'
        ) {
          classes.push('cell-click')
          if (
            this.clickedCells.some(
              cell =>
                cell.pageName === 'advance' &&
                Object.entries(cell.row).every(
                  ([key, value]) => row[key] === value
                ) &&
                cell.columnProp === column.property
            )
          ) {
            classes.push('cell-clicked')
          }
        }
        return classes.join(' ')
      }
    },
    //添加-表格-单元格-点击事件
    cellClickHandler (row, column, cell, event) { },
    tableFormatter () {
      return function (row, column, cellValue) {
        switch (column.property) {
          case 'departureTime':
            return (cellValue ?? '').replace('T', ' ')
          case 'deleted':
            return cellValue === 'DEL' ? cellValue : ''
          case 'activated':
            return Number(cellValue) === 1 ? '激活' : '未激活'
          default:
            return cellValue ?? ''
        }
      }
    },
    tableMountedHandler (refName, ref) {
      this.$refs[refName] = ref
    },
    resetTable () {
      this.dataContent = {}
      this.page = 0;
      this.noMore = false;
      this.tableData = [];
    },
    load () {
      if (this.noMore || this.loading) {
        return
      }
      this.queryTableData()
    },
    async queryTableData () {
      this.loading = true;
      const datacontent = { filter: { 1: 1 } }
      try {
        const { code, returnData } = await Query({
          page: ++this.page,
          serviceid: this.pageServiceId,
          datacontent,
          event: '0'
        });
        if (code == 0) {
          if (returnData.length === 0) {
            this.page--;
            this.noMore = true;
          }
          this.tableData.push(...returnData);
        } else {
          this.page--;
          this.$message.error("获取表格数据失败");
        }
      } catch (error) {
        this.page--;
      }
      this.noMore = true;
      this.loading = false;
    }
  }
}
</script>

<style lang="scss" scoped>
.TablePage {
  height: calc(100vh - 80px);
  padding: 20px;
  &_content {
    margin-top: 20px;
    height: calc(100vh - 180px);
  }
}
</style>