<template>
  <div class="app-container" ref="tableBody">
    <a-spin :spinning="loading">
      <!-- 过滤条件栏目 -->
      <div class="common-card" ref="filterCard">
        <div class="filter-condition-box">
          <span>考试类别：</span>
          <ul>
            <li
              :class="{
                checkedExamType: checkedExamType === item.code,
              }"
              v-for="(item, index) in examType"
              :key="index"
              @click="handleExamQuestionTypeFun(item)"
            >
              {{ item.name }}
            </li>
          </ul>
        </div>
        <div class="border-line"></div>
        <div class="filter-other-box">
          <span class="filter-other-title">其它选项：</span>
          <span class="filter-other-item-title">工种：</span>
          <a-select
            v-model="engineeringWorkChooseValue"
            @change="handleChangeEngineeringWorkValue"
          >
            <a-select-option
              v-for="(item, index) in engineeringWorkList"
              :key="index"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </div>
      </div>
      <!-- 表单 -->
      <div class="common-card a-card-margin-top">
        <!-- 清空、批量删除 -->
        <div class="exam-edit-row">
          <a-button
            type="primary"
            :disabled="!hasSelected"
            @click="handleClearSelectDataFun"
          >
            清空所选
          </a-button>
          <span v-if="hasSelected" class="exam-edit-checkedtxt">
            {{ `已选择 ${selectedRowKeys.length} 项` }}
          </span>
          <a-button
            class="exam-edit-delete"
            type="primary"
            :disabled="!hasSelected"
            @click="handleDeleteSelectDataFun"
          >
            批量删除
          </a-button>
        </div>
        <!-- 表单 :scroll="{ y: tableHeight }" -->
        <a-table
          :columns="columns"
          :data-source="tableData"
          :row-key="(record) => record.id"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
            getCheckboxProps: (record) => ({
              props: {
                disabled: record.disabled,
              },
            }),
          }"
          :pagination="false"
        >
          <template slot="examStatusTxt" slot-scope="text">
            <span
              :class="
                text === examStatusTypeTxt[0]
                  ? 'exam-examStatus-green'
                  : text === examStatusTypeTxt[1]
                  ? 'exam-examStatus-yellow'
                  : text === examStatusTypeTxt[2]
                  ? 'exam-examStatus-red'
                  : ''
              "
              >{{ text }}</span
            >
          </template>
          <template slot="action" slot-scope="text, record">
            <a @click="toQuestionDetailFun(record)">详情</a>
            <a-divider type="vertical" />
            <a
              :class="{
                'exam-delete': true,
                'exam-delete-disable': record.disabled,
              }"
              @click="deleteQuestionFun(record)"
              >删除</a
            >
          </template>
        </a-table>
        <!-- 分页 -->
        <div class="a-pagination-display">
          <a-pagination
            v-model="pagination.current"
            :pageSize="pagination.pageSize"
            :total.sync="pagination.total"
            show-less-items
            show-quick-jumper
            @change="getExamListFun"
          />
        </div>
      </div>
    </a-spin>
    <div class="company-info">
      <span>
        copyright © 浮游科技有限公司出品
      </span>
    </div>
  </div>
</template>

