<template>
  <el-drawer
    v-model="visibleProxy"
    title="用户详细信息"
    size="60%"
    :close-on-click-modal="false"
  >
    <div v-if="userDetail" class="user-detail-content">
      <!-- 用户概览卡片 -->
      <div class="user-summary-section">
        <el-card class="user-summary-card" shadow="hover">
          <div class="user-summary">
            <div class="user-avatar">
              <el-avatar :size="60">
                <el-icon>
                  <User />
                </el-icon>
              </el-avatar>
            </div>
            <div class="user-basic-info">
              <h3>{{ userDetail.realName || userDetail.nickName }}</h3>
              <p class="username">@{{ userDetail.userName }}</p>
              <div class="user-tags">
                <!-- 用户状态标签 -->
                <el-tag type="primary" size="small">
                  {{ getUserStatusLabel(userDetail.status) }}
                </el-tag>
                <!-- 角色类型标签 -->
                <el-tag type="primary" v-if="userDetail.roleType">
                  {{ getRoleTypeLabel(userDetail.roleType) }}
                </el-tag>
                <!-- 渠道类型标签 -->
                <el-tag type="info" v-if="userDetail.branchType">
                  {{ getBranchTypeLabel(userDetail.branchType) }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 基本信息 -->
      <el-divider content-position="left">
        <span class="section-title">
          <el-icon><User /></el-icon>
          基本信息
        </span>
      </el-divider>

      <el-row :gutter="20" class="info-section">
        <el-col :span="12">
          <el-descriptions title="个人信息" :column="1" border>
            <el-descriptions-item label="用户名">
              <el-tag type="info">{{ userDetail.userName }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="用户昵称">{{ userDetail.nickName }}</el-descriptions-item>
            <el-descriptions-item label="真实姓名">
              <strong>{{ userDetail.realName }}</strong>
            </el-descriptions-item>
            <el-descriptions-item label="性别">
              <el-icon v-if="userDetail.sex === '0'" style="color: #409eff">
                <Male />
              </el-icon>
              <el-icon v-else-if="userDetail.sex === '1'" style="color: #f56c6c">
                <Female />
              </el-icon>
              <span class="ml-1">{{ getSexLabel(userDetail.sex) }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="证件号码">
              <span class="id-number">{{ formatIdNumber(userDetail.idNo) }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="12">
          <el-descriptions title="联系方式" :column="1" border>
            <el-descriptions-item label="手机号码">
              <el-icon>
                <Phone />
              </el-icon>
              {{ formatMobile(userDetail.phonenumber) }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱地址">
              <el-icon>
                <Message />
              </el-icon>
              {{ formatEmail(userDetail.email) }}
            </el-descriptions-item>
            <el-descriptions-item label="所属部门">
              <el-tag type="success">{{ userDetail.deptName }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="备注信息">
              <div class="remark-content">{{ userDetail.remark || '无' }}</div>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>

      <!-- 角色权限信息 -->
      <el-divider content-position="left">
        <span class="section-title">
          <el-icon><OfficeBuilding /></el-icon>
          角色权限
        </span>
      </el-divider>

      <el-row :gutter="20" class="info-section">
        <el-col :span="12">
          <el-descriptions title="角色信息" :column="1" border>
            <el-descriptions-item label="用户状态">
              <el-tag type="primary">
                {{ getUserStatusLabel(userDetail.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="角色类型">
              <el-tag type="primary">{{ getRoleTypeLabel(userDetail.roleType) }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="渠道类型">
              <el-tag v-if="userDetail.branchType" type="info">{{ getBranchTypeLabel(userDetail.branchType) }}</el-tag>
              <span v-else class="text-muted">未设置</span>
            </el-descriptions-item>
            <el-descriptions-item label="账户类型">
              <el-tag :type="userDetail.accType === 0 ? 'success' : 'warning'">
                {{ userDetail.accType === 0 ? '长期用户' : '临时用户' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="12">
          <el-descriptions title="角色列表" :column="1" border v-if="userDetail.roles && userDetail.roles.length > 0">
            <el-descriptions-item v-for="role in userDetail.roles" :key="role.roleId" :label="role.roleName">
              <el-tag :type="role.status === '0' ? 'success' : 'danger'" size="small">
                {{ role.status === '0' ? '正常' : '停用' }}
              </el-tag>
              <span class="role-key">{{ role.roleKey }}</span>
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions v-else title="角色信息" :column="1" border>
            <el-descriptions-item label="角色状态">
              <span class="text-muted">暂无角色信息</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>

      <!-- 安全设置 -->
      <el-divider content-position="left">
        <span class="section-title">
          <el-icon><Lock /></el-icon>
          安全设置
        </span>
      </el-divider>

      <el-row :gutter="20" class="info-section">
        <el-col :span="12">
          <el-descriptions title="访问控制" :column="1" border>
            <el-descriptions-item label="绑定IP">
              <el-tag v-if="userDetail.bindIp" type="info">{{ userDetail.bindIp }}</el-tag>
              <span v-else class="text-muted">未绑定（允许任意IP访问）</span>
            </el-descriptions-item>
            <el-descriptions-item label="访问时间">
              <div class="access-time">
                {{ formatAccessTime(userDetail.accessTime) }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="人脸识别">
              <el-switch
                :model-value="userDetail.faceAuthRequired === '1'"
                active-text="开启"
                inactive-text="关闭"
                disabled
              />
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="12">
          <el-descriptions v-if="userDetail.accType === 1" title="有效期设置" :column="1" border>
            <el-descriptions-item label="生效日期">
              <el-tag v-if="userDetail.validDate && userDetail.validDate[0]" type="success">{{ userDetail.validDate[0]
                }}
              </el-tag>
              <span v-else class="text-muted">未设置</span>
            </el-descriptions-item>
            <el-descriptions-item label="失效日期">
              <el-tag v-if="userDetail.validDate && userDetail.validDate[1]" type="danger">{{ userDetail.validDate[1]
                }}
              </el-tag>
              <span v-else class="text-muted">未设置</span>
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions v-else title="长期账户" :column="1" border>
            <el-descriptions-item label="说明">
              <span class="text-muted">该用户为长期用户，无有效期限制</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>

      <!-- 菜单权限 -->
      <el-divider content-position="left">
        <span class="section-title">
          <el-icon><Menu /></el-icon>
          菜单权限
        </span>
      </el-divider>

      <div class="menu-permission-section">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>菜单权限表</span>
              <el-tag type="success" size="small">已授权: {{ authorizedPermissionsCount }}</el-tag>
            </div>
          </template>

          <div v-if="userDetail.menuTree && userDetail.menuTree.length > 0" class="menu-table-container">
            <el-table :data="flattenMenuData" stripe border style="width: 100%" size="small">
              <el-table-column label="菜单名称" width="200" align="left">
                <template #default="scope">
                  <div class="menu-name-cell">
                    <span class="menu-label" :class="getMenuLabelClass(scope.row.menuType)">
                      {{ scope.row.indentedLabel }}
                    </span>
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="类型" width="100" align="center">
                <template #default="scope">
                  <el-tag
                    v-if="scope.row.menuType === 'M'"
                    type="success"
                    size="small"
                    effect="plain"
                  >
                    目录
                  </el-tag>
                  <el-tag
                    v-else-if="scope.row.menuType === 'C'"
                    type="primary"
                    size="small"
                    effect="plain"
                  >
                    菜单
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column label="权限标识" align="left">
                <template #default="scope">
                  <div class="permission-tags">
                    <!-- 目录类型显示特殊内容 -->
                    <template v-if="scope.row.menuType === 'M'">
                      <span class="directory-permissions">📁 目录节点</span>
                    </template>
                    <!-- 菜单类型显示权限按钮 -->
                    <template v-else-if="scope.row.authorizedButtons && scope.row.authorizedButtons.length > 0">
                      <el-tag
                        v-for="button in scope.row.authorizedButtons"
                        :key="button.id"
                        type="success"
                        effect="light"
                        size="small"
                        class="permission-tag"
                      >
                        <el-icon class="check-icon">
                          <Check />
                        </el-icon>
                        {{ button.label }}
                      </el-tag>
                    </template>
                    <!-- 菜单但无权限的情况 -->
                    <template v-else>
                      <span class="no-permissions">暂无操作权限</span>
                    </template>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-else class="empty-menu">
            <el-empty description="暂无菜单权限" />
          </div>
        </el-card>
      </div>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="visibleProxy = false">关 闭</el-button>
        <!-- 只有待激活状态的用户才显示审批按钮 -->
        <el-button
          v-if="isUserPendingActivation"
          type="success"
          :loading="approveLoading"
          @click="handleApproveFromDetail"
        >
          <el-icon>
            <Check />
          </el-icon>
          审批激活
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance, toRefs } from 'vue';
import { Check, Female, Lock, Male, Menu, Message, OfficeBuilding, Phone, User } from '@element-plus/icons-vue';
import api, { batchApproveUsers } from '@/api/system/approval/userApproval';
import { UserApprovalDetailVO } from '@/api/system/approval/types'
import {formatEmail, formatIdNumber, formatMobile} from "../../../../api/system/anonymization";

// ======================== Props & Emits ========================
const props = defineProps<{
  visible: boolean;
  userDetail: UserApprovalDetailVO | null;
}>();
const approveLoading = ref(false);
const emit = defineEmits<{
  'update:visible': [value: boolean];
  'approve': [];
}>();

// ======================== 基础设置 ========================
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 字典数据
const { sys_user_role_type, sys_user_sex, branchtype, sys_user_status } = toRefs<any>(
  proxy?.useDict('sys_user_role_type', 'sys_user_sex', 'branchtype', 'sys_user_status')
);

// ======================== 响应式数据 ========================
const visibleProxy = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

// ======================== 用户状态相关计算属性 ========================
// 判断用户是否为待激活状态
const isUserPendingActivation = computed(() => {
  return props.userDetail?.status === '2'; // 2 = 待激活
});

// ======================== 菜单权限计算属性 ========================
// 统计已授权权限数量
const authorizedPermissionsCount = computed(() => {
  if (!flattenMenuData.value) return 0;

  return flattenMenuData.value.reduce((total, menu) => {
    return total + (menu.authorizedButtons?.length || 0);
  }, 0);
});

// 菜单权限表格数据处理
const flattenMenuData = computed(() => {
  if (!props.userDetail?.menuTree || !props.userDetail?.checkedMenuIds) return [];
  const result: any[] = [];
  const checkedIds = props.userDetail.checkedMenuIds;
  const processMenuNode = (node: any, level: number = 0) => {
    // 处理目录(M)和菜单(C)类型
    if (node.menuType === 'M' || node.menuType === 'C') {
      const menuItem = {
        id: node.id,
        label: node.label,
        icon: node.icon,
        menuType: node.menuType,
        level: level,
        authorizedButtons: [] as any[], // 已授权的按钮
        indentedLabel: '　'.repeat(level * 2) + node.label // 根据层级添加缩进
      };
      // 如果有子节点，处理子节点
      if (node.children && node.children.length > 0) {
        // 收集已授权的按钮类型子节点
        const authorizedButtons = node.children.filter((child: any) =>
          child.menuType === 'F' && checkedIds.includes(child.id)
        );
        menuItem.authorizedButtons = authorizedButtons;
        // 递归处理非按钮类型的子节点
        const nonButtonChildren = node.children.filter((child: any) => child.menuType !== 'F');
        // 先添加当前节点
        result.push(menuItem);
        // 再递归处理子节点
        nonButtonChildren.forEach((child: any) => {
          processMenuNode(child, level + 1);
        });
      } else {
        // 没有子节点的情况，直接添加
        result.push(menuItem);
      }
    }
  };

  props.userDetail.menuTree.forEach((node: any) => {
    processMenuNode(node, 0);
  });

  return result;
});

//实际执行审批操作
const handleApproveFromDetail = async () => {
  if (!props.userDetail?.userId) return;
  try {
    approveLoading.value = true;
    // 使用批量审批接口处理单个用户
    await batchApproveUsers({ userIds: [props.userDetail.userId.toString()], approvalRemark: '' });
    ElMessage.success('用户审批通过成功');
    emit('approve'); // 触发父组件回调
    visibleProxy.value = false; // 关闭抽屉
  } catch (error) {
    ElMessage.error('审批操作失败，请重试');
  } finally {
    approveLoading.value = false;
  }
};

// ======================== 工具方法 ========================
const getRoleTypeLabel = (roleType: string): string => {
  const found = sys_user_role_type.value?.find((item: any) => item.value === roleType);
  return found?.label || '未知角色';
};

const getBranchTypeLabel = (branchType: string): string => {
  const found = branchtype.value?.find((item: any) => item.value === branchType);
  return found?.label || '未知渠道';
};

const getSexLabel = (sex: string): string => {
  const found = sys_user_sex.value?.find((item: any) => item.value === sex);
  return found?.label || '未知';
};



const formatAccessTime = (accessTime: string[]): string => {
  if (!accessTime || accessTime.length !== 2) return '全天候访问';
  if (accessTime[0] && accessTime[1]) return `${accessTime[0]} - ${accessTime[1]}`;
  return '未设置访问时间限制';
};

// 获取用户状态标签
const getUserStatusLabel = (status: string): string => {
  const found = sys_user_status.value?.find((item: any) => item.value === status);
  return found?.label || '未知状态';
};

// ======================== 菜单权限工具方法 ========================
// 获取菜单标签样式类
const getMenuLabelClass = (menuType: string): string => {
  switch (menuType) {
    case 'M':
      return 'directory-label';
    case 'C':
      return 'menu-label';
    default:
      return '';
  }
};

</script>

<style lang="scss" scoped>
.user-detail-content {
  padding: 0 20px 20px 20px;
}

.user-summary-section {
  margin-bottom: 24px;
}

.user-summary-card {
  border: none;

  :deep(.el-card__body) {
    padding: 16px;
  }
}

.user-summary {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-basic-info {
  flex: 1;

  h3 {
    margin: 0 0 8px 0;
    color: #303133;
    font-size: 18px;
  }

  .username {
    margin: 0 0 12px 0;
    color: #909399;
    font-family: monospace;
    font-size: 14px;
  }
}

.user-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

.info-section {
  margin-bottom: 24px;
}

.id-number {
  font-family: monospace;
  letter-spacing: 1px;
}

.remark-content {
  max-width: 300px;
  word-break: break-all;
}

.access-time {
  font-weight: 500;
  color: #409eff;
}

.text-muted {
  color: #909399;
  font-style: italic;
}

.role-key {
  margin-left: 8px;
  font-family: monospace;
  font-size: 12px;
  color: #909399;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 0;
  border-top: 1px solid #e4e7ed;
}

.ml-1 {
  margin-left: 4px;
}

// 响应式设计
@media (max-width: 768px) {
  .user-summary {
    flex-direction: column;
    text-align: center;
  }
}

// ========== 菜单权限表格样式 ==========
.menu-permission-section {
  margin-bottom: 24px;
}

.menu-table-container {
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  overflow: hidden;
}

.menu-name-cell {
  display: flex;
  align-items: center;
}

.menu-display-icon {
  color: #909399;
  font-size: 18px;
}

.no-icon {
  color: #c0c4cc;
  font-style: italic;
}

.menu-label {
  white-space: pre; /* 保持空格缩进 */
  font-family: "Microsoft YaHei", Arial, sans-serif; /* 确保中文字体支持全角空格 */
}

.menu-label.directory-label {
  font-weight: 600;
  color: #303133;
}

.menu-label:not(.directory-label) {
  font-weight: 500;
  color: #2c3e50;
}

.permission-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
}

.permission-tag {
  margin: 0;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  background-color: #f0f9ff !important;
  border-color: #67c23a !important;
  color: #67c23a !important;
}

.check-icon {
  font-size: 12px;
  color: #67c23a;
}

.no-permissions {
  color: #909399;
  font-style: italic;
  font-size: 14px;
}

.directory-permissions {
  color: #e6a23c;
  font-weight: 500;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.empty-menu {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

// ========== 菜单表格样式优化 ==========
:deep(.menu-table-container .el-table) {
  .el-table__header {
    background-color: #fafafa;
  }

  .el-table__row {
    .el-table__cell {
      border-bottom: 1px solid #f0f0f0;
    }
  }

  .el-table__row:hover {
    background-color: #f8f9ff;
  }
}

// ========== 权限标签样式 ==========
:deep(.permission-tag.el-tag--success) {
  background-color: #f0f9ff;
  border-color: #67c23a;
  color: #67c23a;

  &.el-tag--light {
    background-color: #f0f9ff;
    border-color: #b3e19d;
    color: #529b2e;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
