<template>
  <el-dialog
    class="modify-card-rule"
    :visible.sync="modalIsShow"
    title="设置页码规则"
    top="10vh"
    width="950px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="initData"
  >
    <div class="card-title-rule-edit">
      <div class="field-list">
        <div
          v-for="field in fields"
          :key="field.code"
          :class="[
            'field-item',
            {
              'field-item-act': field.selected,
            },
          ]"
          @mousedown="(event) => selectField(field, event)"
        >
          {{ field.name }}（{{ field.code }}）
        </div>
      </div>
      <el-input
        ref="FieldTextarea"
        v-model="content"
        type="textarea"
        resize="none"
        :rows="2"
        placeholder="请输入内容"
        @input="contentChange"
      >
      </el-input>
    </div>

    <div slot="footer">
      <el-button type="primary" @click="submit">确认</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "modify-page-number-rule",
  data() {
    return {
      modalIsShow: false,
      fields: [],
      fieldNameToCode: {},
      fieldCodeToName: {},
      frameWin: null,
      content: "",
      fieldSourses: [
        {
          code: "rootOrgName",
          enable: true,
          name: "学校名称",
        },
        {
          code: "courseName",
          enable: true,
          name: "课程名称",
        },
        {
          code: "courseCode",
          enable: true,
          name: "课程代码",
        },
        {
          code: "pageNumber",
          enable: true,
          name: "页码",
        },
      ],
    };
  },
  computed: {
    ...mapState("paper-export", ["pageConfig"]),
  },
  mounted() {
    this.setFields();
  },
  methods: {
    initData() {
      this.content = this.pageConfig.pageNumberRule || "";
      this.updateFieldStatus();
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    setFields() {
      const selectedCodes = this.fields
        .filter((item) => item.selected)
        .map((item) => item.code);
      this.fields = this.fieldSourses.map((item) => {
        item.selected = selectedCodes.includes(item.code);
        return item;
      });
      this.fields.forEach((field) => {
        this.fieldNameToCode[field.name] = field.code;
        this.fieldCodeToName[field.code] = field.name;
      });
    },
    updateFieldStatus() {
      const rexp = new RegExp(/\$\{.+?\}/, "g");
      const variates = this.content.match(rexp);

      const selectedCodes = variates
        ? variates.map((item) => item.replace("${", "").replace("}", ""))
        : [];
      this.fields = this.fields.map((field) => {
        field.selected = selectedCodes.includes(field.code);
        return field;
      });
    },
    rebuildTextarea() {
      const soursesCodes = this.fieldSourses.map((item) => item.code);
      const deletedCodes = this.fields.filter(
        (item) => item.selected && !soursesCodes.includes(item.code)
      );
      console.log(deletedCodes);
      deletedCodes.forEach((field) => {
        this.content = this.content.replace(`\${${field.code}}`, "");
      });
    },
    selectField(field, event) {
      event.preventDefault();
      field.selected = !field.selected;
      if (field.selected) {
        // 选中
        const variateStr = `\${${field.code}}`;
        const textareaDom = this.$refs.FieldTextarea.$el.children[0];
        const { selectionStart, selectionEnd } = textareaDom;

        this.content =
          this.content.slice(0, selectionStart) +
          variateStr +
          this.content.slice(selectionEnd);
      } else {
        // 取消
        this.content = this.content.replace(`\${${field.code}}`, "");
      }
    },
    contentChange() {
      this.content = this.content.replace("\n", "");
      this.updateFieldStatus();
    },
    submit() {
      if (!this.fields.find((item) => item.code === "pageNumber").selected) {
        this.$message.error("请插入页码");
        return;
      }
      this.$emit("confirm", this.content);
      this.cancel();
    },
  },
};
</script>
