<template>
  <el-drawer v-model="visibleProxy" title="用户数据权限配置" size="70%" :close-on-click-modal="false" @closed="handleDrawerClosed">
    <div class="data-permission-container">
      <!-- 用户信息展示 -->
      <div class="user-info-section">
        <el-card shadow="hover" class="user-info-card">
          <div class="user-summary">
            <el-avatar :size="40">
              <el-icon><User /></el-icon>
            </el-avatar>
            <div class="user-details">
              <h4>{{ userInfo?.userName || '未知用户' }}</h4>
              <p class="user-meta">
                <span>{{ userInfo?.nickName }}</span>
                <el-divider direction="vertical" />
                <span>{{ userInfo?.deptName }}</span>
              </p>
            </div>
            <div class="permission-stats">
              <el-statistic title="已配置权限" :value="configuredCount" suffix="项" />
              <el-statistic title="配置完成度" :value="completionRate" suffix="%" />
            </div>
          </div>
        </el-card>
      </div>

      <!-- 权限配置主体 -->
      <div class="permission-config-body">
        <el-row :gutter="20">
          <!-- 左侧权限类型列表 -->
          <el-col :span="8">
            <el-card shadow="hover" class="permission-types-card">
              <template #header>
                <div class="card-header">
                  <span class="header-title">数据权限类型</span>
                  <el-tag type="info" size="small">{{ permissionTypes.length }}项</el-tag>
                </div>
              </template>

              <div class="permission-types-list">
                <div
                  v-for="type in permissionTypes"
                  :key="type.typeId"
                  class="permission-type-item"
                  :class="{ active: selectedTypeId === type.typeId }"
                  @click="handleTypeSelect(type.typeId)"
                >
                  <div class="type-icon">
                    <el-icon :size="18">
                      <component :is="getTypeIcon(type.typeCode)" />
                    </el-icon>
                  </div>
                  <div class="type-content">
                    <div class="type-name">{{ type.typeName }}</div>
                    <div class="type-desc">{{ type.description }}</div>
                    <div class="type-status">
                      <el-tag :type="getPermissionStatusType(type.typeId)" size="small" effect="plain">
                        {{ getPermissionStatusText(type.typeId) }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 右侧权限配置区域 -->
          <el-col :span="16">
            <el-card shadow="hover" class="permission-config-card">
              <template #header>
                <div class="card-header">
                  <span class="header-title">
                    {{ currentPermissionType?.typeName || '请选择权限类型' }}
                  </span>
                  <div class="header-actions" v-if="currentPermissionType">
                    <el-button size="small" @click="handleExpandAll" :disabled="currentUserPermission?.isAllAccess === 1"> 展开全部 </el-button>
                    <el-button size="small" @click="handleCollapseAll" :disabled="currentUserPermission?.isAllAccess === 1"> 收起全部 </el-button>
                  </div>
                </div>
              </template>

              <div v-if="currentPermissionType" class="permission-config-content">
                <!-- 权限模式选择 -->
                <div class="permission-mode-section">
                  <el-card shadow="never" class="mode-card">
                    <div class="mode-title">权限范围设置</div>
                    <el-radio-group v-model="currentUserPermission.isAllAccess" @change="handlePermissionModeChange" class="mode-radio-group">
                      <el-radio :value="1" class="mode-radio">
                        <div class="radio-content">
                          <div class="radio-title success">全部权限</div>
                          <div class="radio-desc">拥有该类型下的所有数据访问权限</div>
                        </div>
                      </el-radio>
                      <el-radio :value="0" class="mode-radio">
                        <div class="radio-content">
                          <div class="radio-title primary">自定义权限</div>
                          <div class="radio-desc">只能访问指定的数据范围</div>
                        </div>
                      </el-radio>
                    </el-radio-group>
                  </el-card>
                </div>

                <!-- 具体权限选择 -->
                <div class="permission-tree-section">
                  <div v-if="currentUserPermission.isAllAccess === 1" class="all-permission-display">
                    <div class="all-permission-icon">
                      <el-icon :size="48"><CircleCheck /></el-icon>
                    </div>
                    <div class="all-permission-text">
                      <h3>已设置为全部权限</h3>
                      <p>用户将拥有"{{ currentPermissionType.typeName }}"下的所有数据访问权限</p>
                    </div>
                  </div>

                  <div v-else class="custom-permission-area">
                    <div class="tree-header">
                      <span class="tree-title">请选择具体的访问范围：</span>
                      <el-tag v-if="selectedValueIds.length > 0" type="primary" size="small"> 已选择 {{ selectedValueIds.length }} 项 </el-tag>
                    </div>

                    <div v-if="permissionTreeData.length > 0" class="tree-container">
                      <el-tree
                        ref="permissionTreeRef"
                        :data="permissionTreeData"
                        :props="treeProps"
                        show-checkbox
                        node-key="valueId"
                        :default-expand-all="defaultExpandAll"
                        :default-checked-keys="selectedValueIds"
                        @check="handleTreeCheck"
                        class="permission-tree"
                      >
                        <template #default="{ node, data }">
                          <div class="tree-node-content">
                            <span class="node-label">{{ data.valueName }}</span>
                            <el-tag v-if="data.children && data.children.length > 0" size="small" type="info">
                              {{ data.children.length }}
                            </el-tag>
                          </div>
                        </template>
                      </el-tree>
                    </div>

                    <div v-else class="empty-tree">
                      <el-empty description="该权限类型暂无可配置的选项" />
                    </div>
                  </div>
                </div>
              </div>

              <div v-else class="no-type-selected">
                <el-empty description="请从左侧选择权限类型" />
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 底部操作按钮 -->
      <div class="drawer-footer">
        <el-space size="large">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" :loading="saving" @click="handleSave">
            <el-icon><Check /></el-icon>
            保存配置
          </el-button>
        </el-space>
      </div>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance, onMounted, ref, watch } from 'vue';
