<template>
  <div class="role-permission-management">
    <!-- 角色权限分配区域 -->
    <a-card title="角色权限管理" style="margin-bottom: 16px">
      <template #extra>
        <a-space>
          <a-button type="primary" @click="handleRefresh">
            刷新数据
          </a-button>
          <a-button @click="handleCopyPermissions">
            复制权限
          </a-button>
        </a-space>
      </template>

      <!-- 角色选择和权限统计 -->
      <a-row :gutter="16" style="margin-bottom: 16px">
        <a-col :span="8">
          <a-card size="small" title="选择角色">
            <a-select
              v-model:value="selectedRoleId"
              placeholder="请选择角色"
              style="width: 100%"
              @change="handleRoleChange"
            >
              <a-select-option
                v-for="role in roles"
                :key="role.id"
                :value="role.id"
              >
                {{ role.name }} ({{ role.description }})
              </a-select-option>
            </a-select>
          </a-card>
        </a-col>
        <a-col :span="16">
          <a-row :gutter="8">
            <a-col :span="6">
              <a-card size="small">
                <a-statistic
                  title="总权限数"
                  :value="permissionStats.total"
                  :value-style="{ color: '#1890ff' }"
                />
              </a-card>
            </a-col>
            <a-col :span="6">
              <a-card size="small">
                <a-statistic
                  title="已分配"
                  :value="permissionStats.assigned"
                  :value-style="{ color: '#52c41a' }"
                />
              </a-card>
            </a-col>
            <a-col :span="6">
              <a-card size="small">
                <a-statistic
                  title="未分配"
                  :value="permissionStats.unassigned"
                  :value-style="{ color: '#faad14' }"
                />
              </a-card>
            </a-col>
            <a-col :span="6">
              <a-card size="small">
                <a-statistic
                  title="分配率"
                  :value="permissionStats.percentage"
                  suffix="%"
                  :value-style="{ color: '#722ed1' }"
                />
              </a-card>
            </a-col>
          </a-row>
        </a-col>
      </a-row>

      <!-- 权限树形结构 -->
      <div v-if="selectedRoleId">
        <a-divider>权限分配</a-divider>
        
        <!-- 批量操作按钮 -->
        <div style="margin-bottom: 16px">
          <a-space>
            <a-button @click="handleSelectAll">全选</a-button>
            <a-button @click="handleSelectNone">全不选</a-button>
            <a-button @click="handleSelectByModule">按模块选择</a-button>
            <a-button type="primary" @click="handleSavePermissions" :loading="saveLoading">
              保存权限设置
            </a-button>
          </a-space>
        </div>

        <!-- 按模块分组的权限列表 -->
        <a-collapse v-model:activeKey="activeModules" ghost>
          <a-collapse-panel
            v-for="module in permissionModules"
            :key="module.module"
            :header="`${module.module} (${module.permissions.length}个权限)`"
          >
            <template #extra>
              <a-checkbox
                :checked="isModuleAllSelected(module.module)"
                :indeterminate="isModuleIndeterminate(module.module)"
                @change="(e) => handleModuleCheckChange(e, module.module)"
                @click.stop
              >
                全选
              </a-checkbox>
            </template>
            
            <a-row :gutter="[16, 8]">
              <a-col
                v-for="permission in module.permissions"
                :key="permission.id"
                :span="8"
              >
                <a-checkbox
                  v-model:checked="selectedPermissions[permission.id]"
                  @change="handlePermissionChange"
                >
                  <a-tooltip :title="permission.description">
                    <span>{{ permission.name }}</span>
                    <a-tag
                      :color="getPermissionTypeColor(permission.type)"
                      size="small"
                      style="margin-left: 4px"
                    >
                      {{ permission.type }}
                    </a-tag>
                  </a-tooltip>
                </a-checkbox>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </div>

      <!-- 未选择角色时的提示 -->
      <div v-else class="empty-state">
        <a-empty description="请先选择一个角色来管理权限" />
      </div>
    </a-card>

    <!-- 权限复制模态框 -->
    <a-modal
      v-model:open="copyModalVisible"
      title="复制权限"
      @ok="handleConfirmCopy"
      @cancel="copyModalVisible = false"
    >
      <a-form layout="vertical">
        <a-form-item label="源角色">
          <a-select
            v-model:value="copyForm.sourceRoleId"
            placeholder="请选择源角色"
            style="width: 100%"
          >
            <a-select-option
              v-for="role in roles"
              :key="role.id"
              :value="role.id"
            >
              {{ role.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="目标角色">
          <a-select
            v-model:value="copyForm.targetRoleId"
            placeholder="请选择目标角色"
            style="width: 100%"
          >
            <a-select-option
              v-for="role in roles"
              :key="role.id"
              :value="role.id"
            >
              {{ role.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="复制方式">
          <a-radio-group v-model:value="copyForm.mode">
            <a-radio value="replace">替换（清空目标角色权限后复制）</a-radio>
            <a-radio value="merge">合并（保留目标角色原有权限）</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 按模块选择模态框 -->
    <a-modal
      v-model:open="moduleSelectModalVisible"
      title="按模块选择权限"
      @ok="handleConfirmModuleSelect"
      @cancel="moduleSelectModalVisible = false"
    >
      <a-checkbox-group v-model:value="selectedModules" style="width: 100%">
        <a-row>
          <a-col
            v-for="module in permissionModules"
            :key="module.module"
            :span="12"
            style="margin-bottom: 8px"
          >
            <a-checkbox :value="module.module">
              {{ module.module }} ({{ module.permissions.length }}个)
            </a-checkbox>
          </a-col>
        </a-row>
      </a-checkbox-group>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import { rolePermissionAPI } from '@/utils/api'

// 响应式数据
const loading = ref(false)
const saveLoading = ref(false)
const roles = ref([])
const permissions = ref([])
const selectedRoleId = ref(null)
const selectedPermissions = reactive({})
const activeModules = ref([])

// 模态框状态
const copyModalVisible = ref(false)
const moduleSelectModalVisible = ref(false)
const selectedModules = ref([])

// 复制表单
const copyForm = reactive({
  sourceRoleId: null,
  targetRoleId: null,
  mode: 'replace'
})

// 计算属性 - 权限模块分组
const permissionModules = computed(() => {
  const modules = {}
  permissions.value.forEach(permission => {
    if (!modules[permission.module]) {
      modules[permission.module] = {
        module: permission.module,
        permissions: []
      }
    }
    modules[permission.module].permissions.push(permission)
  })
  return Object.values(modules)
})

// 计算属性 - 权限统计
const permissionStats = computed(() => {
  const total = permissions.value.length
  const assigned = Object.values(selectedPermissions).filter(Boolean).length
  const unassigned = total - assigned
  const percentage = total > 0 ? Math.round((assigned / total) * 100) : 0

  return {
    total,
    assigned,
    unassigned,
    percentage
  }
})

// 获取权限类型颜色
const getPermissionTypeColor = (type) => {
  const colorMap = {
    'view': 'blue',
    'create': 'green',
    'update': 'orange',
    'delete': 'red',
    'manage': 'purple',
    'admin': 'magenta'
  }
  return colorMap[type] || 'default'
}

// 检查模块是否全选
const isModuleAllSelected = (module) => {
  const modulePermissions = permissionModules.value.find(m => m.module === module)?.permissions || []
  return modulePermissions.length > 0 && modulePermissions.every(p => selectedPermissions[p.id])
}

// 检查模块是否部分选择
const isModuleIndeterminate = (module) => {
  const modulePermissions = permissionModules.value.find(m => m.module === module)?.permissions || []
  const selectedCount = modulePermissions.filter(p => selectedPermissions[p.id]).length
  return selectedCount > 0 && selectedCount < modulePermissions.length
}

// 获取所有角色和权限数据
const loadData = async () => {
  try {
    loading.value = true
    const [rolesResponse, permissionsResponse] = await Promise.all([
      rolePermissionAPI.getAllRolesWithPermissions(),
      rolePermissionAPI.getAllPermissions()
    ])

    // 处理角色数据
    if (rolesResponse.data && rolesResponse.data.status === 'success') {
      roles.value = rolesResponse.data.data.roles || []
      console.log('加载角色数据成功:', roles.value.length, '个角色')
    } else {
      console.error('角色数据响应格式错误:', rolesResponse)
      message.error('加载角色数据失败: 响应格式错误')
    }

    // 处理权限数据
    if (permissionsResponse.data && permissionsResponse.data.status === 'success') {
      permissions.value = permissionsResponse.data.data || []
      console.log('加载权限数据成功:', permissions.value.length, '个权限')
    } else {
      console.error('权限数据响应格式错误:', permissionsResponse)
      message.error('加载权限数据失败: 响应格式错误')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    message.error('加载数据失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 角色变化处理
const handleRoleChange = async (roleId) => {
  if (!roleId) return

  console.log('=== 角色变化处理开始 ===');
  console.log('选择的角色ID:', roleId);

  try {
    const response = await rolePermissionAPI.getRolePermissions(roleId)
    console.log('获取角色权限API响应:', JSON.stringify(response, null, 2));
    
    if (response.data && response.data.status === 'success') {
      // 清空之前的选择
      console.log('清空前的权限状态:', JSON.stringify(selectedPermissions, null, 2));
      Object.keys(selectedPermissions).forEach(key => {
        selectedPermissions[key] = false
      })
      console.log('清空后的权限状态:', JSON.stringify(selectedPermissions, null, 2));

      // 设置当前角色的权限
      if (response.data.data && response.data.data.allPermissions) {
        const assignedPermissions = response.data.data.allPermissions.filter(p => p.assigned);
        console.log('角色已分配的权限:', assignedPermissions.length, '个');
        console.log('已分配权限详情:', assignedPermissions.map(p => ({ id: p.id, name: p.name, code: p.code })));
        
        assignedPermissions.forEach(permission => {
          selectedPermissions[permission.id] = true
        })
        
        console.log('设置权限后的状态:', JSON.stringify(selectedPermissions, null, 2));
      }

      // 展开所有模块
      activeModules.value = permissionModules.value.map(m => m.module)
      console.log('展开的模块:', activeModules.value);
    } else {
      console.error('获取角色权限详情失败:', response)
      message.error('获取角色权限详情失败')
    }
  } catch (error) {
    console.error('获取角色权限失败:', error)
    message.error('获取角色权限失败')
  }
  
  console.log('=== 角色变化处理结束 ===');
}

// 权限变化处理
const handlePermissionChange = () => {
  // 这里可以添加实时保存逻辑，或者只在点击保存时处理
}

// 模块复选框变化处理
const handleModuleCheckChange = (e, module) => {
  const checked = e.target.checked
  const modulePermissions = permissionModules.value.find(m => m.module === module)?.permissions || []
  
  modulePermissions.forEach(permission => {
    selectedPermissions[permission.id] = checked
  })
}

// 全选处理
const handleSelectAll = () => {
  console.log('=== 全选操作开始 ===');
  console.log('全选前的权限状态:', JSON.stringify(selectedPermissions, null, 2));
  console.log('当前权限列表长度:', permissions.value.length);
  
  permissions.value.forEach(permission => {
    selectedPermissions[permission.id] = true
  })
  
  console.log('全选后的权限状态:', JSON.stringify(selectedPermissions, null, 2));
  console.log('全选操作完成，选中权限数量:', Object.values(selectedPermissions).filter(Boolean).length);
  console.log('=== 全选操作结束 ===');
}

// 全不选处理
const handleSelectNone = () => {
  permissions.value.forEach(permission => {
    selectedPermissions[permission.id] = false
  })
}

// 按模块选择处理
const handleSelectByModule = () => {
  selectedModules.value = []
  moduleSelectModalVisible.value = true
}

// 确认按模块选择
const handleConfirmModuleSelect = () => {
  // 先清空所有选择
  handleSelectNone()
  
  // 选择指定模块的权限
  selectedModules.value.forEach(module => {
    const modulePermissions = permissionModules.value.find(m => m.module === module)?.permissions || []
    modulePermissions.forEach(permission => {
      selectedPermissions[permission.id] = true
    })
  })
  
  moduleSelectModalVisible.value = false
}

// 保存权限设置
const handleSavePermissions = async () => {
  if (!selectedRoleId.value) {
    message.warning('请先选择角色')
    return
  }

  console.log('=== 保存权限设置开始 ===');
  console.log('当前选择的角色ID:', selectedRoleId.value);
  console.log('保存前的权限状态:', JSON.stringify(selectedPermissions, null, 2));
  
  saveLoading.value = true
  try {
    const permissionIds = Object.keys(selectedPermissions)
      .filter(id => selectedPermissions[id])
      .map(id => parseInt(id))

    console.log('准备保存的权限ID列表:', permissionIds);
    console.log('权限ID数量:', permissionIds.length);

    const requestData = {
      permissionIds,
      mode: 'replace'
    };
    console.log('发送的请求数据:', JSON.stringify(requestData, null, 2));

    const response = await rolePermissionAPI.assignRolePermissions(selectedRoleId.value, requestData)
    
    console.log('保存权限API响应:', JSON.stringify(response, null, 2));

    if (response.data && response.data.status === 'success') {
      message.success('权限设置保存成功')
      console.log('✅ 权限保存成功');
    } else {
      console.error('❌ 保存权限设置失败:', response)
      message.error('保存权限设置失败')
    }
  } catch (error) {
    console.error('❌ 保存权限设置异常:', error)
    console.error('错误详情:', error.response?.data || error.message)
    message.error('保存权限设置失败')
  } finally {
    saveLoading.value = false
    console.log('=== 保存权限设置结束 ===');
  }
}

// 复制权限处理
const handleCopyPermissions = () => {
  copyForm.sourceRoleId = null
  copyForm.targetRoleId = null
  copyForm.mode = 'replace'
  copyModalVisible.value = true
}

// 确认复制权限
const handleConfirmCopy = async () => {
  if (!copyForm.sourceRoleId || !copyForm.targetRoleId) {
    message.warning('请选择源角色和目标角色')
    return
  }

  if (copyForm.sourceRoleId === copyForm.targetRoleId) {
    message.warning('源角色和目标角色不能相同')
    return
  }

  try {
    const response = await rolePermissionAPI.copyRolePermissions({
      sourceRoleId: copyForm.sourceRoleId,
      targetRoleId: copyForm.targetRoleId,
      mode: copyForm.mode
    })

    if (response.data && response.data.status === 'success') {
      message.success('权限复制成功')
      copyModalVisible.value = false
      
      // 如果当前选择的是目标角色，刷新权限显示
      if (selectedRoleId.value === copyForm.targetRoleId) {
        handleRoleChange(selectedRoleId.value)
      }
    } else {
      console.error('复制权限失败:', response)
      message.error('复制权限失败')
    }
  } catch (error) {
    console.error('复制权限失败:', error)
    message.error('复制权限失败')
  }
}

// 刷新数据
const handleRefresh = () => {
  loadData()
  if (selectedRoleId.value) {
    handleRoleChange(selectedRoleId.value)
  }
}

// 监听权限数据变化，初始化选择状态
watch(permissions, (newPermissions) => {
  newPermissions.forEach(permission => {
    if (!(permission.id in selectedPermissions)) {
      selectedPermissions[permission.id] = false
    }
  })
}, { immediate: true })

// 组件挂载时获取数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.role-permission-management {
  padding: 0;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.ant-statistic-content {
  font-size: 16px;
  font-weight: bold;
}

.ant-collapse-header {
  font-weight: 500;
}

.ant-checkbox-wrapper {
  margin-bottom: 8px;
}

.ant-tag {
  margin-left: 4px;
}
</style>