<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>
      <!--:disabled="!!user.UserCode"-->
      <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 :label="$t('system:userlist:table:HospitalGroupIdList')"
        :prop="hasPermi(['role:ga']) ? 'groups' : ''" v-if="type === 0">
        <div style="display: flex; align-items: center">
          <el-select ref="userType" v-model="user.groups" size="small" placeholder="Please select" multiple
            style="width: 100%" :disabled="user.CanEditUserType === false || type === 1" @change="handleChangeGroup">
            <template v-for="group of hospitalGroupList">
              <el-option :key="group.Id" :label="group.Name" :value="group.Id" />
            </template>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item :label="$t('system:userlist:table:HospitalGroupIdList')"
        :prop="hasPermi(['role:ga']) ? 'groups' : ''" v-else>
        <div style="display: flex; align-items: center">
          <el-select ref="userType" v-model="groups" size="small" placeholder="Please select" multiple
            style="width: 100%" :disabled="user.CanEditUserType === false || type === 1" @change="handleChangeGroup">
            <template v-for="group of hospitalGroupList">
              <el-option :key="group.Id" :label="group.Name" :value="group.Id" />
            </template>
          </el-select>
          <el-button type="primary" size="small" style="margin-left: 5px" v-if="type === 1" @click.stop="openGroupList">
            {{ $t('system:userlist:button:groups') }}
          </el-button>
        </div>
      </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 :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 :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-form-item label="" v-if="!$IsCanConnectInternet">
        <span>{{ $t('system:userlist:tip:defaultPassword') }}</span>
      </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-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" />
    <groupList v-if="group_visible" :visible.sync="group_visible" :userId="userId" :list="userGroupList"
      :hospitalGroupList="hospitalGroupList" @getGroupList="getGroupList" />
  </el-form>
</template>
<script>
import {
  getUser,
  addUser,
  updateUser,
  getUserTypeListByUserType,
  getHospitalGroupList
} from '@/api/admin.js'
import roleList from './roleList.vue'
import groupList from './groupList.vue'
export default {
  name: 'UserInfo',
  props: {
    userId: { type: String, default: '' },
  },
  components: { roleList, groupList },
  created() {
    this.getUserTypeList()
    if (this.userId !== '') {
      this.getUserInfo()
      this.type = 1
    } else {
      this.type = 0
    }
    this.getHospitalGroupList()
  },
  methods: {
    async getHospitalGroupList() {
      try {
        let res = await getHospitalGroupList({})
        if (res.IsSuccess) {
          this.hospitalGroupList = res.Result
        }
      } catch (err) {
        console.log(err)
      }
    },
    getGroupList() {
      this.user.HospitalGroupList = []
      this.groups = []
      this.user.groups = []
      this.userGroupList.forEach(item => {
        this.user.HospitalGroupList.push(Object.assign({}, item))
        if (!item.IsDisabled) {
          this.groups.push(item.HospitalGroupId)
          this.user.groups.push(item.HospitalGroupId)
        }
      })

    },
    openGroupList() {
      this.userGroupList = []
      this.user.HospitalGroupList.forEach((item) => {
        this.userGroupList.push(Object.assign({}, item))
      })
      this.group_visible = true
    },
    handleChangeGroup(val) {
      this.user.HospitalGroupList = []
      val.forEach((item) => {
        let data = this.hospitalGroupList.find((d) => d.Id === item)
        this.user.HospitalGroupList.push({
          HospitalGroupId: data.Id,
          Name: data.Name,
          IsDisabled: false,
        })
      })
    },
    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('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) => {
        let arr = [2, 4, 5, 8, 9, 12, 14, 35];
        if (this.hasPermi(["role:sa"])) {
          arr = [4, 5, 8, 9, 12, 14, 35];
        }
        if (this.hasPermi(["role:ga"])) {
          arr = [4, 5, 8, 9, 12, 35];
        }
        if (res.IsSuccess) {
          this.userTypeOptions = []
          this.userTypeOptions = res.Result.map((item) => {
            if (arr.includes(item.UserTypeEnum)) {
              return item;
            }
          }).filter((item) => item);
        }
      })
    },
    getUserInfo() {
      getUser({
        IdentityUserId: this.userId,
      }).then((res) => {
        this.user = res.Result
        this.Roles = []
        this.user.Roles = []
        this.user.UserRoleList = []
        this.groups = []
        this.user.groups = []
        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,
          })
        })
        res.Result.HospitalGroupList.forEach(item => {
          if (!item.IsDisabled) {
            this.groups.push(item.HospitalGroupId)
            this.user.groups.push(item.HospitalGroupId)
          }
        })
      })
    },
    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(
              '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 {
      userRoleList: [],
      userGroupList: [],
      Roles: [],
      groups: [],
      user: {
        Roles: [],
        UserRoleList: [],
        UserName: '',
        LastName: '',
        FirstName: '',
        Sex: '',
        EMail: '',
        Phone: '',
        UserTypeId: '',
        IsZhiZhun: '',
        OrganizationName: '',
        DepartmentName: '',
        PositionName: '',
        HospitalGroupList: [],
        groups: [],
        IsTestUser: false,
      },
      visible: false,
      group_visible: false,
      userFormRules: {
        UserName: [
          { required: true, validator: validatePassword, trigger: 'blur' },
        ],
        Roles: [
          {
            required: true,
            type: 'array',
            message: 'Please Select',
            trigger: ['blur', 'change'],
          },
        ],
        groups: [
          {
            required: true,
            type: 'array',
            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',
            pattern: new RegExp(this.$reg().EmailRegexStr),
            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: [],
      hospitalGroupList: [],
      isDisabled: false,
      type: 0, // 1为编辑，0为新增
    }
  },
}
</script>
<style scoped>
::v-deep .is-error.my_new_pwd {
  margin-bottom: 40px;
}
</style>
