<template>
  <el-form ref="participantForm" v-loading="loading" :model="form" :rules="rules" label-width="200px" :inline="true">
    <div class="base-dialog-body">
      <!-- 姓 -->
      <el-form-item :label="$t('trials:staffResearch:form:lastName')" prop="LastName">
        <el-input 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 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="TrialRoleCode">
        <el-select
          v-model="form.TrialRoleCode"
          style="width: 200px"
          :disabled="!(state === 0 && userTypeEnumInt === 0)"
          @change="handleTrialRoleChange"
        >
          <el-option
            v-for="item of $d.SiteSurvey_UserRoles"
            :key="item.id"
            :label="item.label"
            :value="parseInt(item.value)"
          />
        </el-select>
      </el-form-item>
      <!-- 电话号码 -->
      <el-form-item :label="$t('trials:staffResearch:form:phone')" prop="Phone">
        <el-input 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 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
          v-model="form.OrganizationName"
          :disabled="!(state === 0 && userTypeEnumInt === 0)"
          style="width: 200px"
        />
      </el-form-item>
      <!--      <el-row>
        &lt;!&ndash; 是否生成账号 &ndash;&gt;
        <el-form-item
          :label="$t('trials:staffResearch:form:isGenerate')"
        >
          <el-radio-group
            v-model="form.IsGenerateAccount"
            style="width:200px;"
            disabled
          >
            <el-radio v-for="item of $d.YesOrNo" :key="`IsGenerateAccount${item.value}`" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        &lt;!&ndash; 用户类型 &ndash;&gt;
        <el-form-item
          v-if="form.IsGenerateAccount"
          :label="$t('trials:staffResearch:form:userType')"
          prop="UserTypeId"
        >
          <el-select
            v-model="form.UserTypeId"
            style="width:200px;"
            disabled
          >
            <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 { 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('Please specify'))
    //   }
    //   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,
        TrialRoleCode: null,
        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'
          }
        ],
        TrialRoleCode: [
          {
            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: [
          {
            max: 50,
            message: this.$t('common:ruleMessage:maxLength') + ' 50',
            trigger: 'blur'
          }
        ],
        Email: [
          { required: true, validator: validateEmail, trigger: ['blur'] }
        ]
      },
      btnLoading: false,
      userRoles: [],
      userTypeOptions: [],
      userTypeEnumInt: 0,
      errorMsg: '',
      crcId: '',
      craId: '',
      loading: false
    }
  },
  mounted() {
    this.initForm()
  },
  methods: {
    async initForm() {
      this.loading = true
      await this.getUserType()
      Object.keys(this.data).forEach((key) => {
        this.form[key] = this.data[key]
      })
      if (zzSessionStorage.getItem('userTypeEnumInt')) {
        this.userTypeEnumInt = zzSessionStorage.getItem('userTypeEnumInt') * 1
      }
      this.loading = false
    },
    // 保存参与者信息
    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('close', { id: res.Result, errorMessage: '' })
            }
          })
          .catch((res) => {
            if (res.Result && res.Result.Id && res.ErrorMessage) {
              this.$emit('close', {
                id: res.Result.Id,
                errorMessage: res.ErrorMessage
              })
              // this.$confirm(res.ErrorMessage, '', {
              //   type: 'warning'
              // }).then(() => {
              //   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.handleSave()
              // }).catch(() => {

              // })
            }
            this.btnLoading = false
          })
      })
    },
    handleTrialRoleChange(v) {
      console.log(v)
      if (v === 1) {
        // crc
        this.form.IsGenerateAccount = true
        this.form.UserTypeId = this.crcId
      } else if (v === 2) {
        // cra
        this.form.IsGenerateAccount = true
        this.form.UserTypeId = this.craId
      } else {
        this.form.IsGenerateAccount = false
        this.form.UserTypeId = ''
      }
    },
    // 取消保存
    handleCancel() {
      this.$emit('close')
    },
    // 获取系统用户类型
    getUserType() {
      return new Promise((resolve) => {
        getUserTypeList(3).then((res) => {
          this.userTypeOptions = res.Result
          var crcObj = res.Result.find((i) => i.UserTypeEnum === 2)
          this.crcId = crcObj ? crcObj.Id : ''
          var craObj = res.Result.find((i) => i.UserTypeEnum === 9)
          this.craId = craObj ? craObj.Id : ''
        })
        resolve()
      })
    },
    handleIsCorrectChange(val) {
      if (!val) {
        this.form.IsGenerateAccount = false
      }
    },
    handleIsGenerateAccountChange(val) {
      if (!val) {
        this.form.UserTypeId = ''
      }
    }
  }
}
</script>
