<template>
  <el-form
    ref="userForm"
    size="small"
    :model="user"
    :rules="userFormRules"
    label-width="150px"
    style="width:800px;"
  >
    <el-card class="Basic" shadow="never" size="small">
      <div slot="header" class="clearfix">
        <span>{{$t('trials:trials-myinfo:title:basicInfo')}}</span>
      </div>
      <el-form-item v-if="user.UserCode" label="S/N" prop="UserCode">
        <el-input :maxLength="$inputMax" v-model="user.UserCode" disabled />
      </el-form-item>

      <el-form-item :label="$t('admin:UserName')" prop="UserName">
        <el-input :maxLength="16" v-model="user.UserName" />
      </el-form-item>

      <el-form-item :label="$t('trials:staffResearch:form:lastName')" prop="LastName">
        <el-input :maxLength="50" v-model="user.LastName" />
      </el-form-item>
      <el-form-item :label="$t('trials:staffResearch:form:firstName')" prop="FirstName">
        <el-input :maxLength="50" v-model="user.FirstName" />
      </el-form-item>
      <el-form-item :label="$t('admin:Sex')" prop="Sex" style="margin-right:40px;">
        <el-radio-group v-model="user.Sex">
          <el-radio v-for="item of $d.Sex" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('admin:EMail')" prop="EMail">
        <el-input :maxLength="50" v-model="user.EMail" />
      </el-form-item>
      <el-form-item :label="$t('admin:Phone')" prop="Phone">
        <el-input :maxLength="50" v-model="user.Phone" />
      </el-form-item>
      <el-form-item v-if="type==1" :label="$t('admin:Status')">
        <el-switch v-model="user.Status" :active-value="0" :inactive-value="1" />
      </el-form-item>
      <el-form-item :label="$t('admin:IsTestUser')">
        <el-switch v-model="user.IsTestUser" />
      </el-form-item>
      <el-form-item :label="$t('admin:UserType')" prop="UserTypeId">
        <el-select ref="userType" v-model="user.UserTypeId" size="small" style="width:100%;" :disabled="user.CanEditUserType === false">
          <el-option
            v-for="(userType,key) of userTypeOptions"
            v-if="userType.UserTypeEnum !== 20"
            :key="key"
            :label="userType.UserType"
            :value="userType.Id"
          />
        </el-select>
      </el-form-item>
    </el-card>

    <el-card class="Affiliation" shadow="never" style="margin-top:10px;" size="small">
      <div slot="header" class="clearfix">
        <span>{{ $t('admin:OrganizationName') }}</span>
      </div>
      <el-form-item :label="$t('admin:IsZhiZhun')">
        <el-radio-group v-model="user.IsZhiZhun" @change="OrgnizationTypeChanged">
          <el-radio v-for="item of $d.IsZhiZhun" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="user.IsZhiZhun === false" :label="$t('admin:OrganizationName')">
        <el-input :maxLength="50" v-model="user.OrganizationName" />
      </el-form-item>

      <el-form-item :label="$t('admin:DepartmentName')" prop="DepartmentName">
        <el-input :maxLength="50" v-model="user.DepartmentName" />
      </el-form-item>
      <el-form-item :label="$t('admin:PositionName')" prop="PositionName">
        <el-input :maxLength="50" v-model="user.PositionName" />
      </el-form-item>
    </el-card>
    <el-form-item>
      <el-button
        type="primary"
        size="small"
        :disabled="isDisabled"
        style="margin:10px 15px"
        @click="handleSave"
      >{{$t('common:button:save')}}</el-button>
    </el-form-item>

  </el-form>