<script>
import {
  formateUrlParams,
  formatePathParams,
  formatDateTimeT,
  formateExamStatesFun,
  formateEngineeringWork,
} from '@/filters';
import { mapGetters } from 'vuex';
import {
  EXAM_TYPE,
  EXAM_STATUS_TYPE,
  EXAM_STATUS_TYPE_TXT,
} from '@/common/Constant';
export default {
  name: 'examManagementList',
  props: {},
  components: {},
  data() {
    return {
      loading: false, // 是否展示加载动画
      examType: [], // 考试类别列表
      checkedExamType: '', // 所选考试类别
      engineeringWorkList: [], // 工种数据列表
      engineeringWorkChooseValue: '', // 所选工种
      // tableHeight: 400, // 表格高度
      columns: [], // form表单的列参数
      tableData: [], // 表单数据
      pagination: {
        pageSize: 10,
        current: 1,
        total: 0,
      }, // 分页参数
      selectedRowKeys: [], // 多选的结果
      examStatusTypeTxt: EXAM_STATUS_TYPE_TXT, // 考试状态属性文字
    };
  },
  created() {
    this.initDataFun(); //初始化数据
  },
  mounted() {
    // this.initTableHeightFun(); // 初始化表单的高度
  },
  beforeDestroy() {},
  watch: {
    // screenHeight() {
    //   this.initTableHeightFun(); // 初始化表单的高度
    // },
  },
  computed: {
    // 是否选择了数据
    ...mapGetters(['screenHeight', 'GET_ENGINEERING_WORK_LIST']),
    // 判断是否有行被选择
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    },
  },
  methods: {
    // // 初始化表单的高度
    // initTableHeightFun() {
    //   this.tableHeight =
    //     this.$refs.tableBody.offsetHeight -
    //     (this.$refs.filterCard.offsetHeight + 48 * 4);
    // },
    //初始化数据
    initDataFun() {
      this.loading = true;
      // 考试类别
      this.examType = [{ name: '全部', code: '' }, ...EXAM_TYPE];
      this.checkedExamType = this.examType[0].code;
      // 工种类别
      this.engineeringWorkList = [
        { name: '全部', id: '' },
        ...this.GET_ENGINEERING_WORK_LIST,
      ];
      this.engineeringWorkChooseValue = this.engineeringWorkList[0].id;
      // 表单的列的配置参数
      this.columns = [
        // {
        //   title: '考试编号',
        //   dataIndex: 'id',
        //   key: 'id',
        // },
        {
          title: '考试名称',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: '考试时间',
          dataIndex: 'startTimeTxt',
          key: 'startTimeTxt',
          width: 200,
        },
        {
          title: '考试类型',
          dataIndex: 'examCategoryTxt',
          key: 'examCategoryTxt',
          width: 150,
        },
        {
          title: '工种',
          dataIndex: 'engineerTypeTxt',
          key: 'engineerTypeTxt',
          width: 200,
        },
        {
          title: '状态',
          dataIndex: 'examStatusTxt',
          key: 'examStatusTxt',
          scopedSlots: { customRender: 'examStatusTxt' },
          width: 150,
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          width: 150,
        },
      ];
      this.getExamListFun(); // 查询：试题列表数据
    },
    // 初始化分页参数
    initPagination() {
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.pagination.total = 0;
    },
    // 操作：选择某个试题类型
    handleExamQuestionTypeFun(item) {
      if (this.checkedExamType === item.code) {
        return;
      }
      this.checkedExamType = item.code;
      this.initPagination(); // 初始化分页参数
      this.getExamListFun(); // 查询：试题列表数据
    },
    // 操作：选择了某个工种
    handleChangeEngineeringWorkValue() {
      this.initPagination(); // 初始化分页参数
      this.getExamListFun(); // 查询：试题列表数据
    },
    // 查询：试题列表数据
    getExamListFun() {
      this.loading = true;
      let params = {
        page: this.pagination.current - 1,
        size: this.pagination.pageSize,
        category: this.checkedExamType, // 考试类型
        engineertypeid: this.engineeringWorkChooseValue, // 工种类别
      };
      this.$_http
        .get(formateUrlParams(this.$_API.INTERFACE_GET_EXAMS, params))
        .then((res) => {
          let resData = res.data.content;
          resData.forEach((item) => {
            item.startTimeTxt = formatDateTimeT(item.startTime);
            let obj = formateExamStatesFun(item.startTime, item.deadline);
            item.examStatus = obj.examStatus;
            item.examStatusTxt = obj.examStatusTxt;
            item.disabled =
              item.examStatus !== EXAM_STATUS_TYPE.NOT_START ? true : false; // 未开始的才能删除
            // 工种
            if (item.engineerTypes) {
              let findItem = formateEngineeringWork(
                this.engineeringWorkList,
                item.engineerTypes[0]
              );
              item.engineerTypeTxt = findItem.name;
            } else {
              item.engineerTypeTxt = '不限';
            }
            // 考试类型
            EXAM_TYPE.forEach((examType) => {
              if (item.examCategory === examType.code) {
                item.examCategoryTxt = examType.name;
              }
            });
          });
          this.tableData = resData;
          this.pagination.total = res.data.totalElements; // 总条数
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 操作：详情
    toQuestionDetailFun(record) {
      if (!record.id) {
        this.$message.error('试题数据异常');
        this.initPagination(); // 初始化分页参数
        this.getExamListFun(); // 查询：试题列表数据
        return;
      }
      this.$router.push({
        path: '/examManagement/list/detail',
        query: { id: record.id },
      });
    },
    // 操作：删除
    deleteQuestionFun(record) {
      if (record.disabled) {
        return;
      }
      let that = this;
      this.$confirm({
        title: '删除',
        content: `确认删除考试名为 ${record.name} 的考试吗？`,
        okText: '确认',
        cancelText: '取消',
        onOk() {
          let params = {
            examId: record.id,
          };
          that.$_http
            .delete(formatePathParams(that.$_API.INTERFACE_DELETE_EXAM, params))
            .then(() => {
              that.loading = false;
              that.$message.success('删除试题成功');
              that.initPagination(); // 初始化分页参数
              that.getExamListFun(); // 查询：试题列表数据
            })
            .catch(() => {
              that.loading = false;
            });
        },
        onCancel() {},
      });
    },
    // 操作：清空选择
    handleClearSelectDataFun() {
      this.selectedRowKeys = [];
    },
    // 操作：多选变化时
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    // 操作：批量删除
    handleDeleteSelectDataFun() {
      let that = this;
      this.$confirm({
        title: '批量删除',
        content: `确认批量删除考试吗？`,
        okText: '确认',
        cancelText: '取消',
        onOk() {
          that.loading = true;
          that.$_http
            .delete(that.$_API.INTERFACE_DELETE_EXAMS, {
              data: that.selectedRowKeys,
            })
            .then(() => {
              that.selectedRowKeys = [];
              that.loading = false;
              that.$message.success('批量删除试题成功');
              that.initPagination(); // 初始化分页参数
              that.getExamListFun(); // 查询：试题列表数据
            })
            .catch(() => {
              that.loading = false;
            });
        },
        onCancel() {},
      });
    },
  },
};
</script>

<style lang="less"></style>

<style lang="less" scoped>
@import '~@/styles/common/variable.less';
.app-container {
  .filter-condition-box {
    display: flex;
    align-items: center;
    ul {
      margin: 0;
      display: flex;
      li {
        margin-left: @paddingMarginVal;
        color: @mainColorBlack65;
        cursor: pointer;
        &:hover {
          color: @mainColorBlueNormal;
        }
      }
      .checkedExamType {
        color: @mainColorBlueNormal;
        font-weight: bold;
      }
    }
  }
  .filter-other-box {
    width: 100%;
    display: flex;
    align-items: center;
    .filter-other-title {
      color: @mainColorBlack85;
    }
    .filter-other-item-title {
      margin-left: @paddingMarginVal;
      color: @mainColorBlack65;
    }
  }
  .exam-edit-row {
    margin-bottom: @paddingMarginVal;
    .exam-edit-checkedtxt {
      margin-left: @paddingMarginVal;
    }
    .exam-edit-delete {
      margin-left: @paddingMarginVal;
    }
  }
  .exam-examStatus-green {
    color: #58e206;
  }
  .exam-examStatus-yellow {
    color: #ff8d1a;
  }
  .exam-examStatus-red {
    color: #d43030;
  }
  .exam-delete {
    cursor: pointer;
  }
  .exam-delete-disable {
    cursor: no-drop;
    color: #a6a6a6;
  }
}
</style>
