<template>
  <div class="bbsl-common-page">
    <div class="bbsl-table-search">
      <el-form ref="searchForm" v-model="queryParam.querys" :inline="true">
        <el-form-item label="名称：">
          <el-input
            v-model="queryParam.querys[1].value"
            clearable
            maxlength="128"
            placeholder="请输入名称"
          />
        </el-form-item>
        <el-form-item label="发布单位：">
          <el-input
            v-model="queryParam.querys[2].value"
            clearable
            maxlength="128"
            placeholder="请输入发布单位"
          />
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="handleSearch"
            >搜索
          </el-button>
          <el-button icon="el-icon-refresh" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="page-content">
      <div class="tree-container">
        <tree-side
          ref="treeSide"
          :defaultProps="{children: 'children', label: 'name'}"
          :isOperate="isCharge === 1"
          :tabList="['法规文件目录']"
          :treeData="treeData"
          isDeselect
          @currentChange="currentChange"
          @operateEvent="operateEvent"
        ></tree-side>
      </div>
      <div ref="contentPanel" class="bbsl-table-content">
        <div ref="btnPanel" class="bbsl-btn-content">
          <el-button
            v-if="activeTreeItem.id"
            v-charge
            icon="el-icon-plus"
            type="success"
            @click="showDialog('addEdit')"
          >
            新增
          </el-button>
          <el-popconfirm title="确定删除选中数据吗？" @confirm="handleDelete">
            <template v-slot:reference>
              <el-button
                v-charge
                :disabled="!multipleSelection.length"
                icon="el-icon-delete"
                style="margin-left: 10px"
                type="danger"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
          <el-upload
            ref="upload"
            :action="actionUrl"
            :before-upload="beforeUpload"
            :data="{knowledgeTypeId: activeTreeItem.id}"
            :headers="headers"
            :multiple="false"
            :on-error="handleError"
            :on-success="handleSuccess"
            :show-file-list="false"
            class="avatar-uploader"
          >
            <el-button
              v-if="activeTreeItem.id"
              v-charge
              :loading="uploadLoading"
              icon="el-icon-download"
              style="margin-right: 10px;"
              type="primary"
              >导入
            </el-button>
          </el-upload>
          <el-button icon="el-icon-upload2" type="warning" @click="exportFile"
            >导出
          </el-button>
          <el-button
            v-charge
            icon="el-icon-document"
            type="info"
            @click="templateDownload"
          >
            模板下载
          </el-button>
        </div>
        <el-table
          ref="multipleSelection"
          v-loading="loading"
          :cell-style="{'text-align': 'center'}"
          :data="tableData"
          :default-sort="getSorterDirection(queryParam, true)"
          :header-cell-style="{'text-align': 'center'}"
          :max-height="tableMaxHeight"
          :style="{width: '100%'}"
          size="min"
          @row-dblclick="row => isCharge === 1 && showDialog('addEdit', row)"
          @selection-change="handleSelectionChange"
          @sort-change="sortChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
            :index="
              index =>
                index +
                1 +
                (queryParam.pageBean.page - 1) * queryParam.pageBean.pageSize
            "
            fixed
            label="序号"
            type="index"
            width="55"
          />
          <el-table-column
            :formatter="({name}) => name || '-'"
            label="名称"
            min-width="150"
            prop="name"
            show-overflow-tooltip
          />
          <el-table-column
            :formatter="({pushOrg}) => pushOrg || '-'"
            label="发布单位"
            min-width="150"
            prop="pushOrg"
            show-overflow-tooltip
          />
          <el-table-column
            :formatter="({contentType}) => contentType || '-'"
            label="内容类型"
            min-width="100"
            prop="contentType"
            show-overflow-tooltip
          />
          <el-table-column
            :formatter="({pushUser}) => pushUser || '-'"
            label="发布人"
            min-width="100"
            prop="pushUser"
            show-overflow-tooltip
          />
          <el-table-column
            :formatter="({introduction}) => introduction || '-'"
            label="简介"
            min-width="200"
            prop="introduction"
            show-overflow-tooltip
          />
          <el-table-column
            :formatter="({pushTime}) => pushTime || '-'"
            label="发布时间"
            min-width="100"
            prop="pushTime"
            show-overflow-tooltip
            sortable="custom"
          />
          <el-table-column label="操作" min-width="100">
            <template v-slot="{row}">
              <el-dropdown
                size="small"
                split-button
                @click="() => showDialog('addEdit', {...row, showType: '详情'})"
              >
                详情
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          ref="paginationPanel"
          :current-page="queryParam.pageBean.page"
          :page-size="queryParam.pageBean.pageSize"
          :page-sizes="[20, 30, 40, 50]"
          :total="queryParam.pageBean.total"
          background
          class="bbsl-pagination"
          layout="prev, pager, next, total, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>

    <!--  新增修改弹层  -->
    <AddEditDialog
      v-model="dialogs.addEditDialog"
      :active-tree-item="activeTreeItem"
      :row-info="rowInfo"
      @submit="addEditSubmit"
    />

    <!--  目录新增修改弹层  -->
    <TreeAddEditDialog
      v-model="dialogs.treeAddEditDialog"
      :tree-level-data="treeLevelData"
      :type="treeType"
      @submit="getTreeData"
    />
  </div>
