<template>
  <div class="rule-package part-box part-box-pad">
    <h4 class="part-box-tips">卷袋贴字段配置：</h4>
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="170px"
    >
      <el-form-item prop="packageScope" label="卷袋贴显示字段：">
        <rule-field-edit
          v-model="modalForm.packageScope"
          :data="fieldSources"
          @change="validateField('packageScope')"
        ></rule-field-edit>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :disabled="isSubmit"
          style="width: 140px"
          @click="submit"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { examRuleDetail, saveExamRule } from "../api";
import RuleFieldEdit from "./RuleFieldEdit.vue";

export default {
  name: "rule-package",
  components: {
    RuleFieldEdit,
  },
  data() {
    return {
      isSubmit: false,
      examRule: {},
      fieldSources: [],
      modalForm: {
        packageScope: [],
      },
      rules: {
        packageScope: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value || !value.length) {
                return callback(new Error(`请选择卷袋贴显示字段`));
              }

              callback();
            },
            trigger: "change",
          },
        ],
      },
    };
  },
  mounted() {
    this.getFields();
  },
  methods: {
    async getFields() {
      const examRule = await examRuleDetail();
      this.examRule = examRule;
      let fields = [...JSON.parse(examRule.requiredFields)];
      if (examRule.extendFields)
        fields.push(...JSON.parse(examRule.extendFields));

      this.fieldSources = fields
        .filter((item) => item.enable)
        .map((item) => {
          return {
            code: item.code,
            name: item.name,
          };
        });

      const packageScope = examRule.packageScope
        ? JSON.parse(examRule.packageScope)
        : { basic: [] };
      this.modalForm.packageScope = packageScope.basic;
    },
    validateField(field) {
      this.$refs.modalFormComp.validateField(field, () => {});
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      this.examRule.packageScope = JSON.stringify({
        title: [
          {
            code: "semesterName",
            name: "学期",
            disabled: false,
            enable: false,
          },
        ],
        basic: this.modalForm.packageScope,
      });
      const data = await saveExamRule(this.examRule).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.$message.success("保存成功！");
    },
  },
};
</script>
