<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-date-picker
            v-model="queryParam.querys[1].value"
            placeholder="请选择年度"
            style="width: 100%;"
            type="year"
            value-format="yyyy"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划状态：">
          <el-select
            v-model="queryParam.querys[5].value"
            placeholder="请选择计划状态"
            style="width: 100%;"
          >
            <el-option
              :label="item.name"
              :value="item.value"
              v-for="(item, i) in getDictionaryByCode('planStatus')"
              :key="i"
            ></el-option>
          </el-select>
        </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 ref="contentPanel" class="bbsl-table-content">
        <div ref="btnPanel" class="bbsl-btn-content">
          <el-button
            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"
            :headers="headers"
            :multiple="false"
            :on-error="handleError"
            :on-success="handleSuccess"
            :show-file-list="false"
            class="avatar-uploader"
          >
            <el-button
              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="mini"
          @selection-change="handleSelectionChange"
          @sort-change="sortChange"
          @row-dblclick="row => isCharge && menuClick('addEdit', row)"
        >
          <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
            label="年度"
            prop="year"
            width="100"
          ></el-table-column>

          <el-table-column
            label="训练日期"
            prop="subjectName"
            show-overflow-tooltip
          >
            <template v-slot="{row}">
              {{ row.startTime + '-' + row.endTime }}
            </template>
          </el-table-column>

          <el-table-column
            :formatter="
              ({planStatus}) => dictionaryEscape('planStatus', planStatus)
            "
            label="计划状态"
            prop="planStatus"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            :formatter="({createTime}) => createTime || '-'"
            label="创建时间"
            prop="createTime"
            show-overflow-tooltip
            sortable="custom"
          />
          <el-table-column v-if="isCharge === 1" label="操作" min-width="100">
            <template v-slot="{row}">
              <el-dropdown
                size="small"
                split-button
                @click="() => menuClick('info', row)"
                @command="command => menuClick(command, row)"
              >
                详情

                <template v-slot:dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-if="+row.planStatus < 1"
                      command="planIssuance"
                    >
                      计划下发
                    </el-dropdown-item>
                    <!-- <el-dropdown-item v-else command="trainingDetails">
                      训练明细
                    </el-dropdown-item> -->
                  </el-dropdown-menu>
                </template>
              </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"
          align="right"
          background
          class="bbsl-pagination"
          layout="prev, pager, next,total, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>

    <!--  新增修改弹层  -->
    <AddEditDialog
      :row-info="rowInfo"
      :value.sync="dialogs.addEditDialog"
      @submit="dialogSubmit"
    />

    <!--  训练明细  -->
    <training-details-dialog
      v-model="dialogs.trainingDetailsDialog"
      :row-details="rowInfo"
      @submit="dialogSubmit"
    />
  </div>
</template>

<script>
import {TableMixin} from '@/mixins/tableMixin'
import {getSorterDirection, refineRequestBody} from '@/utils/requestWrappers'
import AddEditDialog from './components/AddEditDialog.vue'
import {mapState} from 'vuex'
import * as api from '@/api/examDataMenu/examManagerData/examPlanAll.js'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import moment from 'moment'
import TrainingDetailsDialog from './components/TrainingDetailsDialog/index.vue'

export default {
  name: 'ExamYearPlan',
  components: {
    TrainingDetailsDialog,
    AddEditDialog
  },
  mixins: [TableMixin],
  data() {
    return {
      tableData: [], // 表格数据
      treeData: [],

      // 查询对象
      queryParam: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'LIKE', property: 'orgName'},
          {
            operation: 'EQUAL',
            property: 'year',
            value: moment().format('YYYY')
          },
          {operation: 'LIKE', property: 'post'},
          {operation: 'LIKE', property: 'majorName'},
          {operation: 'EQUAL', property: 'planType', value: '6'},
          {operation: 'EQUAL', property: 'planStatus'}
        ],
        sorter: [{direction: 'DESC', property: 'createTime'}]
      },
      // 统一管理多个弹层
      dialogs: {
        addEditDialog: false, // 新增修改弹层
        trainingDetailsDialog: false // 训练明细弹层
      },
      rowInfo: {}, // 保存行信息
      uploadLoading: false
    }
  },
  computed: {
    actionUrl: _ => window.context.portal + '/biz/exam/plan/importExcel/6',
    ...mapState({
      headers: state => ({
        Authorization: `Bearer ${state.login.currentUser.token}`
      })
    })
  },
  created() {},
  methods: {
    dictionaryEscape,
    getDictionaryByCode,
    // 获取表格数据
    async loadData() {
      try {
        this.loading = true
        const {total = 0, rows = []} = await api.tableData(
          refineRequestBody(this.queryParam)
        )
        this.queryParam.pageBean.total = total
        this.tableData = rows
      } finally {
        this.loading = false
      }
    },

    // 重置搜索
    resetSearch() {
      this.queryParam = this.$options.data().queryParam

      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
          }
        }),
        '6'
      )
    },

    // 模板下载
    async templateDownload() {
      await api.downModel('6')
    },

    // 修改计划状态
    async changeType(row) {
      this.$confirm('是否确认计划下发？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })

        .then(async () => {
          const {state} = await api.updateStatus(row.id)
          if (state) {
            this.$message.success(`计划下发成功`)
            this.loadData()
          } else {
            this.$message.error(`计划下发失败`)
          }
        })
        .catch(_ => _)
    },

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

    // 功能菜单点击
    menuClick(command, row) {
      switch (command) {
        // 编辑
        case 'addEdit':
          if (row.planStatus !== '0')
            return this.$message.warning(`已下发的计划不能进行编辑`)
          this.showDialog(command, row)
          break
        // 计划下发
        case 'planIssuance':
          this.changeType(row)
          break
        // 训练明细
        case 'trainingDetails':
          this.showDialog(command, row)
          break
        // 详情
        case 'info':
          this.showDialog('addEdit', {...row, type: '详情'})
          break
      }
    },

    getSorterDirection
  }
}
</script>
<style lang="scss" scoped>
.type-tag {
  margin: 0 2px;
}

.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;
    }
  }
}

a {
  text-decoration: none;
  color: #ffffff;
}

.title {
  width: 100%;
  margin-bottom: 10px;

  i {
    color: #1289fe;
    font-size: 25px;
  }

  span {
    font-size: 25px;
  }
}

::v-deep .el-tree {
  border: none;
}

.avatar-uploader {
  display: inline-block;
  margin-left: 10px;
}

::v-deep .el-tree-node__content {
  padding: 5px 0;
}
</style>
