<template>
  <div class="card-rule-manage">
    <div class="part-box part-box-filter part-box-flex">
      <el-form ref="FilterForm" label-position="left" label-width="85px" inline>
        <template v-if="checkPrivilege('condition', 'condition')">
          <el-form-item label="规则名称：">
            <el-input
              style="width: 142px"
              v-model.trim="filter.name"
              placeholder="规则名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="创建时间：">
            <el-date-picker
              v-model="createTime"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="创建开始时间"
              end-placeholder="创建结束时间"
              value-format="timestamp"
              align="right"
              unlink-panels
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="启用/禁用：" label-width="90px">
            <el-select
              v-model="filter.enable"
              style="width: 120px"
              placeholder="启用/禁用"
              clearable
            >
              <el-option
                v-for="(val, key) in ABLE_TYPE"
                :key="key"
                :value="key * 1"
                :label="val"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>
        <el-form-item>
          <el-button
            v-if="checkPrivilege('button', 'select')"
            type="primary"
            @click="toPage(1)"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="part-box-action">
        <el-button
          v-if="checkPrivilege('button', 'add')"
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="toAdd"
          >添加</el-button
        >
      </div>
    </div>
    <div class="part-box part-box-pad">
      <el-table ref="TableList" :data="rules">
        <el-table-column
          type="index"
          label="序号"
          width="70"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="题卡规则名称"
          min-width="200"
        ></el-table-column>
        <el-table-column prop="remark" label="备注">
          <span slot-scope="scope">{{
            scope.row.remark | defaultFieldFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="enable" label="启用/禁用" width="100">
          <template slot-scope="scope">
            {{ scope.row.enable | enableFilter }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="170">
          <span slot-scope="scope">{{
            scope.row.createTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column class-name="action-column" label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              v-if="checkPrivilege('link', 'preview')"
              class="btn-primary"
              type="text"
              @click="toDetail(scope.row)"
              >预览</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'edit')"
              class="btn-primary"
              type="text"
              @click="toEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'delete')"
              class="btn-danger"
              type="text"
              @click="toDelete(scope.row)"
              >删除</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'enable')"
              :class="scope.row.enable ? 'btn-danger' : 'btn-primary'"
              type="text"
              @click="toEnable(scope.row)"
              >{{ scope.row.enable ? "禁用" : "启用" }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :pager-count="5"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
          @size-change="pageSizeChange"
        >
        </el-pagination>
      </div>
    </div>
    <!-- ModifyCardRule -->
    <modify-card-rule
      ref="ModifyCardRule"
      :instance="curRule"
      :edit-type="editType"
      @modified="getList"
    ></modify-card-rule>
  </div>
</template>

<script>
import { ABLE_TYPE } from "@/constants/enumerate";
import {
  examRuleDetail,
  cardRuleListPage,
  ableCardRule,
  deleteCardRule,
} from "../api";
import { getEnums } from "../../login/api";
import pickerOptions from "@/constants/datePickerOptions";

import ModifyCardRule from "../components/ModifyCardRule";

export default {
  name: "card-rule-manage",
  components: {
    ModifyCardRule,
  },
  data() {
    return {
      filter: {
        enable: null,
        name: "",
        createStartTime: null,
        createEndTime: null,
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      rules: [],
      examRule: {},
      curRule: {},
      editType: "ADD",
      cardRequiredFields: [],
      cardExtendFields: [],
      ABLE_TYPE,
      // date-picker
      createTime: [],
      pickerOptions,
    };
  },
  mounted() {
    this.getList();
    this.getExamRule();
  },
  methods: {
    async getExamRule() {
      if (!this.checkPrivilege("button", "add")) return;

      const examRequiredFields = await getEnums("REQUIRED_FIELDS");
      this.cardRequiredFields = await getEnums("CARD_REQUIRED_FIELDS");
      const cardRequiredFieldCodes = this.cardRequiredFields.map(
        (item) => item.code
      );
      const extendFields = examRequiredFields
        .filter((field) => !cardRequiredFieldCodes.includes(field.code))
        .map((item) => {
          return {
            code: item.code,
            name: item.name,
          };
        });
      let examRule = await examRuleDetail();
      if (!examRule) {
        this.$notify.error({
          title: "错误",
          message: "请先设置通用考务规则配置",
        });
        return;
      }
      this.examRule = examRule;

      this.cardExtendFields = [
        ...extendFields,
        ...JSON.parse(examRule.extendFields).filter((item) => item.enable),
      ];
    },
    async getList() {
      if (!this.checkPrivilege("list", "list")) return;

      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size,
      };
      if (this.createTime) {
        datas.createStartTime = this.createTime[0];
        datas.createEndTime = this.createTime[1];
      }
      if (datas.enable !== null && datas.enable !== "")
        datas.enable = !!datas.enable;
      const data = await cardRuleListPage(datas);
      this.rules = data.records;
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    toAdd() {
      this.curRule = {
        fillNumber: this.examRule.examNumberDigit,
        requiredFields: this.cardRequiredFields.map((item) => {
          return {
            code: item.code,
            name: item.name,
            enable: true,
          };
        }),
        extendFields: this.cardExtendFields.map((item) => {
          return {
            code: item.code,
            name: item.name,
            enable: false,
          };
        }),
      };
      this.editType = "ADD";
      this.$refs.ModifyCardRule.open();
    },
    toEdit(row) {
      this.curRule = row;
      this.editType = "EDIT";
      this.$refs.ModifyCardRule.open();
    },
    toDetail(row) {
      // this.curRule = row;
      // this.editType = "PREVIEW";
      // this.$refs.ModifyCardRule.open();
      window.open(
        this.getRouterPath({
          name: "CardRulePreview",
          params: {
            cardRuleId: row.id,
          },
        })
      );
    },
    toEnable(row) {
      const action = row.enable ? "禁用" : "启用";

      this.$confirm(`确定要${action}题卡规则【${row.name}】吗?`, "提示", {
        type: "warning",
      })
        .then(async () => {
          const enable = !row.enable;
          await ableCardRule({
            id: row.id,
            enable,
          });
          row.enable = enable;
          this.$message.success("操作成功！");
        })
        .catch(() => {});
    },
    async toDelete(row) {
      const confirm = await this.$confirm(
        `确定要删除题卡规则【${row.name}】吗?`,
        "提示",
        {
          type: "warning",
        }
      ).catch(() => {});
      if (confirm !== "confirm") return;
      await deleteCardRule(row.id);
      this.$message.success("删除成功！");
      this.deletePageLastItem();
    },
  },
};
</script>
