<template>
  <zj-page-template ref="zjpage" style="width: 100%;height: 100%;" :get-table-data="getTableData" :options-evens="evens"
    :options-evens-group="selBtn(optionsEvensGroup)"
    :table-attributes="{ ...defaultTableAttributes, ...tableAttributes }"
    :table-events="{ ...defaultTableEvents, ...tableEvents }" :column-parsing="columnParsing" :reduction="reduction"
    :plan="[...plan, ...morePlan]" :operation="operation" :operation-column-width="operationColumnWidth"
    :show-table="showTable" :code-gather="codeGather" @columnWidthChange="columnWidthChange"
    @columnListChange="columnListChange">
    <sel-export-column-list :column-list="columnList" @determine="exportDetermine" @cancel="columnList = []" />
    <slot />
  </zj-page-template>
</template>

<script>

import { zfireSave, zfireDel, commonDict } from "@/api/user";
import SelExportColumnList from './sel-export-column-list'

export default {
  components: {
    SelExportColumnList
  },
  props: {
    // 事件组合
    optionsEvensGroup: {
      type: Array,
      default: () => []
    },
    // 表格属性
    tableAttributes: {
      type: Object,
      default: () => ({})
    },
    // 表格事件
    tableEvents: {
      type: Object,
      default: () => ({})
    },
    // 表格列解析渲染数据更改
    columnParsing: {
      type: Function
    },
    // 获取列表的方法
    getList: {
      type: Function
    },
    // 导出的方法
    exportList: {
      type: Function
    },
    morePlan: {
      type: Array,
      default: () => []
    },
    operation: {
      type: Function
    },
    operationColumnWidth: {
      type: Number,
      default: 140
    }
  },
  data() {
    return {
      // 菜单id
      moduleId: this.$route.meta.moduleId,
      // 菜单名
      moduleName: this.$route.meta.title,
      // 搜索的参数
      parameter: {},
      plan: [
        {
          name: '默认方案',
          paramCallback: () => {
            return []
          }
        }
      ],
      // 按钮集合
      evens: [],
      // 表格属性
      defaultTableAttributes: {},
      // 表格事件
      defaultTableEvents: {},
      // 记录初始的id
      columnsIds: {},
      // 导出弹窗
      columnList: [],
      showTable: false,
      codeGather: {}
    }
  },
  computed: {
    userid() {
      return this.$store.getters.userid
    }
  },
  mounted() {
    if (this.exportList) {
      this.evens = [
        [
          {
            name: '导出',
            click: this.export,
            loading: false
          }
        ]
      ]
    }

  },

  methods: {
    getDictCode(params) {
    
      commonDict(params).then(res => {
        if (res.data.length) {
          res.data.map(item => {
            if (!this.codeGather[params.code]) {
              this.$set(this.codeGather,params.code,[])
            }
            this.$set(this.codeGather,params.code,[...this.codeGather[params.code],{
              label: item.dictValue,
              value: item.dictCode
            }])
          })
        }
      })
    },
    selBtn(arr) {
      for (var i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
          this.selBtn(arr[i])
        }
        if (
          !(arr[i].isRole || arr[i].isRole === undefined) ||
          arr[i].length == 0
        ) {
          arr.splice(i, 1)
          i--
        }
      }
      return arr
    },
    // 获取列表数据函数
    async getTableData(data) {
      if (!this.getList) {
        return
      }
      try {
        this.parameter = {
          pageNum: data.page,
          pageSize: data.size,
          orderBy: data.orderBy,
          params: data.querylist,
          moduleId: this.moduleId
        }
        var res = await this.getList(this.parameter)
        // res.data.records = []
        if (res.code == 200) {
          if (!this.showTable) {
            this.$nextTick(() => {
              this.showTable = true
            })
          }
          res.fieldBeans.forEach(k => {
            if (k.frontCode) {
              this.getDictCode({ code: k.frontCode })
            }
          });

          return res
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 监听列表显示状态与排序变化
    columnListChange(columnList) {
      zfireSave(
        this.$refs.zjpage.columnList.map((item, index) => {
          var data = {
            ...item.exportField,
            sortNum: index,
            isCopy: item.isCopy,
            isTotal: item.isTotal,
            isShow: !item.hidden,
            moduleId: this.moduleId,
            adminUserId: this.userid
          }
          return data
        }),
        this.moduleId
      )
        .then(res => {
        })
        .catch(err => {
          this.$message.error('保存失败')
        })
    },
    // 监听列宽度变化
    columnWidthChange({ newWidth, oldWidth, column }) {
      zfireSave(
        this.$refs.zjpage.columnList.map((item, index) => {
          if (item.exportField.jname === column.property) {
            item.exportField.width = newWidth
          }
          return {
            ...item.exportField,
            sortNum: index,
            isCopy: item.isCopy,
            isTotal: item.isTotal,
            isShow: !item.hidden,
            moduleId: this.moduleId,
            adminUserId: this.userid
          }
        }),
        this.moduleId
      )
        .then(res => {
        })
        .catch(err => {
          this.$message.error('保存失败')
        })
    },
    // 表格恢复初始默认状态
    reduction() {
      zfireDel({}, this.userid, this.moduleId)
        .then(res => {
          this.$refs.zjpage.refresh()
        })
        .catch(err => {
          this.$message.error('操作失败')
        })
    },
    // 导出
    export() {
      this.columnList = this.$refs.zjpage.columnList
    },
    exportDetermine(data) {
      if (!this.exportList) {
        return
      }
      this.evens[0][0].loading = true
      this.exportList(
        {
          ...this.parameter,
          pageSize: -1,
          exportFields: data
        },
        `${this.moduleName}.xlsx`
      )
        .then(res => {
          this.$message({
            message: '导出成功',
            type: 'success'
          })
          this.columnList = []
          this.evens[0][0].loading = false
        })
        .catch(() => {
          this.$message.error('导出失败')
          this.columnList = []
          this.evens[0][0].loading = false
        })
    },
    refreshList() {
      this.$refs.zjpage.refresh()
    }
  }
}
</script>

<style lang="scss" scoped>
@font-face {
  font-family: "aliyun_iconfont";
  src: url("//at.alicdn.com/t/font_2075393_0cjq4n8ykvds.woff2?t=1647587689181") format("woff2"),
    url("//at.alicdn.com/t/font_2075393_0cjq4n8ykvds.woff?t=1647587689181") format("woff"),
    url("//at.alicdn.com/t/font_2075393_0cjq4n8ykvds.ttf?t=1647587689181") format("truetype");
}

::v-deep .el-table__cell {
  padding: 0 !important;
}

::v-deep .el-table__column-filter-trigger {
  .el-icon-arrow-down {
    font-family: aliyun_iconfont !important;
    font-size: 13px;
    line-height: 34px;
    font-style: normal;
    font-weight: 400;
    font-variant: normal;
    text-transform: none;
    vertical-align: baseline;
    display: inline-block;
    -webkit-font-smoothing: antialiased;
    transform: translate(-2px, 1px);
    color: #c0c4cc;
  }

  .el-icon-arrow-down:before {
    content: "\e64c" !important;
  }
}

::v-deep .zj-buttons-group {
  .el-upload-list {
    display: none !important;
  }
}

::v-deep .operation-btns {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;

  &>*:not(:last-child) {
    margin-right: 5px;
  }

  .el-button {
    margin-left: 0 !important;
  }
}

::v-deep .is-disabled {

  .el-textarea__inner,
  .el-input__inner {
    background-color: #fff;
    color: #606266;
  }
}
</style>
