<template>
  <div class="permission-management">
    <!-- 权限树和表格布局 -->
    <a-row :gutter="16">
      <!-- 左侧权限树 -->
      <a-col :span="8">
        <a-card title="权限树" size="small">
          <template #extra>
            <a-button type="primary" size="small" @click="refreshPermissionTree">
              刷新
            </a-button>
          </template>
          <a-tree
            v-model:selectedKeys="selectedTreeKeys"
            :tree-data="permissionTree"
            :field-names="{ children: 'children', title: 'name', key: 'id' }"
            @select="onTreeSelect"
            show-line
          >
            <template #title="{ name, type }">
              <span>
                <a-tag :color="type === 'menu' ? 'blue' : 'green'" size="small">
                  {{ type === 'menu' ? '菜单' : '操作' }}
                </a-tag>
                {{ name }}
              </span>
            </template>
          </a-tree>
        </a-card>
      </a-col>

      <!-- 右侧权限列表 -->
      <a-col :span="16">
        <a-card title="权限管理" size="small">
          <template #extra>
            <a-space>
              <a-button type="primary" @click="showAddModal">
                <template #icon><PlusOutlined /></template>
                新增权限
              </a-button>
              <a-button @click="refreshPermissionList">
                <template #icon><ReloadOutlined /></template>
                刷新
              </a-button>
            </a-space>
          </template>

          <!-- 搜索表单 -->
          <a-form layout="inline" style="margin-bottom: 16px">
            <a-form-item label="权限名称">
              <a-input
                v-model:value="searchForm.name"
                placeholder="请输入权限名称"
                style="width: 150px"
                @pressEnter="searchPermissions"
              />
            </a-form-item>
            <a-form-item label="权限代码">
              <a-input
                v-model:value="searchForm.code"
                placeholder="请输入权限代码"
                style="width: 150px"
                @pressEnter="searchPermissions"
              />
            </a-form-item>
            <a-form-item label="模块">
              <a-select
                v-model:value="searchForm.module"
                placeholder="请选择模块"
                style="width: 120px"
                allowClear
              >
                <a-select-option value="user">用户管理</a-select-option>
                <a-select-option value="insurance">保险管理</a-select-option>
                <a-select-option value="application">申请管理</a-select-option>
                <a-select-option value="policy">保单管理</a-select-option>
                <a-select-option value="claim">理赔管理</a-select-option>
                <a-select-option value="system">系统管理</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="类型">
              <a-select
                v-model:value="searchForm.type"
                placeholder="请选择类型"
                style="width: 100px"
                allowClear
              >
                <a-select-option value="menu">菜单</a-select-option>
                <a-select-option value="operation">操作</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchPermissions" :loading="loading">
                搜索
              </a-button>
              <a-button style="margin-left: 8px" @click="resetSearch">
                重置
              </a-button>
            </a-form-item>
          </a-form>

          <!-- 权限表格 -->
          <a-table
            :columns="columns"
            :data-source="permissionList"
            :loading="loading"
            :pagination="pagination"
            @change="handleTableChange"
            size="small"
            :scroll="{ x: 1000 }"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'type'">
                <a-tag :color="record.type === 'menu' ? 'blue' : 'green'">
                  {{ record.type === 'menu' ? '菜单' : '操作' }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'status'">
                <a-tag :color="record.status === 'active' ? 'green' : 'red'">
                  {{ record.status === 'active' ? '启用' : '禁用' }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'action'">
                <a-space>
                  <a-button type="link" size="small" @click="editPermission(record)">
                    编辑
                  </a-button>
                  <a-popconfirm
                    title="确定要删除这个权限吗？"
                    @confirm="deletePermission(record.id)"
                  >
                    <a-button type="link" size="small" danger>
                      删除
                    </a-button>
                  </a-popconfirm>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>

    <!-- 新增/编辑权限模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑权限' : '新增权限'"
      width="600px"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :confirm-loading="submitLoading"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="权限名称" name="name">
          <a-input v-model:value="formData.name" placeholder="请输入权限名称" />
        </a-form-item>
        <a-form-item label="权限代码" name="code">
          <a-input v-model:value="formData.code" placeholder="请输入权限代码，如：user:create" />
        </a-form-item>
        <a-form-item label="权限描述" name="description">
          <a-textarea v-model:value="formData.description" placeholder="请输入权限描述" :rows="3" />
        </a-form-item>
        <a-form-item label="所属模块" name="module">
          <a-select v-model:value="formData.module" placeholder="请选择所属模块">
            <a-select-option value="user">用户管理</a-select-option>
            <a-select-option value="insurance">保险管理</a-select-option>
            <a-select-option value="application">申请管理</a-select-option>
            <a-select-option value="policy">保单管理</a-select-option>
            <a-select-option value="claim">理赔管理</a-select-option>
            <a-select-option value="system">系统管理</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="权限类型" name="type">
          <a-select v-model:value="formData.type" placeholder="请选择权限类型">
            <a-select-option value="menu">菜单</a-select-option>
            <a-select-option value="operation">操作</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="父级权限" name="parent_id">
          <a-tree-select
            v-model:value="formData.parent_id"
            :tree-data="parentPermissionOptions"
            :field-names="{ children: 'children', label: 'name', value: 'id' }"
            placeholder="请选择父级权限（可选）"
            allowClear
            tree-default-expand-all
          />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="formData.status" placeholder="请选择状态">
            <a-select-option value="active">启用</a-select-option>
            <a-select-option value="inactive">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="排序" name="sort_order">
          <a-input-number v-model:value="formData.sort_order" :min="0" placeholder="请输入排序值" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import { permissionAPI } from '@/utils/api'

// 数据定义
const loading = ref(false)
const submitLoading = ref(false)
const permissionList = ref([])
const permissionTree = ref([])
const selectedTreeKeys = ref([])

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  module: '',
  type: ''
})

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 60
  },
  {
    title: '权限名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '权限代码',
    dataIndex: 'code',
    key: 'code',
    width: 150
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '模块',
    dataIndex: 'module',
    key: 'module',
    width: 100
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    width: 80
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80
  },
  {
    title: '排序',
    dataIndex: 'sort_order',
    key: 'sort_order',
    width: 80
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right'
  }
]

