<template>
  <div class="app-container">
    <el-row :gutter="16">
      <!-- 左侧部门树 -->
      <el-col :span="5">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>部门结构</span>
              <el-button type="primary" size="small" @click="handleAddDept">新增部门</el-button>
            </div>
          </template>
          <el-tree
            ref="deptTreeRef"
            :data="deptTree"
            :props="{ label: 'name', children: 'children' }"
            node-key="id"
            highlight-current
            :default-expanded-keys="[0]"
            @node-click="handleDeptClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span v-if="data.id !== 0" class="tree-actions">
                  <el-button link type="primary" size="small" @click.stop="handleEditDept(data)">编辑</el-button>
                  <el-button link type="danger" size="small" @click.stop="handleDeleteDept(data)">删除</el-button>
                </span>
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧审批角色列表 -->
      <el-col :span="19">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>审批角色列表</span>
              <el-button type="primary" @click="handleAdd">新增角色</el-button>
            </div>
          </template>

          <el-form :inline="true" :model="queryParams" class="search-form">
            <el-form-item label="角色编码">
              <el-input v-model="queryParams.roleCode" placeholder="请输入角色编码" clearable />
            </el-form-item>
            <el-form-item label="角色名称">
              <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table v-loading="loading" :data="tableData" border>
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="roleCode" label="角色编码" />
            <el-table-column prop="roleName" label="角色名称" />
            <el-table-column prop="deptName" label="所属部门" />
            <el-table-column prop="roleScope" label="描述" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                  {{ row.status === 1 ? '正常' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column label="操作" width="220">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
                <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            class="pagination"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 角色弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="80px">
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="form.roleCode" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-tree-select
            v-model="form.deptId"
            :data="deptTreeForSelect"
            :props="{ label: 'name', value: 'id', children: 'children' }"
            check-strictly
            clearable
            placeholder="请选择所属部门"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.roleScope" type="textarea" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 部门弹窗 -->
    <el-dialog v-model="deptDialogVisible" :title="deptDialogTitle" width="500px">
      <el-form ref="deptFormRef" :model="deptForm" :rules="deptFormRules" label-width="100px">
        <el-form-item label="上级部门">
          <el-tree-select
            v-model="deptForm.parentId"
            :data="deptTreeForSelect"
            :props="{ label: 'name', value: 'id', children: 'children' }"
            check-strictly
            clearable
            placeholder="请选择上级部门"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="deptForm.name" />
        </el-form-item>
        <el-form-item label="部门编码">
          <el-input v-model="deptForm.deptCode" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="deptForm.sort" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="deptDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDeptForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, shallowRef, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { listRole, addRole, updateRole, deleteRole } from '@/api/system/role'
import { listDept, addDept, updateDept, deleteDept } from '@/api/system/dept'
import type { Role, Dept } from '@/types/system'

const loading = ref(false)
const tableData = ref<Role[]>([])
const total = ref(0)
const deptList = ref<Dept[]>([])
const selectedDeptId = ref<number | undefined>(undefined)

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roleCode: undefined as string | undefined,
  roleName: undefined as string | undefined,
  deptId: undefined as number | undefined
})

// 部门树（后端已返回嵌套结构，直接使用）
const deptTree = computed(() => {
  const list = deptList.value
  // 如果有多个顶级部门，统一挂在虚拟根节点"总公司"下
  if (list.length > 1) {
    return [{ id: 0, parentId: 0, name: '总公司', children: list, sort: 0, status: 1 }]
  }
  return list
})

const deptTreeForSelect = shallowRef<Dept[]>([])

// 角色弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const form = reactive<Partial<Role>>({
  id: undefined,
  roleCode: '',
  roleName: '',
  roleScope: '',
  deptId: undefined,
  status: 1
})

const formRules: FormRules = {
  roleCode: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  phone: [{
    pattern: /^1[3-9]\d{9}$/,
    message: '请输入正确的手机号',
    trigger: 'blur'
  }]
}

