<template>
  <!-- doc文档的新增或更新笔记-->
  <el-dialog
    :title="formData.id ? '编辑笔记' : '新增笔记'"
    :visible.sync="dialogVisible"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :append-to-body="true"
  >
    <el-form
      :model="form"
      label-width="80px"
      :rules="rules"
      ref="form"
      size="mini"
    >
      <el-form-item label="原文" prop="bookmarkContent">
        <el-input
          type="textarea"
          rows="5"
          v-model="form.bookmarkContent"
          disabled
        ></el-input>
      </el-form-item>
      <el-form-item label="笔记" prop="noteContent">
        <el-input
          placeholder="请输入笔记"
          v-model="form.noteContent"
          type="textarea"
          rows="5"
        ></el-input>
      </el-form-item>
      <el-form-item label="标签" disabled style="width: 100%">
        <el-select
          style="width: 100%"
          v-model="form.tagsArr"
          multiple
          filterable
          remote
          default-first-option
          allow-create
          placeholder="请输入文章标签"
          :remote-method="remoteMethod"
          :loading="loading"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标记方式">
        <el-radio-group v-model="subtype">
          <el-radio
            :label="item.value"
            v-for="(item, index) in subtypes"
            :key="index"
          >
            <svg-icon
              icon-class="underline"
              style="margin-right: 4px"
            ></svg-icon
            >{{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="标记颜色">
        <el-row class="color-container">
          <el-col
            @click.native="handleClickColor(item)"
            :span="6"
            v-for="(item, index) in colors"
            :key="index"
            :class="[
              `color-item`,
              currentColor == getColor(item) ? 'active' : '',
            ]"
            :style="{ background: `rgb(${getColor(item)})` }"
          ></el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <div class="buttons">
          <el-button
            style="width: 100%"
            type="primary"
            size="mini"
            @click.native="handleSubmitAddNote"
            >提交</el-button
          >
          <el-button
            style="width: 100%"
            size="mini"
            type="text"
            @click="handleCancelSubmit"
            >取消</el-button
          >
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { addOrUpdateNoteDoc } from "@/api/doc/bookMark";
import { tagSuggest } from "@/api/doc/tag";
import { colors } from "./colors";
import { Annotation } from "@/components/PdfViewer/util";
export default {
  props: {
    formData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      dialogVisible: false, //新建笔记窗口可见性
      form: {
        id: "", //笔记ID，新增时没有
        docId: "", //文档ID
        docSType: "", //文档类型
        bookmarkContent: "", //原文
        noteContent: "", //笔记
        tagsArr: "", //标签，提交给后台的时候使用多个用逗号分割
        jsonStr: {
          subtype: "Underline", //标记方式
          color: [255, 0, 0], //标记颜色
          annotationType: 10, //标记方式
        },
        type: "note", //	笔记类型，新增时必传，[underline-下划线,note-笔记,highlight-高亮]
        offset: "0", //偏移量，新增时必传
        sectionId: "0", //父节点ID，新增时必传
      },
      subtypes: [
        {
          label: "下划线",
          value: "Underline",
        },
        {
          label: "高亮",
          value: "Highlight",
        },
        // {
        //   label: "删除线",
        //   value: "StrikeOut",
        // },
      ],
      subtype: "Underline",
      options: [], //标签可选项
      rules: {
        bookmarkContent: [
          {
            required: true,
            message: "请输入原文",
            trigger: "change",
          },
        ],
        noteContent: [
          {
            required: true,
            message: "请输入笔记",
            trigger: "change",
          },
        ],
      },
      loading: false,
      currentColor: [255, 255, 0],
      colors,
    };
  },
  computed: {
    getColor(item) {
      return (item) => {
        let str = item.join(",");
        return str.substring(0, str.length);
      };
    },
  },
  watch: {
    formData: {
      handler(value) {
        this.form = { ...this.form, ...value };
        const { jsonStr } = this.form;
        // 解析从后台穿过来的json串，如果没有值则需要给默认值
        if (jsonStr && typeof jsonStr == "string") {
          this.form.jsonStr = JSON.parse(jsonStr);
        }
        this.currentColor = this.form.jsonStr.color; //回显颜色
        this.subtype = this.form.jsonStr.subtype; //回显标记方式
      },
      deep: true,
      immediate: true,
    },
  },

  methods: {
    //提交新增笔记
    handleSubmitAddNote() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const formData = new FormData();
          const { jsonStr } = this.form;
          const annotation = new Annotation(jsonStr);
          const { currentColor, subtype } = this;
          let jsonStrCopy = JSON.parse(JSON.stringify(this.form.jsonStr));
          jsonStrCopy = Object.assign(jsonStrCopy, {
            color: currentColor,
            annotationType: annotation.getType(subtype),
            subtype,
          });
          this.form.jsonStr = JSON.stringify(jsonStrCopy); //字符串化jsonStr,传给后台的是json字符串
          for (const key in this.form) {
            if (key == "tagsArr") {
              formData.append("tags", this.form.tagsArr.join(","));
            } else if (key == "id") {
              // 只有id有值的时候才append
              if (this.form.id != "") {
                formData.append("id", this.form.id);
              }
            } else {
              formData.append(key, this.form[key]);
            }
          }
          let res = await addOrUpdateNoteDoc(formData);
          this.loading = false;
          if (res.code == 200) {
            this.$message.success("操作成功！");
            this.dialogVisible = false;
            this.$emit("update");
            this.$refs.form.resetFields();
          }
          // 清空表单项
        }
      });
    },

    //取消新增笔记
    handleCancelSubmit() {
      this.dialogVisible = false;
      this.$refs.form.resetFields();
    },
    // 远程搜索标签
    remoteMethod(keyword) {
      if (keyword !== "") {
        this.loading = true;
        const params = {
          keyword,
        };
        tagSuggest(params).then((res) => {
          this.loading = false;
          if (res.code == 200) {
            this.options = res.data.map((item) => {
              return {
                label: item.tagName,
                value: item.id,
              };
            });
          }
        });
      } else {
        this.options = [];
      }
    },
    // 点击选择颜色
    handleClickColor(color) {
      this.currentColor = color;
      console.log("this.currentColor", this.currentColor);
    },
  },
};
</script>

<style lang="scss" scoped>
.buttons {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 16px;
  .el-button + .el-button {
    margin-left: 0;
    margin-top: 10px;
  }
}
.color-container {
  .color-item {
    width: 20px;
    height: 20px;
    margin: 0 8px 8px 0;
    border: 2px solid transparent;
    cursor: pointer;
    &:hover {
      border: 2px solid #666;
    }
  }
  .active {
    border: 2px solid #666;
  }
}
</style>
