<template>
  <div class="permission-management">
    <a-page-header
      title="权限管理"
      sub-title="管理系统用户权限"
    >
      <template #extra>
        <a-space>
          <a-button @click="handleRefresh">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新
          </a-button>
          <a-button 
            v-if="hasPermission('system:write')" 
            type="primary" 
            @click="showCreateModal"
          >
            <template #icon>
              <PlusOutlined />
            </template>
            新增权限
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <a-card>
      <!-- 搜索区域 -->
      <div class="search-container">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="关键词">
            <a-input
              v-model:value="searchForm.keyword"
              placeholder="权限名称/描述"
              allow-clear
            />
          </a-form-item>
          
          <a-form-item>
            <a-button type="primary" @click="handleSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button style="margin-left: 8px" @click="handleReset">
              重置
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 批量操作区域 -->
      <div class="batch-actions" style="margin-bottom: 16px;" v-if="hasPermission('system:write')">
        <a-space>
          <a-button 
            type="primary" 
            danger 
            :disabled="selectedRowKeys.length === 0"
            @click="handleBatchDelete"
          >
            <template #icon>
              <DeleteOutlined />
            </template>
            批量删除
          </a-button>
          <span>已选择 {{ selectedRowKeys.length }} 项</span>
        </a-space>
      </div>

      <!-- 权限表格 -->
      <a-table
        :columns="columns"
        :data-source="permissionList"
        :loading="loading"
        :pagination="pagination"
        :row-key="record => record.id"
        @change="handleTableChange"
        :row-selection="rowSelection"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'actions'">
            <a-space :size="8">
              <a-button 
                v-if="hasPermission('system:write')" 
                size="small" 
                @click="handleEdit(record)"
              >
                <EditOutlined />
                编辑
              </a-button>
              
              <a-button 
                v-if="hasPermission('system:write')" 
                size="small" 
                danger 
                @click="handleDelete(record)"
              >
                <DeleteOutlined />
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 创建/编辑权限模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="600px"
    >
      <a-form
        ref="permissionFormRef"
        :model="currentPermission"
        :rules="formRules"
        layout="vertical"
      >
        <a-form-item label="权限名称" name="name">
          <a-input v-model:value="currentPermission.name" placeholder="请输入权限名称" />
        </a-form-item>
        
        <a-form-item label="权限标识" name="code">
          <a-input v-model:value="currentPermission.code" placeholder="请输入权限标识，如 user:read" />
        </a-form-item>
        
        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="currentPermission.description"
            placeholder="请输入权限描述"
            :rows="3"
          />
        </a-form-item>
        
        <a-form-item label="资源类型" name="resourceType">
          <a-select v-model:value="currentPermission.resource_type" placeholder="请选择资源类型">
            <a-select-option value="user">用户</a-select-option>
            <a-select-option value="merchant">商家</a-select-option>
            <a-select-option value="travel">旅行</a-select-option>
            <a-select-option value="animal">动物</a-select-option>
            <a-select-option value="order">订单</a-select-option>
            <a-select-option value="promotion">推广</a-select-option>
            <a-select-option value="system">系统</a-select-option>
          </a-select>
        </a-form-item>

      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, Modal, type FormInstance } from 'ant-design-vue'
import type { TableProps } from 'ant-design-vue'
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import { useAppStore } from '@/stores/app'
import { 
  getPermissions, 
  createPermission, 
  updatePermission, 
  deletePermission,
  batchDeletePermissions
} from '@/api/permission'
import type { Permission } from '@/api/permission'

interface SearchForm {
  keyword: string
}

const appStore = useAppStore()

// 权限检查方法
const hasPermission = (permission: string) => {
  return appStore.hasPermission(permission)
}

const loading = ref(false)
const searchForm = reactive<SearchForm>({
  keyword: ''
})

const permissionList = ref<Permission[]>([])

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

const columns = [
  {
    title: '权限名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '权限标识',
    dataIndex: 'code',
    key: 'code',
    width: 150
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    width: 200
  },
  {
    title: '资源类型',
    dataIndex: 'resource_type',
    key: 'resource_type',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 120
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    align: 'center'
  }
]

