<template>
  <el-form
    ref="emailForm"
    v-loading="loading"
    :model="form"
    label-width="150px"
    size="small"
    :rules="rules"
    class="email_wrapper"
  >
    <div class="base-dialog-body">
      <!-- Code -->
      <el-form-item :label="$t('trials:emailManageCfg:title:code')" prop="Code">
        <el-input :maxLength="$inputMax" v-model="form.Code" />
      </el-form-item>
      <el-form-item :label="$t('trials:consistencyAnalysis:table:criterionName')" prop="TrialReadingCriterionId">
        <el-select v-model="form.TrialReadingCriterionId" style="width:100%;" clearable>
          <el-option v-for="item of trialCriterionList" :key="'TrialReadingCriterionId' + item.TrialReadingCriterionId" :value="item.TrialReadingCriterionId" :label="item.TrialReadingCriterionName" />
        </el-select>
      </el-form-item>
      <!-- 业务场景 -->
      <el-form-item :label="$t('trials:emailManageCfg:title:businessScenario')" prop="BusinessScenarioEnum">
        <el-select
          v-model="form.BusinessScenarioEnum"
          style="width:100%;"
          size="small"
        >
          <el-option
            v-for="item of $d.Common_File_BusinessScenario"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
<!--      &lt;!&ndash; 发件人 &ndash;&gt;-->
<!--      <el-form-item :label="$t('trials:emailManageCfg:title:fromName')" prop="FromName">-->
<!--        <el-input :maxLength="$inputMax" v-model="form.FromName" />-->
<!--      </el-form-item>-->
<!--      &lt;!&ndash; 发件箱 &ndash;&gt;-->
<!--      <el-form-item :label="$t('trials:emailManageCfg:title:fromEmail')" prop="FromEmail">-->
<!--        <el-input :maxLength="$inputMax" v-model="form.FromEmail" />-->
<!--      </el-form-item>-->
<!--      &lt;!&ndash; SMTP服务器地址 &ndash;&gt;-->
<!--      <el-form-item :label="$t('trials:emailManageCfg:title:SMTPServerAddress')" prop="SMTPServerAddress">-->
<!--        <el-input :maxLength="$inputMax" v-model="form.SMTPServerAddress" placeholder="smtp.qiye.aliyun.com" />-->
<!--      </el-form-item>-->
<!--      &lt;!&ndash; SMTP服务器端口 &ndash;&gt;-->
<!--      <el-form-item :label="$t('trials:emailManageCfg:title:SMTPServerPort')" prop="SMTPServerPort">-->
<!--        <el-input-number v-model="form.SMTPServerPort" controls-position="right" placeholder="25" />-->
<!--      </el-form-item>-->
<!--      &lt;!&ndash; 密码 &ndash;&gt;-->
<!--      <el-form-item :label="$t('trials:emailManageCfg:title:authorizationCode')" prop="AuthorizationCode">-->
<!--        <el-input :maxLength="$inputMax" v-model="form.AuthorizationCode" />-->
<!--      </el-form-item>-->
      <!-- 收件人 -->
      <el-form-item :label="$t('trials:emailManageCfg:title:toUserTypeList')" prop="ToUserTypeList">
        <el-select
          v-model="form.ToUserTypeList"
          style="width:100%;"
          size="small"
          multiple
        >
          <el-option
            v-for="item of toUsers"
            :key="item.Id"
            :label="item.UserTypeShortName"
            :value="item.UserTypeEnum"
          />
        </el-select>
      </el-form-item>
      <!-- 抄送人 -->
      <el-form-item :label="$t('trials:emailManageCfg:title:copyUserTypeList')" prop="CopyUserTypeList">
        <el-select
          v-model="form.CopyUserTypeList"
          style="width:100%;"
          size="small"
          multiple
        >
          <el-option
            v-for="item of copyUsers"
            :key="item.Id"
            :label="item.UserTypeShortName"
            :value="item.UserTypeEnum"
          />
        </el-select>
      </el-form-item>
      <!-- 附件 -->
      <el-form-item v-if="criterionType === 0" :label="$t('trials:emailManageCfg:title:fileName')">
        <div class="upload-container">
          <el-upload
            class="upload-demo"
            action
            accept=".xls,.xlsx,.doc,.docx"
            :before-upload="beforeUpload"
            :http-request="handleUploadFile"
            :on-preview="handlePreview"
            :on-remove="handleRemoveFile"
            :show-file-list="true"
            :file-list="fileList"
            :limit="1"
            :on-exceed="handleExceed"
          >
            <!-- 选择 -->
            <el-button size="small" type="primary">{{ $t('trials:emailManageCfg:button:select') }}</el-button>
            <span
              slot="tip"
              style="margin-left:10px;"
              class="el-upload__tip"
            >
              <!-- (must be in xlsx/xls/doc/docx format) -->
              {{ $t('trials:emailManageCfg:message:format') }}
            </span>
          </el-upload>
        </div>
      </el-form-item>
      <!-- 是否需要回执 -->
      <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"
            :key="'IsReturnRequired' + item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 是否加急 -->
      <el-form-item :label="$t('trials:emailManageCfg:title:isUrgent')" prop="IsUrgent">
        <el-radio-group v-model="form.IsUrgent">
          <el-radio
            v-for="item of $d.YesOrNo"
            :key="'IsUrgent' + item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 是否自动发送 -->
      <el-form-item :label="$t('trials:emailManageCfg:title:isAutoSend')" prop="IsAutoSend">
        <el-radio-group v-model="form.IsAutoSend">
          <el-radio
            v-for="item of $d.YesOrNo"
            :key="'IsAutoSend' + item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item label="是否区分标准" prop="IsDistinguishCriteria">
        <el-radio-group v-model="form.IsDistinguishCriteria">
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
      </el-form-item> -->

      <!-- <el-form-item v-if="!!form.Id" 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> -->
    </div>
    <div class="base-dialog-footer" style="text-align:right;margin-top:10px;">
      <el-form-item style="text-align:right;">
        <!-- 取消 -->
        <el-button size="small" type="primary" @click="close">
          {{ $t('common:button:cancel') }}
        </el-button>
        <!-- 保存 -->
        <el-button size="small" type="primary" @click="handleSave">
          {{ $t('common:button:save') }}
        </el-button>
      </el-form-item>
    </div>
  </el-form>
