<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { roleApi, permissionApi } from '@/api/system.js'

// ─── List state ───────────────────────────────────────────────────────────────

const tableData = ref([])
const total = ref(0)
const loading = ref(false)

const searchForm = reactive({ keyword: '' })
const pagination = reactive({ page: 1, page_size: 20 })

// ─── Role form ────────────────────────────────────────────────────────────────

const dialogVisible = ref(false)
const dialogTitle = ref('新增角色')
const submitLoading = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const form = reactive({
  id: null,
  name: '',
  code: '',
  description: '',
  status: 1
})

const formRules = {
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
}

function genCode() {
  return 'role_' + Date.now().toString(36)
}

// ─── Permission assignment ────────────────────────────────────────────────────

const permDialogVisible = ref(false)
const permLoading = ref(false)
const permTreeRef = ref(null)
const permTree = ref([])
const currentRoleId = ref(null)
const currentRoleName = ref('')
const checkedPermIds = ref([])

const treeProps = {
  label: 'name',
  children: 'children'
}

// ─── Fetch ─────────────────────────────────────────────────────────────────────

async function fetchList() {
  loading.value = true
  try {
    const res = await roleApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || []
    total.value = res.data?.total || 0
  } catch {
    //
  } finally {
    loading.value = false
  }
}

async function fetchPermTree() {
  try {
    const res = await permissionApi.getList({ page_size: 500 })
    // API returns already-tree-structured array in res.data
    const data = res.data
    if (Array.isArray(data)) {
      permTree.value = data
    } else {
      const flat = data?.list || data?.data || []
      permTree.value = buildPermTree(flat)
    }
  } catch {
    //
  }
}

function buildPermTree(nodes, parentId = 0) {
  return nodes
    .filter(n => (n.parent_id ?? 0) === parentId)
    .map(n => ({ ...n, children: buildPermTree(nodes, n.id) }))
}

// ─── Handlers ─────────────────────────────────────────────────────────────────

function handleSearch() {
  pagination.page = 1
  fetchList()
}

function handleReset() {
  searchForm.keyword = ''
  handleSearch()
}

function handleAdd() {
  isEdit.value = false
  dialogTitle.value = '新增角色'
  Object.assign(form, { id: null, name: '', code: genCode(), description: '', status: 1 })
  dialogVisible.value = true
}

async function handleEdit(row) {
  isEdit.value = true
  dialogTitle.value = '编辑角色'
  const res = await roleApi.getDetail(row.id)
  const role = res.data
  Object.assign(form, {
    id: role.id,
    name: role.name,
    code: role.code,
    description: role.description || '',
    status: role.status
  })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) {
        await roleApi.update(form.id, form)
        ElMessage.success('角色更新成功')
      } else {
        await roleApi.create(form)
        ElMessage.success('角色创建成功')
      }
      dialogVisible.value = false
      fetchList()
    } catch {
      //
    } finally {
      submitLoading.value = false
    }
  })
}

async function handleDelete(row) {
  await ElMessageBox.confirm(`确定删除角色「${row.name}」吗？`, '删除确认', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    type: 'warning',
    confirmButtonClass: 'el-button--danger'
  })
  await roleApi.delete(row.id)
  ElMessage.success('删除成功')
  fetchList()
}

async function openPermDialog(row) {
  currentRoleId.value = row.id
  currentRoleName.value = row.name
  permDialogVisible.value = true
  permLoading.value = true

  try {
    // Ensure perm tree is loaded
    if (permTree.value.length === 0) {
      await fetchPermTree()
    }
    // Load role's existing permissions via getDetail
    const res = await roleApi.getDetail(row.id)
    checkedPermIds.value = (res.data?.permissions || []).map((p) => p.id)

    await nextTick()
    if (permTreeRef.value) {
      permTreeRef.value.setCheckedKeys(checkedPermIds.value, true)
    }
  } catch {
    //
  } finally {
    permLoading.value = false
  }
}

async function handleSavePerms() {
  if (!permTreeRef.value) return
  const checked = permTreeRef.value.getCheckedKeys(false)
  const halfChecked = permTreeRef.value.getHalfCheckedKeys()
  const allIds = [...checked, ...halfChecked]
  try {
    await roleApi.assignPermissions(currentRoleId.value, allIds)
    ElMessage.success('权限分配成功')
    permDialogVisible.value = false
  } catch {
    //
  }
}

function handlePageChange(val) {
  pagination.page = val
  fetchList()
}

function handleSizeChange(val) {
  pagination.page_size = val
  pagination.page = 1
  fetchList()
}

onMounted(() => {
  fetchList()
  fetchPermTree()
})
</script>

<template>
  <div class="p-6 space-y-4">
    <!-- Search -->
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-input
        v-model="searchForm.keyword"
        placeholder="搜索角色名称/标识"
        style="width: 240px"
        clearable
        @keydown.enter="handleSearch"
      >
        <template #prefix><el-icon><Search /></el-icon></template>
      </el-input>
      <el-button type="primary" :icon="'Search'" @click="handleSearch">查询</el-button>
      <el-button :icon="'Refresh'" @click="handleReset">重置</el-button>
    </div>

    <!-- Table -->
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-3"></div>
        <el-button type="primary" :icon="'Plus'" @click="handleAdd">新增角色</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width: 100%">
          <el-table-column prop="name" label="角色名称" min-width="140" />
          <el-table-column prop="code" label="角色标识" min-width="140" />
          <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
          <el-table-column prop="user_count" label="用户数" width="90" align="center" />
          <el-table-column label="状态" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" min-width="160" />
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="warning" text @click="openPermDialog(row)">分配权限</el-button>
              <el-button size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.page_size"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- Role Add/Edit Dialog -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="480px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item v-if="isEdit" label="角色标识">
          <el-input v-model="form.code" disabled />
          <div class="form-tip">角色标识由系统自动生成，不可修改</div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述（选填）"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          {{ isEdit ? '保存修改' : '确认创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- Permission Assignment Dialog -->
    <el-dialog
      v-model="permDialogVisible"
      :title="`分配权限 - ${currentRoleName}`"
      width="520px"
      destroy-on-close
    >
      <div v-loading="permLoading" style="min-height: 200px; max-height: 480px; overflow-y: auto">
        <el-tree
          ref="permTreeRef"
          :data="permTree"
          :props="treeProps"
          show-checkbox
          node-key="id"
          default-expand-all
          check-strictly
        />
        <el-empty v-if="!permLoading && permTree.length === 0" description="暂无权限数据" />
      </div>
      <template #footer>
        <el-button @click="permDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePerms">保存权限</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.form-tip {
  font-size: 12px;
  color: var(--color-text-secondary);
  margin-top: 4px;
  line-height: 1.4;
}
</style>
