<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" disabled />
                </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('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('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="effectiveStartDate"
                  :label-col="{ span: 4 }"
                  :wrapper-col="{ span: 20 }"
                >
                  <a-range-picker
                    value-format="yyyy-MM-dd"
                    :value="defaultValue"
                    style="width: 100%"
                    @change="handChange"
                  />
                </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 }"
                >
                  <mega-uploader
                    ref="MegaUploader"
                    :options="upLoadOptions"
                    :file-list="fileList"
                    :allow-duplicate-uploads="true"
                    @fileRemoved="fileRemoved"
                    @filesAdded="filesAdded"
                    @fileSuccess="fileSuccess"
                  >
                    <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>
                  </mega-uploader>
                </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"
                >
                  <editor-bar
                    v-model="form.content"
                    :is-clear="isClear"
                    @returnData="getReturnData"
                  ></editor-bar>
                </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 moment from "moment";
import { v1 as uuidv1 } from "uuid";
import { Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import EditorBar from "./components/editor";

export default {
  components: { EditorBar, Icon },
  data() {
    return {
      upLoadOptions: {
        target: `${ApiConstant.PREFIX_CORE}/api/sys/file/upload/chunk`,
        simultaneousUploads: 1,
        headers: {
          Authorization: this.$auth.getToken("local"),
          tenantId:
            this.$store.state.app.systemConfig.TENANT_OPEN === "true"
              ? this.$store.state.account.tenantId
              : "",
        },
      },
      activeName: "a",
      fileList: [], //  文件的列表
      form: {
        id: "",
        noticeTitle: "",
        // noticeType: "",
        noticeCategory: "",
        // lang: "",
        // effectiveStartDate: "",
        // effectiveEndDate: "",
        content: "",
        noticeAttachMentList: [],
      },
      defaultValue: [],
      noticeCategoryList: [],
      typeList: [],
      isFileUpdate: false,
      rules: {
        noticeTitle: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        // noticeType: [
        //   {
        //     required: true,
        //     message: this.$t("PLACEENTER"),
        //     trigger: "change",
        //   },
        // ],
        noticeCategory: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
        content: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        // lang: [
        //   {
        //     required: true,
        //     message: this.$t("PLACEENTER"),
        //     trigger: "change",
        //   },
        // ],
        // effectiveStartDate: [
        //   {
        //     required: true,
        //     message: this.$t("PLACEENTER"),
        //     trigger: "change",
        //   },
        // ],
      },
      languageList: [], // 语言列表
      editorOption: {
        // some quill options
        modules: {
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"], // toggled buttons
              ["blockquote", "code-block"],
              ["link", "image"],

              [{ header: 1 }, { header: 2 }], // custom button values
              [{ list: "ordered" }, { list: "bullet" }],
              [{ script: "sub" }, { script: "super" }], // superscript/subscript
              [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
              [{ direction: "rtl" }], // text direction

              [{ size: ["small", false, "large", "huge"] }], // custom dropdown
              [{ header: [1, 2, 3, 4, 5, 6, false] }],

              [{ color: [] }, { background: [] }], // dropdown with defaults from theme
              [{ font: [] }],
              [{ align: [] }],

              ["clean"], // remove formatting button
            ],
            handlers: {
              image() {
                this.quill.format("image", false); // 禁用quill内部上传图片方法
                // eslint-disable-next-line no-restricted-globals
                self.imgHandler(this);
              },
            },
          },
        },
      },
      isClear: false,
    };
  },
  mounted() {
    this.form.id = this.$route.query.id || "";
    this.queryDictData();
    this.getData();
  },
  methods: {
    getData() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/notice/get-by-id/${this.form.id}`)
        .then((res) => {
          this.form = { ...res?.data?.data };
          // this.defaultValue = [
          //   moment(this.form.effectiveStartDate, "YYYY-MM-DD"),
          //   moment(this.form.effectiveEndDate, "YYYY-MM-DD"),
          // ];
          this.fileList = [];
          res.data?.data?.noticeAttachMentList.forEach((item) => {
            this.fileList.push({
              id: uuidv1(),
              name: item.fileName,
              url: item.fileUrl,
              isComplete: true,
              percent: 0,
            });
          });
        });
    },
    handChange(val, date) {
      this.defaultValue = [
        moment(date[0], "YYYY-MM-DD"),
        moment(date[1], "YYYY-MM-DD"),
      ];
      // eslint-disable-next-line prefer-destructuring
      this.form.effectiveStartDate = date[0];
      // eslint-disable-next-line prefer-destructuring
      this.form.effectiveEndDate = date[1];
    },
    fileRemoved(row) {
      this.form.noticeAttachMentList.forEach((item, index) => {
        if (item.fileUrl === row.url && item.fileName === row.name) {
          this.form.noticeAttachMentList.splice(index, 1);
          this.fileList.splice(index, 1);
        }
      });
    },
    // eslint-disable-next-line consistent-return
    filesAdded(files) {
      const maxLnegth = 5;
      const length =
        this.$refs.MegaUploader?.sFileList?.length || this.fileList.length || 0;
      // eslint-disable-next-line no-param-reassign
      files.ignored = length > maxLnegth;
      if (files.ignored) {
        this.fileList = [].concat(this.fileList);
        this.$message.warning(
          `${this.$t("UPLOAD_FILE_CANNOT_EXCEED")}5${this.$t("PCS")}`
        );
        return false;
      }
    },
    fileSuccess(rootFile, file) {
      if (!this.isFileUpdate) {
        this.$axios
          .put(
            `${ApiConstant.PREFIX_CORE}/api/sys/file/merge-chunks/${file.name}/${file.size}`
          )
          .then((res) => {
            this.form.noticeAttachMentList.push({
              name: res.data.data?.fileName,
              fileCode: res.data.data?.fileCode,
              fileName: res.data.data?.fileName,
              fileUrl: res.data.data?.fileUrl,
            });
            this.fileList = [];
            this.form.noticeAttachMentList.forEach((item) => {
              this.fileList.push({
                id: uuidv1(),
                name: item.fileName,
                url: item.fileUrl,
                isComplete: true,
                percent: 0,
              });
            });
            this.$message.success(this.$t("ATTACHMENT_SUCCESS"));
          });
      }
    },
    // 获取返回得数据
    getReturnData(val) {
      this.form.content = val;
    },
    // 获取数据字典数据
    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() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          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
            .put(`${ApiConstant.PREFIX_CORE}/api/notice`, req)
            .then((res) => {
              this.$message.success(this.$t("EDIT_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="scss" scoped>
/deep/ .ck-editor__editable {
  height: 350px;
  max-height: 350px !important;
}
/deep/ .el-collapse-item__content p {
  color: #232323 !important;
}
</style>
