<template>
  <div class="template-page-1">
    <zj-page-template
      ref="zjpage"
      :getTableData="getTableData"
      :optionsEvens="evens"
      :optionsEvensGroup="selBtn(optionsEvensGroup)"
      :tableAttributes="{ ...defaultTableAttributes, ...tableAttributes }"
      :tableEvents="{ ...defaultTableEvents, ...tableEvents }"
      :columnParsing="columnParsing"
      :reduction="reduction"
      :plan="[...defaultPlan, ...timePlan, ...paramList, ...morePlan]"
      :operation="operationShow && pk ? caozuojl : operation"
      :operationColumnWidth="(operation ? operationColumnWidth : 0) + (operationShow && pk ? 70 : 0)"
      :showTable="showTable"
      :codeGather="codeGather"
      :loading="loading"
      :lowerLine="true"
      :onSavePlan="onSavePlan"
      :onClosePlain="onClosePlain"
      :defaultSearchData="defaultSearchData"
      :replaceOrNotMap="replaceOrNotMap"
      @columnWidthChange="columnWidthChange"
      @columnListChange="columnListChange"
    >
      <template slot="more-search">
        <slot name="moreSearch"></slot>
      </template>
    </zj-page-template>
    <sel-export-column-list :columnList="columnList" @determine="exportDetermine" @cancel="columnList = []" />
    <slot />
    <el-dialog title="定义方案名" :visible.sync="dialogVisible" width="380px" :before-close="handleClose">
      <el-input size="mini" maxlength="8" show-word-limit v-model="inputText" placeholder="请输入名称"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="handleClose">取 消</el-button>
        <el-button size="mini" type="primary" @click="onSavePlanqd">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="操作记录" :visible.sync="logDialogVisible" width="800px">
      <zj-table
        :columns="pgxxColumns"
        :tableData="pgxxTableData"
        :tableAttributes="{
          height: '100%',
          border: true
        }"
      ></zj-table>
    </el-dialog>
  </div>
</template>

