<template>
  <el-form ref="participantForm" :model="form" :rules="rules" label-width="100px" :inline="true">
    <div class="base-dialog-body">
      <!-- 姓 -->
      <el-form-item :label="$t('trials:staffResearch:form:lastName')" prop="LastName">
        <el-input :maxLength="$inputMax"
          v-model="form.LastName"
          :disabled="!(state === 0 && userTypeEnumInt === 0)"
          style="width:200px;"
        />
      </el-form-item>
      <!-- 名 -->
      <el-form-item :label="$t('trials:staffResearch:form:firstName')" prop="FirstName">
        <el-input :maxLength="$inputMax"
          v-model="form.FirstName"
          :disabled="!(state === 0 && userTypeEnumInt === 0)"
          style="width:200px;"
        />
      </el-form-item>
      <!-- 角色 -->
      <el-form-item :label="$t('trials:staffResearch:form:role')" prop="TrialRoleNameId">
        <el-select
          v-model="form.TrialRoleNameId"
          style="width:200px;"
          :disabled="!(state === 0 && userTypeEnumInt === 0)"
        >
          <el-option
            v-for="item of dictionaryList.SiteSurvey_UserRoles"
            :key="item.Id"
            :label="item.Value"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>
      <!-- 电话号码 -->
      <el-form-item :label="$t('trials:staffResearch:form:phone')" prop="Phone">
        <el-input :maxLength="$inputMax"
          v-model="form.Phone"
          :disabled="!(state === 0 && userTypeEnumInt === 0)"
          style="width:200px;"
        />
      </el-form-item>
      <!-- 邮箱 -->
      <el-form-item :label="$t('trials:staffResearch:form:email')" prop="Email">
        <el-input :maxLength="$inputMax"
          v-model="form.Email"
          :disabled="!(state === 0 && userTypeEnumInt === 0)"
          style="width:200px;"
        />
      </el-form-item>
      <!-- 单位 -->
      <el-form-item :label="$t('trials:staffResearch:form:organization')" prop="OrganizationName">
        <el-input :maxLength="$inputMax"
          v-model="form.OrganizationName"
          :disabled="!(state === 0 && userTypeEnumInt === 0)"
          style="width:200px;"
        />
      </el-form-item>
      <el-row>
        <!-- 是否生成账号 -->
        <el-form-item
          v-if="hasPermi(['role:pm','role:apm'])"
          :label="$t('trials:staffResearch:form:isGenerate')"
        >
          <el-radio-group
            v-model="form.IsGenerateAccount"
            style="width:200px;"
            @change="handleIsGenerateAccountChange"
          >
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 用户类型 -->
        <el-form-item
          v-if="hasPermi(['role:pm','role:apm']) && form.IsGenerateAccount"
          :label="$t('trials:staffResearch:form:userType')"
          prop="UserTypeId"
        >
          <el-select
            v-model="form.UserTypeId"
            style="width:200px;"
            :disabled="!form.IsGenerateAccount"
          >
            <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-row>
      <el-form-item v-if="errorMsg" label="">
        <span v-if="errorMsg" style="font-size: 12px;color: #f66;">{{ errorMsg }}</span>
      </el-form-item>

    </div>
    <div class="base-dialog-footer" style="text-align:right;margin-top:10px;">
      <el-form-item>
        <!-- 取消 -->
        <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-form-item>
    </div>
  </el-form>
</template>
<script>
import { addOrUpdateTrialSiteUserSurvey } from '@/api/research'
import { getUserTypeList } from '@/api/research'
import { getBasicDataSelects } from '@/api/dictionary/dictionary'
import { getQueryString } from '@/utils/history.js'
export default {
  name: 'ResearchParticipantForm',
  props: {
    data: {
      type: Object,
      default() {
        return {}
      }
    },
    state: {
      type: Number,
      required: true
    }
  },
  data() {
    // var checkPhone = (rule, value, callback) => {
    //   const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
    //   if (!value) {
    //     return callback(new Error('请注明'))
    //   }
    //   setTimeout(() => {
    //     if (!Number.isInteger(+value)) {
    //       callback(new Error('The phone should be number.'))
    //     } else {
    //       if (phoneReg.test(value)) {
    //         callback()
    //       }
    //       else {
    //         callback(new Error('The phone is invalid.'))
    //       }
    //     }
    //   }, 100)
    // }
    var validateEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('trials:researchForm:formRule: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:researchForm:formRule:email')))
          this.sendDisabled = true
        }
      }
    }
    return {
      form: {
        Id: '',
        LastName: null,
        FirstName: null,
        TrialRoleNameId: '',
        UserTypeId: null,
        Phone: null,
        Email: null,
        OrganizationName: '',
        // IsCorrect: false,
        IsGenerateAccount: false,
        IsDisable: false

      },
      rules: {
        LastName: [
          { required: true, message: this.$t('trials:researchForm:formRule:specify'), trigger: 'blur' },
          { min: 0, max: 50, message: this.$t('trials:researchForm:formRule:maxLength'), trigger: 'blur' }
        ],
        FirstName: [
          { required: true, message: this.$t('trials:researchForm:formRule:specify'), trigger: 'blur' },
          { min: 0, max: 50, message: this.$t('trials:researchForm:formRule:maxLength'), trigger: 'blur' }
        ],
        TrialRoleNameId: [
          { required: true, message: this.$t('trials:researchForm:formRule:select'), trigger: ['blur', 'change'] }
        ],
        UserTypeId: [{ required: true, message: this.$t('trials:researchForm:formRule:select'), trigger: ['blur'] }],
        Phone: [
          { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        Email: [
          { required: true, validator: validateEmail, trigger: ['blur'] }
        ]
      },
      btnLoading: false,
      userRoles: [],
      userTypeOptions: [],
      userTypeEnumInt: 0,
      errorMsg: '',
      dictionaryList: {}
    }
  },
  mounted() {
    this.initForm()
  },
  methods: {
    async initForm() {
      await this.getDicData()
      Object.keys(this.data).forEach(key => {
        this.form[key] = this.data[key]
      })
      if (zzSessionStorage.getItem('userTypeEnumInt')) {
        this.userTypeEnumInt = zzSessionStorage.getItem('userTypeEnumInt') * 1
        this.getUserType()
      }
    },
    // 保存参与者信息
    handleSave() {
      this.$refs['participantForm'].validate(valid => {
        if (!valid) return
        this.btnLoading = true
        if (!this.form.TrialSiteSurveyId) {
          this.form.TrialSiteSurveyId = getQueryString('trialSiteSurveyId')
        }
        const trialId = getQueryString('trialId')
        addOrUpdateTrialSiteUserSurvey(trialId, this.form).then(res => {
          this.btnLoading = false
          if (res.IsSuccess) {
            // 保存成功
            this.$message.success(this.$t('common:message:savedSuccessfully'))
            this.$emit('getList')
            this.$emit('close')
          }
        }).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.$emit('close')
    },
    // 获取系统用户类型
    getUserType() {
      getUserTypeList(3).then(res => {
        this.userTypeOptions = res.Result
      })
    },
    // 获取下拉框
    getDicData() {
      getBasicDataSelects(['SiteSurvey_UserRoles']).then(res => {
        this.dictionaryList = { ...res.Result }
      }).catch(() => {

      })
    },
    handleIsCorrectChange(val) {
      if (!val) {
        this.form.IsGenerateAccount = false
      }
    },
    handleIsGenerateAccountChange(val) {
      if (!val) {
        this.form.UserTypeId = ''
      }
    }
  }
}
</script>
