<template>
  <div class="data-permission-select">
    <div class="permission-summary" @click="handleOpenConfig">
      <div class="summary-content">
        <div class="summary-title">
          <el-icon><Key /></el-icon>
          <span>数据权限配置</span>
          <el-tag v-if="configuredCount > 0" type="primary" size="small"> 已配置 {{ configuredCount }} 项 </el-tag>
        </div>
        <div class="summary-desc">
          {{ getSummaryText() }}
        </div>
      </div>
      <div class="summary-action">
        <el-button type="primary" size="small" plain>
          <el-icon><Setting /></el-icon>
          配置权限
        </el-button>
      </div>
    </div>

    <!-- 权限配置对话框 -->
    <el-dialog v-model="configDialogVisible" title="数据权限配置" width="900px" :close-on-click-modal="false" @closed="handleDialogClosed">
      <div class="dialog-content">
        <el-tabs v-model="activeTab" class="permission-tabs">
          <el-tab-pane v-for="type in permissionTypes" :key="type.typeId" :label="type.typeName" :name="type.typeId.toString()">
            <div class="tab-content">
              <!-- 权限模式选择 -->
              <div class="permission-mode">

              </div>

              <!-- 权限值选择 -->
              <div v-if="getPermissionMode(type.typeId) === 0" class="permission-values">
                <div class="values-header">
                  <span>请选择具体权限范围：</span>
                  <el-button size="small" @click="handleToggleExpand(type.typeId)"> {{ isExpanded[type.typeId] ? '收起' : '展开' }}全部 </el-button>
                </div>

                <div class="values-tree">
                  <el-tree
                    :ref="(el) => setTreeRef(type.typeId, el)"
                    :data="getTreeData(type.typeId)"
                    :props="treeProps"
                    show-checkbox
                    node-key="valueId"
                    :default-expand-all="isExpanded[type.typeId]"
                    :default-checked-keys="getSelectedValues(type.typeId)"
                    @check="(data, checked) => handleTreeCheck(type.typeId, data, checked)"
                  >
                    <template #default="{ node, data }">
                      <span class="tree-node">{{ data.valueName }}</span>
                    </template>
                  </el-tree>
                </div>
              </div>

              <div v-else class="all-permission-tip">
                <el-icon size="24" color="#52c41a"><CircleCheck /></el-icon>
                <span>该权限类型已设置为全部权限</span>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="configDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSaveConfig">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

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

// ======================== Props & Emits ========================
const props = defineProps<{
  modelValue?: UserDataPermissionConfigItem[];
  disabled?: boolean;
}>();

const emit = defineEmits<{
  'update:modelValue': [value: UserDataPermissionConfigItem[]];
}>();

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

// ======================== 响应式数据 ========================
const configDialogVisible = ref(false);
const activeTab = ref('1');
const permissionTypes = ref<DataPermissionTypeVO[]>([]);
const permissionValues = ref<Record<number, DataPermissionValueVO[]>>({});
const localPermissions = ref<UserDataPermissionConfigItem[]>([]);
const isExpanded = ref<Record<number, boolean>>({});
const treeRefs = ref<Record<number, any>>({});

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

// ======================== 计算属性 ========================
const configuredCount = computed(() => {
  return localPermissions.value.filter((p) => p.isAllAccess === 1 || (p.valueIds && p.valueIds.length > 0)).length;
});

// ======================== 方法 ========================
// 设置树组件引用
const setTreeRef = (typeId: number, el: any) => {
  if (el) {
    treeRefs.value[typeId] = el;
  }
};

// 获取权限模式
const getPermissionMode = (typeId: number): number => {
  const permission = localPermissions.value.find((p) => p.typeId === typeId);
  return permission?.isAllAccess ?? 0;
};

// 获取选中的权限值
const getSelectedValues = (typeId: number): number[] => {
  const permission = localPermissions.value.find((p) => p.typeId === typeId);
  return permission?.valueIds ?? [];
};

// 获取树形数据
const getTreeData = (typeId: number): DataPermissionValueVO[] => {
  const values = permissionValues.value[typeId] || [];
  return convertToTree(values);
};

// 获取摘要文本
const getSummaryText = (): string => {
  if (configuredCount.value === 0) {
    return '未配置数据权限，用户将无法访问任何数据';
  }

  const allAccessCount = localPermissions.value.filter((p) => p.isAllAccess === 1).length;
  const customCount = configuredCount.value - allAccessCount;

  let summary = '';
  if (allAccessCount > 0) {
    summary += `${allAccessCount}项全部权限`;
  }
  if (customCount > 0) {
    if (summary) summary += '，';
    summary += `${customCount}项自定义权限`;
  }

  return summary;
};

