<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" :disabled="true" />
                </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
        v-if="form.id !== ''"
        type="primary"
        @click="() => handleTemplateParam()"
      >
        <Icon type="icon-cur-save_1" :size="18" />
        {{ $t("TEMPLATE_PARAMETERS") }}
      </a-button>
      <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>
    <MegaDrawer
      :visible="drawerVisible"
      :title="$t('TEMPLATE_PARAMETERS')"
      width="60%"
      @close="handleCloseDrawer"
    >
      <template slot="main">
        <MomTable
          ref="MomTable"
          row-key="argName"
          :columns="tableColumns"
          :data-source="tableData"
          :query-param="queryForm"
          :query-param-item="queryFormItem"
          :total="total"
          :action-buttons="actionButtonsItem"
          @edit="handleEditItem"
          @delete="handleDeleteItem"
          @search="searchPageData"
        >
          <div slot="toolbar" class="button-top-table">
            <a-button type="primary" @click="handleInit">
              {{ $t("INIT") }}
            </a-button>
          </div>
        </MomTable>
      </template>
      <footer slot="footer">
        <a-button type="primary" @click="handleSave()">
          <Icon type="icon-cur-save_1" :size="18" />{{ $t("SAVE") }}
        </a-button>
        <a-button @click="handleCloseDrawer">
          <Icon type="icon-dir-f-rollback" :size="18" />{{ $t("CANCEL") }}
        </a-button>
      </footer>
    </MegaDrawer>
    <MegaModal
      :visible="modalVisible"
      :centered="true"
      :mask-closable="false"
      :title="$t('TEMPLATE_PARAMETERS')"
      @cancel="handleCloseConfigDrawer"
      @ok="modalVisible = false"
    >
      <a-form-model
        ref="addConfigForm"
        :model="formConfig"
        :rules="rulesConfig"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-row>
          <a-col :span="24">
            <a-form-model-item :label="$t('PARAMETERS_NAME')" prop="argName">
              <a-input v-model="formConfig.argName" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item
              :label="$t('PARAMETERS_DESCRIPTION')"
              prop="description"
            >
              <a-input v-model="formConfig.description" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <template slot="footer">
        <a-button type="primary" @click="handleSure">{{
          $t("CONFIRM")
        }}</a-button>
        <a-button @click="handleCloseConfigDrawer">{{ $t("CANCEL") }}</a-button>
      </template>
    </MegaModal>
  </div>
</template>

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

export default {
  components: { MegaEditor, MegaModal, MegaDrawer, Icon },
  data() {
    return {
      drawerVisible: false,
      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: [], // 语言列表
      // 查询sort
      tableData: [], // 表格数据
      page: 1, // 分页第几页
      total: 0, // 数据表格总条数
      actionButtonsItem: [
        this.hasAuth("CORE:MESSAGE:RECEIVER_GROUP:EDIT") && "edit",
        this.hasAuth("CORE:MESSAGE:RECEIVER_GROUP:DELETE") && "delete",
      ],
      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);
              }
            },
          },
        },
      },
      // 查询的表单的配置项
      queryForm: {
        argName: "",
      },
      modalVisible: false,
      formConfig: {
        id: "",
        argName: "",
        description: "",
        templateCode: "",
      },
      rulesConfig: {
        argName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        description: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    queryFormItem() {
      return this.$observable("queryFormItem", {
        argName: {
          label: () => this.$t("TEMPLATE_PARAMETERS"),
        },
      });
    },
    tableColumns() {
      return [
        {
          dataIndex: "argName",
          title: () => this.$t("PARAMETERS_NAME"),
          width: 210,
        },
        {
          dataIndex: "description",
          type: "input",
          title: () => this.$t("PARAMETERS_DESCRIPTION"),
        },
      ];
    },
  },
  mounted() {
    this.form.id = this.$route.query.id || "";
    this.getData();
    this.queryDictData();
  },
  methods: {
    // 获取返回得数据
    getReturnData(val) {
      this.form.content = val;
    },
    // 根据主键id获取详情数据
    getData() {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/msg/template/get-by-id/${this.form.id}`
        )
        .then((res) => {
          this.form = { ...res?.data?.data };
        });
    },
    // 获取数据字典数据
    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 req = {
            ...this.form,
          };
          this.$axios
            .put(`${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,
      });
    },
    // 打开模板参数弹框
    handleTemplateParam() {
      this.drawerVisible = true;
    },
    // 获取模板参数数据
    searchPageData(params) {
      // eslint-disable-next-line no-param-reassign
      params.templateId = this.form.id;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/msg/template-arg/search`, {
          params,
        })
        .then((res) => {
          this.tableData = res.data?.data?.records || [];
          this.total = parseFloat(res.data?.data?.total);
        });
    },
    // 初始化模板参数数据
    handleInit() {
      this.$axios
        .put(
          `${ApiConstant.PREFIX_CORE}/api/msg/template-arg/init/${this.form.id}`
        )
        .then((res) => {
          this.tableData = res.data?.data?.records || [];
          this.total = parseFloat(res.data?.data?.total);
        });
    },
    // 关闭弹框
    handleCloseDrawer() {
      this.$refs.addForm.clearValidate();
      this.drawerVisible = false;
    },
    handleEditItem(row) {
      this.formConfig = { ...row };
      this.modalVisible = true;
    },
    // 删除模板参数详情
    handleDeleteItem(row) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          const index = this.tableData.findIndex(
            (item) => item.code === row.code
          );
          this.tableData.splice(index, 1);
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/msg/template-arg/${row.id}`)
            .then((res) => {
              const params = {
                page: 1,
              };
              this.searchPageData(params);
            });
        },
      });
    },
    // 关闭弹框
    handleCloseConfigDrawer() {
      this.$refs.addConfigForm.clearValidate();
      this.modalVisible = false;
    },
    handleSure() {
      this.$refs.addConfigForm.validate((valid) => {
        if (valid) {
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/msg/template-arg`,
              this.formConfig
            )
            .then((res) => {
              const params = {
                page: 1,
              };
              this.searchPageData(params);
            });
        }
      });
      this.modalVisible = false;
    },
  },
};
</script>
<style lang="scss" scoped>
/deep/ .ck-editor__editable {
  height: 450px;
  max-height: 450px !important;
}
/deep/ .el-collapse-item__content p {
  color: #232323 !important;
}
</style>