</template>

<script>
import {TableMixin} from '@/mixins/tableMixin'
import {
  getSorterDirection,
  refineRequestBody,
  setQueryValue
} from '@/utils/requestWrappers'
import AddEditDialog from './components/AddEditDialog'
import {mapState} from 'vuex'
import * as api from '@/api/examDataMenu/examKnowledgeData/regulatoryFile'
import * as publicApi from '@/api/examDataMenu/examKnowledgeData'
import {dictionaryEscape} from '@/utils/dictionary'
import treeSide from '@/components/treeSide'
import TreeAddEditDialog from './components/TreeAddEditDialog'

export default {
  name: 'regulatoryFile',
  components: {
    TreeAddEditDialog,
    AddEditDialog,
    treeSide
  },
  mixins: [TableMixin],
  data() {
    return {
      tableData: [], // 表格数据
      // 查询对象
      queryParam: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'EQUAL', property: 'knowledgeTypeId'},
          {operation: 'LIKE', property: 'name'},
          {operation: 'LIKE', property: 'pushOrg'}
        ],
        sorter: [{direction: 'DESC', property: 'pushTime'}]
      },
      // 统一管理多个弹层
      dialogs: {
        addEditDialog: false, // 新增修改弹层
        treeAddEditDialog: false // 目录新增修改弹层
      },
      rowInfo: {}, // 保存行信息
      uploadLoading: false,
      treeData: [],
      activeTreeItem: {}, // 树选中保存的数据
      treeLevelData: {}, // 进行树编辑的时候保存的层级数据
      treeType: '3', // 1：装备知识树，2：装备知识数据树，3：法规文件树
      noLoadData: true
    }
  },
  computed: {
    actionUrl: _ => window.context.portal + '/biz/regulatory/file/importExcel',
    ...mapState({
      headers: state => ({
        Authorization: `Bearer ${state.login.currentUser.token}`
      })
    })
  },
  created() {
    // 获取树形目录
    this.getTreeData(treeData => {
      // 回调中默认选中第一项并将其id作为参数请求表格
      this.activeTreeItem = treeData[0] || {}
      this.$nextTick(_ => {
        this.$refs.treeSide?.setCurrentKey(treeData[0]?.id)
        setQueryValue(this.queryParam, 'knowledgeTypeId', treeData[0]?.id || '')
        this.loadData()
      })
    })
  },
  methods: {
    dictionaryEscape,

    //获取科目树
    async getTreeData(callback) {
      this.treeData = [
        {
          name: '法规文件',
          id: '',
          parentId: '',
          children: await publicApi.getTree(this.treeType)
        }
      ]
      // 保证重新刷新树数据后，选中效果不失效
      if (this.activeTreeItem.id) {
        this.$nextTick(_ => {
          this.$refs.treeSide?.setCurrentKey(this.activeTreeItem.id)
        })
      }
      callback && callback(this.treeData)
    },

    // 获取表格数据
    async loadData() {
      try {
        this.loading = true
        const {total = 0, rows = []} = await api.tableData(
          refineRequestBody(this.queryParam)
        )
        this.queryParam.pageBean.total = total
        this.tableData = rows.map(i => ({
          ...i,
          yearMonth: i.year && i.month ? `${i.year}-${i.month}` : ''
        }))
      } finally {
        this.loading = false
      }
    },

    // 重置搜索
    resetSearch() {
      this.queryParam = this.$options.data().queryParam
      this.activeTreeItem = this.treeData[0] || {}
      this.$nextTick(_ => {
        this.$refs.treeSide?.setCurrentKey(this.activeTreeItem.id)
      })
      this.loadData()
    },

    // 删除
    async handleDelete(row) {
      let ids = row ? row.id : this.multipleSelection.join()
      const {state} = await api.tableDelete(ids)
      if (state) {
        this.$message.success(`月训练计划删除成功`)
        const {page, pageSize, total} = this.queryParam.pageBean
        const totalPages = Math.ceil(total / pageSize) // 计算总页数
        if (totalPages > 1 && page === totalPages) {
          if (this.tableData.length === 1) {
            // 当前页只有一条数据
            this.queryParam.pageBean.page -= 1 // 返回前一页
          }
        }
        await this.loadData()
      }
    },

    //  导入文件上传前
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        this.uploadLoading = true
        const {size, name} = file
        let passedOrNot = true // 是否通过验证
        const maxSize = 500 * 1024 * 1024 // 20MB
        const typeRegular = /\.(xls|xlsx)$/i
        const verification = [
          {
            condition: !typeRegular.test(name),
            result: () => this.$message.error('只能上传xls或xlsx文件类型')
          }
        ]
        verification.forEach(item => {
          if (item.condition) {
            item.result()
            passedOrNot = false
            this.uploadLoading = false
          }
        })

        passedOrNot ? resolve() : reject()
      })
    },

    // 导入文件上传成功
    async handleSuccess() {
      this.$message.success('月训练计划导入成功')
      this.uploadLoading = false
      await this.loadData()
    },

    // 导入文件上传失败
    handleError() {
      this.$message.error('月训练计划导入失败，请重试')
      this.uploadLoading = false
    },

    // 导出数据
    async exportFile() {
      await api.exportData(
        refineRequestBody({
          querys: this.queryParam.querys,
          pageBean: {
            pageSize: -1
          }
        })
      )
    },

    // 模板下载
    async templateDownload() {
      window.open(this.portal + '/biz/regulatory/file/downModel', '_blank')
    },

    //左边树节点
    currentChange(nodeItem) {
      // 修改对应的字段值
      setQueryValue(this.queryParam, 'knowledgeTypeId', nodeItem?.id || '')
      this.activeTreeItem = nodeItem || {}
      this.calcTableHeight(500)
      this.queryParam.pageBean.page = 1
      this.loadData()
    },

    // 树节点操作
    operateEvent(type, data) {
      switch (type) {
        case '新增':
          const {id: parentId, ..._data} = data
          this.showDialog('treeAddEdit', {..._data, parentId}, 'treeLevelData')
          break
        case '编辑':
          this.showDialog('treeAddEdit', data, 'treeLevelData')
          break
        case '删除':
          this.$confirm('确定删除选中法规文件目录吗？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(async () => {
              const {state} = await publicApi.treeDelete(data.id)
              if (state) {
                this.$message.success(`删除法规文件目录成功`)
              } else {
                this.$message.error(`删除法规文件目录失败`)
              }
              await this.getTreeData()
            })
            .catch(_ => _)
          break
      }
    },

    // 修改计划状态
    async changeType(row) {
      if (!row.id) return this.$message.warning('计划错误，请重新创建计划')
      this.$confirm('是否完成计划？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const {state} = await api.updateStatus(row.id)
          if (state) {
            await this.loadData()
            this.$message.success(`修改计划状态成功`)
          }
        })
        .catch(_ => _)
    },

    // 新增修改弹层提交成功后
    addEditSubmit(type) {
      switch (type) {
        case 'add':
          this.queryParam.pageBean.page = 1
          break
        case 'edit':
          break
      }
      this.loadData()
    },

    getSorterDirection
  }
}
</script>
<style lang="scss" scoped>
.bbsl-common-page {
  display: flex;
  flex-direction: column;
  row-gap: 10px;

  .page-content {
    display: flex;
    height: calc(100% - 70px);
    column-gap: 10px;

    .tree-container {
      height: 100%;
      min-width: 300px;
      background: #fff;
      border-radius: 20px;
      padding: 20px 20px;
      box-shadow: 0px 0px 12px 0 rgba($color: #000000, $alpha: 0.1);
      box-sizing: border-box;
    }

    .bbsl-table-content {
      height: 100%;
      flex: 1;
      margin-top: 0;
      box-sizing: border-box;
    }
  }
}

.avatar-uploader {
  display: inline-block;
  margin-left: 10px;
}
</style>
