<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="{
                checkedExamQuestionType: checkedExamQuestionType === item.code,
              }"
              v-for="(item, index) in examQuestionType"
              :key="index"
              @click="handleExamQuestionTypeFun(item)"
            >
              {{ item.name }}
            </li>
          </ul>
        </div>
        <div class="filter-condition-box a-card-margin-top flexCenter">
          <span>所属类型：</span>
          <div class="create-select-row">
            <div class="create-select-item">
              <span>父类</span>
              <a-select
                v-model="checkedQuestionConditionParentType"
                @change="selectTypeConditionParent"
              >
                <a-select-option
                  v-for="(item, index) in questionConditionParentType"
                  :key="index"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </div>
            <div class="create-select-item">
              <span>子类</span>
              <a-select
                v-model="checkedQuestionConditionChildrenType"
                :disabled="!checkedQuestionConditionParentType"
                @change="selectTypeConditionChildren"
              >
                <a-select-option
                  v-for="(item, index) in questionConditionChildrenType"
                  :key="index"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </div>
          </div>
        </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="engineeringWorkChoose"
            @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-question-edit-row">
          <a-button
            type="primary"
            :disabled="!hasSelected"
            @click="handleClearSelectDataFun"
          >
            清空所选
          </a-button>
          <span v-if="hasSelected" class="exam-question-edit-checkedtxt">
            {{ `已选择 ${selectedRowKeys.length} 项` }}
          </span>
          <a-button
            class="exam-question-edit-delete"
            type="primary"
            :disabled="!hasSelected"
            @click="handleDeleteSelectDataFun"
          >
            批量删除
          </a-button>
        </div>
        <!-- 表单 -->
        <a-table
          :columns="columns"
          :data-source="tableData"
          :row-key="(record) => record.id"
          :scroll="{ y: tableHeight }"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }"
          :pagination="false"
        >
          <template slot="type" slot-scope="text, record">
            <span>{{ record.typeTxt }}</span>
          </template>
          <template slot="questionCategory" slot-scope="text, record">
            <span>{{
              record.questionCategory ? record.questionCategory.name : '不限'
            }}</span>
          </template>
          <template slot="rootQuestionCategory" slot-scope="text, record">
            <span>{{
              record.rootQuestionCategory
                ? record.rootQuestionCategory.name
                : '不限'
            }}</span>
          </template>
          <template slot="action" slot-scope="text, record">
            <a @click="toQuestionDetailFun(record)">详情</a>
            <a-divider type="vertical" />
            <a @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="getQusetionsListFun"
          />
        </div>
      </div>
    </a-spin>
    <div class="company-info">
      <span>
        copyright © 浮游科技有限公司出品
      </span>
    </div>
  </div>
</template>

