<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" disabled v-model="form.Code" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('trials:emailManageCfg:table:EmailTopicCN')" prop="EmailTopicCN">
          <el-input style="width: 300px" disabled v-model="form.EmailTopicCN" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('trials:emailManageCfg:table:EmailTopic')" prop="EmailTopic">
          <el-input style="width: 300px" disabled v-model="form.EmailTopic" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item :label="$t('trials:emailManageCfg:table:BusinessScenarioEnum')" prop="BusinessScenarioEnum">
          <el-select v-model="form.BusinessScenarioEnum" disabled 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:table:ToUserTypeList')" prop="ToUserTypeList">
          <el-select v-model="form.ToUserTypeList" disabled 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:table:CopyUserTypeList')" prop="CopyUserTypeList">
          <el-select v-model="form.CopyUserTypeList" disabled 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('trials:emailManageCfg:table:blackUserIdList')" prop="blackUserIdList">
          <el-select v-model="form.blackUserIdList" clearable multiple class="mr">
            <el-option
              v-for="item of UserList"
              :key="`blackUserIdList${item.UserName}`"
              :label="`${item.UserName}(${item.RealName})`"
              :value="item.UserId"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-col :span="12">
          <el-form-item :label="$t('trials:emailManageCfg:table:EmailUrgentEnum')" prop="EmailUrgentEnum">
            <el-select v-model="form.EmailUrgentEnum" disabled 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 && IntervalShow" prop="EmailCron">
            <el-input-number v-model="Interval" @change="handleIntervalChange" :min="1" :max="365"></el-input-number>
<!--            <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>
      <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">{{ 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">{{ item.label }}</el-radio>
          </el-radio-group>
        </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">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item :label="$t('trials:emailManageCfg:table:CriterionTypeEnum')" v-if="form.CriterionTypeEnum && form.CriterionTypeEnum.length > 0" prop="CriterionTypeEnum">
          <el-select disabled 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="$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"
            :disabled="true"
            :limit="1"
            :file-list="fileListCN"
          >
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <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"
            :disabled="true"
            :limit="1"
            :file-list="fileListEN"
          >
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
<!--    <el-form-item label="邮件内容模版（CN）" prop="EmailHtmlContentCN">-->
<!--      <el-input-->
<!--        v-model="form.EmailHtmlContentCN"-->
<!--        type="textarea"-->
<!--        disabled-->
<!--        :autosize="{ minRows: 8, maxRows: 8}"-->
<!--      />-->
<!--    </el-form-item>-->
<!--    <el-form-item label="邮件内容模版（EN）" prop="EmailHtmlContent">-->
<!--      <el-input-->
<!--        v-model="form.EmailHtmlContent"-->
<!--        type="textarea"-->
<!--        disabled-->
<!--        :autosize="{ minRows: 8, maxRows: 8}"-->
<!--      />-->
<!--    </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>
    <el-dialog append-to-body :title="$t('trials:emailManageCfg:button:generate')" :visible.sync="showCron">
      <vcrontab @hide="showCron=false" @fill="crontabFill" :expression="expression"></vcrontab>
    </el-dialog>
  </el-form>
</template>
<script>
import { Upload, addOrUpdateTrialEmailNoticeConfig, getTrialUserIdSelectList } from '@/api/dictionary'
export default {
  props: {
    data: {
      type: Object,
      default() { return {} }
    }
  },
  data() {
    return {
      expression: '',
      showCron: false,
      form: {
        Id: '',
        Code: '',
        EmailTopicCN: '',
        EmailTopic: '',
        BusinessLevelEnum: '',
        BusinessModuleEnum: '',
        ToUserTypeList: [],
        CopyUserTypeList: [],
        blackUserIdList: [],
        EmailUrgentEnum: '',
        EmailCron: '',
        BusinessScenarioEnum: null,
        EmailHtmlContentCN: '',
        EmailHtmlContent: '',
        AttachPath: '',
        AttachName: '',
        AttachNameCN: '',
        AttachCNPath: '',
        IsDistinguishCriteria: true,
        IsReturnRequired: true,
        IsUrgent: true,
        IsEnable: true,
        IsAutoSend: true,
        CriterionTypeEnum: null,
        FromEmail: 'test@extimaging.com',
        FromName: 'Test_IRC',
        AuthorizationCode: 'SHzyyl2021',
        SMTPServerAddress: 'smtp.qiye.aliyun.com',
        SMTPServerPort: 465,
      },
      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'] }],
        EmailHtmlContentCN: [{ required: true, message: 'Please select', trigger: ['blur'] }],
        EmailHtmlContent: [{ required: true, message: 'Please select', trigger: ['blur'] }],
      },
      scenarioOption: [],
      fileListCN: [],
      fileListEN: [],
      loading: false,
      trialId: this.$route.query.trialId,
      UserList: [],
      Interval: 1,
      IntervalShow: true
    }
  },
  mounted() {
    this.initForm()
  },
  methods: {
    handleIntervalChange(v) {
      let text
      if ([10, 11].includes(this.form.ToUserTypeList)) {
        text = '0 0 17' + ' 1/' + v + ' * *'
      } else {
        text = '0 0 8' + ' 1/' + v + ' * *'
      }
      this.form.EmailCron = text
    },
    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[0] = { name: param.file.name, path: res.Result.FilePath, fullPath: res.Result.FullFilePath }
      })
    },
    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[0] = { name: param.file.name, path: res.Result.FilePath, fullPath: res.Result.FullFilePath }
      })
    },
    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 })
        }
        if (k === 'EmailCron' && this.form[k]) {
          let a = this.form[k].split(' ')
          if (a[3].indexOf('/') > -1) {
            this.Interval = a[3].split('/')[1]
          } else {
            this.IntervalShow = false
          }
        }
      }
      getTrialUserIdSelectList(this.form.Id).then(res => {
        this.UserList = res.Result
      })
      console.log(this.fileListEN, this.fileListCN)
      this.loading = false
    },

    // 保存
    handleSave() {
      this.$refs.emailForm.validate(valid => {
        if (!valid) return
        this.loading = true
        this.form.TrialId = this.trialId
        addOrUpdateTrialEmailNoticeConfig(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
        })
      })
    }
  }
}
</script>
