<template>
  <div class="page-wrapper role-add">
    <div class="page-container">
      <a-form-model
        ref="addForm"
        :model="form"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-collapse
          v-model="activeName"
          :bordered="false"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="a" :header="$t('BASE_INFO')">
            <a-row>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('MESSAGE_TEMPLATE_CODE')"
                  prop="templateCode"
                >
                  <a-input v-model="form.templateCode" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('MESSAGE_TEMPLATE_NAME')"
                  prop="templateName"
                >
                  <a-input v-model="form.templateName" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('MESSAGE_TEMPLATE_TITLE')"
                  prop="templateTitle"
                >
                  <a-input v-model="form.templateTitle" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item :label="$t('LANGUAGE')" prop="lang">
                  <a-select v-model="form.lang">
                    <a-select-option
                      v-for="(item, index) in languageList"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('EXTERNAL_CODE')"
                  prop="externalCode"
                >
                  <a-input v-model="form.externalCode" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-model-item
                  :label-col="{ span: 2 }"
                  :wrapper-col="{ span: 22 }"
                  :label="$t('MESSAGE_TEMPLATE_CONTENT')"
                  prop="content"
                >
                  <MegaEditor
                    v-model="form.content"
                    container-id="upgrade-intro"
                    :height="300"
                    :editor-config="editorConfig"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
    </div>
    <div class="page-bottom-op">
      <a-button type="primary" @click="() => handleSave()">
        <Icon type="icon-cur-save_1" :size="18" /> {{ $t("SAVE") }}
      </a-button>
      <a-button @click="() => handleBack()">
        <Icon type="icon-dir-f-rollback" :size="18" /> {{ $t("CANCEL") }}
      </a-button>
    </div>
  </div>
</template>

<script>
import { Icon, RichTextEditor as MegaEditor } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import { fetchFileUrl } from "@/utils/file";

export default {
  components: { MegaEditor, Icon },
  data() {
    return {
      activeName: "a",
      form: {
        id: "",
        templateCode: "",
        templateName: "",
        templateTitle: "",
        lang: "",
        externalCode: "",
        content: "",
      },
      rules: {
        templateName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        templateTitle: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        lang: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
      },
      languageList: [], // 语言列表
      content: "<p>I am Example</p>",
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            server: `${ApiConstant.PREFIX_CORE}/api/sys/file/upload`,
            timeout: 3 * 1000, // 5s
            fieldName: "file",
            headers: {
              "Access-Control-Allow-Origin": "*",
              Authorization: this.$auth.getToken("local"),
              tenantId:
                this.$store.state.app.systemConfig.TENANT_OPEN === "true"
                  ? this.$store.state.account.tenantId
                  : "",
            },
            maxFileSize: 20 * 1024 * 1024, // 2M
            // base64LimitSize: 5 * 1024, // 5kb 以下插入 base64

            onBeforeUpload(files) {
              return files; // 返回哪些文件可以上传
              // return false 会阻止上传
            },
            customInsert(res, insertFn) {
              // res 即服务端的返回结果
              if (res.code === 200) {
                const url = fetchFileUrl(res.data.fileUrl);

                // 从 res 中找到 url alt href ，然后插图图片
                insertFn(url);
              }
            },
          },
        },
      },
    };
  },
  computed: {},
  mounted() {
    this.queryDictData();
  },
  methods: {
    // 获取数据字典数据
    queryDictData() {
      return Promise.all([
        this.getDictByCode(`DIC:MSG:TEMPLATE_LANG`), // 语言列表
      ]).then(([languageRes]) => {
        this.languageList = languageRes.data.data;
      });
    },
    handleSave() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          const insertStr = (soure, start, newStr) => {
            return soure.slice(0, start) + newStr + soure.slice(start);
          };
          if (this.form.content && this.form.content.includes("<table")) {
            this.form.content = insertStr(
              this.form.content,
              this.form.content.indexOf("<table") + 7,
              "border='1' "
            );
          }
          const req = {
            ...this.form,
          };
          this.$axios
            .post(`${ApiConstant.PREFIX_CORE}/api/msg/template`, req)
            .then((res) => {
              this.$message.success(this.$t("ADD_SUCCESS"));
              this.handleBack();
            });
        }
      });
    },
    handleBack() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: { path: "/upms/service/message/messageTemplate" },
        vm: this,
      });
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.ck-editor__editable {
  height: 350px;
  max-height: 350px !important;
}
</style>