import api from '@/api/system/userDataPermission';
import {
  DataPermissionTypeVO,
  DataPermissionValueVO,
  UserDataPermissionVO,
  UserDataPermissionForm,
  convertToTree
} from '@/api/system/userDataPermission/types';

// ======================== Props & Emits ========================
const props = defineProps<{
  visible: boolean;
  userId?: string | number;
  userInfo?: {
    userId: string | number;
    userName: string;
    nickName: string;
    deptName: string;
  };
}>();

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

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

// ======================== 响应式数据 ========================
const permissionTypes = ref<DataPermissionTypeVO[]>([]);
const permissionValues = ref<Record<number, DataPermissionValueVO[]>>({});
const userPermissions = ref<UserDataPermissionVO[]>([]);
const selectedTypeId = ref<number>();
const saving = ref(false);
const defaultExpandAll = ref(false);

// 树组件引用
const permissionTreeRef = ref();

// 树配置
const treeProps = {
  children: 'children',
  label: 'valueName',
  value: 'valueId'
};

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

// 当前选中的权限类型
const currentPermissionType = computed(() => {
  return permissionTypes.value.find((type) => type.typeId === selectedTypeId.value);
});

// 当前用户在选中类型下的权限配置
const currentUserPermission = computed(() => {
  const permission = userPermissions.value.find((p) => p.typeId === selectedTypeId.value);
  return (
    permission || {
      userId: props.userId,
      typeId: selectedTypeId.value,
      typeName: currentPermissionType.value?.typeName || '',
      isAllAccess: 0,
      permissionValues: [],
      valueIds: []
    }
  );
});

// 当前权限类型的树形数据
const permissionTreeData = computed(() => {
  if (!selectedTypeId.value) return [];
  const values = permissionValues.value[selectedTypeId.value] || [];
  return convertToTree(values);
});

// 选中的权限值ID列表
const selectedValueIds = computed(() => {
  return currentUserPermission.value.valueIds || [];
});

// 已配置权限数量
const configuredCount = computed(() => {
  return userPermissions.value.filter((p) => p.isAllAccess === 1 || (p.valueIds && p.valueIds.length > 0)).length;
});

// 配置完成度
const completionRate = computed(() => {
  if (permissionTypes.value.length === 0) return 0;
  return Math.round((configuredCount.value / permissionTypes.value.length) * 100);
});

// ======================== 方法 ========================
// 获取权限类型图标
const getTypeIcon = (typeCode: string) => {
  const iconMap: Record<string, any> = {
    'region': Location,
    'organization': OfficeBuilding,
    'product': Goods,
    'channel': UserFilled,
    'customer_level': Star,
    'business_type': Lightning,
    'time_range': Clock,
    'amount': Money,
    'department': Histogram
  };
  return iconMap[typeCode] || Location;
};

