<template>
  <el-drawer
    v-model="visibleProxy"
    title="角色权限变更对比"
    size="70%"
    :close-on-click-modal="false"
    class="permission-compare-drawer"
  >
    <div v-loading="loading" class="drawer-content">
      <div v-if="compareData" class="permission-compare-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>{{ compareData.userInfo.realName || compareData.userInfo.nickName }}</h3>
                <p class="username">@{{ compareData.userInfo.userName }}</p>
                <div class="user-tags">
                  <el-tag type="primary" size="small">{{ compareData.userInfo.deptName }}</el-tag>
                  <el-tag
                    :type="compareData.requestInfo.applyType === '1' ? 'success' : 'warning'"
                    size="small"
                  >
                    {{ compareData.requestInfo.applyTypeName }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 申请信息 -->
        <el-divider content-position="left">
          <span class="section-title">
            <el-icon><Document /></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="compareData.requestInfo.applyType === '1' ? 'success' : 'warning'"
                  size="small"
                >
                  {{ compareData.requestInfo.applyTypeName }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="申请角色">
                <div class="role-info">
                  <div class="role-name">
                    <el-tag type="success" size="small">{{ compareData.requestInfo.roleName }}</el-tag>
                  </div>
                  <div class="role-key">{{ compareData.requestInfo.roleKey }}</div>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="申请时间">
                {{ formatDate(compareData.requestInfo.applyTime) }}
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
          <el-col :span="12">
            <el-descriptions title="申请原因" :column="1" border>
              <el-descriptions-item label="详细说明">
                <div class="apply-reason">{{ compareData.requestInfo.applyReason }}</div>
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>

        <!-- 权限变更核心对比区域 -->
        <el-divider content-position="left">
          <span class="section-title">
            <el-icon><Operation /></el-icon>
            权限变更对比
            <el-tag v-if="hasPermissionChanges" type="warning" size="small" class="ml-2">
              有权限变更
            </el-tag>
            <el-tag v-else type="info" size="small" class="ml-2">
              无权限变更
            </el-tag>
          </span>
        </el-divider>

        <div class="permission-changes-section">
          <!-- 权限变更统计 -->
          <div class="changes-summary">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-statistic title="新增菜单" :value="compareData.permissionChanges.addedMenus.length" suffix="个">
                  <template #prefix>
                    <el-icon style="color: #67c23a"><Plus /></el-icon>
                  </template>
                </el-statistic>
              </el-col>
              <el-col :span="6">
                <el-statistic title="移除菜单" :value="compareData.permissionChanges.removedMenus.length" suffix="个">
                  <template #prefix>
                    <el-icon style="color: #f56c6c"><Minus /></el-icon>
                  </template>
                </el-statistic>
              </el-col>
              <el-col :span="6">
                <el-statistic title="新增权限" :value="compareData.permissionChanges.addedButtons.length" suffix="个">
                  <template #prefix>
                    <el-icon style="color: #67c23a"><Check /></el-icon>
                  </template>
                </el-statistic>
              </el-col>
              <el-col :span="6">
                <el-statistic title="移除权限" :value="compareData.permissionChanges.removedButtons.length" suffix="个">
                  <template #prefix>
                    <el-icon style="color: #f56c6c"><Close /></el-icon>
                  </template>
                </el-statistic>
              </el-col>
            </el-row>
          </div>

          <!-- 详细权限变更对比 -->
          <div class="detailed-changes">
            <el-tabs v-model="activeTab" type="border-card">
              <!-- 新增权限标签页 -->
              <el-tab-pane label="新增权限" name="added">
                <template #label>
                  <span class="tab-label">
                    <el-icon style="color: #67c23a"><Plus /></el-icon>
                    新增权限 ({{ totalAddedCount }})
                  </span>
                </template>
                <div class="permission-changes-content">
                  <div v-if="compareData.permissionChanges.addedMenus.length > 0" class="menu-changes-section">
                    <h4 class="changes-title">
                      <el-icon style="color: #67c23a"><Plus /></el-icon>
                      新增菜单权限 ({{ compareData.permissionChanges.addedMenus.length }})
                    </h4>
                    <div class="menu-list">
                      <div
                        v-for="menu in compareData.permissionChanges.addedMenus"
                        :key="menu.id"
                        class="menu-item added"
                      >
                        <div class="menu-info">
                          <el-icon class="menu-icon"><Menu /></el-icon>
                          <span class="menu-label">{{ menu.label }}</span>
                          <el-tag type="success" size="small" effect="plain">{{ getMenuTypeLabel(menu.menuType) }}</el-tag>
                        </div>
                        <div v-if="menu.relatedButtons && menu.relatedButtons.length > 0" class="related-buttons">
                          <span class="button-label">包含操作：</span>
                          <el-tag
                            v-for="button in menu.relatedButtons"
                            :key="button.id"
                            type="success"
                            size="small"
                            effect="light"
                            class="button-tag"
                          >
                            {{ button.label }}
                          </el-tag>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div v-if="compareData.permissionChanges.addedButtons.length > 0" class="button-changes-section">
                    <h4 class="changes-title">
                      <el-icon style="color: #67c23a"><Plus /></el-icon>
                      新增操作权限 ({{ compareData.permissionChanges.addedButtons.length }})
                    </h4>
                    <div class="button-list">
                      <el-tag
                        v-for="button in compareData.permissionChanges.addedButtons"
                        :key="button.id"
                        type="success"
                        size="small"
                        effect="light"
                        class="button-item added"
                      >
                        <el-icon><Plus /></el-icon>
                        {{ button.label }}
                      </el-tag>
                    </div>
                  </div>

                  <div v-if="totalAddedCount === 0" class="no-changes">
                    <el-empty description="无新增权限" :image-size="120" />
                  </div>
                </div>
              </el-tab-pane>

              <!-- 移除权限标签页 -->
              <el-tab-pane label="移除权限" name="removed">
                <template #label>
                  <span class="tab-label">
                    <el-icon style="color: #f56c6c"><Minus /></el-icon>
                    移除权限 ({{ totalRemovedCount }})
                  </span>
                </template>
                <div class="permission-changes-content">
                  <div v-if="compareData.permissionChanges.removedMenus.length > 0" class="menu-changes-section">
                    <h4 class="changes-title">
                      <el-icon style="color: #f56c6c"><Minus /></el-icon>
                      移除菜单权限 ({{ compareData.permissionChanges.removedMenus.length }})
                    </h4>
                    <div class="menu-list">
                      <div
                        v-for="menu in compareData.permissionChanges.removedMenus"
                        :key="menu.id"
                        class="menu-item removed"
                      >
                        <div class="menu-info">
                          <el-icon class="menu-icon"><Menu /></el-icon>
                          <span class="menu-label">{{ menu.label }}</span>
                          <el-tag type="danger" size="small" effect="plain">{{ getMenuTypeLabel(menu.menuType) }}</el-tag>
                        </div>
                        <div v-if="menu.relatedButtons && menu.relatedButtons.length > 0" class="related-buttons">
                          <span class="button-label">包含操作：</span>
                          <el-tag
                            v-for="button in menu.relatedButtons"
                            :key="button.id"
                            type="danger"
                            size="small"
                            effect="light"
                            class="button-tag"
                          >
                            {{ button.label }}
                          </el-tag>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div v-if="compareData.permissionChanges.removedButtons.length > 0" class="button-changes-section">
                    <h4 class="changes-title">
                      <el-icon style="color: #f56c6c"><Minus /></el-icon>
                      移除操作权限 ({{ compareData.permissionChanges.removedButtons.length }})
                    </h4>
                    <div class="button-list">
                      <el-tag
                        v-for="button in compareData.permissionChanges.removedButtons"
                        :key="button.id"
                        type="danger"
                        size="small"
                        effect="light"
                        class="button-item removed"
                      >
                        <el-icon><Minus /></el-icon>
                        {{ button.label }}
                      </el-tag>
                    </div>
                  </div>

                  <div v-if="totalRemovedCount === 0" class="no-changes">
                    <el-empty description="无移除权限" :image-size="120" />
                  </div>
                </div>
              </el-tab-pane>

              <!-- 当前角色权限标签页 -->
              <el-tab-pane label="当前角色" name="current">
                <template #label>
                  <span class="tab-label">
                    <el-icon><UserFilled /></el-icon>
                    当前角色 ({{ compareData.currentRoles.length }})
                  </span>
                </template>
                <div class="current-roles-content">
                  <div v-if="compareData.currentRoles.length > 0">
                    <div class="roles-list">
                      <el-card
                        v-for="role in compareData.currentRoles"
                        :key="role.roleId"
                        class="role-card"
                        shadow="hover"
                      >
                        <div class="role-header">
                          <div class="role-info">
                            <h4>{{ role.roleName }}</h4>
                            <p class="role-key">{{ role.roleKey }}</p>
                          </div>
                          <el-tag type="primary" size="small">{{ getRoleCategoryName(role.roleCategory) }}</el-tag>
                        </div>
                      </el-card>
                    </div>

                    <!-- 当前权限树展示 -->
                    <div v-if="compareData.currentMenuTree.length > 0" class="current-menu-tree">
                      <h4>当前菜单权限</h4>
                      <el-tree
                        :data="compareData.currentMenuTree"
                        show-checkbox
                        default-expand-all
                        node-key="id"
                        :props="{ label: 'label', children: 'children' }"
                        class="permission-tree"
                      >
                        <template #default="{ node, data }">
                          <span class="tree-node">
                            <el-icon v-if="data.menuType === 'M'" class="directory-icon"><Folder /></el-icon>
                            <el-icon v-else-if="data.menuType === 'C'" class="menu-icon"><Menu /></el-icon>
                            <el-icon v-else-if="data.menuType === 'F'" class="button-icon"><Operation /></el-icon>
                            <span class="node-label">{{ node.label }}</span>
                            <el-tag v-if="data.menuType === 'M'" type="success" size="small" effect="plain">目录</el-tag>
                            <el-tag v-else-if="data.menuType === 'C'" type="primary" size="small" effect="plain">菜单</el-tag>
                            <el-tag v-else-if="data.menuType === 'F'" type="warning" size="small" effect="plain">按钮</el-tag>
                          </span>
                        </template>
                      </el-tree>
                    </div>
                  </div>
                  <div v-else class="no-current-roles">
                    <el-empty description="用户暂无角色" :image-size="120" />
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="visibleProxy = false">关 闭</el-button>
        <!-- 只有待审核状态才显示审批按钮 -->
        <template v-if="compareData && compareData.requestInfo.status === '0'">
          <el-button
            type="danger"
            :loading="approveLoading"
            @click="handleApprove(false)"
          >
            <el-icon><Close /></el-icon>
            拒绝申请
          </el-button>
          <el-button
            type="success"
            :loading="approveLoading"
            @click="handleApprove(true)"
          >
            <el-icon><Check /></el-icon>
            通过申请
          </el-button>
        </template>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance, ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Check,
  Close,
  Document,
  Folder,
  Menu,
  Minus,
  Operation,
  Plus,
  User,
  UserFilled
} from '@element-plus/icons-vue';
import {
  // getRolePermissionCompare,
  batchApproveRoleAuthRequest,
  // RolePermissionCompareVO,
  RoleAuthBatchApprovalForm
} from '@/api/system/approval/roleAuthRequest';

// ======================== Props & Emits ========================
const props = defineProps<{
  visible: boolean;
  requestId: number | null;
}>();

const emit = defineEmits<{
  'update:visible': [value: boolean];
  'approve': [];
}>();

// ======================== 基础设置 ========================
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_project_role_category } = toRefs<any>(proxy?.useDict('sys_project_role_category'));

