<template>
  <div class="box-main">
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      :total="total"
      :page.sync="page"
      :action-buttons="actionButtons"
      :show-enable-flag="true"
      @edit="handleEdit"
      @delete="handleDelete"
      @search="searchPageData"
      @enable="
        (record) =>
          handleStatus(
            { status: 'Y', id: record.id },
            'ENABLED',
            'ENABLED_DATA_INFO',
            'ENABLE_SUCCESS'
          )
      "
      @disable="
        (record) =>
          handleStatus(
            { status: 'N', id: record.id },
            'DISABLED',
            'DISABLED_DATA_INFO',
            'DISABLE_SUCCESS'
          )
      "
    >
      <a-row slot="toolbar" class="button-top-table">
        <a-button
          v-if="hasAuth('EMAIL_ACCOUNT:ADD')"
          type="primary"
          @click="handleAdd"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('EMAIL_ACCOUNT:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </a-row>
      <template slot="securityPolicy" slot-scope="text, record">
        {{ formatData(securityPolicyList, record.securityPolicy) }}
      </template>
      <template slot="enableFlag" slot-scope="text">
        <span :class="text === 'Y' ? 'text-success' : 'text-error'">
          {{ getAttrValue(statusList, text) }}
        </span>
      </template>
    </MomTable>
    <MegaDrawer
      :visible="drawerVisible"
      :title="form.id ? $t('EDIT') : $t('ADD')"
      width="60%"
      @close="handleCloseDrawer"
    >
      <template slot="main">
        <a-form-model
          ref="addForm"
          :model="form"
          :rules="rules"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-row>
            <a-col :span="12">
              <a-form-model-item :label="$t('ACCOUNT_CODE')" prop="serverCode">
                <a-input v-model="form.serverCode" :disabled="form.id !== ''" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item :label="$t('ACCOUNT_NAME')" prop="serverName">
                <a-input v-model="form.serverName" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item :label="$t('USER_NAME')" prop="userName">
                <a-input v-model="form.userName" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item :label="$t('PASSWORD')" prop="password">
                <a-input-password v-model="form.password" />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row>
            <a-col :span="12">
              <a-form-model-item :label="$t('MAIL_SERVER')" prop="serverHost">
                <a-input v-model="form.serverHost" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item :label="$t('PORT')" prop="port">
                <a-input
                  v-model="form.port"
                  onkeyup="value=value.replace(/[^\d]/g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')"
                  @change="handleChange"
                />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row>
            <a-col :span="12">
              <a-form-model-item :label="$t('AGREEMENT')" prop="agreement">
                <a-select v-model="form.agreement">
                  <a-select-option
                    v-for="(item, index) in agreementList"
                    :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('NUMBER_OF_RETRIES')"
                prop="tryTimes"
              >
                <a-input
                  v-model="form.tryTimes"
                  onkeyup="value=value.replace(/[^\d]/g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')"
                />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row>
            <a-col :span="12">
              <a-form-model-item :label="$t('SENDER')" prop="sender">
                <a-input v-model="form.sender" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <MomTable
          ref="MomTableDrawer"
          row-key="propertyCode"
          :columns="tableColumnsDrawer"
          :data-source="tableDataDrawer"
          :action-buttons="actionButtonsItem"
          @edit="handleEditConfig"
          @delete="handleDeleteConfig"
        >
          <a-row slot="toolbar" class="button-top-table">
            <a-button type="primary" @click="handleSetSSLProperties">
              {{ $t("SET_SSL_PROPERTIES") }}
            </a-button>
            <a-button type="primary" @click="handleAddConfigItem">
              {{ $t("NEW_SERVER_CONFIGURATION_ITEM") }}
            </a-button>
          </a-row>
        </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('NEW_SERVER_CONFIGURATION_ITEM')"
      @cancel="handleCloseConfigDrawer"
      @ok="modalVisible = false"
    >
      <a-form-model
        ref="addConfigForm"
        :model="formConfig"
        :rules="rulesConfig"
      >
        <a-row>
          <a-col :span="24">
            <a-form-model-item
              :label="$t('ATTRIBUTE_CODE')"
              prop="propertyCode"
            >
              <a-input v-model="formConfig.propertyCode" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item
              :label="$t('ATTRIBUTE_VALUE')"
              prop="propertyValue"
            >
              <a-input v-model="formConfig.propertyValue" />
            </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,
  Drawer as MegaDrawer,
  Icon,
} from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  components: {
    MegaModal,
    MegaDrawer,
    Icon,
  },
  data() {
    const validateNum = (rule, value, callback) => {
      const reg = /(^[1-9]\d*$)/;
      if (value === "") {
        callback(new Error(this.$t("PLACEENTER")));
      } else if (!reg.test(value)) {
        callback(new Error(this.$t("POSITIVE_INTEGER_VALIDATE")));
      }
      callback();
    };
    return {
      title: "", // 弹框标题
      drawerVisible: false, // 新增修改的弹框
      drawerVisibleView: false, // 查看弹框
      // 查询sort
      tableData: [], // 表格数据
      page: 1, // 分页第几页
      total: 0, // 数据表格总条数
      form: {
        id: "",
        serverCode: "",
        serverName: "",
        userName: "",
        password: "",
        serverHost: "",
        port: "",
        agreement: "",
        tryTimes: "",
        sender: "",
        securityPolicy: "",
        msgEmailServerProperties: [],
      },
      rules: {
        serverCode: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        serverName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        userName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        serverHost: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        port: [{ required: true, validator: validateNum, trigger: "blur" }],
        agreement: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        tryTimes: [{ required: true, validator: validateNum, trigger: "blur" }],
        sender: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      },
      rulesConfig: {
        propertyCode: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        propertyValue: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      },
      agreementList: [], // 协议列表
      securityPolicyList: [], // 安全策略列表
      statusList: [], // 状态列表
      // 查询的表单的配置项
      queryForm: {
        serverCode: "",
        serverName: "",
      },
      actionButtons: [
        this.hasAuth("EMAIL_ACCOUNT:EDIT") && "edit",
        this.hasAuth("EMAIL_ACCOUNT:DELETE") && "delete",
      ],
      actionButtonsItem: ["edit", "delete"],
      tableDataDrawer: [],
      modalVisible: false,
      formConfig: {
        propertyCode: "",
        propertyValue: "",
      },
      isEditConfig: false,
      configIndex: null,
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        serverCode: {
          label: () => this.$t("ACCOUNT_CODE"),
        },
        serverName: {
          label: () => this.$t("ACCOUNT_NAME"),
        },
      });
    },
    tableColumns() {
      return [
        {
          dataIndex: "serverCode",
          title: this.$t("ACCOUNT_CODE"),
          minWidth: 210,
        },
        {
          dataIndex: "serverName",
          title: this.$t("ACCOUNT_NAME"),
          minWidth: 210,
        },
        {
          dataIndex: "serverHost",
          title: this.$t("MAIL_SERVER"),
          width: 210,
          sorter: false,
        },
        {
          dataIndex: "port",
          title: this.$t("PORT"),
          width: 210,
          sorter: false,
        },
        {
          dataIndex: "enableFlag",
          title: () => this.$t("STATUS"),
          scopedSlots: { customRender: "enableFlag" },
          width: 120,
        },
        // 更新人员
        {
          dataIndex: "updateBy",
          sorter: false,
          title: this.$t("UPDATE_BY"),
          width: 210,
        },
        // 更新时间
        {
          dataIndex: "updateTime",
          sorter: false,
          title: this.$t("UPDATE_TIME"),
          width: 210,
        },
      ];
    },
    tableColumnsDrawer() {
      return [
        {
          dataIndex: "propertyCode",
          title: this.$t("ATTRIBUTE_CODE"),
        },
        {
          dataIndex: "propertyValue",
          title: this.$t("ATTRIBUTE_VALUE"),
        },
      ];
    },
  },
  mounted() {
    this.queryDictData();
  },
  methods: {
    handleChange() {},
    queryDictData() {
      return Promise.all([
        this.getDictByCode(`DIC:COMMON:ENABLE_FLAG`), // 启用状态
        this.getDictByCode(`DIC:MSG:EMAIL_AGREEMENT`), // 协议列表
        this.getDictByCode(`DIC:MSG:SECURITY_POLICY`), // 安全策略列表
      ]).then(([enableStatusRes, agreementRes, securityPolicyRes]) => {
        this.statusList = enableStatusRes.data.data;
        this.agreementList = agreementRes.data.data;
        this.securityPolicyList = securityPolicyRes.data.data;
      });
    },
    formatData(data, curItem) {
      const result = data.find((item) => item.value === curItem.toString());
      return result ? result.label : "";
    },
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/msg/email-server/search`, {
          params,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = parseFloat(res.data.data.total);
        });
    },
    // 启用、禁用
    handleStatus(record, titleText, contentText, tips) {
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          const { id, status } = record;
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/msg/email-server/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 新增按钮的点击
    handleAdd() {
      this.$set(this, "form", {
        id: "",
        serverCode: "",
        serverName: "",
        userName: "",
        password: "",
        serverHost: "",
        port: "",
        agreement: "",
        tryTimes: "",
        sender: "",
        securityPolicy: "",
        msgEmailServerProperties: [],
      });
      this.$set(this, "tableDataDrawer", []);
      this.drawerVisible = true;
    },
    // 编辑按钮点击
    handleEdit(row) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/msg/email-server/get-by-id//${row.id}`
        )
        .then((res) => {
          this.form = { ...res?.data?.data };
          this.tableDataDrawer =
            res?.data?.data?.msgEmailServerProperties || [];
          this.drawerVisible = true;
        });
    },
    // 监听点击保存事件
    handleSave() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.form.msgEmailServerProperties = this.tableDataDrawer;
          const req = {
            ...this.form,
          };
          if (!this.form?.id) {
            this.$axios
              .post(`${ApiConstant.PREFIX_CORE}/api/msg/email-server`, req)
              .then((res) => {
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.$refs.MomTable?.query();
                this.drawerVisible = false;
              });
          } else {
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/msg/email-server`, req)
              .then((res) => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.$refs.MomTable?.query();
                this.drawerVisible = false;
              });
          }
        }
      });
    },
    handDelete() {
      if (this.selectedRowKeys.length > 0) {
        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: () => {
            this.$axios
              .delete(
                `${ApiConstant.PREFIX_CORE}/api/msg/email-server/batch-delete`,
                {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                }
              )
              .then((res) => {
                this.$message.success(this.$t("DELETE_SUCCESS"));
                this.$refs.MomTable?.query();
              });
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    // 点击表格行内的删除
    handleDelete(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: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/msg/email-server/${row.id}`)
            .then((res) => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 关闭弹框
    handleCloseDrawer() {
      this.$refs.addForm.clearValidate();
      this.drawerVisible = false;
    },
    // 关闭弹框
    handleCloseConfigDrawer() {
      this.$refs.addConfigForm.clearValidate();
      this.modalVisible = false;
    },
    // 设置SSL属性
    handleSetSSLProperties() {
      this.tableDataDrawer = [
        {
          propertyCode: "mail.smtp.socketFactory.class",
          propertyValue: "javax.net.ssl.SSLSocketFactory",
        },
        {
          propertyCode: "mail.smtp.socketFactory.port",
          propertyValue: "465",
        },
        {
          propertyCode: "mail.smtp.ssl.enable",
          propertyValue: "true",
        },
      ];
    },
    // 新增服务器配置项
    handleAddConfigItem() {
      this.$set(this, "formConfig", {
        propertyCode: "",
        propertyValue: "",
      });
      this.isEditConfig = false;
      this.modalVisible = true;
    },
    // 编辑服务器配置项
    handleEditConfig(row) {
      this.isEditConfig = true;
      const { propertyCode, propertyValue } = row;
      this.$set(this, "formConfig", {
        propertyCode,
        propertyValue,
      });
      this.configIndex = this.tableDataDrawer.findIndex(
        (item) => item.propertyCode === this.formConfig.propertyCode
      );
      this.modalVisible = true;
    },
    handleDeleteConfig(row) {
      const index = this.tableDataDrawer.findIndex(
        (item) => item.propertyCode === row.propertyCode
      );
      this.tableDataDrawer.splice(index, 1);
    },
    handleSure() {
      this.$refs.addConfigForm.validate((valid) => {
        if (valid) {
          if (this.isEditConfig === true) {
            this.tableDataDrawer[this.configIndex] = this.formConfig;
          } else {
            if (
              this.tableDataDrawer.find(
                (item) => item.propertyCode === this.formConfig.propertyCode
              )
            ) {
              this.$message.warning(this.$t("ADD_CONFIG_TIP"));
              return;
            }
            this.tableDataDrawer.push(this.formConfig);
          }
          this.modalVisible = false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
/deep/ .mega-design-drawer__footer {
  border-top: none;
  button:last-child {
    margin-left: 10px;
    i {
      margin-right: 5px;
    }
  }
}
</style>
