<template>
  <div class="info-print-plan">
    <el-form
      ref="modalFormComp"
      label-width="120px"
      :rules="rules"
      :model="modalForm"
      label-position="left"
    >
      <div class="part-box">
        <h4 class="part-box-tips">
          试卷&题卡印品：
          <el-checkbox
            v-show="infoShow"
            v-model="allSelected"
            label="全选"
            @change="selectAll"
          ></el-checkbox>
        </h4>
        <el-form-item prop="printContent" label="试卷、题卡：">
          <el-checkbox-group
            v-model="modalForm.printContent"
            @change="() => checkSelectAll()"
          >
            <el-checkbox
              v-for="(val, key) in PRINT_CONTENT_TYPE"
              :key="key"
              :label="key"
              >{{ val }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          v-if="modalForm.printContent.length"
          prop="backupMethod"
          label="备用数量："
        >
          <el-select
            v-model="modalForm.backupMethod"
            class="mr-2"
            size="small"
            placeholder="请选择"
          >
            <el-option
              v-for="(val, key) in PAPER_BACKUP_TYPE"
              :key="key"
              :value="key"
              :label="val"
            ></el-option>
          </el-select>
          <el-input-number
            class="mr-1"
            v-model="modalForm.backupCount"
            size="small"
            :min="0"
            :max="200"
            :step="1"
            step-strictly
            :controls="false"
            style="width: 60px"
          ></el-input-number>
          <span>份</span>
        </el-form-item>
        <el-form-item
          v-show="infoShow"
          v-if="contentIncludesPaper"
          prop="drawRule"
          label="抽卷规则："
        >
          <el-radio-group v-model="modalForm.drawRule">
            <el-radio
              v-for="(val, key) in DRAW_RULE_TYPE"
              :label="key"
              :key="key"
              >{{ val }}</el-radio
            >
          </el-radio-group>
          <p class="tips-info">
            1.只抽取一次：不同印刷计划下，同一试卷编号下的卷型只能被抽取一次；
          </p>
          <p class="tips-info">
            2.可反复抽取：不同印刷计划下，同一试卷编号下的卷型可重复抽取，系统默认优先抽取未曝光卷型。
          </p>
        </el-form-item>
      </div>

      <div class="part-box" v-show="infoShow">
        <h4 class="part-box-tips">变量印品：</h4>
        <el-form-item
          v-for="(item, index) in modalForm.variableContent"
          :key="item.type"
          :label="`${TEMPLATE_CLASSIFY[item.type]}：`"
          :prop="`variableContent.${index}.templateId`"
          :rules="{
            required: false,
            validator: templateValidator,
            trigger: 'change'
          }"
          :required="!!item.templateId.length"
        >
          <el-checkbox-group
            v-model="item.templateId"
            @change="vals => tempChange(vals, `variableContent.${index}`)"
          >
            <el-checkbox
              v-for="temp in templateSources[item.type]"
              :label="temp.id"
              :key="temp.id"
              >{{ temp.name }}</el-checkbox
            >
          </el-checkbox-group>
          <div v-if="item.templateId.length">
            <el-select
              v-model="item.backupMethod"
              class="mr-2"
              size="small"
              placeholder="请选择"
            >
              <el-option
                v-for="(val, key) in PRINT_BACKUP_TYPE"
                :key="key"
                :value="key"
                :label="val"
              ></el-option>
            </el-select>
            <el-input-number
              v-model="item.backupCount"
              class="mr-1"
              size="small"
              :min="1"
              :max="200"
              :step="1"
              step-strictly
              :controls="false"
              style="width: 60px"
            ></el-input-number>
            <span>份</span>
          </div>
        </el-form-item>
      </div>

      <div class="part-box" v-show="infoShow">
        <h4 class="part-box-tips">普通印品：</h4>
        <el-form-item
          v-for="(item, index) in modalForm.ordinaryContent"
          :key="item.type"
          :label="`${TEMPLATE_CLASSIFY[item.type]}：`"
          label-width="130px"
          :prop="`ordinaryContent.${index}.templateId`"
          :rules="{
            required: false,
            validator: templateValidator,
            trigger: 'change'
          }"
          :required="!!item.templateId.length"
        >
          <el-checkbox-group
            v-model="item.templateId"
            @change="vals => tempChange(vals, `ordinaryContent.${index}`)"
          >
            <el-checkbox
              v-for="temp in templateSources[item.type]"
              :label="temp.id"
              :key="temp.id"
              >{{ temp.name }}</el-checkbox
            >
          </el-checkbox-group>
          <div v-if="item.templateId.length">
            <el-select
              v-model="item.backupMethod"
              class="mr-2"
              size="small"
              placeholder="请选择"
            >
              <el-option
                v-for="(val, key) in PRINT_BACKUP_TYPE"
                :key="key"
                :value="key"
                :label="val"
              ></el-option>
            </el-select>
            <el-input-number
              v-model="item.backupCount"
              class="mr-1"
              size="small"
              :min="1"
              :max="200"
              :step="1"
              step-strictly
              :controls="false"
              style="width: 60px"
            ></el-input-number>
            <span>份</span>
          </div>
        </el-form-item>
      </div>

      <el-form-item prop="selectedPrint"></el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  PRINT_CONTENT_TYPE,
  DRAW_RULE_TYPE,
  PRINT_BACKUP_TYPE,
  PAPER_BACKUP_TYPE,
  TEMPLATE_CLASSIFY
} from "@/constants/enumerate";
import { deepCopy } from "@/plugins/utils";

