<template>
  <div class="TablePage">
    <PublicPageTable ref="table" :loading="loading" :fast-filter="fastFilter" :selected="selected" :table-cols="tableCols" :table-btns="authBtns" :data="tableData" :header-cell-class-name="headerCellClass" :row-class-name="rowClass" :cell-class-name="cellClass" :formatter="tableFormatter" :selectedDatas="selectedDatas" :selectedCheck="selectedDataCheck" :show-summary="summaryFlag" @mounted="tableMountedHandler" @load="load" @cell-click="cellClickHandler" />
  </div>
</template>

<script>
import PublicPageTable from '@/components/SimpleTable'
import { Query } from "@/api/webApi"
import { listToTree } from '@/utils/validate'
export default {
  name: 'TablePage',
  components: { PublicPageTable },
  props: {
    msgContent: {
      type: Array,
      default: () => new Array()
    },
    fastFilter: {
      type: Function,
      default: () => () => true
    },
  },
  data () {
    return {
      page: 0, //当前table页面
      noMore: false, //当前table是否加载到最后开关
      loading: false, //页面加载
      dialogLoading: false, //新增/编辑确认按钮禁用
      advancedDrawer: false, //高级查询弹框开关
      defaultfilter: { 1: 1 }, //默认查询参数
      pageQuery: {},
      dialogFlag: false,
      dialogName: '', //弹框名称
      pageTitle: '', //页面名称
      treeData: [], //tree数据
      treeParameters: {}, //tree传递参数
      treeNodeMap: {}, //tree传递map
      tableCols: [], //表头数据
      tableData: [], //表格数据
      tableBtns: [], //表格按钮权限
      authBtns: [], //表格里面的操作按钮
      tableBtnForms: [], //表格按钮下的form表单权限
      dataContent: {}, //表格查询数据
      pageServiceId: null, //表格serviceid
      formItem: [], //弹框表单渲染数据
      flag: false, //弹框表单开关
      formAuth: true, //弹框表单按钮开关
      tableType: "add", //弹框表单弹框类型
      tableTitle: "新增", //弹框表单标题
      tableForm: {}, //弹框表单数据
      rmFlag: false, //删除弹框开关
      rmTitle: '', //删除弹框标题
      tableObj: {}, //删除数据
      tableOptions: {}, //表单数据下拉
      labelWidth: '120px', //表单文字距离
      fromDataReqCatch: [], //表单规则缓存
      tableKey: null,//表格主键
      depMath: 0,
      selected: 0, //是否勾选
      selectedDatas: [], //回显勾选的数据
      selectedDatasCath: [],//回显数据缓存
      selectedDataAlls: [], //勾选数据
      selectedDataCheck: {}, //勾选树-选中
      triggerserviceid: null, //勾选后查询的serviceid
      summaryFlag: false, //是否显示合计行
      simpleQueryFlag: false, //是否开启了简易查询
      simpleQueryItem: [], //简易查询表单数据项
      simpleQueryValue: [], //简易查询缓存值
      advancedQueryValue: [], //高级查询缓存值
    }
  },
  watch: {
    msgContent: {
      handler (val) {
        if (val?.length) {
          this.getPageTableSetting(val)
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    //页面初始化
    pageInit () {
      if (this.msgContent?.length) this.getPageTableSetting(this.msgContent)
    },
    //根据页面table设置数据
    getPageTableSetting (pageAuthtables) {
      const pageAuths = this.$store.state.auth.authArrs ?? []
      const authTableObj = pageAuthtables[0]
      //获取当前页面table的配置
      const { pagename, pageconfigurationid, serviceid, pagecode, userpermissionsid, nfilter, selected, triggerserviceid } = authTableObj
      this.pageServiceId = serviceid
      this.pageTitle = pagename
      this.selected = selected
      this.triggerserviceid = triggerserviceid
      this.defaultfilter = nfilter
      const tableColumnArrs = pageAuths.filter(item => item['superiorid'] == pageconfigurationid && item['pagetype'] == 'column')
      this.getColumnData(tableColumnArrs)
    },
    //获取表头数据
    getColumnData (columnArrs = []) {
      const returnData = [...columnArrs]
      this.$store.dispatch('auth/changeAuthMsg', returnData)
      const tableColsCopy = _.cloneDeep(returnData).filter((item) => item.isdisplay != 0)
      const tableColsCopyOrder = _.orderBy(tableColsCopy, ['displaynumber'], ['asc'])
      const msgCounts = tableColsCopyOrder.filter(item => item.enablecount)
      this.tableCols = listToTree(tableColsCopyOrder, 'groupid', 'pagecode')
      if (msgCounts.length) {
        this.summaryFlag = true
      }
      const columncode = returnData.find(
        (item) => item.isprimarykey == 1
      )
      if (columncode && Object.keys(columncode).length) {
        this.tableKey = columncode['pagecode']
      }
      this.queryTableData(true)
    },
    //格式化传递参数数据
    formatDefault (item, data = {}) {
      if (typeof item != 'string') return {}
      const filterItem = {}
      const parameters = item.replace('{', '').replace('}', '')
      const parametersSplit = parameters?.split(',')
      parametersSplit.map(item => {
        const [key, val] = item?.split(':')
        filterItem[key] = data[val]
      })
      return filterItem
    },
    formatData (returnData) {
      return typeof returnData == 'string' ? this.retParse(returnData) : returnData
    },
    retParse (returnData) {
      try {
        return JSON.parse(returnData) ? JSON.parse(returnData) : returnData
      } catch (error) {
        return returnData
      }
    },
    //回显下拉数据
    resPassters (obj) {
      const narr = []
      const nitem = _.cloneDeep(obj)
      const { passparameters } = nitem
      if (!passparameters) return ''
      const ndata = this.formatData(passparameters)
      if (!Array.isArray(ndata)) return ''
      ndata.map(({ pageconfigurationid }) => { narr.push(pageconfigurationid) })
      return narr
    },
    findRepetData (nitems1, nitems2) {
      const key = 'serviceid'
      const res = [...nitems1, ...nitems2].filter(
        (item) =>
          !(
            nitems1.some((p) => item[key] == p[key]) &&
            nitems2.some((c) => item[key] == c[key])
          )
      )
      return res
    },
    // 给表头单元格加上 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 = []
        const { property } = column
        const ndata = _.cloneDeep(this.tableCols).filter(item => item.pagecode == property)
        if (ndata?.length) {
          const { pageroute } = ndata[0]
          if (pageroute) classes.push('cell-click')
        }
        return classes.join(' ')
      }
    },
    formatPass (pass = []) {
      if (typeof pass != 'string') return {}
      const ndata = JSON.parse(pass)
      if (!ndata) return {}
      const nitem = {}
      ndata.map(item => {
        const ns = Object.values(item)
        nitem[ns[0]] = ns[1]
      })
      return nitem
    },
    //添加-表格-单元格-点击事件
    cellClickHandler (row, column, cell, event) {
      const { property } = column
      const ndata = _.cloneDeep(this.tableCols).filter(item => item.pagecode == property)
      const params = {}
      if (ndata?.length) {
        const { defaultfilter, pageroute, passparameters } = ndata[0]
        if (!pageroute) return
        if (defaultfilter || passparameters) {
          if (passparameters) {
            // const nitem = this.formatPass(passparameters)
            const passparametersArray = JSON.parse(passparameters)
            passparametersArray.map(item => {
              if (row[item.pagecode]) {
                const alias = item.alias
                const pagecode = item.pagecode
                if (alias) {
                  params[alias] = row[item['pagecode']]
                }
                else {
                  params[pagecode] = row[item['pagecode']]
                }
              }
            })
            this.$router.push({
              path: pageroute,
              query: params
            })
            return
          }
          if (defaultfilter) {
            const filterItem = this.formatDefault(defaultfilter, row)
            this.$router.push({
              path: pageroute,
              query: filterItem
            })
            return
          }
        }
        else {
          this.$router.push(pageroute)
        }
      }
    },
    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.pageServiceId) {
        if (this.noMore || this.loading) {
          return
        }
        this.queryTableData()
      }
    },
    async queryTableData (jumpSing = false) {
      if (jumpSing) {
        const initialize = _.once(this.resetTable)
        initialize()
      }
      this.loading = true;
      const datacontent = { filter: this.defaultfilter }
      const parmas = {
        page: ++this.page,
        serviceid: this.pageServiceId,
        datacontent,
        event: '0'
      }
      if (this.selected) {
        parmas.size = 9999
      }
      try {
        const { code, returnData } = await Query(parmas)
        if (code == 0) {
          if (returnData.length === 0) {
            this.page--
            this.noMore = true
          }
          this.tableData.push(...returnData)
          this.$emit('tableLoad', [...this.tableData])
        } else {
          this.page--
          this.noMore = true
          this.$message.error("获取表格数据失败")
        }
      } catch (error) {
        this.page--
        this.noMore = true
      }
      if (this.selected) {
        this.noMore = true
      }
      this.loading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.TablePage {
  width: 100%;
  height: 100%;
}
</style>
