<template>
  <div
    v-loading="loading"
    class="participants_form_content"
  >
    <el-form
      ref="participantForm"
      :model="form"
      :rules="rules"
      label-width="80px"
      label-position="left"
    >
      <!-- 姓 -->
      <el-form-item
        :label="$t('trials:staffResearch:form:lastName')"
        prop="LastName"
      >
        <el-input
          v-model="form.LastName"
          :disabled="!(state === 0 && userTypeEnumInt === 0)"
        />
      </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)"
        />
      </el-form-item>
      <!-- 角色 -->
      <el-form-item
        :label="$t('trials:staffResearch:form:role')"
        prop="TrialRoleCode"
      >
        <el-select
          v-model="form.TrialRoleCode"
          :disabled="!(state === 0 && userTypeEnumInt === 0)"
          style="width:100%"
          @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)"
        />
      </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)"
        />
      </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)"
        />
      </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 style="text-align: center;padding:20px 0px;">
        <!-- 取消 -->
        <el-button
          size="large"
          type="primary"
          @click="handleCancel"
        >
          {{ $t("common:button:cancel") }}
        </el-button>
        <!-- 保存 -->
        <el-button
          size="large"
          type="primary"
          @click="handleSave"
        >
          {{ $t("common:button:save") }}
        </el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
import { addOrUpdateTrialSiteUserSurvey } from '@/api/research'
import { getUserTypeList } from '@/api/research'
import { getQueryString } from '@/utils/history.js'
export default {
  name: 'ParticipantForm',
  props: {
    participantInfo: {
      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,
        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'] }
        ]
      },
      userRoles: [],
      userTypeOptions: [],
      userTypeEnumInt: 0,
      errorMsg: '',
      crcId: '',
      craId: '',
      loading: false
    }
  },
  mounted() {
    this.initForm()
  },
  methods: {
    async initForm() {
      this.loading = true
      const res = await getUserTypeList(3)
      if (res.IsSuccess) {
        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 : ''
      }
      Object.keys(this.participantInfo).forEach((key) => {
        this.form[key] = this.participantInfo[key]
      })
      if (zzSessionStorage.getItem('userTypeEnumInt')) {
        this.userTypeEnumInt = zzSessionStorage.getItem('userTypeEnumInt') * 1
      }
      this.loading = false
    },
    // 保存参与者信息
    async handleSave() {
      try {
        const validate = await this.$refs.participantForm.validate()
        if (!validate) return
        this.loading = true
        if (!this.form.TrialSiteSurveyId) {
          this.form.TrialSiteSurveyId = getQueryString('trialSiteSurveyId')
        }
        const trialId = getQueryString('trialId')
        const res = await addOrUpdateTrialSiteUserSurvey(trialId, this.form)
        this.loading = false
        if (res.IsSuccess) {
          this.$message.success(
            this.$t('common:message:savedSuccessfully')
          )

          this.$emit('close', { id: res.Result, errorMessage: '' })
        }
      } catch (e) {
        if (e.Result && e.Result.Id && e.ErrorMessage) {
          this.$emit('close', {
            id: e.Result.Id,
            errorMessage: e.ErrorMessage
          })
        } else {
          console.log(e)
        }
        this.loading = false
      }
    },
    handleTrialRoleChange(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')
    },
    handleIsCorrectChange(val) {
      if (!val) {
        this.form.IsGenerateAccount = false
      }
    },
    handleIsGenerateAccountChange(val) {
      if (!val) {
        this.form.UserTypeId = ''
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.participants_form_content{
  padding: 0 10px;
  ::v-deep.el-form-item {
    margin-bottom: 0px;
    padding: 5px 0 20px 0;
    border-bottom: 1px solid #f5f7fa;
    .el-form-item__content{
      color: #82848a;
    }
  }
}
</style>
