<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('system:userlist:title:Information') }}</span>
      </div>
      <el-form-item v-if="user.UserCode" :label="$t('system:userlist:table:S/N')" prop="UserCode">
        <el-input v-model="user.UserCode" disabled />
      </el-form-item>

      <el-form-item :label="$t('system:userlist:table:UserName')" class="my_new_pwd" prop="UserName">
        <el-input v-model="user.UserName" />
      </el-form-item>

      <el-form-item :label="$t('system:userlist:table:LastName')" prop="LastName">
        <el-input v-model="user.LastName" />
      </el-form-item>
      <el-form-item :label="$t('system:userlist:table:FirstName')" prop="FirstName">
        <el-input v-model="user.FirstName" />
      </el-form-item>
      <!-- <el-form-item :label="$t('system:userlist:table:Gender')" prop="Sex" style="margin-right:40px;">
        <el-radio-group v-model="user.Sex">
          <el-radio :label="1">Male</el-radio>
          <el-radio :label="0">Female</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item :label="$t('system:userlist:table:Email')" prop="EMail">
        <el-input v-model="user.EMail" :disabled="!!user.UserCode" />
      </el-form-item>
      <el-form-item :label="$t('system:userlist:table:Phone')" prop="Phone">
        <el-input v-model="user.Phone" />
      </el-form-item>
      <el-form-item v-if="type == 1" :label="$t('system:userlist:table:Disable')">
        <el-switch v-model="user.Status" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item :label="$t('system:userlist:table:IsTestUser')">
        <el-radio-group v-model="user.IsTestUser">
          <el-radio v-for="item of $d.YesOrNo" :key="item.id" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('system:userlist:table:UserWorkLanguage')" prop="UserWorkLanguage">
        <el-select v-model="user.UserWorkLanguage" style="width: 100%">
          <el-option v-for="item of $d.UserWorkLanguage" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('system:userlist:table:UserType')" prop="Roles" v-if="type === 0">
        <div style="display: flex; align-items: center">
          <el-select ref="userType" v-model="user.Roles" size="small" placeholder="Please select" multiple
            style="width: 100%" :disabled="user.CanEditUserType === false || type === 1" @change="handleChange">
            <template v-for="userType of userTypeOptions">
              <el-option v-if="![4, 6, 20].includes(userType.UserTypeEnum)" :key="userType.Id"
                :label="userType.UserType" :value="userType.Id" />
            </template>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item :label="$t('system:userlist:table:UserType')" prop="userTypeId" v-else>
        <div style="display: flex; align-items: center">
          <el-select ref="userType" v-model="Roles" size="small" placeholder="Please select" multiple
            style="width: 100%" :disabled="user.CanEditUserType === false || type === 1" @change="handleChange">
            <template v-for="userType of userTypeOptions">
              <el-option v-if="![4, 6, 20].includes(userType.UserTypeEnum)" :key="userType.Id"
                :label="userType.UserType" :value="userType.Id" />
            </template>
          </el-select>
          <el-button type="primary" size="small" style="margin-left: 5px" v-if="type === 1" @click.stop="openRoleList">
            {{ $t('system:userlist:button:roles') }}
          </el-button>
        </div>
      </el-form-item>
    </el-card>

    <el-card class="Affiliation" shadow="never" style="margin-top: 10px" size="small">
      <div slot="header" class="clearfix">
        <span>{{ $t('system:userlist:title:Affiliation') }}</span>
      </div>
      <el-form-item prop="IsZhiZhun">
        <el-radio-group v-model="user.IsZhiZhun" @change="OrgnizationTypeChanged">
          <el-radio :label="true">{{
            $t('system:userlist:title:Internal')
          }}</el-radio>
          <el-radio :label="false">{{
            $t('system:userlist:title:External')
          }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="user.IsZhiZhun === false" :label="$t('system:userlist:table:OrganizationName')">
        <el-input v-model="user.OrganizationName" />
      </el-form-item>
      <el-form-item :label="$t('system:userlist:table:Department')" prop="DepartmentName">
        <el-input v-model="user.DepartmentName" />
      </el-form-item>
      <el-form-item :label="$t('system:userlist:table:Position')" prop="PositionName">
        <el-input 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>
    <roleList v-if="visible" :visible.sync="visible" :userId="userId" :list="userRoleList"
      :userTypeOptions="userTypeOptions" @getRoleList="getRoleList" />
  </el-form>
</template>
<script>
import {
  getUser,
  addUser,
  updateUser,
  getUserTypeListByUserType,
} from '@/api/admin.js'
import roleList from './roleList.vue'
export default {
  name: 'UserInfo',
  props: {
    userId: { type: String, default: '' },
  },
  components: { roleList },
  created() {
    this.getUserTypeList()
    if (this.userId !== '') {
      this.getUserInfo()
      this.type = 1
    } else {
      this.type = 0
    }
  },
  methods: {
    openRoleList() {
      this.userRoleList = []
      this.user.UserRoleList.forEach((item) => {
        this.userRoleList.push(Object.assign({}, item))
      })
      this.visible = true
    },
    handleChange(val) {
      this.user.UserRoleList = []
      val.forEach((item) => {
        let data = this.userTypeOptions.find((d) => d.Id === item)
        this.user.UserRoleList.push({
          UserTypeEnum: data.UserTypeEnum,
          UserTypeId: data.Id,
          IsUserRoleDisabled: false,
        })
      })
    },
    updateQueryParam(param, newValue, wurl) {
      // 获取当前URL
      let url = wurl || window.location.href

      // 正则表达式匹配参数
      let regex = new RegExp('([?&])' + param + '=.*?(&|$)')
      let separator = url.indexOf('?') !== -1 ? '&' : '?'

      // 如果参数存在，替换它，如果不存在，添加它
      if (regex.test(url)) {
        return url.replace(regex, '$1' + param + '=' + newValue + '$2')
      } else {
        return url + separator + param + '=' + newValue
      }
    },
    handleSave() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          this.isDisabled = true
          const selectedUserType = this.userTypeOptions.filter(
            (item) => item.Id === this.user.UserTypeId
          )
          let newUrl = this.updateQueryParam('userName', this.user.UserName)
          newUrl = this.updateQueryParam('email', this.user.EMail, newUrl)
          window.history.pushState({ path: newUrl }, '', newUrl)
          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.forEach((item) => {
            if (item.UserTypeEnum !== 21) {
              this.userTypeOptions.push(item)
            }
          })
        }
      })
    },
    getUserInfo() {
      getUser({
        IdentityUserId: this.userId,
      }).then((res) => {
        this.user = res.Result
        this.Roles = []
        this.user.Roles = []
        this.user.UserRoleList = []
        res.Result.AccountList.forEach((item) => {
          if (!item.IsUserRoleDisabled) {
            this.Roles.push(item.UserTypeId)
            this.user.Roles.push(item.UserTypeId)
          }
          this.user.UserRoleList.push({
            UserTypeEnum: item.UserTypeEnum,
            UserTypeId: item.UserTypeId,
            IsUserRoleDisabled: item.IsUserRoleDisabled,
            UserTypeShortName: item.UserTypeShortName,
          })
        })
      })
    },
    getRoleList() {
      getUser({
        IdentityUserId: this.userId,
      }).then((res) => {
        this.Roles = []
        this.user.Roles = []
        this.user.UserRoleList = []
        res.Result.AccountList.forEach((item) => {
          if (!item.IsUserRoleDisabled) {
            this.Roles.push(item.UserTypeId)
            this.user.Roles.push(item.UserTypeId)
          }
          this.user.UserRoleList.push({
            UserTypeEnum: item.UserTypeEnum,
            UserTypeId: item.UserTypeId,
            IsUserRoleDisabled: item.IsUserRoleDisabled,
            UserTypeShortName: item.UserTypeShortName,
          })
        })
      })
    },
    OrgnizationTypeChanged(val) {
      this.user.OrganizationName = ''
    },
  },
  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位以上、必须含有字母、数字、特殊符号
      if (!reg1.test(value)) {
        callback(
          lang === 'zh'
            ? new Error(
              '新建账号，用户名字符长度最小为4个字符，最大为16个字符，只可使用字母、数字、下划线；'
            )
            : new Error(
              'For a new account, the username must have:1) At least 4 characters;2) At most 16 characters;3)Only letters, numbers, and underscores are allowed.'
            )
        )
      } else {
        callback()
      }
    }
    return {
      userRoleList: [],
      Roles: [],
      user: {
        UserWorkLanguage: null,
        Roles: [],
        UserRoleList: [],
        UserName: '',
        LastName: '',
        FirstName: '',
        Sex: '',
        EMail: '',
        Phone: '',
        UserTypeId: '',
        IsZhiZhun: '',
        OrganizationName: '',
        DepartmentName: '',
        PositionName: '',
        IsTestUser: false,
      },
      visible: false,
      userFormRules: {
        UserName: [
          { required: true, validator: validatePassword, trigger: 'blur' },
        ],
        UserWorkLanguage: [
          {
            required: true,
            message: this.$t("common:ruleMessage:select"),
            trigger: ['blur', 'change'],
          },
        ],
        Roles: [
          {
            required: true,
            message: this.$t("common:ruleMessage:select"),
            trigger: ['blur', 'change'],
          },
        ],
        IsZhiZhun: [
          {
            required: true,
            message: this.$t("common:ruleMessage:select"),
            trigger: ['blur', 'change'],
          },
        ],
        OrganizationName: [
          { required: true, message: this.$t("common:ruleMessage:specify"), trigger: 'blur' },
        ],
        LastName: [
          { required: true, message: this.$t("common:ruleMessage:specify"), trigger: 'blur' },
          { max: 50, message: this.$t("trials:researchForm:formRule:maxLength") },
        ],
        FirstName: [
          { required: true, message: this.$t("common:ruleMessage:specify"), trigger: 'blur' },
          { max: 50, message: this.$t("trials:researchForm:formRule:maxLength") },
        ],
        Phone: [
          {
            max: 20,
            min: 7,
            message: this.$t("system:userInfo:ruleMessage:length7to20"),
            trigger: ['blur'],
          },
        ],
        EMail: [
          {
            required: true,
            message: this.$t("common:ruleMessage:specify"),
            trigger: 'blur',
          },
          {
            // type: 'email',
            pattern: new RegExp(this.$reg().EmailRegexStr),
            message: this.$t("trials:site:ruleMessage:correctEmail"),
            trigger: ['blur'],
          },
          { max: 50, message: this.$t("trials:researchForm:formRule:maxLength") },
        ],
        Sex: [{ required: true, message: this.$t("common:ruleMessage:specify"), trigger: 'blur' }],
        Status: [
          { required: true, message: this.$t("common:ruleMessage:specify"), trigger: 'blur' },
        ],
        DepartmentName: [{ max: 50, message: this.$t("trials:researchForm:formRule:maxLength") }],
        PositionName: [{ max: 50, message: this.$t("trials:researchForm:formRule:maxLength") }],
      },
      userTypeOptions: [],
      isDisabled: false,
      type: 0, // 1为编辑，0为新增
    }
  },
}
</script>
<style scoped>
::v-deep .is-error.my_new_pwd {
  margin-bottom: 40px;
}
</style>
