<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" />
      </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:UserType')"
        prop="UserTypeId"
      >
        <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, key) of userTypeOptions">
              <el-option
                v-if="userType.UserTypeEnum !== 20"
                :key="key"
                :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"
        >Save</el-button
      >
    </el-form-item>
    <roleList
      v-if="visible"
      :visible.sync="visible"
      :list="user.UserRoleList"
      :roles.sync="user.Roles"
      :userTypeOptions="userTypeOptions"
    />
  </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.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('Updated successfully')
              })
              .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('Added successfully')
                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({
        IdentityUserId: this.userId,
      }).then((res) => {
        this.user = res.Result
        this.user.Roles = []
        this.user.UserRoleList = []
        res.Result.AccountList.forEach((item) => {
          if (!item.IsUserRoleDisabled) {
            this.user.Roles.push(item.UserTypeId)
          }
          this.user.UserRoleList.push({
            UserTypeEnum: item.UserType,
            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位以上、必须含有字母、数字、特殊符号
      console.log(!reg1.test(value))
      if (!reg1.test(value)) {
        callback(
          lang === 'zh'
            ? new Error(
                '1）新建账号，用户名字符长度最小为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 {
      user: {
        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' },
        ],
        Roles: [
          {
            required: true,
            message: 'Please Select',
            trigger: ['blur', 'change'],
          },
        ],
        IsZhiZhun: [
          {
            required: true,
            message: 'Please Select',
            trigger: ['blur', 'change'],
          },
        ],
        OrganizationName: [
          { required: true, message: 'Please specify', trigger: 'blur' },
        ],
        LastName: [
          { required: true, message: 'Please specify', trigger: 'blur' },
          { max: 50, message: 'The maximum length is 50' },
        ],
        FirstName: [
          { required: true, message: 'Please specify', trigger: 'blur' },
          { max: 50, message: 'The maximum length is 50' },
        ],
        Phone: [
          {
            max: 20,
            min: 7,
            message: 'The length is 7 to 20',
            trigger: ['blur'],
          },
        ],
        EMail: [
          {
            required: true,
            message: 'Please input the email address',
            trigger: 'blur',
          },
          {
            type: 'email',
            message: 'Please input the correct email address',
            trigger: ['blur'],
          },
          { max: 50, message: 'The maximum length is 50' },
        ],
        Sex: [{ required: true, message: 'Please specify', trigger: 'blur' }],
        Status: [
          { required: true, message: 'Please specify', trigger: 'blur' },
        ],
        DepartmentName: [{ max: 50, message: 'The maximum length is 50' }],
        PositionName: [{ max: 50, message: 'The maximum length is 50' }],
      },
      userTypeOptions: [],
      isDisabled: false,
      type: 0, // 1为编辑，0为新增
    }
  },
}
</script>
<style scoped>
::v-deep .is-error.my_new_pwd {
  margin-bottom: 40px;
}
</style>