<script>
import { commonLogList } from '@/api/common.js'
import { zfireSave, zfireDel } from '@/api/fieldMan.js'
import { dictListDict } from '@/api/dataDictionary2.js'
import { zfireParamList, zfireParamSave, zfireParamDelete } from '@/api/zfireParam.js'
import SelExportColumnList from './sel-export-column-list.vue'
import selectData from './selectData.js'
export default {
  components: {
    SelExportColumnList
  },
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    // 事件组合
    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
    },
    // 是否显示操作记录
    operationShow: {
      type: Boolean,
      default: true
    },
    // 获取操作记录的主键字段
    operationRecordkey: {
      type: String,
      default: ''
    },
    // 操作按钮单元格宽度
    operationColumnWidth: {
      type: Number,
      default: 140
    },
    // 自定义列
    cstomClumn: {
      type: Function
    },
    // 结构数据钩子
    fieldBeansHook: {
      type: Function
    },
    // 菜单名称
    customModuleName: {
      type: String,
      default: ''
    },
    defaultSearchData: {
      type: Array,
      default: () => []
    },
    replaceOrNotMap: {
      type: Boolean,
      default: true
    },
    setModuleId: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      logDialogVisible: false,
      dialogVisible: false,
      // 搜索的参数
      parameter: {},
      // 按钮集合
      evens: [],
      // 表格属性
      defaultTableAttributes: {},
      // 表格事件
      defaultTableEvents: {},
      // 记录初始的id
      columnsIds: {},
      // 导出弹窗
      columnList: [],
      showTable: false,
      codeGather: {},
      frontCodes: [],
      pk: '',
      planItem: null,
      inputText: '',
      defaultPlan: [
        {
          name: '默认方案',
          paramCallback: () => {
            return []
          }
        }
      ],
      paramList: [],
      timePlan: [],
      pgxxColumns: [
        {
          columnAttributes: {
            label: '帐号',
            prop: 'userName'
          }
        },
        {
          columnAttributes: {
            label: '操作内容',
            prop: 'content'
          }
        },
        {
          columnAttributes: {
            label: 'ip',
            prop: 'ip'
          }
        },
        {
          columnAttributes: {
            label: '模块名称',
            prop: 'moduleName'
          }
        }
      ],
      pgxxTableData: []
    }
  },
  computed: {
    userid() {
      return this.$store.getters.userid
    },
    moduleId() {
      return this.setModuleId || this.$route.meta.moduleId
    },
    moduleName() {
      return this.customModuleName || this.$route.meta.title
    }
  },
  mounted() {
    if (this.exportList) {
      this.evens = [
        [
          {
            name: '导出',
            click: this.export,
            loading: false
          }
        ]
      ]
    }
    this.getZfireParamList()
  },
  methods: {
    setDefaultPlan(createTimeKey) {
      this.$nextTick(() => {
        if (createTimeKey) {
          var [y, m, d] = new Date(new Date().getTime()).toJSON().split('T').join(' ').substr(0, 10).split('-')
          this.timePlan = [
            {
              name: '今日',
              paramCallback: () => {
                return [
                  { param: createTimeKey, compare: '>', value: `${y}-${m}-${Number(d) - 1} 23:59:59` },
                  { param: createTimeKey, compare: '<', value: `${y}-${m}-${Number(d) + 1} 00:00:00` }
                ]
              }
            },
            {
              name: '昨日',
              paramCallback: () => {
                return [
                  { param: createTimeKey, compare: '>', value: `${y}-${m}-${Number(d) - 2} 23:59:59` },
                  { param: createTimeKey, compare: '<', value: `${y}-${m}-${Number(d)} 00:00:00` }
                ]
              }
            }
          ]
        }
      })
    },
    // 关闭方案命名弹窗
    handleClose() {
      this.planItem = null
      this.inputText = ''
      this.dialogVisible = false
    },
    // 获取方案记录
    getZfireParamList() {
      zfireParamList({
        moduleId: this.moduleId
      }).then(res => {
        this.paramList = res.data.map(item => {
          return {
            name: item.name,
            id: item.id,
            closable: true,
            paramCallback: () => {
              return item.items.map(dav => {
                if (dav.value[0] == '[' && dav.value[dav.value.length - 1] == ']') {
                  return {
                    param: dav.param,
                    compare: dav.compare,
                    value: dav.value.substring(1, dav.value.length - 1).split(',')
                  }
                }
                return { param: dav.param, compare: dav.compare, value: dav.value }
              })
            }
          }
        })
      })
    },
    // 点击获取保存方案数据
    onSavePlan(p) {
      if (this.paramList.length >= 10) {
        this.$message.error('自定义方案最多支持保留10个')
        return
      }
      if (p.length) {
        this.planItem = p
        this.dialogVisible = true
      } else {
        this.$message.error('请先设置搜索条件')
      }
    },
    // 确定保存方案
    onSavePlanqd() {
      if (this.inputText) {
        zfireParamSave({
          moduleId: this.moduleId,
          name: this.inputText,
          items: this.planItem
        }).then(res => {
          this.handleClose()
          this.getZfireParamList()
        })
      } else {
        this.$message.error('请先填写方案名称')
      }
    },
    // 删除方案
    onClosePlain(p) {
      if (p.id) {
        this.$confirm('删除此方案, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            zfireParamDelete({ id: p.id }).then(res => {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.getZfireParamList()
            })
          })
          .catch(() => {})
      }
    },
    // 全局操作记录按钮
    caozuojl(h, { row, index, column }) {
      return (
        <div class="operation-btns">
          <el-button
            size="mini"
            type="text"
            onClick={() => {
              if (row[this.pk]) {
                commonLogList({
                  objId: row[this.pk],
                  pageNum: 1,
                  pageSize: -1
                }).then(res => {
                  this.pgxxTableData = res.data.records
                  this.logDialogVisible = true
                })
              }
            }}
          >
            操作记录
          </el-button>
          {this.operation ? this.operation(h, { row, index, column }) : null}
        </div>
      )
    },
    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
    },
    // 获取下拉对应数据
    getCodeGather() {
      let codes = this.frontCodes.filter(key => (this.codeGather[key] ? false : true))
      if (codes && codes.length) {
        var codeGather = {}
        Promise.all(
          codes.map(code => {
            if (selectData[code]) {
              return selectData[code]()
            }
            return dictListDict({ code: code })
          })
        ).then(resAll => {
          codes.map((code, index) => {
            var arr = resAll[index].data.map(item => {
              return { value: item.dictCode, label: item.dictValue }
            })
            codeGather[code] = arr
          })
          this.codeGather = { ...this.codeGather, ...codeGather }
        })
      }
    },
    // 获取列表数据函数
    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)
        if (res.code == 200) {
          if (!this.showTable) {
            this.$nextTick(() => {
              this.showTable = true
            })
          }
          if (this.fieldBeansHook) {
            res.fieldBeans = this.fieldBeansHook(res.fieldBeans) || res.fieldBeans
          }
          for (let item of res.fieldBeans) {
            if (item.jname === 'createTime') {
              this.setDefaultPlan(`${item.tbName ? item.tbName + '.' : ''}${item.colName}`)
            }
            if (item.pk) {
              this.$nextTick(() => {
                this.pk = item.colName
              })
            }
            if (item.frontCode && !~this.frontCodes.indexOf(item.frontCode)) {
              this.frontCodes.push(item.frontCode)
            }
            if (this.cstomClumn && item.label === 'cstomClumn') {
              this.cstomClumn(item.jname, res.data.records, res.fieldBeans, this.parameter)
            }
          }
          this.getCodeGather()
          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.refreshList(true)
        })
        .catch(err => {
          this.$message.error('操作失败')
        })
    },
    // 导出
    export() {
      this.columnList = this.$refs.zjpage.columnList
    },
    exportDetermine(data) {
      if (!this.exportList) {
        return
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      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
          loading.close()
        })
        .catch(err => {
          this.$message.error('导出失败')
          this.columnList = []
          this.evens[0][0].loading = false
          loading.close()
        })
    },
    refreshList(bool) {
      if (bool === true) {
        this.showTable = false
        this.$refs.zjpage.refresh()
      } else {
        this.$refs.zjpage.refresh()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.template-page-1 {
  width: 100%;
  height: 100%;
  position: relative;
  box-sizing: border-box;
  min-width: 860px;
  overflow: auto;
}
.zj-page-template {
  position: relative;
  z-index: 0;
}
@font-face {
  font-family: 'aliyun_iconfont';
  src: url('~@/components/template/font/font_2075393_0cjq4n8ykvds.woff2') format('woff2'),
    url('~@/components/template/font/font_2075393_0cjq4n8ykvds.woff') format('woff'),
    url('~@/components/template/font/font_2075393_0cjq4n8ykvds.ttf') format('truetype');
}
::v-deep .el-table__cell {
  padding: 0 !important;
}
::v-deep .el-table--mini td,
::v-deep .el-table--mini th {
  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;
    width: 20px;
    text-align: center;
  }
  .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: 35px;
  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,
  .el-radio__label,
  .el-radio__input {
    background-color: #fff !important;
    color: #606266 !important;
    // border: none !important;
  }
}
::v-deep .el-checkbox.is-bordered.is-checked,
::v-deep .el-radio.is-bordered.is-checked {
  border-color: #409eff !important;
}
::v-deep .el-checkbox__input.is-checked .el-checkbox__inner,
::v-deep .el-radio__input.is-checked .el-radio__inner {
  border-color: #409eff !important;
  background: #409eff !important;
}
::v-deep .el-checkbox.is-bordered {
  margin-left: 0 !important;
  margin-right: 10px !important;
}
</style>