// ======================== 响应式数据 ========================
const loading = ref(false);
const approveLoading = ref(false);
const compareData = ref<RolePermissionCompareVO | null>(null);
const activeTab = ref('added');

// ======================== 计算属性 ========================
const visibleProxy = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

// 是否有权限变更
const hasPermissionChanges = computed(() => {
  if (!compareData.value) return false;
  return totalAddedCount.value > 0 || totalRemovedCount.value > 0;
});

// 新增权限总数
const totalAddedCount = computed(() => {
  if (!compareData.value) return 0;
  return compareData.value.permissionChanges.addedMenus.length +
    compareData.value.permissionChanges.addedButtons.length;
});

// 移除权限总数
const totalRemovedCount = computed(() => {
  if (!compareData.value) return 0;
  return compareData.value.permissionChanges.removedMenus.length +
    compareData.value.permissionChanges.removedButtons.length;
});

// ======================== 工具方法 ========================
const formatDate = (timestamp: number | Date): string => {
  if (!timestamp) return '';
  const date = timestamp instanceof Date ? timestamp : new Date(timestamp);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

const getMenuTypeLabel = (menuType: string): string => {
  const typeLabels = {
    'M': '目录',
    'C': '菜单',
    'F': '按钮'
  };
  return typeLabels[menuType] || '';
};

const getRoleCategoryName = (category: string): string => {
  const dictItem = sys_project_role_category.value?.find((item: any) => item.value === category);
  return dictItem ? dictItem.label : '';
};

// ======================== 数据获取 ========================
const loadCompareData = async () => {
  if (!props.requestId) return;

  try {
    loading.value = true;
    const res = await getRolePermissionCompare(props.requestId);
    compareData.value = res.data;

    // 根据权限变更情况自动选择默认标签页
    if (totalAddedCount.value > 0) {
      activeTab.value = 'added';
    } else if (totalRemovedCount.value > 0) {
      activeTab.value = 'removed';
    } else {
      activeTab.value = 'current';
    }
  } catch (error) {
    proxy?.$modal.msgError('获取权限对比数据失败');
  } finally {
    loading.value = false;
  }
};

// ======================== 事件处理 ========================
const handleApprove = async (approve: boolean) => {
  if (!compareData.value) return;

  try {
    const action = approve ? '通过' : '拒绝';
    const confirmTitle = approve ? '确认通过申请' : '确认拒绝申请';
    let message = '';

    if (approve) {
      if (hasPermissionChanges.value) {
        message = `通过后用户权限将发生变更：\n`;
        if (totalAddedCount.value > 0) {
          message += `• 新增 ${totalAddedCount.value} 项权限\n`;
        }
        if (totalRemovedCount.value > 0) {
          message += `• 移除 ${totalRemovedCount.value} 项权限\n`;
        }
        message += `\n权限变更将立即生效，确认通过吗？`;
      } else {
        message = '该申请不会导致权限变更，确认通过吗？';
      }
    } else {
      message = '拒绝后申请状态将变更为已拒绝，用户可重新申请';
    }

    const { value: approveRemark } = await ElMessageBox.prompt(
      message + '\n\n请输入审批意见（可选）',
      confirmTitle,
      {
        confirmButtonText: `确认${action}`,
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPlaceholder: '请输入审批意见...'
      }
    );

    approveLoading.value = true;
    const batchForm: RoleAuthBatchApprovalForm = {
      ids: [compareData.value.requestInfo.id],
      approve,
      approveRemark
    };

    await batchApproveRoleAuthRequest(batchForm);

    const successMessage = approve ?
      '审批通过成功，角色权限已生效' :
      '审批拒绝成功';

    ElMessage.success(successMessage);
    emit('approve');
  } catch (error) {
    if (error !== 'cancel') {
      proxy?.$modal.msgError('审批操作失败');
    }
  } finally {
    approveLoading.value = false;
  }
};

// ======================== 监听器 ========================
watch([() => props.visible, () => props.requestId], ([visible, requestId]) => {
  if (visible && requestId) {
    loadCompareData();
  } else {
    compareData.value = null;
  }
});
</script>

<style lang="scss" scoped>
.permission-compare-drawer {
  :deep(.el-drawer__body) {
    padding: 0;
  }
}

.drawer-content {
  height: 100%;
  overflow-y: auto;
  padding: 20px;
}

.permission-compare-content {
  max-width: 1200px;
  margin: 0 auto;
}

// 用户概览样式
.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;
}

