<template>
  <div class="accessPageTable">
    <PublicPageHeader class="accessPageTable_head" :page-title="pageTitle">
      <AuthButton :auth="pageAuthBtnAdd" />
    </PublicPageHeader>
    <div class="accessPageTable_content">
      <PublicPageTable :loading="loading" :table-cols="tableCols" :table-btns="authBtns" :data="tableData" @mounted="tableMountedHandler" @load="load" @handleEdit="handleEdit" @handleOther="handleOther" @handleRemove="handleRemove" />
    </div>
    <div class="accessPageTable_dialog">
      <PublicPageDialog :dialog-title="tableTitle" dialogSize="630px" :dialog-drawer="flag" @handleClose="submitClickClose('ruleForm')" @handleSubmit="submitClickHandler">
        <PublicPageForm ref="ruleForm" :label-width="labelWidth" :form-data="tableForm" />
      </PublicPageDialog>
    </div>
  </div>
</template>

<script>
import PublicPageHeader from '@/components/PublicPageHeader'
import PublicPageDialog from '@/components/PublicPageDialog'
import PublicPageForm from './accessPageForm.vue'
import PublicPageTable from '@/components/SimpleTable'
import AuthButton from '@/components/AuthButton'
import { mapGetters } from 'vuex'
import { Query, newData, modifyData, moveData } from "@/api/webApi"
import { formatChange } from '@/utils/validate'

export default {
  name: 'AccessPageTable',
  components: { PublicPageHeader, PublicPageDialog, PublicPageForm, PublicPageTable, AuthButton },
  props: {
    msgContent: {
      type: Object,
      default: () => new Object()
    }
  },
  data () {
    return {
      pageQuery: {},
      authBtns: [],
      page: 0, //当前table页面
      noMore: false, //当前table是否加载到最后开关
      loading: false, //页面加载
      dialogFlag: false,
      pageTitle: '', //页面名称
      tableCols: [], //表头数据
      tableData: [], //表格数据
      tableBtns: [], //表格按钮权限
      dataContent: {}, //表格查询数据
      pageServiceId: null, //表格serviceid
      formItem: [], //弹框表单渲染数据
      flag: false, //弹框表单开关
      tableType: "add", //弹框表单弹框类型
      tableTitle: "新增", //弹框表单标题
      tableForm: {}, //弹框表单数据
      tableOptions: {}, //表单数据下拉
      labelWidth: '120px', //表单文字距离
      fromDataReqCatch: [], //表单规则缓存
      tableKey: null,//表格主键
      defaultfilter: { 1: 1 }, //默认查询参数
    }
  },
  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]
    },
  },
  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
    },
  },
  mounted () {
    this.pageInit()
  },
  methods: {
    //页面初始化
    pageInit () {
      //获取页面查询参数
      const { query } = this.$route
      this.pageQuery = query
      //获取页面配置
      const { 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 == 'table')
      if (pageAuthtables?.length) this.getPageTableSetting(pageAuths, pageAuthtables)
      //获取按钮权限
      const pageAuthbtns = pageAuthArrs.filter(item => item.pagetype == 'button')
      if (pageAuthbtns?.length) this.getPageBtnSetting(pageAuthbtns)
    },
    //根据页面table设置数据
    getPageTableSetting (pageAuths, pageAuthtables) {
      const authTableObj = pageAuthtables[0]
      //获取当前页面table的配置
      const { pagename, pageconfigurationid, serviceid, pagecode, userpermissionsid, defaultfilter } = 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 = serviceid;
      this.pageTitle = pagename
      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)
    },
    //获取表头数据
    getColumnData (columnArrs = []) {
      const returnData = [...columnArrs]
      this.$store.dispatch('auth/changeAuthMsg', returnData)
      const tableColsCopy = _.cloneDeep(returnData).filter((item) => item.isdisplay == 1 || item.isdisplay == 'true');
      const tableColsCopyOrder = _.orderBy(tableColsCopy, ['displaynumber'], ['asc']);
      // const formItemCopy = _.cloneDeep(returnData).filter((item) => item.isdisplay == 2 || item.isdisplay == 3);
      // this.formItem = _.orderBy(formItemCopy, ['displaynumber'], ['asc']);
      this.tableCols = tableColsCopyOrder
      const columncode = returnData.find(
        (item) => item.isprimarykey == 1
      );
      if (columncode && Object.keys(columncode).length) {
        this.tableKey = columncode['pagecode']
      }
    },
    //格式化传递参数数据
    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)
    },
    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;
      }
    },
    //表单-新增
    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 = {
        serviceid: '',
        preconditions: '',
        algorithmtype: '',
        algorithmname: '',
        algorithmsourcelibraryid: '',
        executionorder: '',
        targetsource: '',
        datasourceid: '',
        computingexpression: '',
        algorithmdescription: ''
      }
    },
    //表格-编辑
    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, passparameters } = this.pageAuthBtnOther
      if (!openmode) return
      if (openmode != 2) this.autoBtnClick(openmode, pageroute, passparameters, row)
    },
    //表格-删除
    handleRemove (row) {
      const { openmode, pageroute } = this.pageAuthBtnDel
      if (!openmode) return
      if (openmode != 2) this.autoBtnClick(openmode, pageroute)
      this.$confirm('确认要删除这条信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.generalDataReception(3, row, this.tableKey)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 新增/编辑-取消
    submitClickClose (formName) {
      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) {
      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.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 = {}
      }
    },
    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 }
      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>
.accessPageTable {
  height: 100%;
  &_content {
    margin-top: 20px;
    height: calc(100% - 60px);
  }
}
</style>