</template>
<script>
import { getUser, addUser, updateUser, getUserTypeListByUserType } from '@/api/admin.js'
export default {
  name: 'UserInfo',
  props: {
    userId: { type: String, default: '' }
  },
  data() {
    var validatePassword = (rule, value, callback) => {
      var lang = zzSessionStorage.getItem('lang')?zzSessionStorage.getItem('lang'):'zh'
      /* eslint-disable */
      var reg1 = /^[a-zA-Z0-9_]{4,16}$/; //密码必须是8位以上、必须含有字母、数字、特殊符号
      console.log(!reg1.test(value))
      if (!reg1.test(value)) {
        callback(lang==='zh' ? new Error("1）新建账号，用户名字符长度最小为4个字符，最大为16个字符，只可使用字母、数字、下划线；") : new Error('Passwords must have: 1) 8 - 32 characters; 2) At least 1 number; 3) At least 1 uppercase letter; 4) At least 1 lowercase letter; 5) At least 1 special character (~!-@#$%^&*_+?) '))
      } else {
        callback();
      }
    }
    return {
      user: {
        UserName: '',
        LastName: '',
        FirstName: '',
        Sex: '',
        EMail: '',
        Phone: '',
        UserTypeId: '',
        IsZhiZhun: '',
        OrganizationName: '',
        DepartmentName: '',
        PositionName: '',
        IsTestUser: false
      },
      userFormRules: {
        UserName: [
          { required: true, validator: validatePassword, trigger: 'blur' }
        ],
        UserTypeId: [
          { required: true, message: 'Please Select', trigger: ['blur', 'change'] }
        ],
        IsZhiZhun: [
          { required: true, message: 'Please Select', trigger: ['blur', 'change'] }
        ],
        OrganizationName: [
          { required: true, message: '请注明', trigger: 'blur' }
        ],
        LastName: [
          { required: true, message: '请注明', trigger: 'blur' },
          { max: 50, message: '最大长度为 50' }
        ],
        FirstName: [
          { required: true, message: '请注明', trigger: 'blur' },
          { max: 50, message: '最大长度为 50' }
        ],
        Phone: [
        ],
        EMail: [
          {
            required: true,
            message: '请输入邮箱地址',
            trigger: 'blur'
          },
          {
            type: 'email',
            message: '请输入邮箱地址',
            trigger: ['blur']
          },
          { max: 50, message: '最大长度为 50' }
        ],
        Sex: [
          { required: true, message: '请注明', trigger: 'blur' }
        ],
        Status: [
          { required: true, message: '请注明', trigger: 'blur' }
        ],
        DepartmentName: [
          { max: 50, message: '最大长度为 50' }],
        PositionName: [{ max: 50, message: '最大长度为 50' }
        ]
      },
      userTypeOptions: [],
      isDisabled: false,
      type: 0 // 1为编辑，0为新增
    }
  },
  created() {
    this.getUserTypeList()
    if (this.userId !== '') {
      this.getUserInfo()
      this.type = 1
    } else {
      this.type = 0
    }
  },
  methods: {
    handleSave() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          this.isDisabled = true
          const selectedUserType = this.userTypeOptions.filter(item => item.Id === this.user.UserTypeId)
          if (selectedUserType.length > 0) {
            this.user.UserTypeEnum = selectedUserType[0].UserTypeEnum
          }
          this.user.BaseUrl = `${location.protocol}//${location.host}/login`
          this.user.RouteUrl = `${location.protocol}//${location.host}/email-recompose`
          if (this.user.Id) {
            updateUser(this.user).then(res => {
              this.isDisabled = false
              this.$message.success(this.$t('common:message:updatedSuccessfully'))
            }).catch(() => { this.isDisabled = false })
          } else {
            addUser(this.user).then(res => {
              this.isDisabled = false
              this.user.Id = res.Result.Id
              this.user.UserCode = res.Result.UserCode
              this.$emit('getUserId', res.Result.Id)
              this.$message.success(this.$t('common:message:addedSuccessfully'))
              this.$router.push({ path: '/system/user/list' })
            }).catch(() => { this.isDisabled = false })
          }
        }
      })
    },
    getUserTypeList() {
      getUserTypeListByUserType(0).then(res => {
        if (res.IsSuccess) {
          this.userTypeOptions = res.Result
        }
      })
    },
    getUserInfo() {
      getUser(this.userId).then(res => {
        this.user = res.Result
      })
    },
    OrgnizationTypeChanged(val) {
      this.user.OrganizationName = ''
    }
  }
}
</script>