// 获取权限状态类型
const getPermissionStatusType = (typeId: number) => {
  const permission = userPermissions.value.find((p) => p.typeId === typeId);
  if (!permission) return '';

  if (permission.isAllAccess === 1) return 'success';
  if (permission.valueIds && permission.valueIds.length > 0) return 'primary';
  return 'info';
};

// 获取权限状态文本
const getPermissionStatusText = (typeId: number) => {
  const permission = userPermissions.value.find((p) => p.typeId === typeId);
  if (!permission) return '未配置';

  if (permission.isAllAccess === 1) return '全部权限';
  if (permission.valueIds && permission.valueIds.length > 0) {
    return `已选择 ${permission.valueIds.length} 项`;
  }
  return '未配置';
};

// 选择权限类型
const handleTypeSelect = async (typeId: number) => {
  selectedTypeId.value = typeId;

  // 如果还没有加载过该类型的权限值，则加载
  if (!permissionValues.value[typeId]) {
    try {
      const res = await api.listDataPermissionValues(typeId);
      permissionValues.value[typeId] = res.data;
    } catch (error) {
      proxy?.$modal.msgError('加载权限值失败');
    }
  }
};

// 权限模式变更
const handlePermissionModeChange = (value: number) => {
  const permission = userPermissions.value.find((p) => p.typeId === selectedTypeId.value);
  if (permission) {
    permission.isAllAccess = value;
    if (value === 1) {
      // 切换到全部权限时，清空具体选择
      permission.valueIds = [];
      permission.permissionValues = [];
    }
  } else {
    // 新增权限配置
    userPermissions.value.push({
      userId: props.userId,
      typeId: selectedTypeId.value!,
      typeName: currentPermissionType.value?.typeName || '',
      isAllAccess: value,
      permissionValues: [],
      valueIds: []
    });
  }
};

// 树节点选择变更
const handleTreeCheck = (data: DataPermissionValueVO, { checkedKeys }: any) => {
  const permission = userPermissions.value.find((p) => p.typeId === selectedTypeId.value);
  if (permission) {
    permission.valueIds = checkedKeys;
    // 更新 permissionValues
    const allValues = permissionValues.value[selectedTypeId.value!] || [];
    permission.permissionValues = allValues.filter((v) => checkedKeys.includes(v.valueId));
  }
};

// 展开全部
const handleExpandAll = () => {
  defaultExpandAll.value = true;
  permissionTreeRef.value?.setCheckedKeys(selectedValueIds.value);
};

// 收起全部
const handleCollapseAll = () => {
  defaultExpandAll.value = false;
  const allNodes = permissionTreeRef.value?.store?.nodesMap || {};
  Object.values(allNodes).forEach((node: any) => {
    if (node.expanded) {
      node.collapse();
    }
  });
};

// 保存配置
const handleSave = async () => {
  try {
    saving.value = true;

    const formData: UserDataPermissionForm = {
      userId: props.userId,
      permissions: userPermissions.value.map((p) => ({
        typeId: p.typeId,
        isAllAccess: p.isAllAccess,
        valueIds: p.valueIds
      }))
    };

    await api.saveUserDataPermissions(props.userId!, formData);
    proxy?.$modal.msgSuccess('数据权限配置保存成功');
    emit('save');
    visibleProxy.value = false;
  } catch (error) {
    proxy?.$modal.msgError('保存失败');
  } finally {
    saving.value = false;
  }
};

// 取消
const handleCancel = () => {
  visibleProxy.value = false;
};

// 抽屉关闭处理
const handleDrawerClosed = () => {
  selectedTypeId.value = undefined;
  defaultExpandAll.value = false;
};

// 加载数据
const loadData = async () => {
  try {
    // 加载权限类型
    const typesRes = await api.listDataPermissionTypes();
    permissionTypes.value = typesRes.data;

    // 加载用户权限配置
    if (props.userId) {
      const userRes = await api.getUserDataPermissions(props.userId);
      userPermissions.value = userRes.data;
    }

    // 默认选择第一个权限类型
    if (permissionTypes.value.length > 0) {
      await handleTypeSelect(permissionTypes.value[0].typeId);
    }
  } catch (error) {
    proxy?.$modal.msgError('加载数据失败');
  }
};