// 打开配置对话框
const handleOpenConfig = async () => {
  if (props.disabled) return;

  try {
    // 加载权限类型
    if (permissionTypes.value.length === 0) {
      const typesRes = await api.listDataPermissionTypes();
      permissionTypes.value = typesRes.data;

      // 初始化本地权限数据
      if (!props.modelValue || props.modelValue.length === 0) {
        localPermissions.value = permissionTypes.value.map((type) => ({
          typeId: type.typeId,
          isAllAccess: 0,
          valueIds: []
        }));
      }
    }

    // 加载权限值数据
    for (const type of permissionTypes.value) {
      if (!permissionValues.value[type.typeId]) {
        const valuesRes = await api.listDataPermissionValues(type.typeId);
        permissionValues.value[type.typeId] = valuesRes.data;
      }
    }

    configDialogVisible.value = true;
    activeTab.value = permissionTypes.value[0]?.typeId.toString() || '1';
  } catch (error) {
    proxy?.$modal.msgError('加载权限数据失败');
  }
};

// 权限模式变更
const handleModeChange = (typeId: number, value: number) => {
  const permission = localPermissions.value.find((p) => p.typeId === typeId);
  if (permission) {
    permission.isAllAccess = value;
    if (value === 1) {
      // 切换到全部权限时，清空具体选择
      permission.valueIds = [];
    }
  } else {
    localPermissions.value.push({
      typeId,
      isAllAccess: value,
      valueIds: []
    });
  }
};

// 树节点选择变更
const handleTreeCheck = (typeId: number, data: DataPermissionValueVO, { checkedKeys }: any) => {
  const permission = localPermissions.value.find((p) => p.typeId === typeId);
  if (permission) {
    permission.valueIds = checkedKeys;
  }
};

// 切换展开状态
const handleToggleExpand = (typeId: number) => {
  isExpanded.value[typeId] = !isExpanded.value[typeId];
  const treeRef = treeRefs.value[typeId];
  if (treeRef) {
    if (isExpanded.value[typeId]) {
      treeRef.setCheckedKeys(getSelectedValues(typeId));
    }
  }
};

// 保存配置
const handleSaveConfig = () => {
  emit('update:modelValue', [...localPermissions.value]);
  configDialogVisible.value = false;
  proxy?.$modal.msgSuccess('权限配置保存成功');
};

// 对话框关闭处理
const handleDialogClosed = () => {
  // 重置为原始值
  localPermissions.value = props.modelValue ? [...props.modelValue] : [];
};

// ======================== 监听器 ========================
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue) {
      localPermissions.value = [...newValue];
    } else {
      localPermissions.value = [];
    }
  },
  { immediate: true, deep: true }
);
</script>

<style lang="scss" scoped>
.data-permission-select {
  .permission-summary {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s;

    &:hover {
      border-color: #409eff;
      background-color: #f5f7fa;
    }

    .summary-content {
      flex: 1;

      .summary-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 4px;

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

        span {
          font-weight: 500;
          color: #303133;
        }
      }

      .summary-desc {
        font-size: 12px;
        color: #606266;
        line-height: 1.4;
      }
    }

    .summary-action {
      margin-left: 16px;
    }
  }

  &.disabled {
    .permission-summary {
      cursor: not-allowed;
      background-color: #f5f5f5;
      color: #c0c4cc;

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

.dialog-content {
  .permission-tabs {
    :deep(.el-tabs__nav-scroll) {
      padding: 0 20px;
    }

    .tab-content {
      padding: 20px;

      .permission-mode {
        margin-bottom: 24px;

        .mode-option {
          display: block;
          margin-bottom: 16px;

          .radio-label {
            margin-left: 8px;

            .label-text {
              display: block;
              font-weight: 500;
              margin-bottom: 4px;

              &.success {
                color: #67c23a;
              }

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

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

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

          span {
            font-weight: 500;
            color: #303133;
          }
        }

        .values-tree {
          max-height: 300px;
          overflow: auto;
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          padding: 12px;
          background: #fafafa;

          .tree-node {
            font-size: 14px;
          }
        }
      }

      .all-permission-tip {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 40px;
        background: #f6ffed;
        border: 1px solid #b7eb8f;
        border-radius: 6px;
        color: #52c41a;
        font-weight: 500;
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}

// 响应式设计
@media (max-width: 768px) {
  .permission-summary {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;

    .summary-action {
      margin-left: 0;
      align-self: stretch;

      .el-button {
        width: 100%;
      }
    }
  }

  .dialog-content {
    .permission-tabs {
      :deep(.el-tabs__nav-scroll) {
        padding: 0 10px;
      }

      .tab-content {
        padding: 15px;
      }
    }
  }
}
</style>