<script>
import { EXAM_QUESTION_TYPE } from '@/common/Constant';
import { mapGetters } from 'vuex';
import { formatePathParams, formateEngineeringWork } from '@/filters';
export default {
  name: 'examQuestionList',
  props: {},
  components: {},
  data() {
    return {
      examQuestionType: [], // 试题类别列表
      checkedExamQuestionType: '', // 所选试题类别
      questionConditionParentType: [], // 试题类型列表-父类
      checkedQuestionConditionParentType: '', // 所选试题类型-父类
      questionConditionChildrenType: [], // 试题类型列表-子类
      checkedQuestionConditionChildrenType: '', // 所选试题类型-子类
      engineeringWorkList: [], // 工种数据列表
      engineeringWorkChoose: '', // 所选工种信息
      tableHeight: 400, // 表格高度
      columns: [], // form表单的列参数
      tableData: [], // 表单数据
      pagination: {
        pageSize: 7,
        current: 1,
        total: 0,
      }, // 分页参数
      loading: false, // 是否展示加载动画
      selectedRowKeys: [], // 多选的结果
    };
  },
  created() {
    this.initDataFun(); //初始化数据
  },
  mounted() {
    this.initTableHeightFun(); // 初始化表单的高度
  },
  beforeDestroy() {},
  watch: {
    screenHeight() {
      this.initTableHeightFun(); // 初始化表单的高度
    },
  },
  computed: {
    ...mapGetters([
      'screenHeight',
      'GET_ENGINEERING_WORK_LIST',
      'GET_EXAM_QUESTION_TYPE_CONDITION_PARENT',
    ]),
    // 判断是否有行被选择
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    },
  },
  methods: {
    // 初始化表单的高度
    initTableHeightFun() {
      this.tableHeight =
        this.$refs.tableBody.offsetHeight -
        (this.$refs.filterCard.offsetHeight + 48 * 4 - 5);
    },
    //初始化数据
    initDataFun() {
      // 试题类别
      this.examQuestionType = [
        { name: '全部', code: '' },
        ...EXAM_QUESTION_TYPE,
      ];
      // 试题类型
      this.questionConditionParentType = [
        { name: '不限', id: '' },
        ...this.GET_EXAM_QUESTION_TYPE_CONDITION_PARENT,
      ];
      this.checkedQuestionConditionParentType = this.questionConditionParentType[0].id;
      // 工种类别
      this.engineeringWorkList = [
        { name: '不限', id: '' },
        ...this.GET_ENGINEERING_WORK_LIST,
      ];
      // 表单的列的配置参数
      this.columns = [
        {
          title: '试题编号',
          dataIndex: 'id',
          key: 'id',
        },
        {
          title: '试题',
          dataIndex: 'content',
          key: 'content',
        },
        {
          title: '试题类别',
          dataIndex: 'type',
          key: 'type',
          scopedSlots: { customRender: 'type' },
        },
        {
          title: '试题父类',
          dataIndex: 'questionCategory',
          key: 'questionCategory',
          scopedSlots: { customRender: 'questionCategory' },
        },
        {
          title: '试题子类',
          dataIndex: 'rootQuestionCategory',
          key: 'rootQuestionCategory',
          scopedSlots: { customRender: 'rootQuestionCategory' },
        },
        {
          title: '工种',
          dataIndex: 'engineerTypeTxt',
          key: 'engineerTypeTxt',
          scopedSlots: { customRender: 'engineerTypeTxt' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ];
      this.getQusetionsListFun(); // 查询：试题列表数据
    },
    // 初始化分页参数
    initPagination() {
      this.pagination.current = 1;
      this.pagination.pageSize = 7;
      this.pagination.total = 0;
    },
    // 查询：试题类型列表-子类
    getTableChildrenListFun() {
      if (!this.checkedQuestionConditionParentType) {
        this.checkedQuestionConditionChildrenType = '';
        this.questionConditionChildrenType = [];
        this.initPagination(); // 初始化分页参数
        this.getQusetionsListFun(); // 查询：试题列表数据
        return;
      }
      this.loading = true;
      let params = {
        categoryId: this.checkedQuestionConditionParentType,
      };
      this.$_http
        .get(
          formatePathParams(
            this.$_API.INTERFACE_GET_EXAMS_QUESTION_TYPE_CONDITION_CHILDRENS,
            params
          )
        )
        .then((res) => {
          this.questionConditionChildrenType = res.data;
          this.checkedQuestionConditionChildrenType = this.questionConditionChildrenType[0].id;
          this.loading = false;
          this.initPagination(); // 初始化分页参数
          this.getQusetionsListFun(); // 查询：试题列表数据
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 查询：试题列表数据
    getQusetionsListFun() {
      this.loading = true;
      let params = {
        page: this.pagination.current - 1,
        size: this.pagination.pageSize,
        type: this.checkedExamQuestionType,
        categoryid: this.checkedQuestionConditionChildrenType,
        engineertypeid: this.engineeringWorkChoose,
      };
      this.$_http
        .get(this.$_API.INTERFACE_GET_EXAMS_QUESTION_LIST, { params })
        .then((res) => {
          let resData = res.data.content;
          resData.forEach((item) => {
            this.examQuestionType.forEach((it) => {
              if (item.type === it.code) {
                item.typeTxt = it.name;
              }
            }); // 试题类别---注意之后从engineertypes中拿
            // 工种
            if (item.engineerTypes) {
              let findItem = formateEngineeringWork(
                this.engineeringWorkList,
                item.engineerTypes[0]
              );
              item.engineerTypeTxt = findItem.name;
            } else {
              item.engineerTypeTxt = '不限';
            }
          });
          this.pagination.total = res.data.totalElements; // 总条数
          this.tableData = resData;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 操作：选择某个试题类别
    handleExamQuestionTypeFun(item) {
      if (this.checkedExamQuestionType === item.code) {
        return;
      }
      this.checkedExamQuestionType = item.code;
      this.initPagination(); // 初始化分页参数
      this.getQusetionsListFun(); // 查询：试题列表数据
    },
    // 操作：选择了父类
    selectTypeConditionParent() {
      this.getTableChildrenListFun(); // 查询：试题类型列表-子类
    },
    // 操作：选择了子类
    selectTypeConditionChildren() {
      this.initPagination(); // 初始化分页参数
      this.getQusetionsListFun(); // 查询：试题列表数据
    },
    // 操作：选择了某个工种
    handleChangeEngineeringWorkValue() {
      this.initPagination(); // 初始化分页参数
      this.getQusetionsListFun(); // 查询：试题列表数据
    },
    // 操作：详情
    toQuestionDetailFun(record) {
      console.log('查看某个试题的详情', record);
      // if (!record || !record.id) {
      //   this.$message.error('数据异常，请重新进入当前页面');
      //   return;
      // }
      // switch (record.type) {
      //   case EXAM_QUESTION_TYPE[0].code:
      //     this.$router.push({
      //       path: '/examQuestionManagement/create/singleChoice',
      //       query: { id: record.id },
      //     });
      //     break;
      //   case EXAM_QUESTION_TYPE[1].code:
      //     this.$router.push({
      //       path: '/examQuestionManagement/create/multipleChoice',
      //       query: { id: record.id },
      //     });
      //     break;
      //   case EXAM_QUESTION_TYPE[2].code:
      //     this.$router.push({
      //       path: '/examQuestionManagement/create/trueOrFalse',
      //       query: { id: record.id },
      //     });
      //     break;
      //   case EXAM_QUESTION_TYPE[3].code:
      //     this.$router.push({
      //       path: '/examQuestionManagement/create/gapFilling',
      //       query: { id: record.id },
      //     });
      //     break;
      //   default:
      //     this.$message.error('试题类别异常，无法查看详情');
      //     break;
      // }
    },
    // 操作：删除
    deleteQuestionFun(record) {
      let that = this;
      this.$confirm({
        title: '删除',
        content: `确认删除编号为 ${record.id} 的试题吗？`,
        okText: '确认',
        cancelText: '取消',
        onOk() {
          that.loading = true;
          let params = {
            questionId: record.id,
          };
          that.$_http
            .delete(
              formatePathParams(
                that.$_API.INTERFACE_DELETE_EXAMS_QUESTION_DELETE,
                params
              )
            )
            .then(() => {
              that.selectedRowKeys = that.selectedRowKeys.filter((id) => {
                if (id !== record.id) {
                  return id;
                }
              });
              that.loading = false;
              that.$message.success('删除试题成功');
              that.initPagination(); // 初始化分页参数
              that.getQusetionsListFun(); // 查询：试题列表数据
            })
            .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_QUESTION_DELETE_LIST, {
              data: that.selectedRowKeys,
            })
            .then(() => {
              that.selectedRowKeys = [];
              that.loading = false;
              that.$message.success('批量删除试题成功');
              that.initPagination(); // 初始化分页参数
              that.getQusetionsListFun(); // 查询：试题列表数据
            })
            .catch(() => {
              that.loading = false;
            });
        },
        onCancel() {},
      });
    },
  },
};
</script>

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

<style lang="less" scoped>
@import '~@/styles/common/variable.less';
</style>
