<template>
  <div class="page-wrapper role-add">
    <div class="page-container">
      <a-form-model
        ref="addForm"
        :model="form"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <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('NOTICE_CODE')"
                  prop="noticeCode"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                >
                  <a-input v-model="form.noticeCode" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('NOTICE_TITLE')"
                  prop="noticeTitle"
                >
                  <a-input v-model="form.noticeTitle" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('NOTICE_CATEGORY')"
                  prop="noticeCategory"
                >
                  <a-select v-model="form.noticeCategory">
                    <a-select-option
                      v-for="(item, index) in noticeCategoryList"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="12">
                <a-form-model-item :label="$t('TYPE')" prop="noticeType">
                  <a-select v-model="form.noticeType">
                    <a-select-option
                      v-for="(item, index) in typeList"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col> -->
            </a-row>
            <a-row>
              <!-- <a-col :span="12">
                <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-row>
            <!-- <a-row>
              <a-col :span="12">
                <a-form-model-item
                  :label="$t('EQP_EXPIRES')"
                  prop="time"
                  :label-col="{ span: 4 }"
                  :wrapper-col="{ span: 20 }"
                >
                  <a-range-picker v-model="form.time" style="width: 100%" />
                </a-form-model-item>
              </a-col>
            </a-row> -->
            <a-row>
              <a-col :span="16">
                <a-form-model-item
                  :label="$t('ATTACHMENT')"
                  :label-col="{ span: 3 }"
                  :wrapper-col="{ span: 18 }"
                >
                  <a-upload
                    name="file"
                    :action="url"
                    :headers="headers"
                    :multiple="true"
                    :file-list="fileList"
                    @change="handleChange"
                  >
                    <div style="display: flex">
                      <a-button icon="upload">
                        {{ $t("SELECT_FILE") }}
                      </a-button>
                      <a-alert
                        :message="`${$t('UPLOAD_FILE_CANNOT_EXCEED')}5${$t(
                          'PCS'
                        )}`"
                        banner
                        style="margin-left: 10px"
                      />
                    </div>
                  </a-upload>
                </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('NOTICE_CONTENT')"
                  prop="content"
                >
                  <MegaEditor
                    ref="upgrade-intro-editor"
                    v-model="form.content"
                    container-id="upgrade-intro"
                    :height="400"
                    :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 { v1 as uuidv1 } from "uuid";
import { Icon, RichTextEditor as MegaEditor } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import { fetchFileUrl } from "@/utils/file";

export default {
  components: { Icon, MegaEditor },
  data() {
    return {
      url: `${ApiConstant.PREFIX_CORE}/api/sys/file/upload`, // 上传文件路径
      headers: {
        Authorization: this.$auth.getToken("local"),
        tenantId:
          this.$store.state.app.systemConfig.TENANT_OPEN === "true"
            ? this.$store.state.account.tenantId
            : "",
      },
      limit: 5,
      activeName: "a",
      fileList: [], //  文件的列表
      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);
              }
            },
          },
        },
      },
      form: {
        id: "",
        noticeCode: "",
        noticeTitle: "",
        noticeCategory: "",
        content: "",
        noticeAttachMentList: [],
      },
      noticeCategoryList: [],
      typeList: [],
      isFileUpdate: false,
      rules: {
        noticeTitle: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        noticeCategory: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
        content: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.$refs["upgrade-intro-editor"].editor.isEmpty()) {
                callback(new Error(this.$t("PLACEENTER")));
              }
              callback();
            },
            trigger: "change",
          },
        ],
      },
      languageList: [], // 语言列表
      isClear: false,
    };
  },
  mounted() {
    this.queryDictData();
  },
  methods: {
    handleChange(info) {
      let fileList = [...info.fileList];
      // 1. Limit the number of uploaded files
      //    Only to show two recent uploaded files, and old ones will be replaced by the new
      if (fileList.length > this.limit) {
        this.$message.warning(
          this.$t("UPLOAD_FILE_CANNOT_EXCEED") + this.limit + this.$t("PCS")
        );
        fileList = fileList.filter((e, i) => Boolean(e.uid) && i < this.limit);
      }
      this.$set(this, "fileList", fileList);
    },
    // 获取数据字典数据
    queryDictData() {
      return Promise.all([
        this.getDictByCode(`DIC:MSG:TEMPLATE_LANG`), // 语言列表
        this.getDictByCode(`DIC:MSG:NOTICE_TYPE`), // 类型
        this.getDictByCode(`DIC:MSG:NOTICE_CATEGORY`), // 公告类别
      ]).then(([languageRes, typeRes, noticeCategoryRes]) => {
        this.languageList = languageRes.data.data;
        this.typeList = typeRes.data.data;
        this.noticeCategoryList = noticeCategoryRes.data.data;
      });
    },
    handleSave() {
      const arr = [];
      this.fileList.forEach((item) => {
        arr.push({
          fileCode: item.response?.data?.fileCode,
          fileName: item.response?.data?.fileName,
          fileUrl: item.response?.data?.fileUrl,
        });
      });
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.form.noticeAttachMentList = arr;
          const req = {
            ...this.form,
            effectiveStartDate: this.form.time?.length
              ? this.formatDate(this.form.time?.length && this.form.time[0]) ||
                null
              : null,
            effectiveEndDate: this.form.time?.length
              ? this.formatDate(this.form.time?.length && this.form.time[1]) ||
                null
              : null,
          };
          delete req.time;
          this.$axios
            .post(`${ApiConstant.PREFIX_CORE}/api/notice`, req)
            .then((res) => {
              this.$message.success(this.$t("ADD_SUCCESS"));
              this.handleBack();
            });
        }
      });
    },
    formatDate(value) {
      const date = new Date(value);
      const y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? `0${MM}` : MM;
      let d = date.getDate();
      d = d < 10 ? `0${d}` : d;
      return `${y}-${MM}-${d}`;
    },
    handleBack() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: { path: "/upms/service/message/notice" },
        vm: this,
      });
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.ck-editor__editable {
  height: 350px;
  max-height: 350px !important;
}
</style>