</template>
<script>
import { addOrUpdateTrialEmailNoticeConfig, getUserTypeList } from '@/api/trials'
import { getTrialCriterionList } from '@/api/trials/reading'
import { uploadCommonDoc } from '@/api/dictionary'
export default {
  props: {
    data: {
      type: Object,
      default() { return {} }
    },
    criterionType: {
      type: Number,
      required: true
    }
  },

  data() {
    return {
      form: {
        Id: '',
        Code: '',
        AuthorizationCode: '',
        SMTPServerAddress: 'smtp.qiye.aliyun.com',
        SMTPServerPort: 465,
        BusinessScenarioEnum: null,
        CriterionTypeEnum: null,
        TrialReadingCriterionId: null,
        // FromEmail: '',
        // ReceiveEmail: '',
        // CopyEmail: '',
        FromName: '',
        FromEmail: '',
        ToUserTypeList: [],
        CopyUserTypeList: [],
        IsReturnRequired: true,
        IsUrgent: true,
        IsEnable: true,
        IsAutoSend: true,
        FilePath: '',
        FileName: ''
      },
      rules: {
        Code: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: ['blur'] }],
        AuthorizationCode: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: ['blur'] }],
        SMTPServerAddress: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: ['blur'] }],
        SMTPServerPort: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: ['blur'] }],
        FromName: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: ['blur'] }],
        TrialReadingCriterionId: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: ['blur'] }],
        FromEmail: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: 'blur'
          },
          {
            type: 'email',
            message: this.$t('passwordReset:formRule:passwordinvalid'),
            trigger: ['blur']
          }
        ],
        ToUserTypeList: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] }],
        BusinessScenarioEnum: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] }]
      },
      scenarioOption: [],
      fileList: [],
      toUsers: [],
      copyUsers: [],
      loading: false,
      trialCriterionList: []
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    this.initForm()
    this.getTrialCriterionList()
  },
  methods: {
    getTrialCriterionList() {
      this.loading = true
      getTrialCriterionList(this.trialId).then(res => {
        this.trialCriterionList = res.Result
        // this.activeTab = this.trialCriterionList[0].TrialReadingCriterionId
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    async initForm() {
      this.loading = true
      await this.getToUserTypeSelectList()
      await this.getToCopyTypeSelectList()
      for (const k in this.form) {
        if (this.data.hasOwnProperty(k)) {
          this.form[k] = this.data[k]
        }
      }
      this.loading = false
    },
    getToUserTypeSelectList() {
      getUserTypeList(4).then(res => {
        this.toUsers = res.Result
      }).catch(() => { this.loading = false })
    },
    getToCopyTypeSelectList() {
      getUserTypeList(5).then(res => {
        this.copyUsers = res.Result
      }).catch(() => { this.loading = false })
    },
    // 保存
    handleSave() {
      this.$refs.emailForm.validate(valid => {
        if (!valid) return
        this.loading = true
        this.form.TrialId = this.$route.query.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
        })
      })
    },
    beforeUpload(file) {
      // 检测文件类型是否符合要求
      if (this.checkFileSuffix(file.name)) {
        this.fileList = []
        return true
      } else {
        this.$message.error(this.$t('trials:emailManageCfg:message:format'))// '必须是word/excel格式'

        return false
      }
    },
    handleUploadFile(param) {
      this.loading = true
      uploadCommonDoc(param.file).then(res => {
        this.loading = false
        if (res.IsSuccess) {
          this.form.FilePath = res.Result.FilePath
          this.form.FileName = param.file.name
          const file = { name: this.form.FileName, path: this.form.FilePath }
          this.fileList.push(file)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    handleRemoveFile() {
      this.fileList = []
      this.form.FilePath = ''
      this.form.FileName = ''
    },
    handlePreview(file) {
      if (file.fullPath) {
        window.open(file.fullPath, '_blank')
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(this.$t('trials:emailManageCfg:message:onlyOneFile'))// `最多只允许上传一个文件`
    },
    checkFileSuffix(fileName) {
      var typeArr = ['xls', 'xlsx', 'doc', 'docx']
      var extendName = fileName.substring(fileName.lastIndexOf('.') + 1).toLocaleLowerCase()
      if (typeArr.indexOf(extendName) !== -1) {
        return true
      } else {
        return false
      }
    },
    close() {
      this.$emit('closeDialog')
    }
  }
}
</script>
<style lang="scss" scoped>
.email_wrapper{
  .upload-container{
    >>>.el-upload {
    width: 100%;
      text-align: left;
    }
    >>>.el-upload--text {
      border: none;
      width: 80px;
      height: 40px;
    }
    .el-input--small {
      margin-bottom: 5px;
    }
    .el-icon-circle-check {
      color: #00d1b2;
      font-size: 13px;
    }
    .account_item_clear{
      .el-tag__close{
        display: none !important;
      }
    }
  }

}
</style>