const deptDialogVisible = ref(false)
const deptDialogTitle = ref('')
const isEditDept = ref(false)
const deptFormRef = ref<FormInstance>()
const deptForm = reactive<Partial<Dept>>({
  id: undefined,
  parentId: 0,
  name: '',
  deptCode: '',
  sort: 0,
  status: 1
})

const deptFormRules: FormRules = {
  name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }]
}

async function loadDepts() {
  try {
    const res = await listDept()
    deptList.value = res
    deptTreeForSelect.value = [{ id: 0, parentId: 0, name: '根部门', sort: 0, status: 1 }, ...res]
  } catch (error: any) {
    ElMessage.error(error?.message || '加载部门失败')
  }
}

async function loadData() {
  loading.value = true
  try {
    const params = { ...queryParams }
    if (selectedDeptId.value) {
      params.deptId = selectedDeptId.value
    }
    const res = await listRole(params)
    tableData.value = res.list
    total.value = res.total
  } finally {
    loading.value = false
  }
}

function handleQuery() {
  queryParams.pageNum = 1
  loadData()
}

function handlePageChange() {
  loadData()
}

function handleSizeChange() {
  queryParams.pageNum = 1
  loadData()
}

function resetQuery() {
  queryParams.roleCode = undefined
  queryParams.roleName = undefined
  queryParams.pageNum = 1
  loadData()
}

function handleDeptClick(data: Dept) {
  selectedDeptId.value = data.id
  queryParams.pageNum = 1
  loadData()
}

function handleAdd() {
  isEdit.value = false
  dialogTitle.value = '新增角色'
  Object.assign(form, {
    id: undefined,
    roleCode: '',
    roleName: '',
    roleScope: '',
    deptId: selectedDeptId.value,
    status: 1
  })
  dialogVisible.value = true
}

function handleEdit(row: Role) {
  isEdit.value = true
  dialogTitle.value = '编辑角色'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

async function handleDelete(row: Role) {
  try {
    await ElMessageBox.confirm(`确认删除角色 "${row.roleName}" 吗？`, '提示', { type: 'warning' })
    await deleteRole(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch {
    // cancel
  }
}

async function submitForm() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return
  if (isEdit.value) {
    await updateRole(form)
    ElMessage.success('修改成功')
  } else {
    await addRole(form)
    ElMessage.success('新增成功')
  }
  dialogVisible.value = false
  loadData()
}

function handleEditDept(data: Dept) {
  isEditDept.value = true
  deptDialogTitle.value = '编辑部门'
  Object.assign(deptForm, {
    id: data.id,
    parentId: data.parentId ?? 0,
    name: data.name,
    deptCode: data.deptCode,
    sort: data.sort,
    status: data.status
  })
  deptDialogVisible.value = true
}

async function handleDeleteDept(data: Dept) {
  try {
    await ElMessageBox.confirm(`确认删除部门 "${data.name}" 吗？`, '提示', { type: 'warning' })
    await deleteDept(data.id)
    ElMessage.success('删除成功')
    loadDepts()
  } catch {
    // cancel
  }
}

// 部门管理
function handleAddDept() {
  isEditDept.value = false
  deptDialogTitle.value = '新增部门'
  Object.assign(deptForm, {
    id: undefined, parentId: 0, name: '', deptCode: '', sort: 0, status: 1
  })
  deptDialogVisible.value = true
}

async function submitDeptForm() {
  const valid = await deptFormRef.value?.validate().catch(() => false)
  if (!valid) return
  if (isEditDept.value) {
    await updateDept(deptForm)
    ElMessage.success('修改成功')
  } else {
    await addDept(deptForm)
    ElMessage.success('新增成功')
  }
  deptDialogVisible.value = false
  loadDepts()
}

onMounted(() => {
  Promise.all([loadDepts(), loadData()])
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-form {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.tree-actions {
  display: none;
}
.custom-tree-node:hover .tree-actions {
  display: inline;
}
.text-gray {
  color: #909399;
}
</style>
