<template>
  <div :style="pageTableHeight" class="TablePage">
    <PublicPageHeader class="TablePage_header" :page-title="dataTitle ? dataTitle : pageTitle">
      <template slot="d_foot">
        <SimpleQuery v-if="simpleQueryFlag" :selectOptions="advancedQueryValue" :simple-query-item="simpleQueryItem" @queryValue="queryValue" />
      </template>
      <template v-if="pageAuthBtnInstall">
        <el-button size="small" type="primary" @click="onInstall">初始化</el-button>
      </template>
      <AuthButton :auth="pageAuthBtnAdd" />
      <AuthButton :auth="pageAuthBtnQuery" />
      <AuthButton :auth="pageAuthBtnExport" />
    </PublicPageHeader>
    <div :style="pageTableContentHeight" class="TablePage_content flex-wrap">
      <template v-if="!dataFlag">
        <div v-if="treeData.length" class="TablePage_content_left">
          <PublicPageTree ref="pageTree" :tree-data="treeData" :dep-math="depMath" :tree-map="treeNodeMap" @treeNodeClick="treeNodeClick" />
        </div>
      </template>
      <div :class="dataFlag ? 'tableAuto' : treeData.length ? 'tableSacle' : 'tableAuto'" class="TablePage_content_right">
        <div class="check_header">
          <el-scrollbar style="height: 100%" :horizontal="false">
            <el-form ref="ruleForm" :model="tableForm" :label-width="labelWidth">
              <el-row :gutter="6">
                <el-col v-for="(item, index) in formItemArr" :key=" index" :span="4" v-show="isShow(item.isdisplay)">
                  <el-form-item :rules="fromDataReq(item)" :prop="item.pagecode" :label="item.pagename">
                    <span slot="label">
                      {{ item.pagename }}
                      <el-tooltip :content="item.pagedescribe" placement="top">
                        <i class="el-icon-question"></i>
                      </el-tooltip>
                    </span>
                    <template v-if="fromDataType(item.datatype) == 'SELECT' || fromDataType(item.datatype) == 'SELECTS'">
                      <el-select class="input-shadow" size="small" :multiple="fromDataType(item.datatype) == 'SELECTS'?true:false" filterable default-first-option style="width: 100%" v-model="tableForm[item.pagecode]" @change="changeSelect(item.pagecode, item)" placeholder="请选择" clearable @clear="tableForm[item.pagecode] = ''">
                        <el-option v-for="itemParams in tableOptions[item.pagecode]" :key="itemParams[item['dropdownlistid']]" :label="itemParams[item['dropdownlistlabel']]" :value="itemParams[item['dropdownlistid']]">
                        </el-option>
                      </el-select>
                    </template>
                    <template v-else-if="fromDataType(item.datatype) == 'DROP'">
                      <el-select class="input-shadow" size="small" multiple filterable default-first-option style="width: 100%" v-model="tableForm[item.pagecode]" @change="changeSelect(item.pagecode, item)" placeholder="请选择" clearable @clear="tableForm[item.pagecode] = ''">
                        <el-option v-for="itemParams in tableOptions[item.pagecode]" :key="itemParams['dropdownlistid']" :label="itemParams['dropdownlistlabel']" :value="itemParams['dropdownlistid']">
                        </el-option>
                      </el-select>
                    </template>
                    <template v-else-if="fromDataType(item.datatype) == 'ICON' || fromDataType(item.datatype) == 'icon'">
                      <el-select size="small" clearable v-model="tableForm[item.pagecode]" placeholder="请选择图标">
                        <el-option v-for="(item,index) in formIcons" :key="index" :label="item.name" :value="item.value">
                          <i style="font-size: 18px;" :class="item.name"></i>
                        </el-option>
                      </el-select>
                    </template>
                    <template v-else-if="fromDataType(item.datatype) == 'TEXT' || fromDataType(item.datatype) == 'VARCHAR'">
                      <el-input size="small" @change="inputChangeHandler(item.pagecode)" v-model="tableForm[item.pagecode]"></el-input>
                    </template>
                    <template v-else-if="fromDataType(item.datatype) == 'TEXTAREA'">
                      <el-input type="textarea" @focus="setText(item.pagecode)" v-model="tableForm[item.pagecode]"></el-input>
                    </template>
                    <template v-else-if="fromDataType(item.datatype) == 'PASSWORD'">
                      <el-input show-password v-model="tableForm[item.pagecode]"></el-input>
                    </template>
                    <template v-else-if="fromDataType(item.datatype) == 'UNPASSWORD'">
                      <el-input show-password v-model="tableForm[item.pagecode]"></el-input>
                    </template>
                    <template v-else-if="fromDataType(item.datatype) == 'UPLOAD'">
                      <upload-item :id="index" :base-img="tableForm[item.pagecode]" ref="upload" />
                    </template>
                    <template v-else-if="fromDataType(item.datatype) == 'SWITCH'">
                      <el-switch v-model="tableForm[item.pagecode]"></el-switch>
                    </template>
                    <template v-else-if="fromDataType(item.datatype) == 'CASCADER'">
                      <el-cascader v-model="tableForm[item.pagecode]" :options="tableOptions[item.pagecode]"></el-cascader>
                    </template>
                    <template v-else-if="fromDataType(item.datatype) == 'CHECKBOX'">
                      <el-checkbox-group v-model="tableForm[item.pagecode]">
                        <el-checkbox v-for="itemParams in tableOptions[item.pagecode]" :key="itemParams[item['dropdownlistid']]" :label="itemParams[item['dropdownlistid']]" name="type">{{ [item['dropdownlistlabel']] }}</el-checkbox>
                      </el-checkbox-group>
                    </template>
                    <template v-else-if="fromDataType(item.datatype) == 'RADIO'">
                      <el-radio-group v-model="tableForm[item.pagecode]">
                        <el-radio v-for="itemParams in tableOptions[item.pagecode]" :key="itemParams[item['dropdownlistid']]" :label="itemParams[item['dropdownlistid']]" name="type">{{ [item['dropdownlistlabel']] }}</el-radio>
                      </el-radio-group>
                    </template>
                    <template v-else-if="fromDataType(item.datatype) == 'TIME'">
                      <el-time-picker size="small" :picker-options="{selectableRange: '00:00:00 - 23:59:59'}" v-model="tableForm[item.pagecode]" placeholder="选择任意时间段" @change="inputChangeHandler(item.pagecode)">
                      </el-time-picker>
                    </template>
                    <template v-else-if="fromDataType(item.datatype) == 'DATE'">
                      <el-date-picker size="small" class="datetimes" value-format="yyyy-MM-dd" v-model="tableForm[item.pagecode]" type="date" placeholder="选择日期" @change="inputChangeHandler(item.pagecode)">
                      </el-date-picker>
                    </template>
                    <template v-else-if="fromDataType(item.datatype) == 'DATETIME'">
                      <el-date-picker size="small" class="datetimes" value-format="yyyy-MM-dd HH:mm:ss" v-model="tableForm[item.pagecode]" type="datetime" placeholder="选择日期时间" @change="inputChangeHandler(item.pagecode)">
                      </el-date-picker>
                    </template>
                    <template v-else-if="fromDataType(item.datatype) == 'INT' || fromDataType(item.datatype) == 'tinyint' || fromDataType(item.datatype) == 'NUMBER'">
                      <el-input size="small" v-model.number="tableForm[item.pagecode]" onkeyup="value=value.replace(/[^1-9]/g,'')" @change="inputChangeHandler(item.pagecode)"></el-input>
                    </template>
                    <template v-else>
                      <el-input size="small" v-model="tableForm[item.pagecode]" @change="inputChangeHandler(item.pagecode)"></el-input>
                    </template>
                  </el-form-item>
                </el-col>
                <el-col :span="4" style="height: 41px;display: flex;align-items: center;">
                  <el-checkbox v-model="checkedtre" label="显示树" @change="handleCheckedCitiesChange"></el-checkbox>
                </el-col>
                <el-col :span="4" style="height: 41px;display: flex;align-items: center;">
                  <el-checkbox v-model="checkedtable" label="显示表格" @change="handleCheckedCitiesChanges"></el-checkbox>
                </el-col>
            </el-row>
          </el-form>
          </el-scrollbar>
        </div>
        <div class="TablePage_child flex-wrap">
          <template v-if="leftFlag">
            <div v-if="treeData.length" class="TablePage_content_left">
              <PublicPageTree ref="pageTree" :tree-data="treeData" :dep-math="depMath" :tree-map="treeNodeMap" @treeNodeClick="treeNodeClick" />
            </div>
          </template>
          <PublicPageTable v-if="tableFlag" ref="table" :loading="loading" :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" @handleDetail="handleDetail" @handleEdit="handleEdit" @handleOther="handleOther" @handleRemove="handleRemove" @handleSelectionChange="handleSelectionChange" />
        </div>
      </div>
    </div>
    <div class="TablePage_dialog">
      <!--新增/编辑-->
      <PublicPageDialog :dialog-body="authId ? true : false " :dialog-loading="dialogLoading" :dialog-title="tableTitle" dialogSize="630px" :form-auth="formAuth" :dialog-drawer="flag" @handleClose="submitClickClose('ruleForm')" @handleSubmit="submitClickHandler">
        <PublicPageForm ref="ruleForm" :label-width="labelWidth" :form-pass="tableData" :form-type="tableType" :form-item="formItem" :form-data="tableForm" />
      </PublicPageDialog>
      <!--高级查询-->
      <PublicPageDialog dialog-title="高级查询" dialogSize="600px" :dialog-drawer="advancedDrawer" @handleClose="advancedClose" @handleSubmit="advancedTable('advancedDialogForm')">
        <AdvancedQuery ref="advancedDialogForm" :selectOptions="simpleQueryValue" @getAdvancedQueryData="getAdvancedQueryData" />
        <template slot="d_foot">
          <el-button size="small" @click="restCollect('advancedDialogForm')" type="warning">重置</el-button>
          <el-button size="small" @click="queryCollect('advancedDialogForm')" type="primary">收藏</el-button>
        </template>
      </PublicPageDialog>
      <!--初始化-->
      <PublicPageDialog dialog-title="初始化" dialogSize="600px" :dialog-drawer="installFlag" @handleClose="installClose" @handleSubmit="installTable('installForm')">
        <AuthInstall ref="installForm" />
      </PublicPageDialog>
    </div>
  </div>
