<template>
  <div class="card-head-edit">
    <div class="part-box">
      <div class="part-box-header">
        <h2 class="part-box-title">版头模板预选设置</h2>
        <el-button type="danger" plain icon="icon icon-back" @click="goback"
          >返回</el-button
        >
      </div>
      <el-form
        ref="modalFormComp"
        class="padding-tb-20"
        label-width="140px"
        :rules="rules"
        :model="modalForm"
      >
        <el-form-item prop="name" label="版头名称：">
          <el-input
            v-model.trim="modalForm.name"
            placeholder="请输入版头名称"
            maxlength="255"
            style="width: 100%"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="title" label="题卡标题：">
          <el-input
            v-model="modalForm.title"
            maxlength="255"
            type="textarea"
            :rows="2"
          ></el-input>
        </el-form-item>
        <el-form-item prop="attention" label="注意事项：">
          <el-input
            v-model="modalForm.attention"
            maxlength="1000"
            type="textarea"
            :rows="4"
          ></el-input>
          <p class="tips-info">
            提示：换行之后，题卡注意事项会展示为多条内容，内容序号会被自动添加。
          </p>
        </el-form-item>
        <el-form-item prop="objectiveAttention" label="客观题注意事项：">
          <el-input
            v-model="modalForm.objectiveAttention"
            maxlength="1000"
            placeholder="请输入"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="subjectiveAttention" label="主观题注意事项：">
          <el-input
            v-model="modalForm.subjectiveAttention"
            maxlength="1000"
            placeholder="请输入"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="pageSize" label="纸张类型：">
          <el-select
            v-model="modalForm.pageSize"
            placeholder="请选择纸张类型"
            @change="pageSizeChange"
          >
            <el-option
              v-for="item in PAPER_SIZE_TYPE"
              :key="item"
              :value="item"
              :label="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="cardTemplateId" label="模板选择">
          <div class="template-list">
            <div
              v-for="item in templateList"
              :key="item.id"
              :class="[
                'template-item',
                { 'is-active': modalForm.cardTemplateId === item.id },
              ]"
            >
              <div class="template-item-body">
                <img :src="item.imgSrc" :alt="item.name" />
                <div class="template-item-action">
                  <el-button type="success" @click="viewTemplate(item)"
                    >预览</el-button
                  >
                  <el-button type="primary" @click="selectTemplate(item)"
                    >使用</el-button
                  >
                </div>
              </div>
              <p class="template-item-title">{{ item.name }}</p>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <div class="margin-top-20 text-center">
        <el-button type="primary" :loading="isSubmit" @click="submit"
          >保存</el-button
        >
      </div>
    </div>

    <!-- PreviewCardTemplate -->
    <preview-card-template
      ref="PreviewCardTemplate"
      :image-list="imageList"
    ></preview-card-template>
  </div>
</template>

<script>
import {
  cardHeadDetailApi,
  cardHeadUpdateApi,
  cardTemplateListApi,
} from "../api";
import PreviewCardTemplate from "../components/PreviewCardTemplate.vue";
import { PAPER_SIZE_TYPE } from "../enumerate";

const initModalForm = {
  id: null,
  name: "",
  title: "",
  attention: "",
  objectiveAttention: "",
  subjectiveAttention: "",
  pageSize: "A3",
  cardTemplateId: null,
};

export default {
  name: "CardHeadEdit",
  components: { PreviewCardTemplate },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      isSubmit: false,
      loading: false,
      cardHeadId: this.$route.params.cardHeadId,
      templates: [],
      modalForm: { ...initModalForm },
      PAPER_SIZE_TYPE,
      rules: {
        name: [
          {
            required: true,
            message: "请输入版头名称",
            trigger: "change",
          },
          {
            message: "版头名称不能超过50个字",
            max: 50,
            trigger: "change",
          },
        ],
        title: [
          {
            required: true,
            message: "请输入题卡标题",
            trigger: "change",
          },
          {
            validator: (rule, value, callback) => {
              const vals = value.split(/\n/);
              if (vals.length > 2) {
                callback(new Error("题卡标题只能换行一次"));
              } else if (vals.some((item) => item.length > 26)) {
                callback(new Error("题卡标题每行最多只允许输入26个字符"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        attention: [
          {
            required: true,
            message: "请输入注意事项",
            trigger: "change",
          },
          {
            validator: (rule, value, callback) => {
              const val = value.replace(/\n/g, "");
              if (val.length > 200) {
                callback(new Error("注意事项最多只能输入200个字符"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        objectiveAttention: [
          {
            required: true,
            message: "请输入客观题注意事项",
            trigger: "change",
          },
          {
            max: 26,
            message: "客观题注意事项最多只能输入26个汉字",
            trigger: "change",
          },
        ],
        subjectiveAttention: [
          {
            required: true,
            message: "请输入主观题注意事项",
            trigger: "change",
          },
          {
            max: 26,
            message: "主观题注意事项最多只能输入26个汉字",
            trigger: "change",
          },
        ],
        pageSize: [
          {
            required: true,
            message: "请选择纸张类型",
            trigger: "change",
          },
        ],
        cardTemplateId: [
          {
            required: true,
            message: "请选择模板",
            trigger: "change",
          },
        ],
      },
      imageList: [],
    };
  },
  computed: {
    templateList() {
      return this.templates.filter(
        (item) => item.pageSize === this.modalForm.pageSize
      );
    },
  },
  mounted() {
    this.initData();
    this.getTemplates();
  },
  methods: {
    async initData() {
      if (this.cardHeadId) {
        this.loading = true;
        const res = await cardHeadDetailApi(this.cardHeadId);
        this.modalForm = { ...res.data };
      } else {
        this.modalForm = { ...initModalForm };
      }
    },
    async getTemplates() {
      const res = await cardTemplateListApi();
      const dataList = res.data || [];
      this.templates = dataList.map((item) => {
        item.imgSrc = item.imagePath[0];
        return item;
      });
    },
    viewTemplate(item) {
      this.imageList = item.imagePath;
      this.$refs.PreviewCardTemplate.open();
    },
    selectTemplate(item) {
      this.modalForm.cardTemplateId = item.id;
      this.$refs.modalFormComp.validateField("cardTemplateId");
    },
    pageSizeChange() {
      this.modalForm.cardTemplateId = "";
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let datas = {
        ...this.modalForm,
      };
      const data = await cardHeadUpdateApi(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

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