<template>
  <el-dialog
    :visible.sync="modalIsShow"
    title="批量关联"
    top="15vh"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="85px"
    >
      <el-form-item prop="relateType" label="关联类型：">
        <el-select
          v-model="modalForm.relateType"
          placeholder="请选择"
          multiple
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="(item, index) in paperTypes"
            :key="index"
            :value="item"
            :label="`卷${item}`"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { planBatchLinkPaper, planAllRelatePaperTypes } from "../api";

export default {
  name: "print-plan-batch-link-paper",
  props: {
    filterData: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { relateType: [] },
      paperTypes: [],
      rules: {
        relateType: [
          {
            required: true,
            validator: (rule, value, callback) => {
              console.log(value);
              if (!value || !value.length) {
                return callback(new Error("请选择关联类型"));
              }
              callback();
            },
          },
        ],
      },
    };
  },
  methods: {
    visibleChange() {
      this.modalForm.relatePaperType = [];
      this.getPaperTypes();
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async getPaperTypes() {
      const data = await planAllRelatePaperTypes(this.filterData);
      this.paperTypes = data || [];
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let datas = { ...this.filterData, ...this.modalForm };
      let res = true;
      await planBatchLinkPaper(datas).catch(() => {
        res = false;
      });
      this.isSubmit = false;

      if (!res) return;

      this.$message.success("操作成功！");
      this.$emit("modified");
      this.cancel();
    },
  },
};
</script>
