<template>
  <base-model :config="model_cfg">
    <template slot="dialog-body">
      <el-form
        ref="anonymizationFrom"
        :model="form"
        :rules="rules"
        label-width="100px"
        size="small"
      >
        <!-- 姓 -->
        <el-form-item :label="$t('trials:externalStaff:table:lastName')" prop="LastName">
          <el-input v-model="form.LastName" />
        </el-form-item>
        <!-- 名 -->
        <el-form-item :label="$t('trials:externalStaff:table:firstName')" prop="FirstName">
          <el-input v-model="form.FirstName" />
        </el-form-item>
        <!-- 用户类型 -->
        <el-form-item :label="$t('trials:externalStaff:table:userType')" prop="UserTypeId">
          <el-select
            v-if="userTypeOptions"
            v-model="form.UserTypeId"
            style="width:100%"
          >
            <el-option
              v-for="item of userTypeOptions"
              :key="item.Id"
              :label="item.UserTypeShortName"
              :value="item.Id"
            >
              <span>{{ item.UserType }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 电话号码 -->
        <el-form-item :label="$t('trials:externalStaff:table:phone')" prop="Phone">
          <el-input v-model="form.Phone" />
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item :label="$t('trials:externalStaff:table:email')" prop="Email">
          <el-input v-model="form.Email" />
        </el-form-item>
        <!-- 单位 -->
        <el-form-item :label="$t('trials:externalStaff:table:organization')" prop="OrganizationName">
          <el-input v-model="form.OrganizationName" />
        </el-form-item>
      </el-form>
      <div v-if="errorMsg" style="font-size: 12px;color: #f66;">{{ errorMsg }}</div>
    </template>
    <template slot="dialog-footer">
      <!-- 取消 -->
      <el-button size="small" type="primary" :disabled="btnLoading" @click="handleCancel">
        {{ $t('common:button:cancel') }}
      </el-button>
      <!-- 保存 -->
      <el-button size="small" type="primary" :loading="btnLoading" @click="handleSave">
        {{ $t('common:button:save') }}
      </el-button>
      <!-- 保存且发邮件 -->
      <el-button size="small" type="primary" :loading="btnLoading" @click="handleSave('SendEmail')">
        {{ $t('trials:externalStaff:button:saveAndSendEmail') }}
      </el-button>
    </template>
  </base-model>
</template>
<script>
import { addOrUpdateTrialExternalUser } from '@/api/trials'
import BaseModel from '@/components/BaseModel'

const formDataDefault = () => {
  return {
    Id: null,
    TrialId: null,
    LastName: null,
    FirstName: null,
    UserTypeId: '',
    Phone: null,
    Email: null,
    OrganizationName: null
  }
}
export default {
  name: 'StaffExternalAdd',
  components: { BaseModel },
  props: {
    userTypeOptions: {
      type: Array,
      default: function() {
        return {}
      }
    }
  },
  data() {
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
      if (!value) {
        callback()
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error(this.$t('trials:externalStaff:formRule:phone')))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error(this.$t('trials:externalStaff:formRule:phone')))
          }
        }
      }, 100)
    }
    var validateEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('common:ruleMessage:specify')))
      } else {
        var reg = /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/
        if (this.form.Email && reg.test(this.form.Email)) {
          this.sendDisabled = false
          callback()
        } else {
          callback(new Error(this.$t('trials:externalStaff:formRule:email')))
          this.sendDisabled = true
        }
      }
    }
    return {
      form: {
        Id: null,
        LastName: null,
        FirstName: null,
        UserTypeId: '',
        Phone: null,
        Email: null,
        TrialId: null,
        IsSendEmail: false
      },
      rules: {
        LastName: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { min: 0, max: 50, message: `${this.$t('common:ruleMessage:maxLength')} 50`, trigger: 'blur' }
        ],
        FirstName: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { min: 0, max: 50, message: `${this.$t('common:ruleMessage:maxLength')} 50`, trigger: 'blur' }
        ],
        UserTypeId: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] }],
        Phone: [
          { required: false, validator: checkPhone, trigger: ['blur'] }
        ],
        Email: [
          { required: true, validator: validateEmail, trigger: ['blur'] }
        ]
      },
      btnLoading: false,
      userRoles: [],
      userTypeEnumInt: 0,
      model_cfg: { visible: false, showClose: true, width: '600px', title: '', appendToBody: true },
      trialId: '',
      errorMsg: null
    }
  },
  watch: {
    model_cfg: {
      handler(newName, oldName) {
        this.errorMsg = null
      },
      deep: true
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
  },
  methods: {
    openDialog(title, data) {
      this.model_cfg.visible = true
      this.model_cfg.title = title
      if (Object.keys(data).length) {
        this.form = { ...data }
      } else {
        this.form = formDataDefault()
      }
    },
    handleSave(v) {
      this.$refs.anonymizationFrom.validate(valid => {
        if (valid) {
          this.btnLoading = true
          this.form.TrialId = this.trialId
          if (v === 'SendEmail') {
            this.form.IsSendEmail = true
            this.form.BaseUrl = `${location.protocol}//${location.host}/login`
            this.form.RouteUrl = `${location.protocol}//${location.host}/email-recompose`
          }
          addOrUpdateTrialExternalUser(this.form).then(res => {
            this.btnLoading = false
            this.$message.success(this.$t('common:message:savedSuccessfully'))
            this.model_cfg.visible = false
            this.$emit('getList')
          }).catch((res) => {
            if (res.Result) {
              this.$set(this.form, 'LastName', res.Result.LastName)
              this.$set(this.form, 'FirstName', res.Result.FirstName)
              this.$set(this.form, 'Phone', res.Result.Phone)
              this.errorMsg = res.ErrorMessage
            }
            this.btnLoading = false
          })
        }
      })
    },
    handleCancel() {
      this.model_cfg.visible = false
    }
  }
}
</script>
