<template>
  <el-form
    ref="emailForm"
    v-loading="loading"
    :model="form"
    label-width="180px"
    size="small"
    :rules="rules"
  >
    <el-row>
      <el-col :span="24">
        <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">
        <el-form-item label="邮件主题（CN）" prop="EmailTopicCN">
          <el-input style="width: 300px" v-model="form.EmailTopicCN" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="邮件主题（EN）" prop="EmailTopic">
          <el-input style="width: 300px" v-model="form.EmailTopic" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="邮件延时发送s数" 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="业务层级" 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="业务模块" 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="业务场景" 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="收件人" 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="抄送人" 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="加急状态" 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="发送周期和时间"
          v-if="form.EmailUrgentEnum !== 1"
          prop="EmailCron"
        >
          <el-input style="width: 300px" readonly v-model="form.EmailCron" />
          <el-button type="primary" @click="showDialog">生成 cron</el-button>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="是否需要回执" prop="IsReturnRequired">
          <el-radio-group v-model="form.IsReturnRequired">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="是否自动发送" prop="IsAutoSend">
          <el-radio-group v-model="form.IsAutoSend">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12" v-if="systemLevel">
        <el-form-item label="是否区分标准" prop="IsDistinguishCriteria">
          <el-radio-group
            v-model="form.IsDistinguishCriteria"
            @change="
              () => {
                form.CriterionTypeEnum = null
              }
            "
          >
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</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="CriterionTypeEnum"
        >
          <el-select v-model="form.CriterionTypeEnum" clearable class="mr">
            <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="是否启用" prop="IsEnable">
          <el-radio-group v-model="form.IsEnable">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="附件（CN）" 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">
        <el-form-item label="附件（EN）" 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>
    <el-form-item
      label="邮件内容模版（CN）"
      prop="EmailHtmlContentCN"
      style="position: relative"
    >
      <el-input
        v-model="form.EmailHtmlContentCN"
        type="textarea"
        :autosize="{ minRows: 8, maxRows: 8 }"
      />
      <el-button
        :disabled="!form.EmailHtmlContentCN"
        type="text"
        @click="PreviewHTML(form.EmailHtmlContentCN)"
        style="position: absolute; left: -50px; top: 30px"
      >
        {{ $t('common:button:preview') }}
      </el-button>
    </el-form-item>
    <el-form-item
      label="邮件内容模版（EN）"
      prop="EmailHtmlContent"
      style="position: relative"
    >
      <el-input
        v-model="form.EmailHtmlContent"
        type="textarea"
        :autosize="{ minRows: 8, maxRows: 8 }"
      />
      <el-button
        :disabled="!form.EmailHtmlContent"
        type="text"
        @click="PreviewHTML(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"
          >Save</el-button
        >
      </el-form-item>
    </div>
    <el-dialog append-to-body title="生成 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'
export default {
  props: {
    data: {
      type: Object,
      default() {
        return {}
      },
    },
    systemLevel: {
      type: Number,
      default() {
        return 0
      },
    },
    isDistinguishCriteria: {
      type: Boolean,
      default() {
        return false
      },
    },
  },
  components: { vcrontab },
  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,
      },
      rules: {
        Code: [{ required: true, message: 'Please select', trigger: ['blur'] }],
        BusinessScenarioEnum: [
          { required: true, message: 'Please select', trigger: ['blur'] },
        ],
        EmailTopicCN: [
          { required: true, message: 'Please select', trigger: ['blur'] },
        ],
        EmailTopic: [
          { required: true, message: 'Please select', trigger: ['blur'] },
        ],
        BusinessLevelEnum: [
          { required: true, message: 'Please select', trigger: ['blur'] },
        ],
        // ToUserTypeList: [
        //   { required: true, message: 'Please select', trigger: ['blur'] },
        // ],
        // EmailCron: [
        //   { required: true, message: 'Please select', trigger: ['blur'] },
        // ],
        EmailUrgentEnum: [
          { required: true, message: 'Please select', trigger: ['blur'] },
        ],
        EmailHtmlContentCN: [
          { required: true, message: 'Please select', trigger: ['blur'] },
        ],
        EmailHtmlContent: [
          { required: true, message: 'Please select', trigger: ['blur'] },
        ],
        CriterionTypeEnum: [
          { required: true, message: 'Please 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: {
    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('最多只能传一个附件')
        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('最多只能传一个附件')
        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('Saved successfully')
          })
          .catch(() => {
            this.loading = false
          })
      })
    },
    // 预览模板
    PreviewHTML(html) {
      this.$emit('PreviewHTML', html)
    },
  },
}
</script>
