<template>

  <Dialog :title="dialogTitle" v-model="dialogVisible" width="70%">

    <ContentWrap v-loading="formLoading" style="max-height:360px;min-height:360px;overflow-y: auto;border:none ;">
      <div class="left">
        <!--  class="child-tabs" -->
        <SPuUploadImg v-model="avatar" :disabled="isDetail" height="143px"/>
        <el-tabs v-model="activeName" tab-position="left"  class="child-tabs">
          <el-tab-pane label="基本信息" name="info" />
          <el-tab-pane label="分配角色" name="AssignRoles" v-if="openType != 'create'" />
        </el-tabs>
      </div>
      <div class="right">
        <UserForm :obj="userObj" ref="userFormRef" :avatar="avatar" :isDetail="isDetail" :openType="openType"  v-if="activeName == 'info'" />
        <UserAssignRoleForm :obj="userObj" ref="userAssignRoleFormRef" :isDetail="isDetail"  v-if="activeName == 'AssignRoles'" />
      </div>

      <div style="clear: both;"></div>
    </ContentWrap>
    <template #footer v-if="!isDetail">
      <div class="dialog-footer">
        <el-button v-if="!isDetail && activeName == 'info' && checkPermi(['system:user:delete']) && openType != 'create'" :loading="formLoading" type="danger" @click="handleDelete">删除</el-button>
        <el-button v-if="!isDetail && activeName == 'info' && openType != 'create'" :type="(userObj.status == 1 ? 'primary' : 'danger')" :loading="formLoading"  @click="handleStatusChange">
          {{ userObj.status == 1 ? '启用' : '停用'}}
        </el-button>
        <el-button v-if="!isDetail && activeName == 'info' && checkPermi(['system:user:update-password']) && openType != 'create'" :loading="formLoading" type="primary" @click="handleResetPwd">重置密码</el-button>
        <!-- 基本信息的保存 -->
        <el-button v-if="!isDetail && activeName == 'info'" :loading="formLoading" type="primary" @click="userFormSubmit" v-hasPermi="['system:user:update'] || ['system:user:create']">保存</el-button>
        <!-- 分配人员的保存 -->
        <el-button v-if="!isDetail && activeName == 'AssignRoles' && checkPermi(['system:permission:assign-user-role'])" :loading="formLoading" type="primary" @click="userAssignRoleForm" >保存</el-button>
      </div>
    </template>
  </Dialog>
  <!-- </div> -->

</template>

<script lang="ts" setup>
import Dialog from '@/components/Dialog/src/Dialog.vue'
import UserForm from './UserForm.vue';
import UserAssignRoleForm from './UserAssignRoleForm.vue';
import { CommonStatusEnum } from '@/utils/constants'
import * as UserApi from '@/api/system/user'
import { checkPermi } from '@/utils/permission'


const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const activeName = ref('info') // Tag 激活的窗口
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const isDetail = ref(false)
const openType = ref('create')
const userObj = ref({})
const avatar = ref('avatar') //头像
/** 打开弹窗 */
const open = async (type: string, obj: object) => {

  if (type == 'create' || obj.avatar == '' ) {
    avatar.value = "https://mall-ffkj.oss-cn-guangzhou.aliyuncs.com/2e05b76706334aef023b85ec6aef6ffd4615aae3d06f302aa7d273e97f263025.png"
  } else {
    avatar.value = obj.avatar
  }
  userObj.value = obj
  openType.value = type
  dialogTitle.value = t('action.' + type)
  if (type == "view") {
    dialogTitle.value = "查看"
  }
  // 判断打开状态，如果是view那就只能查看 否则可以编辑
  if ('view' == type) {
    isDetail.value = true
  } else {
    isDetail.value = false
  }
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const userFormRef = ref() // 表单 Ref
const userFormSubmit = async () => {
  if (await userFormRef.value?.submitForm()){
    emit('success')
    dialogVisible.value = false
  }
  
}
const userAssignRoleFormRef = ref() // 表单 Ref
const userAssignRoleForm = async () => {
  if (await userAssignRoleFormRef.value?.submitForm()){
    emit('success')
    dialogVisible.value = false
  }
}
/** 修改用户状态 */
const handleStatusChange = async () => {
  const row = userObj.value 
  try {
    // 修改状态的二次确认
    const text = row.status === CommonStatusEnum.ENABLE ? '停用' : '启用'
    await message.confirm('确认要"' + text + '""' + row.username + '"用户吗?')
    // 发起修改状态
    await UserApi.updateUserStatus(row.id, row.status ? CommonStatusEnum.ENABLE : CommonStatusEnum.DISABLE)
    // 刷新列表
    message.success(row.username+'已'+text)
    // 关闭弹窗
    dialogVisible.value = false
    emit('success')

  } catch {
    // 取消后，进行恢复按钮
    row.status = row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  }
}
/** 删除按钮操作 */
const handleDelete = async () => {
  
  try {
    const id = userObj.value.id
    // 删除的二次确认
    await message.delConfirm('确认要删除' + userObj.value.username + '吗?')
    // 发起删除
    await UserApi.deleteUser(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    dialogVisible.value = false
    emit('success')
  } catch { }
}
/** 重置密码 */
const handleResetPwd = async (row: UserApi.UserVO) => {
  
  try {
    const id = userObj.value.id
    // 重置的二次确认
    const result = await message.prompt(
      '请输入"' + userObj.value.username + '"的新密码',
      t('common.reminder')
    )
    const password = result.value
    // 发起重置
    await UserApi.resetUserPwd(id, password)
    message.success('修改成功，新密码是：' + password)
    dialogVisible.value = false
    emit('success')
  } catch { }
}
</script>

<style lang="scss" >
.el-dialog__body{
    padding: 0 ;
  }
.left {
  width: 106px;
  float: left;
}

.child-tabs {
  border-top: 2px solid #e4e7ef;
  margin-top: -7px;
}
.child-tabs .el-tabs__item {
  width: 106px;
  justify-content: center;
}
.right {
  // padding: 10px 0 60px 10px;
  border-left: 2px solid #e4e7ee;
  margin-left: -2px;
  float: left;
  width: calc(100% - 120px);
  min-height: 300px;
  
}
</style>