// ======================== 监听器 ========================
watch(
  () => props.visible,
  (visible) => {
    if (visible && props.userId) {
      loadData();
    }
  }
);

// ======================== 生命周期 ========================
onMounted(() => {
  if (props.visible && props.userId) {
    loadData();
  }
});
</script>

<style lang="scss" scoped>
.data-permission-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0 20px 20px 20px;
}

.user-info-section {
  margin-bottom: 20px;
}

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

  .user-details {
    flex: 1;

    h4 {
      margin: 0 0 4px 0;
      font-size: 16px;
      color: #303133;
    }

    .user-meta {
      margin: 0;
      font-size: 14px;
      color: #606266;
    }
  }

  .permission-stats {
    display: flex;
    gap: 40px;
  }
}

.permission-config-body {
  flex: 1;
  overflow: hidden;
}

.permission-types-card,
.permission-config-card {
  height: 600px;

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

    .header-title {
      font-weight: 600;
      font-size: 16px;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }
}

.permission-types-list {
  height: 520px;
  overflow-y: auto;
}

.permission-type-item {
  display: flex;
  align-items: flex-start;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  border: 2px solid transparent;
  margin-bottom: 8px;

  &:hover {
    background-color: #f5f5f5;
  }

  &.active {
    background-color: #e6f7ff;
    border-color: #1890ff;
  }

  .type-icon {
    margin-right: 12px;
    margin-top: 2px;
    color: #666;
  }

  .type-content {
    flex: 1;

    .type-name {
      font-weight: 500;
      margin-bottom: 4px;
      color: #303133;
    }

    .type-desc {
      font-size: 12px;
      color: #909399;
      margin-bottom: 8px;
      line-height: 1.4;
    }

    .type-status {
      // Status styles handled by el-tag
    }
  }
}

.permission-config-content {
  height: 520px;
  display: flex;
  flex-direction: column;
}

.permission-mode-section {
  margin-bottom: 20px;

  .mode-card {
    background: #fafafa;
    border: none;

    .mode-title {
      font-weight: 600;
      margin-bottom: 16px;
      color: #303133;
    }

    .mode-radio-group {
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .mode-radio {
      .radio-content {
        margin-left: 8px;

        .radio-title {
          font-weight: 500;
          margin-bottom: 4px;

          &.success {
            color: #67c23a;
          }

          &.primary {
            color: #409eff;
          }
        }

        .radio-desc {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}

.permission-tree-section {
  flex: 1;
  overflow: hidden;

  .all-permission-display {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 300px;
    background: #f6ffed;
    border: 1px solid #b7eb8f;
    border-radius: 8px;

    .all-permission-icon {
      color: #52c41a;
      margin-bottom: 16px;
    }

    .all-permission-text {
      text-align: center;

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

      p {
        margin: 0;
        color: #666;
      }
    }
  }

  .custom-permission-area {
    height: 100%;
    display: flex;
    flex-direction: column;

    .tree-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .tree-title {
        font-weight: 500;
        color: #303133;
      }
    }

    .tree-container {
      flex: 1;
      border: 1px solid #dcdfe6;
      border-radius: 6px;
      padding: 12px;
      overflow: auto;
      background: white;

      .permission-tree {
        .tree-node-content {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;

          .node-label {
            flex: 1;
          }
        }
      }
    }

    .empty-tree {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid #dcdfe6;
      border-radius: 6px;
      background: #fafafa;
    }
  }
}

.no-type-selected {
  height: 520px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.drawer-footer {
  text-align: center;
  padding: 16px 0;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
}

// 响应式设计
@media (max-width: 1200px) {
  .permission-config-body {
    :deep(.el-col-8) {
      flex: 0 0 35%;
      max-width: 35%;
    }

    :deep(.el-col-16) {
      flex: 0 0 65%;
      max-width: 65%;
    }
  }
}

@media (max-width: 768px) {
  .user-summary {
    flex-direction: column;
    text-align: center;

    .permission-stats {
      flex-direction: column;
      gap: 20px;
    }
  }

  .permission-config-body {
    :deep(.el-row) {
      flex-direction: column;
    }

    :deep(.el-col) {
      flex: none;
      max-width: 100%;
    }
  }

  .permission-types-card,
  .permission-config-card {
    height: auto;
    margin-bottom: 20px;
  }
}
</style>
