<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"
            clearable
            placeholder="请选择年度"
            type="year"
            value-format="yyyy"
          >
          </el-date-picker>
        </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"
          :default-expand-all="false"
          :defaultProps="{children: 'children', label: 'name'}"
          :tabList="['组织维度']"
          :treeData="treeData"
          isDeselect
          @currentChange="currentChange"
        ></tree-side>
      </div>
      <div ref="contentPanel" class="bbsl-table-content">
        <div ref="btnPanel" class="bbsl-btn-content">
          <el-button icon="el-icon-upload2" type="warning" @click="exportFile"
            >导出
          </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"
          @sort-change="sortChange"
        >
          <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="month"
            width="100"
          ></el-table-column>
          <el-table-column
            label="训练课目"
            prop="subjectName"
            show-overflow-tooltip
          ></el-table-column>

          <el-table-column
            label="训练场地"
            prop="spaceName"
            show-overflow-tooltip
          >
          </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
            label="平均训练时长"
            prop="hour"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            label="教练员"
            prop="coachName"
            show-overflow-tooltip
          ></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="创建时间"
            min-width="150"
            prop="createTime"
            show-overflow-tooltip
            sortable="custom"
          />
        </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>
  </div>
</template>

<script>
import {TableMixin} from '@/mixins/tableMixin'
import {
  getSorterDirection,
  refineRequestBody,
  setQueryValue
} from '@/utils/requestWrappers'
import {mapState} from 'vuex'
import * as api from '@/api/examDataMenu/examSafeguardData/trainStatisticPage'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import treeSide from '@/components/treeSide/index.vue'
import {treeDataByDem} from '@/api/systemInterface'
import moment from 'moment'
import {isNotEmpty} from '@/utils/helpers'

export default {
  name: 'TrainStatisticPage',
  components: {
    treeSide
  },
  mixins: [TableMixin],
  data() {
    return {
      tableData: [], // 表格数据
      // 查询对象
      queryParam: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'EQUAL', property: 'org_id_'},
          {operation: 'LIKE', property: 'year', value: moment().format('YYYY')}
        ],
        sorter: [
          {direction: 'DESC', property: 'createTime'},
          {direction: '', property: 'distributeTime'}
        ]
      },
      // 统一管理多个弹层
      dialogs: {
        addEditDialog: false, // 新增修改弹层
        borrowingReturningDialog: false, // 接触归还弹层
        detailedDialog: false // 使用明细弹层
      },
      rowInfo: {}, // 保存行信息
      treeData: [],
      activeTreeItem: {},
      uploadLoading: false,
      noLoadData: true
    }
  },
  computed: {
    actionUrl: _ =>
      window.context.portal + '/biz/trainEquipment/data/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)
        this.$refs.treeSide?.expandHandle(true, 2)
        setQueryValue(this.queryParam, 'org_id_', treeData[0]?.id || '')
        this.loadData()
      })
    })
  },
  methods: {
    getDictionaryByCode,
    isNotEmpty,
    dictionaryEscape,

    //获取树
    async getTreeData(callback) {
      this.treeData = [
        {
          name: '单位信息',
          id: '',
          parentId: '',
          children: await treeDataByDem()
        }
      ]
      // 保证重新刷新树数据后，选中效果不失效
      if (this.activeTreeItem.id) {
        this.$nextTick(_ => {
          this.$refs.treeSide?.setCurrentKey(this.activeTreeItem.id)
        })
      }
      callback && callback(this.treeData)
    },

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

    // 获取表格数据
    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
      setQueryValue(this.queryParam, 'org_id_', this.activeTreeItem?.id || '')
      this.$refs.treeSide?.setCurrentKey(this.activeTreeItem?.id || '')
      this.loadData()
    },

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

    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>