// 模态框相关
const modalVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()
const formData = reactive({
  name: '',
  code: '',
  description: '',
  module: '',
  type: '',
  parent_id: null,
  status: 'active',
  sort_order: 0
})

const parentPermissionOptions = ref([])

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限代码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9:_-]+$/, message: '权限代码只能包含字母、数字、冒号、下划线和横线', trigger: 'blur' }
  ],
  module: [
    { required: true, message: '请选择所属模块', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 方法定义
const loadPermissions = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    const response = await permissionAPI.getList(params)
    const responseData = response.data || response
    
    permissionList.value = (responseData.permissions || []).map(permission => ({
      ...permission,
      key: permission.id
    }))
    
    pagination.total = responseData.total || 0
  } catch (error) {
    console.error('加载权限列表失败:', error)
    message.error('加载权限列表失败')
  } finally {
    loading.value = false
  }
}

const loadPermissionTree = async () => {
  try {
    const response = await permissionAPI.getTree()
    const responseData = response.data || response
    permissionTree.value = responseData.tree || []
    
    // 同时更新父级权限选项
    parentPermissionOptions.value = buildParentOptions(permissionTree.value)
  } catch (error) {
    console.error('加载权限树失败:', error)
    message.error('加载权限树失败')
  }
}

const buildParentOptions = (tree) => {
  const options = []
  const traverse = (nodes) => {
    nodes.forEach(node => {
      options.push({
        id: node.id,
        name: node.name,
        children: node.children ? buildParentOptions(node.children) : []
      })
      if (node.children && node.children.length > 0) {
        traverse(node.children)
      }
    })
  }
  traverse(tree)
  return options
}

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

const resetSearch = () => {
  Object.assign(searchForm, {
    name: '',
    code: '',
    module: '',
    type: ''
  })
  pagination.current = 1
  loadPermissions()
}

const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadPermissions()
}

const refreshPermissionList = () => {
  loadPermissions()
}

const refreshPermissionTree = () => {
  loadPermissionTree()
}

const onTreeSelect = (selectedKeys, info) => {
  console.log('选中的权限:', info.selectedNodes)
}

const showAddModal = () => {
  isEdit.value = false
  modalVisible.value = true
  resetForm()
}

const editPermission = (record) => {
  isEdit.value = true
  modalVisible.value = true
  Object.assign(formData, {
    id: record.id,
    name: record.name,
    code: record.code,
    description: record.description,
    module: record.module,
    type: record.type,
    parent_id: record.parent_id,
    status: record.status,
    sort_order: record.sort_order
  })
}

const resetForm = () => {
  Object.assign(formData, {
    name: '',
    code: '',
    description: '',
    module: '',
    type: '',
    parent_id: null,
    status: 'active',
    sort_order: 0
  })
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value) {
      await permissionAPI.update(formData.id, formData)
      message.success('更新权限成功')
    } else {
      await permissionAPI.create(formData)
      message.success('创建权限成功')
    }
    
    modalVisible.value = false
    loadPermissions()
    loadPermissionTree()
  } catch (error) {
    console.error('提交失败:', error)
    message.error(isEdit.value ? '更新权限失败' : '创建权限失败')
  } finally {
    submitLoading.value = false
  }
}

const handleCancel = () => {
  modalVisible.value = false
  resetForm()
}

const deletePermission = async (id) => {
  try {
    await permissionAPI.delete(id)
    message.success('删除权限成功')
    loadPermissions()
    loadPermissionTree()
  } catch (error) {
    console.error('删除权限失败:', error)
    message.error('删除权限失败')
  }
}

// 初始化
onMounted(() => {
  loadPermissions()
  loadPermissionTree()
})
</script>

<style scoped>
.permission-management {
  height: 100%;
}

.ant-card {
  height: 100%;
}

.ant-tree {
  max-height: 500px;
  overflow-y: auto;
}
</style>