<template>
  <el-form ref="participantForm" :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 style="width: 200px" />
      </el-form-item>
      <!-- 名 -->
      <el-form-item :label="$t('trials:staffResearch:form:firstName')" prop="FirstName">
        <el-input v-model="form.FirstName" disabled 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
        >
          <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 style="width: 200px" />
      </el-form-item>
      <!-- 邮箱 -->
      <el-form-item :label="$t('trials:staffResearch:form:email')" prop="Email">
        <el-input v-model="form.Email" disabled style="width: 200px" />
      </el-form-item>
      <!-- 单位 -->
      <el-form-item :label="$t('trials:staffResearch:form:organization')" prop="OrganizationName">
        <el-input v-model="form.OrganizationName" disabled style="width: 200px" />
      </el-form-item>
      <!-- 是否生成账号 -->
      <!-- <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> -->
      <!-- 用户类型 -->
      <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-form-item :label="$t('trials:staffResearch:form:updateState')">
        <el-radio-group v-model="form.IsHistoryUserDeleted" style="width: 200px">
          <el-radio v-for="item of $d.IsUserExitTrial" :key="`IsHistoryUserDeleted${item.value}`" :label="item.value">{{
            item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <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: 'HistoricalParticipantForm',
  props: {
    data: {
      type: Object,
      default() {
        return {}
      }
    },
    state: {
      type: Number,
      required: true
    }
  },
  data() {
    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.$reg().EmailRegexStr) {
          reg = new RegExp(this.$reg().EmailRegexStr)
        }
        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: '',
        IsGenerateAccount: false,
        IsHistoryUserDeleted: ''
      },
      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'] }
        ],
        IsHistoryUserDeleted: [
          {
            required: true,
            message: this.$t('trials:researchForm:formRule:select'),
            trigger: ['blur', 'change']
          }
        ]
      },
      btnLoading: false,
      userRoles: [],
      userTypeOptions: [],
      userTypeEnumInt: 0,
      errorMsg: ''
    }
  },
  mounted() {
    this.initForm()
  },
  methods: {
    async initForm() {
      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
      }
    },
    // 保存参与者信息
    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
          })
      })
    },
    // 取消保存
    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()
      })
    }
  }
}
</script>
