<template>
  <div class="customEmail" v-loading="loading">
    <div class="emailConfig">
      <h3>{{ $t("trials:emailManageCfg:customEmail:title:emailConfig") }}</h3>
      <el-form :inline="true" :model="emailConfig" :rules="emailConfigRule" class="demo-form-inline" ref="emailConfig">
        <el-form-item :label="$t('trials:emailManageCfg:customEmail:label:consigneeEmail')" prop="EMail">
          <el-input v-model="emailConfig.EMail" placeholder=""></el-input>
        </el-form-item>
        <el-form-item :label="$t('trials:emailManageCfg:customEmail:label:consigneeName')" prop="Name">
          <el-input v-model="emailConfig.Name" placeholder=""></el-input>
        </el-form-item>
        <!-- <el-form-item :label="$t('trials:emailManageCfg:customEmail:label:addresserEmail')" prop="EMail">
          <el-input v-model="emailConfig.EMail" placeholder=""></el-input>
        </el-form-item>
        <el-form-item :label="$t('trials:emailManageCfg:customEmail:label:addresserName')" prop="EMail">
          <el-input v-model="emailConfig.EMail" placeholder=""></el-input>
        </el-form-item> -->
      </el-form>
    </div>
    <div class="emailContent">
      <div class="template">
        <h3>{{ $t("trials:emailManageCfg:customEmail:title:emailEditAndPreview") }}</h3>
        <el-form :model="emailTemplate" label-position="top">
          <div style="display: flex;">
            <div style="width: 48%;margin-right: 2%;">
              <el-form-item :label="$t('trials:emailManageCfg:customEmail:label:emailTemplate')">
                <el-select v-model="emailTemplate.Id" placeholder="" filterable clearable style="width: 100%;"
                  @change="handleChange" @clear="reset">
                  <el-option v-for="item in list" :key="item.Id" :label="isEN ? item.EmailTopic : item.EmailTopicCN"
                    :value="item.Id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('trials:emailManageCfg:customEmail:label:emailSubject')" v-if="isEN">
                <el-input v-model="emailTemplate.EmailTopic" placeholder="" disabled></el-input>
              </el-form-item>
              <el-form-item :label="$t('trials:emailManageCfg:customEmail:label:emailSubject')" v-else>
                <el-input v-model="emailTemplate.EmailTopicCN" placeholder="" disabled></el-input>
              </el-form-item>
              <el-form-item :label="$t('trials:emailManageCfg:customEmail:label:emailContent')" v-if="isEN">
                <el-input v-model="emailTemplate.EmailHtmlContent" placeholder="" disabled type="textarea"
                  :row="4"></el-input>
              </el-form-item>
              <el-form-item :label="$t('trials:emailManageCfg:customEmail:label:emailContent')" v-else>
                <el-input v-model="emailTemplate.EmailHtmlContentCN" placeholder="" disabled type="textarea"
                  :rows="10"></el-input>
              </el-form-item>
              <el-button size="small" type="primary" :disabled="!isFull" @click="sendEmail">
                {{ $t('trials:emailManageCfg:customEmail:button:sendEmail') }}
              </el-button>
              <!-- <el-button size="small">
                {{ $t('trials:emailManageCfg:customEmail:button:saveTemplate') }}
              </el-button> -->
              <el-button size="small" @click="reset">
                {{ $t('trials:emailManageCfg:customEmail:button:reset') }}
              </el-button>
            </div>
            <div style="width: 50%;">
              <el-form-item :label="$t('trials:emailManageCfg:customEmail:label:emailPreview')">
                <div v-html="emailHtmlContent" class="previewBox"></div>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>
      <div class="inputBox">
        <h3>{{ $t("trials:emailManageCfg:customEmail:title:placeholderData") }}</h3>
        <el-form :model="placeholderData" v-if="emailSubject.length > 0 && emailContent.length > 0">
          <p>{{ $t('trials:emailManageCfg:customEmail:label:emailSubject') }}</p>
          <el-form-item v-for="item in emailSubject" :key="item.key" :label="item.name">
            <el-input v-model="placeholderData[item.key]" placeholder=""></el-input>
          </el-form-item>
          <p>{{ $t('trials:emailManageCfg:customEmail:label:emailContent') }}</p>
          <el-form-item v-for="item in emailContent" :key="item.key" :label="item.name">
            <el-input v-model="placeholderData[item.key]" placeholder="" @blur="handleBlur"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import { getAllEmailNoticeConfigList, manualSendEmail } from '@/api/dictionary'