// 添加模态框相关状态
const modalVisible = ref(false)
const modalLoading = ref(false)
const modalTitle = ref('新增权限')
const isEditing = ref(false)
const permissionFormRef = ref<FormInstance>()

// 当前权限数据
const currentPermission = ref<Partial<Permission>>({
  resource_type: 'user'  // 设置默认资源类型
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入权限名称' }
  ],
  code: [
    { required: true, message: '请输入权限标识' }
  ],
  resourceType: [
    { required: true, message: '请选择资源类型' }
  ]
}

// 生命周期
onMounted(() => {
  loadPermissions()
})

// 方法
const loadPermissions = async () => {
  loading.value = true
  try {
    const response = await getPermissions({
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword
    })
    
    if (response.success) {
      permissionList.value = response.data.permissions
      pagination.total = response.data.pagination.total
    } else {
      message.error('加载权限列表失败')
    }
  } catch (error) {
    message.error('加载权限列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadPermissions()
}

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: ''
  })
  pagination.current = 1
  loadPermissions()
}

const handleRefresh = () => {
  loadPermissions()
  message.success('数据已刷新')
}

const handleTableChange: TableProps['onChange'] = (pag) => {
  pagination.current = pag.current!
  pagination.pageSize = pag.pageSize!
  loadPermissions()
}

const handleEdit = (record: Permission) => {
  modalTitle.value = '编辑权限'
  isEditing.value = true
  currentPermission.value = { ...record }
  modalVisible.value = true
}

const showCreateModal = () => {
  modalTitle.value = '新增权限'
  isEditing.value = false
  currentPermission.value = {}
  modalVisible.value = true
}

const handleModalOk = () => {
  permissionFormRef.value
    ?.validate()
    .then(() => {
      if (isEditing.value) {
        handleUpdatePermission()
      } else {
        handleCreatePermission()
      }
    })
    .catch((error: any) => {
      console.error('表单验证失败:', error)
    })
}

const handleModalCancel = () => {
  modalVisible.value = false
  permissionFormRef.value?.resetFields()
}

const handleCreatePermission = async () => {
  try {
    modalLoading.value = true
    const response = await createPermission(currentPermission.value as any)
    
    if (response.success) {
      message.success('创建权限成功')
      modalVisible.value = false
      loadPermissions()
    } else {
      message.error('创建权限失败')
    }
  } catch (error) {
    message.error('创建权限失败')
  } finally {
    modalLoading.value = false
  }
}

const handleUpdatePermission = async () => {
  try {
    modalLoading.value = true
    if (currentPermission.value.id) {
      const response = await updatePermission(currentPermission.value.id, currentPermission.value as any)
      
      if (response.success) {
        message.success('更新权限成功')
        modalVisible.value = false
        loadPermissions()
      } else {
        message.error('更新权限失败')
      }
    }
  } catch (error) {
    message.error('更新权限失败')
  } finally {
    modalLoading.value = false
  }
}

const handleDelete = (record: Permission) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除权限 "${record.name}" 吗？`,
    okText: '确定',
    okType: 'danger',
    onOk: async () => {
      try {
        const response = await deletePermission(record.id)
        
        if (response.success) {
          message.success('权限已删除')
          loadPermissions()
        } else {
          message.error('删除失败')
        }
      } catch (error) {
        message.error('删除失败')
      }
    }
  })
}

// 批量操作相关状态
const selectedRowKeys = ref<number[]>([])
const rowSelection = {
  selectedRowKeys: selectedRowKeys.value,
  onChange: (selectedKeys: number[]) => {
    selectedRowKeys.value = selectedKeys
  }
}

const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请先选择要删除的权限')
    return
  }
  
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个权限吗？`,
    okText: '确定',
    okType: 'danger',
    onOk: async () => {
      try {
        const response = await batchDeletePermissions(selectedRowKeys.value)
        
        if (response.success) {
          message.success(response.data.message || '权限已删除')
          selectedRowKeys.value = []
          loadPermissions()
        } else {
          message.error('删除失败')
        }
      } catch (error) {
        message.error('删除失败')
      }
    }
  })
}
</script>

<style scoped lang="less">
.permission-management {
  .search-container {
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
    
    :deep(.ant-form-item) {
      margin-bottom: 16px;
    }
  }
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}
</style>