export default {
  name: "info-print-plan",
  props: {
    datas: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    const printContentValidator = (rule, value, callback) => {
      if (!this.modalForm.printContent.length) {
        return callback(new Error("请选择试卷"));
      }

      callback();
    };
    const backupMethodValidator = (rule, value, callback) => {
      if (!this.modalForm.printContent.length) {
        return callback();
      }
      if (!value) {
        return callback(new Error("请选择备份方式"));
      }
      if (!this.modalForm.backupCount && this.modalForm.backupCount !== 0) {
        return callback(new Error("请输入备份数量"));
      }

      callback();
    };
    const selectedPrintValidator = (rule, value, callback) => {
      const printInfo = [
        ...this.modalForm.variableContent,
        ...this.modalForm.ordinaryContent
      ];
      const hasPrintInfo = printInfo.some(item => item.templateId.length);

      if (hasPrintInfo || this.modalForm.printContent.length) {
        callback();
      } else {
        callback(new Error("必须选择一项印品"));
      }
    };
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: {},
      createTime: [],
      PRINT_CONTENT_TYPE,
      // PRINT_CONTENT_TYPE: {
      //   PAPER: "试卷"
      // },
      DRAW_RULE_TYPE,
      PRINT_BACKUP_TYPE,
      PAPER_BACKUP_TYPE,
      TEMPLATE_CLASSIFY,
      variableContent: [],
      ordinaryContent: [],
      templateSources: {},
      oldPrintContent: [],
      allSelected: false,
      infoShow: false,
      rules: {
        printContent: [
          {
            required: true,
            validator: printContentValidator,
            trigger: "change"
          }
        ],
        backupMethod: [
          {
            required: true,
            validator: backupMethodValidator,
            trigger: "change"
          }
        ],
        drawRule: [
          {
            required: true,
            message: "请选择抽卷规则",
            trigger: "change"
          }
        ],
        selectedPrint: [
          {
            required: false,
            validator: selectedPrintValidator,
            trigger: "change"
          }
        ]
      }
    };
  },
  computed: {
    contentIncludesPaper() {
      return this.modalForm.printContent.includes("PAPER");
    }
  },
  created() {
    this.initData();
  },
  methods: {
    async initData() {
      const val = this.datas.printPlan;
      this.modalForm = deepCopy(val);
      this.templateSources = val.templateSources;
      const transformInfo = item => {
        const templateIds = item.templateId ? [item.templateId] : [];
        return {
          type: item.type,
          templateId: templateIds,
          oldTemplateId: templateIds,
          backupMethod: item.backupMethod,
          backupCount: item.backupCount
        };
      };
      this.modalForm.variableContent = val.variableContent.map(transformInfo);
      this.modalForm.ordinaryContent = val.ordinaryContent.map(transformInfo);

      if (!this.checkHasSelect()) {
        this.allSelected = true;
        this.selectAll(this.allSelected);
      } else {
        this.checkSelectAll();
      }
      this.$emit("on-ready");
    },
    async checkData() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) {
        this.$emit("on-ready");
        return;
      }

      this.updateData();
      this.$emit("next-step");
    },
    getData() {
      const printPlan = { ...this.modalForm };
      const transformInfo = item => {
        const templateId = item.templateId.join();
        const template = this.templateSources[item.type].find(
          temp => temp.id === templateId
        );
        return {
          type: item.type,
          templateId,
          attachmentId: template && template.attachmentId,
          backupMethod: item.backupMethod,
          backupCount: item.backupCount
        };
      };
      printPlan.variableContent = this.modalForm.variableContent.map(
        transformInfo
      );
      printPlan.ordinaryContent = this.modalForm.ordinaryContent.map(
        transformInfo
      );

      return { printPlan };
    },
    updateData() {
      this.$emit("data-change", this.getData());
    },
    selectAll(selected) {
      if (selected) {
        this.modalForm.printContent = Object.keys(this.PRINT_CONTENT_TYPE);
        this.modalForm.variableContent.forEach(item => {
          if (item.templateId && item.templateId.length) return;

          const source = this.templateSources[item.type][0];
          item.templateId = source && [source.id];
          item.oldTemplateId = source && [source.id];
        });
        this.modalForm.ordinaryContent.forEach(item => {
          if (item.templateId && item.templateId.length) return;

          const source = this.templateSources[item.type][0];
          item.templateId = source && [source.id];
          item.oldTemplateId = source && [source.id];
        });
      } else {
        this.modalForm.printContent = [];
        this.modalForm.variableContent.forEach(item => {
          item.templateId = [];
          item.oldTemplateId = [];
        });
        this.modalForm.ordinaryContent.forEach(item => {
          item.templateId = [];
          item.oldTemplateId = [];
        });
      }
    },
    checkSelectAll() {
      const vNotSelected = this.modalForm.variableContent.some(
        item => !item.templateId.length
      );
      const oNotSelected = this.modalForm.ordinaryContent.some(
        item => !item.templateId.length
      );
      const pNotSelected =
        this.modalForm.printContent.length <
        Object.keys(this.PRINT_CONTENT_TYPE).length;

      const selecteds = [vNotSelected, oNotSelected, pNotSelected];

      this.allSelected = !selecteds.some(item => item);
    },
    checkHasSelect() {
      const vSelected = this.modalForm.variableContent.some(
        item => item.templateId.length
      );
      const oSelected = this.modalForm.ordinaryContent.some(
        item => item.templateId.length
      );
      const pSelected = !!this.modalForm.printContent.length;

      const selecteds = [vSelected, oSelected, pSelected];

      return selecteds.some(item => item);
    },
    templateValidator(rule, value, callback) {
      const [field, index] = rule.field.split(".");
      const val = this.modalForm[field][index];
      if (val.templateId.length) {
        if (!val.backupMethod) {
          return callback(new Error("请选择备份方式"));
        }
        if (!val.backupCount) {
          return callback(new Error("请输入备份数量"));
        }
        callback();
      } else {
        callback();
      }
    },
    tempChange(vals, name) {
      const [field, index] = name.split(".");
      const info = this.modalForm[field][index];
      const newVals = vals.filter(item => !info.oldTemplateId.includes(item));
      info.templateId = newVals;
      info.oldTemplateId = newVals;

      this.checkSelectAll();
      this.$refs.modalFormComp.validateField("selectedPrint");
    }
  }
};
</script>