const searchDataDefault = () => {
  return {
    IsReturnRequired: '',
    IsUrgent: '',
    IsEnable: '',
    PageIndex: 1,
    PageSize: 1000,
  }
}
export default {
  name: "customEmail",
  data() {
    return {
      searchData: searchDataDefault(),
      loading: false,
      list: [],
      emailConfig: {
        EMail: '',
        Name: ''
      },
      emailHtmlContent: null,
      emailTemplate: {
        Id: null,
        EmailTopic: null,
        EmailTopicCN: null,
        EmailHtmlContent: null,
        EmailHtmlContentCN: null
      },
      emailSubject: [],
      emailContent: [],
      placeholderData: {},
      emailConfigRule: {
        EMail: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: 'blur',
          },
          {
            // type: 'email',
            pattern: new RegExp(this.$reg().EmailRegexStr),
            message: this.$t('trials:site:ruleMessage:correctEmail'),
            trigger: ['blur'],
          }
        ],
        Name: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: 'blur',
          },
        ]
      }
    }
  },
  computed: {
    isEN() {
      return this.$i18n.locale !== 'zh'
    },
    isFull() {
      if (!this.emailTemplate.Id) return false
      if (Object.keys(this.placeholderData).length === 0) return false
      if (Object.keys(this.placeholderData).some(key => !this.placeholderData[key])) return false
      return true
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    reset() {
      Object.keys(this.emailTemplate).forEach(key => {
        this.emailTemplate[key] = null
      })
      this.emailHtmlContent = null
      this.emailSubject = []
      this.emailContent = []
      this.placeholderData = {}
    },
    getList() {
      this.loading = true
      getAllEmailNoticeConfigList(this.searchData).then(res => {
        this.loading = false
        this.list = res.Result.CurrentPageData
      }).catch(() => { this.loading = false })
    },
    formatArray(arr) {
      const obj = {};
      const unique = arr.filter(item => {
        if (!obj[item]) {
          obj[item] = true;
          return true;
        }
        return false;
      });
      return unique
    },
    handleChange(Id) {
      let tempalte = this.list.find(item => item.Id === Id)
      Object.keys(this.emailTemplate).forEach(key => {
        this.emailTemplate[key] = tempalte[key]
      })
      this.emailHtmlContent = this.isEN ? this.emailTemplate.EmailHtmlContent : this.emailTemplate.EmailHtmlContentCN
      this.emailSubject = []
      this.emailContent = []
      this.placeholderData = {}
      let emailTopic = tempalte.EmailTopic.match(/\{([^}]*)\}/g)?.map(s => s.slice(1, -1))
      emailTopic = this.formatArray(emailTopic)
      let emailHtmlContent = tempalte.EmailHtmlContent.match(/\{([^}]*)\}/g)?.map(s => s.slice(1, -1))
      emailHtmlContent = this.formatArray(emailHtmlContent)
      emailTopic.forEach(item => {
        let data = {
          key: `emailTopic_${item}`,
          name: `{${item}}`
        }
        this.emailSubject.push(data)
        this.$set(this.placeholderData, `emailTopic_${item}`, null)
      })
      emailHtmlContent.forEach(item => {
        let data = {
          key: `emailHtmlContent_${item}`,
          name: `{${item}}`
        }
        this.emailContent.push(data)
        this.$set(this.placeholderData, `emailHtmlContent_${item}`, null)
      })
    },
    handleBlur() {
      let emailHtmlContent = this.isEN ? this.emailTemplate.EmailHtmlContent : this.emailTemplate.EmailHtmlContentCN
      this.emailContent.forEach(item => {
        if (this.placeholderData[item.key]) {
          emailHtmlContent = emailHtmlContent.replaceAll(item.name, this.placeholderData[item.key])
        }
      })
      this.emailHtmlContent = emailHtmlContent
    },
    async sendEmail() {
      try {
        let validate = this.$refs.emailConfig.validate()
        if (!validate) return false
        let data = {
          TrialId: this.$route.query.trialId,
          ToEmailList: [
            {
              Name: this.emailConfig.Name,
              EmailAddress: this.emailConfig.EMail,
            }
          ],
          Subject: null,
          Content: this.emailHtmlContent
        }
        let Subject = this.isEN ? this.emailTemplate.EmailTopic : this.emailTemplate.EmailTopicCN
        this.emailSubject.forEach(item => {
          if (this.placeholderData[item.key]) {
            Subject = Subject.replaceAll(item.name, this.placeholderData[item.key])
          }
        })
        data.Subject = Subject
        this.loading = true
        let res = await manualSendEmail(data)
        this.loading = false
        if (res.IsSuccess) this.$message.success(this.$t('trials:emailManageCfg:message:sendEmailSuccess'))
      } catch (err) {
        console.log(err)
        this.loading = false
      }
    }
  }

}
</script>
<style lang="scss" scoped>
.customEmail {
  width: 100%;
  height: 100%;
  overflow-y: auto;

  .emailConfig {
    padding: 0 10px;
  }

  .previewBox {
    min-height: 500px;
    width: 100%;
    border: 1px solid #eee;
    border-radius: 10px;
    overflow: auto;
  }

  .emailContent {
    display: flex;

    .template {
      padding: 0 10px;
      width: 68%;
      margin-right: 2%;
    }

    .inputBox {
      padding: 0 10px;
      width: 30%;
      border-left: 1px solid #eee;
    }
  }

  ::v-deep .el-form-item {
    margin-bottom: 10px;
  }
}
</style>