<template>
  <el-form ref="emailForm" v-loading="loading" :model="form" label-width="180px" size="small" :rules="rules">
    <el-row>
      <el-col :span="24">
        <!-- Code -->
        <el-form-item label="Code: " prop="Code">
          <el-input style="width: 300px" v-model="form.Code" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 邮件主题（CN） -->
        <el-form-item :label="$t('trials:emailManageCfg:table:EmailTopicCN')" prop="EmailTopicCN">
          <el-input style="width: 300px" v-model="form.EmailTopicCN" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 邮件主题（EN） -->
        <el-form-item :label="$t('trials:emailManageCfg:table:EmailTopic')" prop="EmailTopic">
          <el-input style="width: 300px" v-model="form.EmailTopic" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 邮件延时发送s数 -->
        <el-form-item :label="$t('dictionary:email:label:emailDelaySeconds')" prop="EmailDelaySeconds">
          <el-input v-model.number="form.EmailDelaySeconds" style="width: 300px" type="number" clearable>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 业务层级 -->
        <el-form-item :label="$t('dictionary:email:label:businessLevel')" prop="BusinessLevelEnum">
          <el-select v-model="form.BusinessLevelEnum" clearable class="mr">
            <el-option v-for="item of $d.BusinessLevel" :key="`BusinessLevel${item.label}`" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 业务模块 -->
        <el-form-item :label="$t('dictionary:email:label:businessModule')" prop="BusinessModuleEnum">
          <el-select v-model="form.BusinessModuleEnum" clearable class="mr">
            <el-option v-for="item of $d.BusinessModule" :key="`BusinessModule${item.label}`" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 业务场景 -->
        <el-form-item :label="$t('trials:emailManageCfg:table:BusinessScenarioEnum')" prop="BusinessScenarioEnum">
          <el-select v-model="form.BusinessScenarioEnum" clearable class="mr">
            <el-option v-for="item of $d.Email_BusinessScenario" :key="`BusinessScenarioEnum${item.label}`"
              :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 收件人 -->
        <el-form-item :label="$t('trials:emailManageCfg:title:toUserTypeList')" prop="ToUserTypeList">
          <el-select v-model="form.ToUserTypeList" clearable multiple class="mr">
            <el-option v-for="item of $d.UserType" :key="`ToUserTypeList${item.label}`" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 抄送人 -->
        <el-form-item :label="$t('trials:emailManageCfg:title:copyUserTypeList')" prop="CopyUserTypeList">
          <el-select v-model="form.CopyUserTypeList" clearable multiple class="mr">
            <el-option v-for="item of $d.UserType" :key="`CopyUserTypeList${item.label}`" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 加急状态 -->
        <el-form-item :label="$t('dictionary:email:label:IsUrgent')" prop="EmailUrgentEnum">
          <el-select v-model="form.EmailUrgentEnum" @change="
            (v) => {
              v === 1 ? (form.EmailCron = null) : null
            }
          " clearable class="mr">
            <el-option v-for="item of $d.EmailUrgent" :key="`EmailUrgent${item.label}`" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 发送周期和时间 -->
        <el-form-item :label="$t('trials:emailManageCfg:table:EmailCron')" v-if="form.EmailUrgentEnum !== 1"
          prop="EmailCron">
          <el-input style="width: 300px" readonly v-model="form.EmailCron" />
          <!-- 生成 cron -->
          <el-button type="primary" @click="showDialog"> {{ $t('dictionary:email:button:cron') }} </el-button>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 是否需要回执 -->
        <el-form-item :label="$t('trials:emailManageCfg:title:isReturnRequired')" prop="IsReturnRequired">
          <el-radio-group v-model="form.IsReturnRequired">
            <el-radio v-for="item of $d.YesOrNo" :label="item.value" :key="`IsReturnRequired${item.value}`">{{
              item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 是否自动发送 -->
        <el-form-item :label="$t('trials:emailManageCfg:table:IsAutoSend')" prop="IsAutoSend">
          <el-radio-group v-model="form.IsAutoSend">
            <el-radio v-for="item of $d.YesOrNo" :label="item.value" :key="`IsAutoSend${item.value}`">{{ item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12" v-if="systemLevel">
        <!-- 是否区分标准 -->
        <el-form-item :label="$t('dictionary:email:button:isDistinguishCriteria')" prop="IsDistinguishCriteria">
          <el-radio-group v-model="form.IsDistinguishCriteria" @change="
            () => {
              form.CriterionTypeEnum = null
            }
          ">
            <el-radio v-for="item of $d.YesOrNo" :label="item.value" :key="`IsDistinguishCriteria${item.value}`">{{
              item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('trials:auditRecord:table:criterion')" v-if="form.IsDistinguishCriteria"
          prop="CriterionTypeList">
          <el-select v-model="form.CriterionTypeList" clearable class="mr" multiple>
            <el-option v-for="item of $d.CriterionType" :key="`CriterionType${item.label}`" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 是否启用 -->
        <el-form-item :label="$t('trials:emailManageCfg:table:IsEnable')" prop="IsEnable">
          <el-radio-group v-model="form.IsEnable">
            <el-radio v-for="item of $d.YesOrNo" :label="item.value" :key="`IsEnable${item.value}`">{{ item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 附件（CN） -->
        <el-form-item :label="$t('trials:emailManageCfg:table:fileListCN')" prop="IsEnable">
          <el-upload class="upload-demo" action :before-upload="beforeUploadCN" :http-request="handleUploadFileCN"
            :on-preview="handlePreviewCN" :on-remove="handleRemoveFileCN" :show-file-list="true" :limit="1"
            :file-list="fileListCN">
            <el-button size="small" type="primary" :disabled="fileListCN.length > 0">{{ $t('common:button:upload')
            }}</el-button>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 附件（EN） -->
        <el-form-item :label="$t('trials:emailManageCfg:table:fileListEN')" prop="IsEnable">
          <el-upload class="upload-demo" action :before-upload="beforeUploadEN" :http-request="handleUploadFileEN"
            :on-preview="handlePreviewEN" :on-remove="handleRemoveFileEN" :show-file-list="true" :limit="1"
            :file-list="fileListEN">
            <el-button size="small" type="primary" :disabled="fileListEN.length > 0">{{ $t('common:button:upload')
            }}</el-button>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 邮件内容模版（CN） -->
    <el-form-item :label="$t('dictionary:email:label:emailHtmlContentCN')" prop="EmailHtmlContentCN"
      style="position: relative">
      <div class="html_temp">
        <prism-editor class="my-editor" v-model="form.EmailHtmlContentCN" :highlight="highlighter" :line-numbers="true"
          style="width: 50%;max-height: 500px;"></prism-editor>
        <div v-html="form.EmailHtmlContentCN" style="width: 50%;"></div>
      </div>
      <!-- <el-input v-model="form.EmailHtmlContentCN" type="textarea" :autosize="{ minRows: 8, maxRows: 8 }" />
      <el-button :disabled="!form.EmailHtmlContentCN && form.EmailHtmlContent" type="text"
        @click="PreviewHTML(form.EmailHtmlContentCN, form.EmailHtmlContent)"
        style="position: absolute; left: -50px; top: 30px">
        {{ $t('common:button:preview') }}
      </el-button> -->
    </el-form-item>
    <!-- 邮件内容模版（EN） -->
    <el-form-item :label="$t('dictionary:email:label:emailHtmlContent')" prop="EmailHtmlContent"
      style="position: relative">
      <div class="html_temp">
        <prism-editor class="my-editor" v-model="form.EmailHtmlContent" :highlight="highlighter" :line-numbers="true"
          style="width: 50%;max-height: 500px;"></prism-editor>
        <div v-html="form.EmailHtmlContent" style="width: 50%;"></div>
      </div>
      <!-- <el-input v-model="form.EmailHtmlContent" type="textarea" :autosize="{ minRows: 8, maxRows: 8 }" />
      <el-button :disabled="!form.EmailHtmlContentCN && form.EmailHtmlContent" type="text"
        @click="PreviewHTML(form.EmailHtmlContentCN, form.EmailHtmlContent)"
        style="position: absolute; left: -50px; top: 30px">
        {{ $t('common:button:preview') }}
      </el-button> -->
    </el-form-item>
    <div class="base-dialog-footer" style="text-align: right; margin-top: 10px; padding-bottom: 10px">
      <el-form-item style="text-align: right">
        <el-button size="small" type="primary" @click="handleSave">
          {{ $t('common:button:save') }}
        </el-button>
      </el-form-item>
    </div>
    <!-- 生成 cron -->
    <el-dialog append-to-body :title="$t('dictionary:email:button:cron')" :visible.sync="showCron">
      <vcrontab :hideComponent="['year']" @hide="showCron = false" @fill="crontabFill" :expression="expression">
      </vcrontab>
    </el-dialog>
  </el-form>
</template>
<script>
import { Upload, addOrUpdateEmailNoticeConfigList } from '@/api/dictionary'
import vcrontab from 'vcrontab'

import { PrismEditor } from 'vue-prism-editor';
import 'vue-prism-editor/dist/prismeditor.min.css';
import { highlight, languages } from 'prismjs/components/prism-core';
import 'prismjs/components/prism-clike';
import 'prismjs/components/prism-javascript';
import 'prismjs/themes/prism.css';

export default {
  props: {
    data: {
      type: Object,
      default() {
        return {}
      },
    },
    systemLevel: {
      type: Number,
      default() {
        return 0
      },
    },
    isDistinguishCriteria: {
      type: Boolean,
      default() {
        return false
      },
    },
  },
  components: { vcrontab, PrismEditor },
  data() {
    return {
      expression: '',
      showCron: false,
      form: {
        Id: '',
        Code: '',
        EmailTopicCN: '',
        EmailTopic: '',
        BusinessLevelEnum: '',
        BusinessModuleEnum: '',
        ToUserTypeList: '',
        CopyUserTypeList: '',
        EmailUrgentEnum: '',
        EmailCron: '',
        BusinessScenarioEnum: null,
        EmailHtmlContentCN: '',
        EmailHtmlContent: '',
        AttachPath: '',
        AttachName: '',
        AttachNameCN: '',
        AttachCNPath: '',
        IsDistinguishCriteria: true,
        IsReturnRequired: true,
        IsUrgent: true,
        IsEnable: true,
        IsAutoSend: true,
        CriterionTypeEnum: null,
        EmailDelaySeconds: null,
        CriterionTypeList: []
      },
      rules: {
        Code: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] }],
        BusinessScenarioEnum: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] },
        ],
        EmailTopicCN: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] },
        ],
        EmailTopic: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] },
        ],
        BusinessLevelEnum: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] },
        ],
        // ToUserTypeList: [
        //   { required: true, message: 'Please select', trigger: ['blur'] },
        // ],
        // EmailCron: [
        //   { required: true, message: 'Please select', trigger: ['blur'] },
        // ],
        EmailUrgentEnum: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] },
        ],
        EmailHtmlContentCN: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] },
        ],
        EmailHtmlContent: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] },
        ],
        CriterionTypeList: [
          { required: true, type: 'array', message: this.$t('common:ruleMessage:select'), trigger: ['blur'] },
        ],
      },
      scenarioOption: [],
      fileListCN: [],
      fileListEN: [],
      loading: false,
    }
  },
  mounted() {
    this.initForm()
    if (this.systemLevel) {
      if (this.systemLevel === 1) {
        this.form.ToUserTypeList = []
      }
      this.form.CopyUserTypeList = []
      this.form.EmailUrgentEnum = 3
      this.form.IsReturnRequired = false
      this.form.IsDistinguishCriteria = false
    } else {
      this.form.IsDistinguishCriteria = this.isDistinguishCriteria
    }
  },
  methods: {
    highlighter(code) {
      return highlight(code, languages.js);
    },
    showDialog() {
      this.expression = this.form.EmailCron //传入的 cron 表达式，可以反解析到 UI 上
      this.showCron = true
    },
    crontabFill(value) {
      this.form.EmailCron = value
    },
    handleRemoveFileCN() {
      this.form.AttachNameCN = null
      this.form.AttachCNPath = null
      this.fileListCN = []
    },
    beforeUploadCN() {
      if (this.fileListCN.length > 0) {
        this.$alert(this.$t('trials:emailManageCfg:message:msg1'))
        return
      }
    },
    handlePreviewCN(row, r2) {
      if (row.fullPath) {
        window.open(row.fullPath, '_blank')
      }
    },
    handleUploadFileCN(param) {
      this.btnLoading = true
      const formData = new FormData()
      formData.append('file', param.file)
      this.form.AttachNameCN = param.file.name
      Upload(formData, 3).then((res) => {
        this.form.AttachCNPath = res.Result.FilePath
        this.btnLoading = false
        this.fileListCN.push({
          name: param.file.name,
          path: res.Result.FilePath,
          fullPath: res.Result.FullFilePath,
          url: res.Result.FilePath,
        })
      })
    },
    handleUploadFileEN(param) {
      this.btnLoading = true
      const formData = new FormData()
      formData.append('file', param.file)
      this.form.AttachName = param.file.name
      Upload(formData, 3).then((res) => {
        this.form.AttachPath = res.Result.FilePath
        this.btnLoading = false
        this.fileListEN.push({
          name: param.file.name,
          path: res.Result.FilePath,
          fullPath: res.Result.FullFilePath,
          url: res.Result.FilePath,
        })
      })
    },
    handleRemoveFileEN() {
      this.form.AttachName = null
      this.form.AttachPath = null
      this.fileListEN = []
    },
    beforeUploadEN() {
      if (this.fileListEN.length > 0) {
        this.$alert(this.$t('trials:emailManageCfg:message:msg1'))
        return
      }
    },
    handlePreviewEN(row, r2) {
      if (row.fullPath) {
        window.open(row.fullPath, '_blank')
      }
    },
    async initForm() {
      this.loading = true
      // await this.getScenarios()
      for (const k in this.form) {
        if (this.data.hasOwnProperty(k)) {
          this.form[k] = this.data[k]
        }
        if (k === 'AttachPath' && this.form[k]) {
          this.fileListEN.push({
            name: this.data.AttachName,
            path: this.data.AttachPath,
            fullPath: this.data.AttachPath,
            url: this.data.AttachPath,
          })
        }
        if (k === 'AttachCNPath' && this.form[k]) {
          this.fileListCN.push({
            name: this.data.AttachNameCN,
            path: this.data.AttachCNPath,
            fullPath: this.data.AttachCNPath,
            url: this.data.AttachCNPath,
          })
        }
      }
      this.loading = false
    },

    // 保存
    handleSave() {
      this.$refs.emailForm.validate((valid) => {
        if (!valid) return
        this.loading = true
        this.form.systemLevel = this.systemLevel
        addOrUpdateEmailNoticeConfigList(this.form)
          .then((res) => {
            this.loading = false
            this.$emit('closeDialog')
            this.$emit('getList')
            this.$message.success(this.$t('common:message:savedSuccessfully'))
          })
          .catch(() => {
            this.loading = false
          })
      })
    },
    // 预览模板
    PreviewHTML(html, htmlEn) {
      this.$emit('PreviewHTML', html, htmlEn)
    },
  },
}
</script>
<style lang="scss" scoped>
.html_temp {
  display: flex;

  .my-editor {
    border: 1px solid #333;
  }

}
</style>