// 申请信息样式
.role-info {
  .role-name {
    margin-bottom: 4px;
  }

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

.apply-reason {
  max-width: 400px;
  word-break: break-all;
  line-height: 1.5;
}

// 权限变更对比样式
.permission-changes-section {
  margin-bottom: 24px;
}

.changes-summary {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.detailed-changes {
  .tab-label {
    display: flex;
    align-items: center;
    gap: 4px;
  }
}

.permission-changes-content {
  padding: 20px;
}

.menu-changes-section,
.button-changes-section {
  margin-bottom: 24px;
}

.changes-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
}

// 菜单项样式
.menu-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.menu-item {
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;

  &.added {
    background-color: #f0f9ff;
    border-color: #b3e19d;
  }

  &.removed {
    background-color: #fef0f0;
    border-color: #fbc4c4;
  }

  .menu-info {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;

    .menu-icon {
      color: #409eff;
      font-size: 16px;
    }

    .menu-label {
      font-weight: 500;
      flex: 1;
    }
  }

  .related-buttons {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;

    .button-label {
      font-size: 12px;
      color: #909399;
    }

    .button-tag {
      margin: 0;
    }
  }
}

// 按钮权限样式
.button-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.button-item {
  display: inline-flex;
  align-items: center;
  gap: 4px;

  &.added {
    background-color: #f0f9ff;
    border-color: #67c23a;
    color: #67c23a;
  }

  &.removed {
    background-color: #fef0f0;
    border-color: #f56c6c;
    color: #f56c6c;
  }
}

// 当前角色样式
.current-roles-content {
  padding: 20px;
}

.roles-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.role-card {
  .role-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .role-info {
      flex: 1;

      h4 {
        margin: 0 0 4px 0;
        color: #303133;
      }

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

.current-menu-tree {
  h4 {
    margin-bottom: 16px;
    color: #303133;
  }
}

.permission-tree {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 10px;

  .tree-node {
    display: flex;
    align-items: center;
    gap: 6px;
    width: 100%;

    .directory-icon {
      color: #e6a23c;
    }

    .menu-icon {
      color: #409eff;
    }

    .button-icon {
      color: #f56c6c;
    }

    .node-label {
      flex: 1;
      margin-right: 8px;
    }
  }
}

// 无数据样式
.no-changes,
.no-current-roles {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

// 抽屉底部操作栏
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
  background-color: #fff;
}

.ml-2 {
  margin-left: 8px;
}

// 响应式设计
@media (max-width: 768px) {
  .drawer-content {
    padding: 10px;
  }

  .user-summary {
    flex-direction: column;
    text-align: center;
  }

  .roles-list {
    grid-template-columns: 1fr;
  }

  .menu-item .menu-info {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
