<template>
  <div id="emailNoticeViewId">
    <div class="email-top">
      <h3 class="top-title">{{ traduction('ALARM_REPORT_SMTP_FUNC') }}</h3>
      <el-form
        ref="SMTPRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        label-position="left"
        :validate-on-rule-change="false"
        @validate="validate"
      >
        <!-- SMTP使能 -->
        <el-form-item :label="formMailSMTP.smtp.label" class="small-item">
          <el-switch
            id="smtp"
            v-model="formMailSMTP.smtp.state"
            :disabled="isSystemLock || !hasBaseConfigPrivil"
            @change="formMailSMTP.smtp.change"
          ></el-switch>
        </el-form-item>
        <!-- SMTP服务器地址 -->
        <el-form-item
          :label="formMailSMTP.serviceAddr.label"
          class="service-addr"
          :class="{ 'hide-required-icon': !formMailSMTP.smtp.state }"
          prop="serviceAddr"
          :rule="rules.serviceAddr"
        >
          <el-popover
            v-model:visible="popoverVisible.serviceAddr"
            popper-class="no-wrap-popover"
            placement="right"
            :teleported="false"
            :content="formMailSMTP.serviceAddr.tip"
            trigger="focus"
            trigger-keys
          >
            <template #reference>
              <el-input
                v-model="ruleForm.serviceAddr"
                v-addId.input="'addrInputBox'"
                v-clearable
                clearable
                :disabled="isSystemLock || !hasBaseConfigPrivil"
                @focus="focus('serviceAddr')"
                @blur="blur('serviceAddr')"
                @clear="clear('serviceAddr')"
                @input="change('serviceAddr', $event)"
              >
                <template #suffix>
                  <ErrorIcon />
                  <ClearableIcon />
                </template>
              </el-input>
            </template>
          </el-popover>
        </el-form-item>
        <!-- SMTP服务器端口 -->
        <el-form-item
          :label="formMailSMTP.servicePort.label"
          class="service-addr"
          prop="servicePort"
          :rule="rules.servicePort"
        >
          <el-popover
            v-model:visible="popoverVisible.servicePort"
            popper-class="no-wrap-popover"
            placement="right"
            :teleported="false"
            :content="formMailSMTP.servicePort.tip"
            trigger="focus"
            trigger-keys
          >
            <template #reference>
              <el-input
                v-model="ruleForm.servicePort"
                v-addId.input="'emailInputPort'"
                v-clearable
                clearable
                type="text"
                :disabled="isSystemLock || !hasBaseConfigPrivil"
                @focus="focus('servicePort')"
                @blur="blur('servicePort')"
                @clear="clear('servicePort')"
                @input="change('servicePort', $event)"
              >
                <template #suffix>
                  <ErrorIcon />
                  <ClearableIcon />
                </template>
              </el-input>
            </template>
          </el-popover>
        </el-form-item>
        <!-- 是否启用TLS -->
        <el-form-item :label="formMailSMTP.tls.label" class="small-item">
          <el-radio-group
            v-model="formMailSMTP.tls.value"
            :disabled="isSystemLock || !hasBaseConfigPrivil"
            @change="formMailSMTP.tls.change"
          >
            <el-radio
              v-for="item in formMailSMTP.tls.list"
              :id="item.tlsId"
              :key="item.tlsId"
              :label="item.id"
            >
              {{ item.key }}
            </el-radio>
          </el-radio-group>
          <span v-show="!formMailSMTP.tls.value" id="emailAlert">
            {{ traduction('ALARM_REPORT_EMAIL_TLS') }}
          </span>
        </el-form-item>
        <!-- 校验端服务器证书 -->
        <el-form-item v-if="formMailSMTP.tls.value" :label="formMailSMTP.certificate.label">
          <el-switch
            id="validCertificate"
            v-model="formMailSMTP.certificate.state"
            :disabled="isSystemLock || !hasBaseConfigPrivil"
            @change="formMailSMTP.certificate.change"
          ></el-switch>
        </el-form-item>
        <!-- 端服务器证书上传 -->
        <el-form-item
          v-if="false && formMailSMTP.tls.value"
          :label="traduction('ALARM_TERMINA_CERTIFICATE')"
        >
          <div id="smtpUpload">
            <el-upload
              id="smtpUpload"
              :name="smtpUpload.alias"
              :action="smtpUpload.url"
              :headers="smtpUpload.headers"
              :accept="smtpUpload.filters"
              :auto-upload="smtpUpload.autoUpload"
              :show-file-list="false"
              :on-success="smtpUpload.successItems"
              :on-error="smtpUpload.errorItems"
              :before-upload="smtpUpload.beforeUpload"
              :disabled="isSystemLock || !hasBaseConfigPrivil"
            >
              <el-button id="rootUploadBtn" :disabled="isSystemLock || !hasBaseConfigPrivil">
                {{ $t('COMMON_UPLOAD') }}
              </el-button>
            </el-upload>
          </div>
          <div id="smtpCertificate">
            <SyslogCertificate
              v-if="formMailSMTP.certificateInfo.showSmtpCertificate"
              :info="formMailSMTP.certificateInfo"
              :type="'client'"
              :is-system-lock="isSystemLock"
              :has-permission="hasBaseConfigPrivil"
            ></SyslogCertificate>
          </div>
        </el-form-item>
        <!-- 端服务器证书 -->
        <el-form-item
          v-if="formMailSMTP.tls.value"
          :label="traduction('ALARM_TERMINA_CERTIFICATE')"
        >
          <CertificateRedirect
            ref="redirectComp"
            :need-save="!emailDisabled"
            message="CERTIFICATE_TO_CA"
            @callback="callback()"
            @redirect="redirect()"
          />
        </el-form-item>
        <el-form-item id="midTitle">
          <template #label>
            <h3 class="mid-title">{{ traduction('ALARM_REPORT_EMAIL_INFO') }}</h3>
          </template>
        </el-form-item>
        <!-- 是否启用匿名 -->
        <el-form-item :label="formMailInfo.emailInfo.label" class="small-item">
          <el-radio-group
            v-model="formMailInfo.emailInfo.value"
            :disabled="isSystemLock || !hasBaseConfigPrivil"
            @change="formMailInfo.emailInfo.change"
          >
            <el-radio
              v-for="item in formMailInfo.emailInfo.list"
              :id="item.id"
              :key="item.emailInfoId"
              :label="item.id"
            >
              {{ item.key }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 发件人用户名 -->
        <el-form-item
          :label="formMailInfo.sendEmailUserName.label"
          prop="sendEmailUserName"
          :rule="rules.sendEmailUserName"
          :class="{ 'hide-required-icon': formMailInfo.emailInfo.value }"
        >
          <el-popover
            v-model:visible="popoverVisible.sendEmailUserName"
            popper-class="no-wrap-popover"
            placement="right"
            :teleported="false"
            :content="formMailInfo.sendEmailUserName.tip"
            trigger="focus"
            trigger-keys
          >
            <template #reference>
              <el-input
                v-model="ruleForm.sendEmailUserName"
                v-addId.input="'sendEmailUserName'"
                v-clearable
                maxlength="64"
                clearable
                :disabled="isSystemLock || !hasBaseConfigPrivil || formMailInfo.emailInfo.value"
                @focus="focus('sendEmailUserName')"
                @blur="blur('sendEmailUserName')"
                @clear="clear('sendEmailUserName')"
                @input="change('sendEmailUserName', $event)"
              >
                <template #suffix>
                  <ErrorIcon />
                  <ClearableIcon />
                </template>
              </el-input>
            </template>
          </el-popover>
        </el-form-item>
        <!-- 发件人密码 -->
        <el-form-item
          :label="formMailInfo.sendEmailUserPwd.label"
          prop="sendEmailUserPwd"
          :rule="rules.sendEmailUserPwd"
          :class="{ 'hide-required-icon': formMailInfo.emailInfo.value }"
        >
          <el-input
            v-model="ruleForm.sendEmailUserPwd"
            v-addId.input="'sendEmailUserPwd'"
            v-clearable
            clearable
            type="password"
            maxlength="50"
            :disabled="isSystemLock || !hasBaseConfigPrivil || formMailInfo.emailInfo.value"
            @focus="focus('sendEmailUserPwd')"
            @blur="blur('sendEmailUserPwd')"
            @clear="clear('sendEmailUserPwd')"
            @input="change('sendEmailUserPwd', $event)"
          >
            <template #suffix>
              <ErrorIcon />
              <ClearableIcon />
            </template>
          </el-input>
        </el-form-item>
        <!-- 发件人邮件地址 -->
        <el-form-item
          :label="formMailInfo.sendEmailAddr.label"
          prop="sendEmailAddr"
          :rule="rules.sendEmailAddr"
        >
          <el-popover
            v-model:visible="popoverVisible.sendEmailAddr"
            popper-class="no-wrap-popover email-popover"
            placement="right-start"
            :teleported="false"
            :content="formMailInfo.sendEmailAddr.tip"
            trigger="focus"
            trigger-keys
          >
            <template #reference>
              <el-input
                v-model="ruleForm.sendEmailAddr"
                v-addId.input="'sendEmailAddr'"
                v-clearable
                clearable
                maxlength="255"
                :disabled="isSystemLock || !hasBaseConfigPrivil"
                @focus="focus('sendEmailAddr')"
                @blur="blur('sendEmailAddr')"
                @clear="clear('sendEmailAddr')"
                @input="change('sendEmailAddr', $event)"
              >
                <template #suffix>
                  <ErrorIcon />
                  <ClearableIcon />
                </template>
              </el-input>
            </template>
          </el-popover>
        </el-form-item>
        <!-- 邮件主题 -->
        <el-form-item
          :label="formMailInfo.sendEmailSubject.label"
          prop="sendEmailSubject"
          :rule="rules.sendEmailSubject"
        >
          <el-popover
            v-model:visible="popoverVisible.sendEmailSubject"
            popper-class="no-wrap-popover"
            placement="right"
            :teleported="false"
            :content="formMailInfo.sendEmailSubject.tip"
            trigger="focus"
            trigger-keys
          >
            <template #reference>
              <el-input
                v-model="ruleForm.sendEmailSubject"
                v-addId.input="'sendEmailSubject'"
                v-clearable
                clearable
                :disabled="isSystemLock || !hasBaseConfigPrivil"
                @focus="focus('sendEmailSubject')"
                @blur="blur('sendEmailSubject')"
                @clear="clear('sendEmailSubject')"
                @input="change('sendEmailSubject', $event)"
              >
                <template #suffix>
                  <ErrorIcon />
                  <ClearableIcon />
                </template>
              </el-input>
            </template>
          </el-popover>
        </el-form-item>
        <!-- 主题附带 -->
        <el-form-item :label="formMailInfo.sendEmailSubjectAppend.label" class="small-item">
          <el-checkbox-group
            v-model="formMailInfo.sendEmailSubjectAppend.value"
            :disabled="isSystemLock || !hasBaseConfigPrivil"
            @change="formMailInfo.sendEmailSubjectAppend.change"
          >
            <el-checkbox
              v-for="item in formMailInfo.sendEmailSubjectAppend.list"
              :id="item.id"
              :key="item.id"
              :label="item.id"
            >
              {{ item.key }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- 告警发送级别 -->
        <el-form-item :label="formMailInfo.sendEmailLevel.label">
          <el-select
            v-model="formMailInfo.sendEmailLevel.value"
            v-addId.select="'sendEmailLevel'"
            :teleported="false"
            :disabled="isSystemLock || !hasBaseConfigPrivil"
            :suffix-icon="PullDownTriangle"
            @change="formMailInfo.sendEmailLevel.change"
          >
            <el-option
              v-for="item in formMailInfo.sendEmailLevel.list"
              :key="item.id"
              :label="item.key"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 告警类型 -->
        <el-form-item
          :label="$t('ALARM_REPORT_SYSLOG_ALARM_TYPE')"
          class="small-item"
        >
          <el-radio-group
            v-model="oemInfo.alarmType.value"
            :disabled="isSystemLock || !hasBaseConfigPrivil"
            @change="oemInfo.alarmType.change"
          >
            <el-radio
              v-for="item in oemInfo.alarmType.list"
              :id="'email' + item.id"
              :key="item.id"
              :label="item.id"
            >
              {{ $t(item.key) }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button id="emailSaveBtn" :disabled="emailDisabled" type="primary" @click="emailSave(false)">
            {{ traduction('COMMON_SAVE') }}
          </el-button>
          <el-button v-show="!emailDisabled" id="emailCancelBtn" @click="emailCancelFun">
            {{ $t('COMMON_CANCEL') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div id="emailTableBox" class="email-table">
      <h3 class="content">{{ traduction('ALARM_REPORT_SMTP_TITLE') }}</h3>
      <EmailTable
        :data="srcData.data"
        :is-system-lock="isSystemLock"
        :has-base-config="hasBaseConfigPrivil"
        @operate-change="tableChange"
      ></EmailTable>
    </div>
  </div>
  <Dialog ref="commonDialogRef" :config="commonDialogConfig" @close="commonDialogClose" />
</template>

<script lang="ts" setup>
import { getErrorTranslate, traduction } from '@/utils/language';
import { ref, reactive, nextTick, onMounted, computed } from 'vue';
import { emailSaveFun, emailSendTest, getEmailInfo } from '../report.service';
import EmailTable from './EmailTable.vue';
import { rangeVerification, strVerification } from '@/validators/validation-functions';
import useStore from '@/stores';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { UserPrivil } from '@/model/base-enum';
import {
  VALID_USERNAME,
  DESCRIPTION,
  STR_MATCH_0_255,
  IPV4,
  IPV6,
  DOMAIN_NAME,
} from '@/utils/regular';
import { loading, showFailedMessage, showSuccessMessage } from '@/utils/composition';
import ErrorIcon from '@/components/ErrorIcon/ErrorIcon.vue';
import ClearableIcon from '@/components/ClearableIcon/ClearableIcon.vue';
import PullDownTriangle from '@/components/PullDownTriangle/PullDownTriangle.vue';
import { UploadFile } from 'element-plus/es/components/upload/src/upload';
import { escapeHeader, getMessageId, showElMessage } from '@/utils/utils';
import SyslogCertificate from './SyslogCertificate.vue';
import { useRouter } from 'vue-router';
import CertificateRedirect from '@/pages/User/Certificate/CertificateRedirect.vue';

const redirectComp = ref();
const $router = useRouter();
const store = useStore();
let isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});

const hasBaseConfigPrivil = checkPrivil(UserPrivil.baseConfig);
const loct = localStorage.getItem('loct');

const srcData = reactive({
  data: <any[]>[],
});
const isEmailCancel = ref(false);
let defaultData: any;
const SERVICE_PORT = 25;
const emailDisabled = ref(true);
const SMTPRef = ref();
let response: IEmailType;

const commonDialogRef = ref();
const commonDialogConfig = reactive({
  id: 'emailTestModel',
  content: traduction('ALARM_REPORT_EMAIL_TEST'),
  title: traduction('COMMON_CONFIRM'),
  cancelButton: {
    hide: true,
  },
});
// 表单校验结果
const validateResult = {};
const ruleForm = reactive({
  serviceAddr: '',
  servicePort: SERVICE_PORT,
  sendEmailUserName: '',
  sendEmailUserPwd: '',
  sendEmailAddr: '',
  sendEmailSubject: '',
});
const formMailSMTP: any = reactive({
  smtp: {
    label: traduction('ALARM_REPORT_SMTP_ENABLE'),
    state: true,
    change: () => {
      addressRequire();
      changeSaveStatus();
    },
  },
  serviceAddr: {
    label: traduction('ALARM_REPORT_SMTP_ADDR'),
    value: '',
    tip: traduction('COMMON_IPV4_IPV6_DOMIN'),
    change: () => {
      changeSaveStatus();
    },
  },
  servicePort: {
    label: traduction('ALARM_REPORT_SMTP_PORT'),
    value: SERVICE_PORT,
    tip: traduction('VALIDTOR_RANGE'),
    change: () => {
      changeSaveStatus();
    },
  },
  tls: {
    label: traduction('ALARM_REPORT_TLS_ENABLE'),
    list: [
      {
        id: true,
        key: traduction('COMMON_YES'),
        tlsId: 'tlsOk',
      },
      {
        id: false,
        key: traduction('COMMON_NO'),
        tlsId: 'tlsNo',
      },
    ],
    value: false,
    change: () => {
      changeSaveStatus();
    },
  },
  certificate: {
    label: traduction('ALARM_VERIFYING_TERMINA_CERTIFICATE'),
    state: true,
    change: () => {
      changeSaveStatus();
    },
  },
  certificateInfo: {
    showSmtpCertificate: false,
    issuer: '',
    subject: '',
    validNotBefore: '',
    validNotAfter: '',
    serialNumber: '',
  },
});
// 上传smtp端证书
const smtpUpload = reactive({
  url: '/UI/Rest/Maintenance/EmailNotification/ImportRootCertificate',
  headers: {
    From: 'WebUI',
    'X-CSRF-Token': escapeHeader(loct ? JSON.parse(loct).to : ''),
  },
  type: 'POST',
  filters: '.crt,.cer,.pem',
  autoUpload: true,
  alias: 'Content',
  successItems: (data: UploadFile) => {
    showSuccessMessage();
    init();
  },
  beforeUpload: (rawFile: UploadFile): any => {
    const type = rawFile.name.split('.').reverse()[0];
    if (!['crt', 'cer', 'pem'].includes(type)) {
      showFailedMessage(traduction('COMMON_FILE_SUFFIX_CER_PEM_CRT'));
      return false;
    } else if ((rawFile.size as any) > 100 * 1024) {
      showFailedMessage(traduction('COMMON_UPLOAD_FILE_MORN_1M_ERROR4'));
      return false;
    }
  },
  errorItems: (err: any) => {
    const errorId = getMessageId(JSON.parse(err.message));
    const errorMsg = getErrorTranslate(errorId[0].code as string);
    showElMessage('error', errorMsg);
  },
});
const formMailInfo = reactive({
  emailInfo: {
    label: traduction('ALARM_REPORT_IS_ANONYMOUS'),
    list: [
      {
        id: true,
        key: traduction('COMMON_YES'),
        emailInfoId: 'infoOk',
      },
      {
        id: false,
        key: traduction('COMMON_NO'),
        emailInfoId: 'infoNo',
      },
    ],
    value: false,
    change: (e: boolean) => {
      if (e) {
        ruleForm.sendEmailUserPwd = '';
        formMailInfo.sendEmailUserPwd.value = '';
        ruleForm.sendEmailUserName = defaultData['userName'];
        SMTPRef.value.validateField('sendEmailUserName');
        SMTPRef.value.validateField('sendEmailUserPwd');
      } else {
        SMTPRef.value.validateField('sendEmailUserName');
      }

      changeSaveStatus();
    },
  },
  sendEmailUserName: {
    label: traduction('ALARM_REPORT_SEND_USERNAME'),
    value: '',
    tip: traduction('ALARM_REPORT_EMAIL_USERNAME_REQUIRE'),
    change: () => {
      changeSaveStatus();
    },
  },
  sendEmailUserPwd: {
    label: traduction('ALARM_REPORT_SEND_PWD'),
    value: '',
    change: () => {
      changeSaveStatus();
    },
  },
  sendEmailAddr: {
    label: traduction('ALARM_REPORT_SEND_ADDR'),
    value: '',
    tip: traduction('ALARM_FULL_EMAIL_TIP'),
    change: () => {
      changeSaveStatus();
    },
  },
  sendEmailSubject: {
    label: traduction('ALARM_REPORT_EMAIL_SUBJECT'),
    value: '',
    tip: traduction('ALARM_REPORT_EMAIL_SUBJECT_TIP'),
    change: () => {
      changeSaveStatus();
    },
  },
  sendEmailSubjectAppend: {
    label: traduction('ALARM_REPORT_EMAIL_SUBJECT_APPEND'),
    value: ['BoardSN'],
    list: [
      {
        id: 'BoardSN',
        key: traduction('ALARM_REPORT_EMAIL_SUBJECT_1'),
        checked: false,
      },
      {
        id: 'ProductAssetTag',
        key: traduction('ALARM_REPORT_EMAIL_SUBJECT_2'),
        checked: false,
      },
      {
        id: 'HostName',
        key: traduction('ALARM_REPORT_EMAIL_SUBJECT_3'),
        checked: false,
      },
    ],
    change: () => {
      changeSaveStatus();
    },
  },
  sendEmailLevel: {
    label: traduction('ALARM_REPORT_EMAIL_ALARM_LEVEL'),
    value: 'None',
    list: [
      {
        id: 'None',
        key: '[NULL]',
      },
      {
        id: 'Critical',
        key: traduction('ALARM_EVENT_CRITICAL'),
      },
      {
        id: 'Major',
        key: traduction('ALARM_EVENT_MAJOR'),
      },
      {
        id: 'Minor',
        key: traduction('ALARM_EVENT_MINOR'),
      },
      {
        id: 'Normal',
        key: traduction('ALARM_EVENT_NORMAL'),
      },
    ],
    change: () => {
      changeSaveStatus();
    },
  },
});
const oemInfo =reactive({
  alarmType: {
    value: 'OemEvent',
    list: [
      {
        id: 'OemEvent',
        key: 'ALARM_REPORT_SYSLOG_ALARM_EVENT',
      },
      {
        id: 'SEL',
        key: 'ALARM_REPORT_SYSLOG_ALARM_SEL',
      },
    ],
    change: () => {
      changeSaveStatus();
    },
  },
});
const rules = reactive({
  serviceAddr: {
    type: 'string',
    trigger: 'blur',
    required: formMailSMTP.smtp.state,
    validator: (rule: any, value: any, callback: any) => {
      if (!value) {
        if (!formMailSMTP.smtp.state) {
          callback();
          return true;
        } else {
          callback(new Error(traduction('VALID_REQUIRED_ERR')));
          return false;
        }
      }

      let result = false;
      if (/^[0-9.]+$/.test(value)) {
        result = IPV4.test(value);
      } else if (value.indexOf(':') > -1) {
        result = IPV6.test(value);
      } else {
        result = DOMAIN_NAME.test(value);
      }

      !result ? callback(new Error(traduction('COMMON_FORMAT_ERROR'))) : callback();
      return result;
    },
  },
  servicePort: {
    trigger: 'blur',
    required: false,
    type: 'number',
    isInteger: true,
    min: 1,
    max: 65535,
    message: traduction('VALIDTOR_RANGE'),
    validator: rangeVerification,
  },
  sendEmailUserName: {
    trigger: 'blur',
    required: !formMailInfo.emailInfo.value, // 非匿名时用户名必填
    type: 'text',
    validator: (rule: any, value: any, callback: (error?: Error) => void) => {
      let result = false;
      // 非匿名时用户名不能为空
      if (!formMailInfo.emailInfo.value && !value) {
        callback(new Error(traduction('VALID_REQUIRED_ERR')));
        return false;
      } else {
        result = VALID_USERNAME.test(value);
      }
      result ? callback() : callback(new Error(traduction('ALARM_REPORT_EMAIL_USERNAME_REQUIRE')));
      return result;
    },
  },
  sendEmailUserPwd: {
    trigger: 'blur',
    required: !formMailInfo.emailInfo.value, // 非匿名时密码必填
    type: 'text',
    validator: (rule: any, value: any, callback: (error?: Error) => void) => {
      if (!formMailInfo.emailInfo.value && !value) {
        callback(new Error(traduction('VALID_REQUIRED_ERR')));
        return false;
      }
      callback();
      return true;
    },
  },
  sendEmailAddr: {
    trigger: 'blur',
    message: traduction('COMMON_FORMAT_ERROR'),
    validator: (rule: any, value: any, callback: (error?: Error) => void) => {
      if (value === '') {
        callback();
        return true;
      }
      if (!DESCRIPTION.test(value)) {
        callback(new Error(traduction('COMMON_FORMAT_ERROR')));
        return false;
      }
      let iAtPos = 0;
      let lastPos = 0;
      let iAtTimes = 0;
      let i = 0;
      for (const char of value) {
        if (char === '@') {
          iAtPos = i;
          iAtTimes++;
        } else if (char === '.') {
          lastPos = i;
        }
        i++;
      }
      if (
        i > 255 ||
        iAtPos < 1 ||
        lastPos - 2 < iAtPos ||
        i - lastPos < 3 ||
        i - lastPos > 64 ||
        iAtTimes !== 1
      ) {
        callback(new Error(traduction('COMMON_FORMAT_ERROR')));
        return false;
      }
      callback();
      return true;
    },
  },
  sendEmailSubject: {
    trigger: 'blur',
    message: traduction('COMMON_FORMAT_ERROR'),
    type: 'text',
    required: false,
    minLength: 0,
    maxLength: 255,
    containsEmptyString: true,
    matchRule: STR_MATCH_0_255,
    validator: strVerification,
  },
});
// SMTP使能开启时增加服务器地址必填校验
function addressRequire() {
  SMTPRef.value.validateField('serviceAddr');
}
function change(key: string, value: string) {
  switch (key) {
    case 'serviceAddr':
      formMailSMTP.serviceAddr.value = value;
      break;
    case 'servicePort':
      formMailSMTP.servicePort.value = value;
      break;
    case 'sendEmailUserName':
      formMailInfo.sendEmailUserName.value = value;
      break;
    case 'sendEmailAddr':
      formMailInfo.sendEmailAddr.value = value;
      break;
    case 'sendEmailSubject':
      formMailInfo.sendEmailSubject.value = value;
      break;
    case 'sendEmailUserPwd':
      formMailInfo.sendEmailUserPwd.value = value;
      break;
    default:
      break;
  }
  validateResult[key] = rules[key].validator(rules[key], value, () => {});
  nextTick(() => {
    changeSaveStatus();
  });
}
let allState: boolean[] = [];

// 判断和接口数据是否相同
function isEqulAction() {
  return (
    formMailSMTP.smtp.state === defaultData['smtpEnable'] &&
    formMailSMTP.serviceAddr.value === defaultData['smtpServiceAddr'] &&
    formMailSMTP.servicePort.value + '' === defaultData['smtpServicePort'] + '' &&
    formMailSMTP.tls.value === defaultData['tlsEnable'] &&
    formMailSMTP.certificate.state === defaultData['certVerificationEnabled'] &&
    formMailInfo.emailInfo.value === defaultData['emailAnonymous'] &&
    formMailInfo.sendEmailUserName.value === defaultData['userName'] &&
    formMailInfo.sendEmailUserPwd.value === defaultData['userPwd'] &&
    formMailInfo.sendEmailAddr.value === defaultData['emailAddress'] &&
    formMailInfo.sendEmailSubject.value === defaultData['emailSubject'] &&
    formMailInfo.sendEmailLevel.value === defaultData['alarmLevel'] &&
    oemInfo.alarmType.value === defaultData['alarmType'] &&
    _checkSubjectAppend()
  );
}

function changeSaveStatus() {
  if (JSON.stringify(validateResult).includes('false')) {
    emailDisabled.value = true;
    return;
  }
  if (!formMailSMTP.tls.value && formMailSMTP.tls.value !== defaultData['tlsEnable']) {
    formMailSMTP.certificate.state = defaultData['certVerificationEnabled'];
  }
  const isEqul = isEqulAction();

  if (isEqul) {
    emailDisabled.value = true;
  } else {
    emailDisabled.value = false;
  }
}
function _checkSubjectAppend() {
  let emailSubjectAppendChange = true;
  formMailInfo?.sendEmailSubjectAppend?.value?.forEach(item => {
    if (!defaultData.emailSubjectAppend.includes(item)) {
      emailSubjectAppendChange = false;
    }
  });
  if (
    formMailInfo.sendEmailSubjectAppend?.value?.length !== defaultData.emailSubjectAppend?.length
  ) {
    emailSubjectAppendChange = false;
  }
  return emailSubjectAppendChange;
}
function _checkAlarmEvent() {
  return defaultData['alarmLevel'] === formMailInfo.sendEmailLevel.value;
}

function _setSubjectAppend(arr: []) {
  if (arr.length === 0) {
    return;
  }
  formMailInfo?.sendEmailSubjectAppend?.list?.forEach(item => {
    for (const key of arr) {
      if (key === item.id) {
        item.checked = true;
      }
    }
  });
}
function getParams(params: Object, emailInfo: Object) {
  if (!formMailInfo.emailInfo.value) {
    if (formMailInfo.sendEmailUserName.value !== defaultData['userName']) {
      emailInfo['SenderUserName'] = formMailInfo.sendEmailUserName.value;
    }
    if (formMailInfo.sendEmailUserPwd.value !== defaultData['userPwd']) {
      emailInfo['SenderPassword'] = formMailInfo.sendEmailUserPwd.value;
    }
  }
  if (formMailSMTP.smtp.state !== defaultData['smtpEnable']) {
    params['Enabled'] = formMailSMTP.smtp.state;
  }
  if (formMailSMTP.serviceAddr.value !== defaultData['smtpServiceAddr']) {
    params['ServerAddress'] = formMailSMTP.serviceAddr.value;
  }
  if (formMailSMTP.servicePort.value + '' !== defaultData['smtpServicePort'] + '') {
    params['ServerPort'] = Number(formMailSMTP.servicePort.value);
  }
  if (formMailSMTP.tls.value !== defaultData['tlsEnable']) {
    params['TLSEnabled'] = formMailSMTP.tls.value;
  }
  if (formMailSMTP.certificate.state !== defaultData['certVerificationEnabled']) {
    params['CertVerificationEnabled'] = formMailSMTP.certificate.state;
  }
  if (formMailInfo.emailInfo.value !== defaultData['emailAnonymous']) {
    emailInfo['AnonymousLoginEnabled'] = formMailInfo.emailInfo.value;
  }
  if (formMailInfo.sendEmailAddr.value !== defaultData['emailAddress']) {
    emailInfo['SenderAddress'] = formMailInfo.sendEmailAddr.value;
  }
  if (formMailInfo.sendEmailSubject.value !== defaultData['emailSubject']) {
    emailInfo['EmailSubject'] = formMailInfo.sendEmailSubject.value;
  }
  if (!_checkSubjectAppend()) {
    emailInfo['EmailSubjectContains'] = formMailInfo.sendEmailSubjectAppend.value;
  }
  if (!_checkAlarmEvent()) {
    emailInfo['AlarmSeverity'] = formMailInfo.sendEmailLevel.value;
  }
  if (oemInfo.alarmType.value !== defaultData['alarmType']) {
    params['ReportType'] = oemInfo.alarmType.value;
  }
  if (JSON.stringify(emailInfo) !== '{}') {
    params['EmailInfo'] = emailInfo;
  }
}
// 邮件保存
function emailSave(isRedirect: boolean) {
  const isPassword = !formMailInfo.sendEmailUserPwd.value && !formMailInfo.emailInfo.value;
  if (isPassword) {
    SMTPRef.value.validateField('sendEmailUserPwd');
    return;
  }

  loading(true);
  const params = {};
  const emailInfo = {};
  getParams(params, emailInfo);
  emailSaveFun(params)
    .then(res => {
      if (res?.data?.error) {
        loading(false);
        showFailedMessage(traduction('USER_EDIT_PARTIALLY_FAILED'));
        if (isRedirect) {
          redirectComp.value.hide();
        }
        return;
      }
      showSuccessMessage();
      emailDisabled.value = true;
      if (isRedirect) {
        redirectComp.value.hide();
        $router.push('/navigate/user/certificate/ca-certificate-list');
      }
      init();
    })
    .catch(error => {
      loading(false);
      const errorCode = error?.data?.error?.[0]?.code;
      if (errorCode) {
        showFailedMessage(traduction(errorCode + '.errorMessage'));
      } else {
        showFailedMessage()
      }
      emailDisabled.value = false;
      if (isRedirect) {
        redirectComp.value.hide();
      }
    });
}

const tempTableData: any[] = [];
function copy(obj: any) {
  return Object.assign({}, obj);
}
function tableChange(event: any) {
  switch (event.key) {
    case 'save':
      event.value.isEdit = false;
      save(event.value);
      break;
    case 'cancel':
      cancel(event.value);
      event.value.isEdit = false;
      break;
    case 'edit':
      tempTableData[event.value.num - 1] = copy(event.value);
      event.value.isEdit = true;
      break;
    case 'test':
      // 若参数未保存，弹框提示。
      if (!emailDisabled.value) {
        commonDialogRef.value.show();
      } else {
        test(event.value);
      }
      break;
    default:
      return;
  }
}
interface rowType {
  address: string;
  description: string;
  emailEnable: boolean;
  isEdit: boolean;
  num: number;
}
function save(data: rowType) {
  const obj = {
    ID: data.num - 1,
    Enabled: data.emailEnable,
    EmailAddress: data.address,
    Description: data.description,
  };
  const params = {
    RecipientList: [obj],
  };
  emailSaveFun(params)
    .then(res => {
      const response = res['data'];
      const resSingle = response.RecipientList[data.num - 1];
      data['isEdit'] = false;
      data['num'] = Number(resSingle.ID) + 1;
      data['emailEnable'] = resSingle.Enabled;
      data['address'] = resSingle.EmailAddress ? resSingle.EmailAddress : '';
      data['description'] = resSingle.Description ? resSingle.Description : '';
      showSuccessMessage();
    })
    .catch(error => {
      cancel(data);
      showFailedMessage();
    });
}
function cancel(data: rowType) {
  data.address = tempTableData[data.num - 1]['address'];
  data.description = tempTableData[data.num - 1]['description'];
  data.emailEnable = tempTableData[data.num - 1]['emailEnable'];
  tempTableData[data.num - 1] = null;
}
function test(data: rowType) {
  const params = {
    ID: data.num - 1,
  };
  emailSendTest(params).then(
    () => {
      showSuccessMessage(traduction('ALARM_REPORT_TEST_MESSAGE'));
    },
    error => {
      const code = error?.data?.error[0]?.code;
      if (code) {
        const errorMessage = code + '.errorMessage';
        showFailedMessage(traduction(errorMessage));
        return;
      }
      showFailedMessage();
    },
  );
}

interface IEmailType {
  EmailInfo: any;
  Enabled: boolean;
  RecipientList: any;
  ServerAddress: string;
  ServerPort: number;
  TLSEnabled: boolean;
  RootCertificate?: any;
  CertVerificationEnabled?: boolean;
  ReportType: string;
}
const userNameControl = ref(false);
const userPwdControl = ref(false);
function setTableData(response: IEmailType) {
  const arr: any[] = [];
  response?.RecipientList?.forEach((item: any) => {
    const obj = {};
    obj['isEdit'] = false;
    obj['num'] = Number(item.ID) + 1;
    obj['emailEnable'] = item.Enabled;
    obj['address'] = item.EmailAddress ? item.EmailAddress : '';
    obj['description'] = item.Description ? item.Description : '';
    arr.push(obj);
  });
  if (!isEmailCancel.value) {
    srcData.data = arr;
  }
}
function init() {
  loading(true);
  getEmailInfo().then(res => {
    response = res['data'] as IEmailType;
    initForm(response);
    let servicePort: any = formMailSMTP?.servicePort?.value;
    if (servicePort || servicePort === 0) {
      servicePort = servicePort.toString();
    } else {
      servicePort = '';
    }
    defaultData = {
      smtpEnable: formMailSMTP?.smtp?.state,
      smtpServiceAddr: formMailSMTP?.serviceAddr?.value,
      smtpServicePort: servicePort,
      tlsEnable: formMailSMTP?.tls?.value,
      certVerificationEnabled: formMailSMTP?.certificate?.state,
      emailAnonymous: formMailInfo?.emailInfo?.value,
      userName: formMailInfo?.sendEmailUserName?.value,
      userPwd: formMailInfo?.sendEmailUserPwd?.value,
      emailAddress: formMailInfo?.sendEmailAddr?.value,
      emailSubject: formMailInfo?.sendEmailSubject?.value,
      emailSubjectAppend: formMailInfo?.sendEmailSubjectAppend?.value,
      alarmLevel: formMailInfo?.sendEmailLevel?.value,
      alarmType: oemInfo?.alarmType?.value,
    };
    setTableData(response);
    isEmailCancel.value = false;
    rules.serviceAddr['required'] = true;
    loading(false);
  });
}
function initForm(response: IEmailType) {
  formMailSMTP.smtp.state = response.Enabled ? response.Enabled : false;
  formMailSMTP.serviceAddr.value = response.ServerAddress ? response.ServerAddress : '';
  formMailSMTP.servicePort.value = response.ServerPort ? response.ServerPort : SERVICE_PORT;
  formMailSMTP.tls.value = response.TLSEnabled;
  formMailInfo.emailInfo.value = response?.EmailInfo?.AnonymousLoginEnabled;
  // 初始化用户密码，当接口没有返回值时默认为''以避免undefined与''不相等影响保存按钮状态
  formMailInfo.sendEmailUserPwd.value = response?.EmailInfo?.SenderPassword
    ? response?.EmailInfo?.SenderPassword
    : '';
  if (response?.EmailInfo?.AnonymousLoginEnabled) {
    userNameControl.value = true;
    userPwdControl.value = true;
  } else {
    // 匿名不需要密码
    userNameControl.value = false;
    userPwdControl.value = false;
    formMailInfo.sendEmailUserPwd.value = response?.EmailInfo?.SenderPassword
      ? response.EmailInfo.SenderPassword
      : '';
  }
  formMailSMTP.certificate.state = response.CertVerificationEnabled;
  // 有端证书时处理证书信息显示内容
  if (response.RootCertificate) {
    formMailSMTP.certificateInfo.issuer = response?.RootCertificate?.Issuer;
    formMailSMTP.certificateInfo.subject = response?.RootCertificate?.Subject;
    formMailSMTP.certificateInfo.validNotBefore = response?.RootCertificate?.ValidNotBefore;
    formMailSMTP.certificateInfo.validNotAfter = response?.RootCertificate?.ValidNotAfter;
    formMailSMTP.certificateInfo.serialNumber = response?.RootCertificate?.SerialNumber;
    formMailSMTP.certificateInfo.showSmtpCertificate = true;
  } else {
    formMailSMTP.certificateInfo.showSmtpCertificate = false;
  }
  formMailInfo.sendEmailUserName.value = response?.EmailInfo?.SenderUserName
    ? response.EmailInfo.SenderUserName
    : '';
  formMailInfo.sendEmailAddr.value = response?.EmailInfo?.SenderAddress
    ? response.EmailInfo.SenderAddress
    : '';
  formMailInfo.sendEmailSubject.value = response?.EmailInfo?.EmailSubject;
  formMailInfo.sendEmailLevel.value = response?.EmailInfo?.AlarmSeverity;
  oemInfo.alarmType.value = response?.ReportType;
  formMailInfo.sendEmailSubjectAppend.value = response?.EmailInfo?.EmailSubjectContains;
  ruleForm.serviceAddr = formMailSMTP.serviceAddr.value;
  ruleForm.servicePort = formMailSMTP.servicePort.value;
  ruleForm.sendEmailUserName = formMailInfo.sendEmailUserName.value;
  ruleForm.sendEmailUserPwd = formMailInfo.sendEmailUserPwd.value;
  ruleForm.sendEmailAddr = formMailInfo.sendEmailAddr.value;
  ruleForm.sendEmailSubject = formMailInfo.sendEmailSubject.value;
}
function emailCancelFun() {
  initForm(response);
  emailDisabled.value = true;
}
onMounted(() => {
  init();
});
const popoverVisible = reactive({
  serviceAddr: false,
  servicePort: false,
  VNCPassword: false,
  sendEmailUserName: false,
  sendEmailAddr: false,
  sendEmailSubject: false,
});
// 表单校验发生时 - 控制保存按钮状态 state:校验结果
function validate(key: string, state: boolean) {
  validateResult[key] = state;
  nextTick(() => {
    changeSaveStatus();
  });
}

function focus(key: string) {
  SMTPRef.value.clearValidate(key);
  popoverVisible[key] = true;
}

function blur(key: string) {
  popoverVisible[key] = false;
}

function clear(key: string) {
  // 如果没有focus，那么这个地方需要手动调用一次校验
  if (!popoverVisible[key]) {
    SMTPRef.value.validateField(key);
  }
}

function commonDialogClose(reason: boolean) {
  commonDialogRef.value.hide();
}

function redirect(): void {
  $router.push('/navigate/user/certificate/ca-certificate-list');
}

function callback(): void {
  emailSave(true);
}
</script>

<style lang="scss" scoped>
#emailNoticeViewId {
  height: calc(100% - 104px);
  margin-right: 24px;
}

#emailAlert {
  color: var(--o-color-major);
  margin-left: 8px;
  position: relative;
  top: -2px;
}

.email-top,
.email-table {
  padding: 24px;
  background: var(--o-bg-color-base);
  border-radius: 4px;
}

.email-top {
  margin-bottom: 16px;
  :deep(.el-select) {
    width: 320px;
  }
}

.email-table {
  .content {
    font-size: 16px;
    margin-bottom: 16px;
  }
}

:deep(.email-top .el-input) {
  width: 320px;
}

:deep(.email-popover) {
  width: 320px !important;
}

.top-title,
.mid-title {
  font-size: 16px;
  margin-bottom: 16px;
  color: var(--o-text-color-primary);
}

#midTitle {
  margin-bottom: 0;
}

:deep(.small-item) {
  height: 16px;
  .el-form-item__label {
    padding-top: 0;
    padding-bottom: 0;
  }

  .el-form-item__content {
    line-height: 16px;
  }

  .el-radio {
    height: 16px;
  }

  .el-radio__label {
    color: var(--o-text-color-secondary);
  }

  .el-checkbox-group {
    .el-checkbox {
      height: auto;
    }
  }
}

.hide-required-icon {
  :deep(.el-form-item__label::before) {
    display: none;
  }
}

#smtpUpload {
  width: 100%;
}
</style>
