<template>
  <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, 'field-item-disabled': disabled },
        ]"
        @mousedown="(event) => selectField(field, event)"
      >
        {{ field.name }}（{{ field.code }}）
      </div>
    </div>
    <el-input
      ref="FieldTextarea"
      v-model="content"
      placeholder="请输入内容"
      :disabled="disabled"
      @input="contentChange"
    >
    </el-input>
  </div>
</template>

<script>
export default {
  name: "card-title-rule-edit",
  props: {
    value: {
      type: String,
      default: "",
    },
    fieldSourses: {
      type: Array,
      default() {
        return [];
      },
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      fields: [],
      fieldNameToCode: {},
      fieldCodeToName: {},
      frameWin: null,
      content: "",
    };
  },
  watch: {
    fieldSourses: {
      immediate: true,
      handler(val) {
        this.rebuildTextarea();
        this.setFields(val);
        this.updateFieldStatus();
      },
    },
    value: {
      immediate: true,
      handler(val) {
        // if (!val) return;
        this.content = val;
        this.updateFieldStatus();
      },
    },
  },
  methods: {
    setFields(data) {
      const selectedCodes = this.fields
        .filter((item) => item.selected)
        .map((item) => item.code);
      this.fields = data.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) {
      if (this.disabled) return;
      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}}`, "");
      }
      this.contentChange();
    },
    contentChange() {
      this.$emit("input", this.content);
      this.$emit("change", this.content);
    },
  },
};
</script>