</template>

<script>
import PublicPageHeader from '@/components/PublicPageHeader'
import PublicPageTable from '@/components/SimpleTable'
import PublicPageTree from '@/components/publicPageTree'
import PublicPageDialog from '@/components/PublicPageDialog'
import PublicPageForm from '@/components/publicPageForm'
import AdvancedQuery from '@/components/AdvancedQuery'
import AuthButton from '@/components/AuthButton'
import AuthInstall from '@/components/AuthInstall'
import SimpleQuery from '@/components/SimpleQuery'
import allIcons from '@/utils/icons'
import { mapGetters } from 'vuex'
import { Query, newData, modifyData, moveData, start, stop, startAll, stopAll } from "@/api/webApi"
import { formatChange, listToTree } from '@/utils/validate'
import { exportToExcel } from '@/utils/table'

export default {
  name: 'TablePage',
  components: { PublicPageHeader, PublicPageTable, PublicPageDialog, PublicPageTree, PublicPageForm, AdvancedQuery, AuthButton, SimpleQuery, AuthInstall },
  props: {
    dataTitle: {
      type: String,
      default: ''
    },
    dataFlag: {
      type: Boolean,
      default: false
    },
    msgContent: {
      type: Object,
      default: () => new Object()
    },
    authId: {
      type: Number,
      default: 0
    },
    authQuery: {
      type: Object,
      default: () => new Object()
    },
  },
  data () {
    return {
      page: 0, //当前table页面
      noMore: false, //当前table是否加载到最后开关
      loading: false, //页面加载
      dialogLoading: false, //新增/编辑确认按钮禁用
      advancedDrawer: false, //高级查询弹框开关
      defaultfilter: { 1: 1 }, //默认查询参数
      pageQuery: {},
      installFlag: false,
      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: [], //高级查询缓存值
      formItemArr: [],
      pageSizeDatas: ['outairportpage', 'landairportpage', 'transairportpage'],
      pageInstall: 'creatManagementPage',
      formIcons: allIcons,
      checkedtre: true,
      checkedtable: true,
      leftFlag: true,
      tableFlag:true
    }
  },
  computed: {
    ...mapGetters(['authArrs']),
    pageTableHeight () {
      if (this.dataFlag) return 'height:100%'
      if (this.authId) return 'height:calc(100vh - 180px);padding:0'
      return ''
    },
    pageTableContentHeight () {
      if (this.dataFlag) return 'height:calc(100% - 60px)'
      if (this.authId) return 'height:calc(100% - 130px)'
      return ''
    },
    pageAuthBtnQuery () {
      return this.tableBtns.filter(item => item.servicetype == 0)[0]
    },
    pageAuthBtnDetail () {
      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]
    },
    pageAuthBtnExport () {
      return this.tableBtns.filter(item => item.servicetype == 6)[0]
    },
    pageAuthBtnInstall () {
      return this.pageInstall == this.$route.path.replace('/', '')
    },
    //设置新增修改表单类型
    fromDataType () {
      return function (type) {
        if (type) {
          return type.toLocaleUpperCase().replace(/\([^\)]*\)/g, "");
        }
      }
    },
    //设置新增修改表单必填类型
    fromDataReq () {
      return function (item) {
        const { dropdownlist, datatype, pagename, isrequired, formatrule } = item
        const itemType = datatype ? datatype.replace(/\([^\)]*\)/g, "") : datatype
        const itemReq = isrequired ? true : false
        const itemRule = formatrule ? true : false
        if (dropdownlist || dropdownlist == 0) return [{ required: itemReq, message: `${pagename}不能为空`, trigger: 'change' }]
        else if (itemType == 'date' || itemType == 'datetime') return [{ required: itemReq, type: 'date', message: `${pagename}不能为空`, trigger: 'change' }]
        else
          if (itemReq && itemRule) return [{ required: itemReq, message: `${pagename}不能为空`, trigger: 'blur' }, { pattern: new RegExp(formatrule), message: `请输入合法的${pagename}规则`, trigger: 'blur' }]
        return [{ required: itemReq, message: `${pagename}不能为空`, trigger: 'blur' }]
      }
    },
  },
  watch: {
    msgContent: {
      handler (row) {
        if (row && Object.keys(row).length) {
          const { passparameters } = row
          const filterItem = this.formatDefault(passparameters, row)
          if (!Object.keys(filterItem).length) return
          this.defaultfilter = filterItem
          this.queryTableData(true)
        }
      },
      deep: true,
      immediate: true
    },
    authQuery: {
      handler (row) {
        if (row && Object.keys(row).length) {
          this.defaultfilter = row
          this.queryTableData(true)
        }
      },
      deep: true,
    }
  },
  mounted () {
    this.authId ? this.pageInit(this.authId) : this.pageInit()
    this.queryTableData(true)
  },
  methods: {
    //页面初始化
    pageInit (authId) {
      //获取页面查询参数
      const { query } = this.$route
      authId ? this.pageQuery = this.authQuery : this.pageQuery = query
      //获取页面配置
      const { pagecode, qid, auth_id } = this.$route.meta
      //获取页面权限类型组件  pagetype 1模块  2页面  3按钮 4表格 5树形  6弹窗
      const pageAuths = this.authArrs
      if (!pageAuths.length) return
      let pageAuthArrs = null
      authId ? pageAuthArrs = pageAuths.filter(item => item['superiorid'] == authId) : pageAuthArrs = pageAuths.filter(item => item['superiorid'] == auth_id)
      //获取当前页面权限类型
      if (!pageAuthArrs.length) return
      //获取tree权限
      const pageAuthtrees = pageAuthArrs.filter(item => item.pagetype == 'tree')
      if (pageAuthtrees?.length) this.getPageTreeSetting(pageAuthtrees)
      //获取table权限
      const pageAuthtables = pageAuthArrs.filter(item => item.pagetype == 'table')
      if (pageAuthtables?.length) this.getPageTableSetting(pageAuths, pageAuthtables)
      //获取按钮权限
      const pageAuthbtns = pageAuthArrs.filter(item => item.pagetype == 'button')
      if (pageAuthbtns?.length) this.getPageBtnSetting(pageAuthbtns)
      const pageAuthFforms = pageAuthArrs.filter(item => item.pagetype == 'form')
      //获取form表单弹框权限
      if (pageAuthFforms?.length) this.getPageBtnFormSetting(pageAuths, pageAuthFforms)
      this.tableForm = {}
      for (let k in this.defaultfilter) {
        if (k != 1) {
          this.tableForm[k] = this.defaultfilter[k]
        }
      }
      for (let k in this.formItem) {
        if (this.formItem[k].defaultvalue && this.formItem[k].defaultvalue != "") {
          this.$set(this.tableForm, this.formItem[k].pagecode, this.formItem[k].defaultvalue)
        }
      }
      // this.getSelectData(this.formItem)
    },
    //根据页面tree设置数据
    getPageTreeSetting (pageAuthtrees) {
      const { defaultfilter, dropdownlistid, dropdownlistlabel } = pageAuthtrees[0]
      this.treeNodeMap = { nodeKey: dropdownlistid, nodeValue: dropdownlistlabel }
      this.treeParameters = defaultfilter
      this.treeData = pageAuthtrees
    },
    //根据页面table设置数据
    getPageTableSetting (pageAuths, pageAuthtables) {
      const authTableObj = pageAuthtables[0]
      //获取当前页面table的配置
      const { pagename, pageconfigurationid, serviceid, pagecode, userpermissionsid, defaultfilter, selected, triggerserviceid } = authTableObj
      //获取当前页面table的按钮权限
      const currPageBtns = pageAuths.filter(item => item['superiorid'] == pageconfigurationid && item.pagetype == 'button')
      if (currPageBtns?.length) this.tableBtns.push(...currPageBtns)
      this.authBtns = pageAuths.filter(item => item.superiorid == pageconfigurationid && item.pagetype == 'button')
      this.pageServiceId = Object.keys(this.msgContent).length ? this.msgContent.serviceid : serviceid;
      this.pageTitle = pagename
      this.selected = selected
      this.triggerserviceid = triggerserviceid
      this.defaultfilter = Object.keys(this.pageQuery).length ? this.pageQuery : defaultfilter ? this.formatDefault(defaultfilter, authTableObj) : { 1: 1 }
      const tableColumnArrs = pageAuths.filter(item => item['superiorid'] == pageconfigurationid && item['pagetype'] == 'column')
      this.getColumnData(tableColumnArrs)
    },
    //根据页面按钮设置数据
    getPageBtnSetting (pageAuthbtns) {
      this.tableBtns.push(...pageAuthbtns)
    },
    //根据页面按钮设置表单form数据
    getPageBtnFormSetting (pageAuths, pageAuthForms) {
      const { pageconfigurationid } = [...pageAuthForms][0]
      const tableColumnArrs = pageAuths.filter(item => item['superiorid'] == pageconfigurationid && item['pagetype'] == 'column')
      const formItemCopy = tableColumnArrs.filter((item) => item.isdisplay != 0)
      this.formItem = _.orderBy(formItemCopy, ['displaynumber'], ['asc'])
      console.log(this.formItem)
    },
    //获取表头数据
    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 formItemCopy = _.cloneDeep(returnData).filter((item) => item.isdisplay == 2 || item.isdisplay == 3);
      // this.formItem = _.orderBy(formItemCopy, ['displaynumber'], ['asc']);
      const msgCounts = tableColsCopyOrder.filter(item => item.enablecount)
      const simpleQueryItem = _.cloneDeep(returnData).filter((item) => item.easysearch && item.isfiltercolumn)
      if (msgCounts.length) {
        this.summaryFlag = true
      }
      this.tableCols = listToTree(tableColsCopyOrder, 'groupid', 'pagecode')
      const columncode = returnData.find(
        (item) => item.isprimarykey == 1
      )
      if (columncode && Object.keys(columncode).length) {
        this.tableKey = columncode['pagecode']
      }
      if (simpleQueryItem?.length) {
        this.simpleQueryFlag = true
        this.simpleQueryItem = simpleQueryItem
      }
    },
    //获取tree点击
    treeNodeClick (data) {
      const nrow = _.cloneDeep(data)
      this.selectedDataCheck = nrow
      if (this.selected) {
        this.treeCheckQuery(nrow)
      } else {
        const values = Object.values(data)
        const filterItem = this.formatDefault(this.treeParameters, data)
        if (!Object.keys(filterItem).length) return
        this.defaultfilter = values.includes(-1) || values.includes('全部') ? { 1: 1 } : filterItem
        this.queryTableData(true)
      }
    },
    //存在勾选-点击树-查询
    async treeCheckQuery (data) {
      const values = Object.values(data)
      const filterItem = this.formatDefault(this.treeParameters, data)
      if (!Object.keys(filterItem).length) return
      const itemFilter = values.includes(-1) || values.includes('全部') ? { 1: 1 } : filterItem
      const datacontent = { filter: itemFilter }
      this.loading = true
      this.selectedDataAlls = []
      try {
        const { code, returnData } = await Query({
          page: 1,
          serviceid: this.triggerserviceid,
          datacontent,
          event: '0',
          size: 9999
        });
        if (code == 0) {
          const datas = []
          this.tableData.filter(item => {
            [...returnData].forEach(pt => {
              if (item['serviceid'] == pt['serviceid']) {
                datas.push(item)
              }
            })
          })
          this.selectedDatas = [...datas]
          this.selectedDatasCath = [...returnData]
          this.selectedDataAlls.push([...datas])
        } else {
          this.$message.error("获取表格数据失败")
        }
      } catch (error) {
        this.$message.error("获取表格数据失败")
      }
      this.loading = false
    },
    //格式化传递参数数据
    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
    },
    //根据按钮权限查询表单权限
    findBtntoForm (pageroute) {
      return this.tableBtnForms.filter(item => item.pagecode == pageroute)
    },
    //表单-查看
    handleDetail (row) {
      const { openmode, pageroute } = this.pageAuthBtnDetail
      if (!openmode) return
      if (openmode != 2) this.autoBtnClick(openmode, pageroute)
      this.flag = true
      this.formAuth = false
      this.tableType = "detail"
      this.tableTitle = "查看"
      this.tableForm = _.cloneDeep(row)
    },
    //表单-新增
    async handleAdd () {
      const { openmode, pageroute, pagecode } = this.pageAuthBtnAdd
      if (!openmode) return
      // if (!this.findBtntoForm(pageroute).length) return
      if (openmode != 2) this.autoBtnClick(openmode, pageroute)
      // const { pageconfigurationid } = this.findBtntoForm(pageroute)[0]
      // const pageAuths = this.authArrs
      // const tableColumnArrs = pageAuths.filter(item => item['superiorid'] == pageconfigurationid && item['pagetype'] == 'column')
      // this.dialogName = pageroute
      if (pagecode == 'startBtnAll') {
        if (!Object.keys(this.selectedDataCheck).length) {
          this.$message.error('请选中容器后再操作')
          return
        }
        const { code, message } = await startAll(this.selectedDataCheck)
        if (code == 0) {
          this.$message.success(message || '操作成功')
          this.queryTableData(true)
        } else {
          this.$message.error(message || '操作失败')
        }
      } else {
        if (this.$refs['ruleForm']) {
          this.$nextTick(() => {
            this.$refs['ruleForm'].restForm()
          })
        }
        this.flag = true;
        this.tableType = "add"
        this.tableTitle = "新增"
        this.tableForm = {}
        for (let k in this.defaultfilter) {
          if (k != 1) {
            this.tableForm[k] = this.defaultfilter[k]
          }
        }
        for (let k in this.formItem) {
          if (this.formItem[k].defaultvalue && this.formItem[k].defaultvalue != "") {
            this.$set(this.tableForm, this.formItem[k].pagecode, this.formItem[k].defaultvalue)
          }
        }
      }
      // this.formItem = tableColumnArrs.filter(item => item.isdisplay == 1)
    },
    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
    },
    //表格-编辑
    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 = "编辑"
      const nrow = _.cloneDeep(row)
      if (nrow.passparameters) {
        nrow.passparameters = this.resPassters(row)
      }
      if (nrow.dropdownlist) {
        nrow.dropdownlist = Number(nrow.dropdownlist)
      }
      this.tableForm = nrow
    },
    //表格-其他类型按钮操作
    handleOther (row, auth) {
      const { openmode, pageroute, passparameters } = this.pageAuthBtnOther
      if (!openmode) return
      if (openmode != 2) this.autoBtnClick(openmode, pageroute, passparameters, row)
      const { pagecode } = auth
      if (pagecode == 'stopBtn' || pagecode == 'startBtn') {
        this.stateChange(row)
      }
    },
    //启动 & 停止
    async stateChange (row) {
      const { runstate, serviceid, containercode } = row
      const filter = { serviceid, containercode }
      if (runstate == 1) {
        const { code, returnData } = await stop(filter)
        if (code == 0) {
          this.$message.success(returnData || '操作成功')
          this.queryTableData(true)
        } else {
          this.$message.error(returnData || '操作失败')
        }
      } else {
        const { code, returnData } = await start(filter)
        if (code == 0) {
          this.$message.success(returnData || '操作成功')
          this.queryTableData(true)
        } else {
          this.$message.error(returnData || '操作失败')
        }
      }
    },
    //表格-删除
    handleRemove (row) {
      const { openmode, pageroute } = this.pageAuthBtnDel
      if (!openmode) return
      if (openmode != 2) this.autoBtnClick(openmode, pageroute)
      let name = ''
      const nrow = _.cloneDeep(row)
      for (const key in nrow) {
        if (key.includes('name')) {
          name = nrow[key] || ''
        }
      }
      this.$confirm(`确认要删除 ${name} 这条信息吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.generalDataReception(3, row, this.tableKey)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //表格-勾选
    handleSelectionChange (val) {
      this.selectedDataAlls.push([...val])
      const ndatas = _.cloneDeep(this.selectedDataAlls)
      if (ndatas.length == 1) {
        this.sendCheckData('add', ndatas[0])
      } else {
        const [nitems1, nitems2] = [ndatas.at(-1), ndatas.at(-2)]
        if (nitems1.length > nitems2.length) {
          const res = this.findRepetData(nitems1, nitems2)
          this.sendCheckData('add', res)
        } else {
          const res = this.findRepetData(nitems1, nitems2)
          this.sendCheckData('del', res)
        }
      }
    },
    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
    },
    //发送新增编辑删除数据
    sendCheckData (types, data, key = 'serviceid') {
      const event = types == 'add' ? 1 : types == 'edit' ? 2 : 3
      const querys = []
      const items = _.cloneDeep(data)
      const { serviceid, servicename } = items[0]
      const { containerid, containercode, containername } = this.selectedDataCheck
      const pitem = {
        serviceid,
        servicename,
        containerid,
        containercode,
        containername
      }
      const params = {
        serviceid: this.triggerserviceid,
        datacontent: formatChange(pitem, event, key),
        event,
      }
      if (event == 3) {
        params.datacontent[0].filter.containerid = containerid
        delete params.datacontent[0].value.containerid
      }
      event == 1 ? querys.push(newData(params)) : querys.push(moveData(params))
      this.getAnscyData(querys)
    },
    //获取异步数据
    async getAnscyData (allResult) {
      if (!allResult.length) return
      this.loading = true
      const results = await Promise.allSettled(allResult)
      results.map((item) => {
        const { status, value } = item
        if (status == 'fulfilled') {
          const { code } = value
          if (code == 0) {
            this.treeCheckQuery(this.selectedDataCheck)
            this.$message.success('操作成功')
          } else {
            this.$message.error('操作失败')
          }
        } else {
          this.$message.error('网络错误')
        }
      })
      // this.loading = false
    },
    // 新增/编辑-取消
    submitClickClose (formName) {
      this.formAuth = true
      this.flag = false
      this.$refs[formName].restForm()
    },
    // 新增/编辑-确认
    submitClickHandler () {
      const flag = this.$refs["ruleForm"].submitClickHandler()
      if (flag) this.tableType == "add" ? this.generalDataReception(1, this.tableForm) : this.generalDataReception(2, this.tableForm, this.tableKey)
    },
    //表格-增/删/改
    async generalDataReception (event, data, key) {
      this.dialogLoading = true
      try {
        const params = {
          serviceid: this.pageServiceId,
          datacontent: 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.dialogLoading = false
          this.tableObj = {}
          this.tableForm = {}
          this.resetTable()
          this.load();
          this.depMath = Math.random()
          // this.$router.go(0);
        } else {
          this.$message.error("操作失败");
          this.flag = false
          this.rmFlag = false
          this.dialogLoading = false
          this.tableObj = {};
          this.tableForm = {};
        }
      } catch (error) {
        this.flag = false
        this.rmFlag = false
        this.dialogLoading = false
        this.tableObj = {}
        this.tableForm = {}
      }
    },
    autoBtnClick (id, url, passparameters, row = {}) {
      switch (Number(id)) {
        case 1:
          if (passparameters && Object.keys(row).length) {
            const filterItem = this.formatDefault(passparameters, row)
            this.$router.push({
              path: url,
              query: filterItem
            })
          }
          break;
        case 2:
          this.$router.push(url)
          break;
        default:
          break;
      }
    },
    //高级查询-弹框打开
    async handleQuery () {
      const { openmode, pageroute, pagecode } = this.pageAuthBtnQuery
      if (!openmode) return
      if (pagecode == 'stopBtnAll') {
        if (!Object.keys(this.selectedDataCheck).length) {
          this.$message.error('请选中容器后再操作')
          return
        }
        const { code, message } = await stopAll(this.selectedDataCheck)
        if (code == 0) {
          this.$message.success(message || '操作成功')
          this.queryTableData(true)
        } else {
          this.$message.error(message || '操作失败')
        }
      } else {
        if (openmode != 3) this.advancedDrawer = true // this.autoBtnClick(openmode, pageroute)
      }
    },
    //简易查询-确定
    queryValue (dataRules) {
      const arr = [...dataRules]
      if (arr && arr.length) {
        arr.forEach(item => {
          item.value = typeof item.value == 'string' ? item.value.replace(/\s*/g, "") : item.value
        })
      }
      this.defaultfilter = arr.length ? arr : { 1: 1 }
      this.simpleQueryValue = arr
      this.queryTableData(true)
    },
    //高级查询-确定
    advancedTable (refName) {
      this.$refs[refName].advancedQueryHandler()
    },
    //高级查询-取消
    advancedClose () {
      this.advancedDrawer = false
      // this.defaultfilter = { 1: 1 }
      // this.queryTableData(true)
    },
    //初始化
    onInstall () {
      if (!Object.keys(this.selectedDataCheck).length) {
        this.$message.error('请选中权限后再操作')
        return
      }
      const { pagetype } = this.selectedDataCheck
      if (pagetype != 'table') {
        this.$message.error('请选择表格后再操作')
        return
      }
      this.installFlag = true
    },
    //初始化-关闭
    installClose () {
      this.installFlag = false
    },
    //初始化-确定
    installTable () {
      this.installSubmit()
      this.installFlag = false
    },
    async installSubmit () {
      const { pageconfigurationid } = this.selectedDataCheck
      const { code, returnData } = await Query({
        serviceid: 134,
        datacontent: {
          tableName: this.$refs['installForm'].tableinfo,
          datasourceid: this.$refs['installForm'].datasourceid,
          pageconfigurationid
        },
        deletedatacontent: {
          datacontent: [
            {
              filter: {
                superiorid: pageconfigurationid
              },
              value: {}
            }
          ],
          event: '3'
        },
        event: '0'
      })
      if (code == 0 && returnData?.length) {
        this.$message.success('数据初始化成功')
        this.$refs['pageTree'].pageInit()
        this.queryTableData(true)
        this.$refs['installForm'].tableinfo = ''
        this.$refs['installForm'].datasourceid = ''
      }
    },
    //高级查询-确定-数据
    getAdvancedQueryData (dataRules) {
      const arr = [...dataRules]
      if (arr && arr.length) {
        arr.forEach(item => {
          item.value = typeof item.value == 'string' ? item.value.replace(/\s*/g, "") : item.value
        })
      }
      this.defaultfilter = arr
      this.advancedQueryValue = arr
      this.queryTableData(true)
    },
    //高级查询-收藏
    queryCollect (refName) {
      this.$refs[refName].advancedQueryCollect()
    },
    //高级查询-重置
    restCollect (refName) {
      this.defaultfilter = { 1: 1 }
      this.queryTableData(true)
      this.$refs[refName].advancedRestCollect()
    },
    // 给表头单元格加上 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)
        }
      }
    },
    //导出
    handleExport () {
      if (!this.tableData.length) {
        this.$message.info('无数据')
        return
      }
      const table = this.$refs['table'].$el.cloneNode(true)
      const fileName = this.pageTitle + '.xlsx'
      exportToExcel(table, this.pageTitle, fileName)
    },
    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 (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 || this.pageSizeDatas.includes(this.$route.path.replace('/', ''))) {
        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.formItemArr = this.tableData
        } else {
          this.page--
          this.noMore = true
          this.$message.error("获取表格数据失败")
        }
      } catch (error) {
        this.page--
        this.noMore = true
      }
      if (this.selected || this.pageSizeDatas.includes(this.$route.path.replace('/', ''))) {
        this.noMore = true
      }
      this.loading = false
    },
    //获取表单下拉数据
    getSelectData (formItem = []) {
      if (!formItem.length || !Array.isArray(formItem)) return
      const formItemCopy = _.cloneDeep(formItem)
      const [allResult, allResultKey, allResultList] = [[], [], []]
      formItemCopy.map(({ dropdownlist, pagecode, defaultparameters }) => {
        if (((dropdownlist || dropdownlist == 0) && dropdownlist != "")) {
          const datacontent = defaultparameters ? { filter: this.formatDefault(defaultparameters) } : { filter: { 1: 1 } }
          const params = {
            dropdownlist,
            pagecode,
            datacontent
          }
          allResultList.push(params)
        }
      })
      if (allResultList?.length) {
        this.reduceHttp(allResultList, formItemCopy)
      } else {
        this.formItemArr = formItemCopy
      }
    },
    //格式化传递参数数据
    formatDefault (item) {
      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] = val
      })
      return filterItem
    },
    //去除重复请求
    reduceHttp (arr = [], formItem = []) {
      const datas = _.cloneDeep(arr)
      const dataMap = new Map()
      const [columnArrs1, columnArrs2, allResult, allResultKey] = [[], [], [], []]
      if (!datas.length) return
      datas.map(item => {
        const { datacontent, dropdownlist } = item
        const nameter = Object.entries(datacontent.filter)[0]
        const namekey = dropdownlist + nameter[0] + nameter[1]
        if (!dataMap.get(namekey)) {
          dataMap.set(namekey, item)
          columnArrs1.push(item)
        } else {
          columnArrs2.push(item)
        }
      })
      columnArrs1.map(({ dropdownlist, pagecode, datacontent }) => {
        allResultKey.push(pagecode)
        allResult.push(Query({ serviceid: dropdownlist, datacontent, event: '0', page: 1, size: 9999 }))
      })
      this.getAnscyData(allResultKey, allResult, _.cloneDeep(formItem), _.cloneDeep(columnArrs1), _.cloneDeep(columnArrs2))
    },
      //获取异步数据
    async getAnscyData (allResultKey = [], allResult = [], formItem = [], columnArrs1 = [], columnArrs2 = []) {
      this.loading = true
      if (allResult.length && allResultKey.length) {
        const results = await Promise.allSettled(allResult)
        const resultDatas = []
        results.map((item, index) => {
          const { status, value } = item
          if (status == 'fulfilled') {
            const { code, returnData } = value
            const nitem = {
              pagecode: allResultKey[index],
              dropdownlist: columnArrs1[index].dropdownlist,
              returnData
            }
            resultDatas.push(nitem)
            this.tableOptions[allResultKey[index]] = code == 0 && returnData?.length ? this.formatData(returnData) : []
          }
        })
        if (resultDatas?.length) this.serRepets(_.cloneDeep(resultDatas), columnArrs1, columnArrs2)
        this.formItemArr = formItem
      } else {
        this.formItemArr = formItem
      }
      this.setPassters(this.formPass)
      this.loading = false
    },
    //设置重复下拉数据
    serRepets (resultDatas = [], columnArrs1, columnArrs2) {
      resultDatas.map(item => {
        columnArrs1.map(ci => {
          if (item.pagecode == ci.pagecode) {
            item.datacontent = ci.datacontent
          }
        })
      })
      const result = [...resultDatas]
      result.map(item => {
        const { datacontent, dropdownlist, returnData } = item
        const nameterItem = Object.entries(datacontent.filter)[0]
        const namekeyItem = dropdownlist + nameterItem[0] + nameterItem[1]
        columnArrs2.map(ci => {
          const { datacontent, dropdownlist, pagecode } = ci
          const nameterCi = Object.entries(datacontent.filter)[0]
          const namekeyCi = dropdownlist + nameterCi[0] + nameterCi[1]
          if (namekeyItem == namekeyCi) {
            this.tableOptions[pagecode] = _.cloneDeep(returnData)
          }
        })
      })
    },
    //设置下拉数据
    setPassters (array = []) {
      const passitem = this.formItemArr.filter(item => item.pagecode == 'passparameters')
      if (passitem?.length) {
        const ndata = _.cloneDeep(array)
        const passitemkey = passitem[0]
        passitemkey.datatype = 'DROP'
        ndata.map(item => {
          item.dropdownlistid = item.pageconfigurationid
          item.dropdownlistlabel = item.pagename
        })
        this.tableOptions['passparameters'] = ndata
        this.formPassCopy = ndata
      }
    },
    isShow (isdisplay) {
      let show = false
      if (eval(isdisplay)) {
        show = true
      }
      else {
        show = false
      }
      return show
    },
    handleCheckedCitiesChange (value) {
      this.leftFlag = value
    },
    handleCheckedCitiesChanges (value) {
      this.tableFlag = value
    }
  },
}
</script>

<style lang="scss" scoped>
.TablePage {
  height: calc(100vh - 90px);
  padding: 20px;
  &_content {
    margin-top: 20px;
    height: calc(100vh - 190px);
    &_left {
      width: 360px;
      margin-right: 20px;
    }
    &_right {
      height: calc(100% - 100px);
    }
    .tableAuto {
      width: 100%;
    }
    .tableSacle {
      width: calc(100% - 380px);
    }

    .check_header{
      width: 100%;
      height:100px;
      overflow: hidden;
    }
    .TablePage{
      &_child {
        height:100%;
        &_left {
          width: 360px;
          margin-right: 20px;
        }
      }
    }
  }
}
</style>
