<template>
  <div class="form-page">
    <!-- 页面头部 -->
    <el-page-header @back="handleBack" :title="isEdit ? '编辑角色' : '新增角色'" />
    <el-divider />

    <!-- 表单卡片 -->
    <el-card class="form-card" shadow="never">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <!-- 基本信息 -->
        <el-divider content-position="left">
          <span class="form-section-title">基本信息</span>
        </el-divider>

        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="form.roleCode" placeholder="请输入角色编码" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="所属系统" prop="systemId">
          <el-select v-model="form.systemId" placeholder="请选择系统" style="width: 100%">
            <el-option
              v-for="sys in systemList"
              :key="sys.systemId"
              :label="sys.systemName"
              :value="sys.systemId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用" />
        </el-form-item>

        <!-- 其他信息 -->
        <el-divider content-position="left">
          <span class="form-section-title">其他信息</span>
        </el-divider>

        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </el-form-item>

        <!-- 按钮区域 -->
        <el-divider />
        <div class="form-footer">
          <el-button @click="handleBack">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import request from '@/utils/request'

interface SystemItem {
  id: string
  systemId: string
  systemName: string
}

const route = useRoute()
const router = useRouter()

const isEdit = ref(false)
const editId = ref<string>()
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

/** 系统列表（下拉用） */
const systemList = ref<SystemItem[]>([])

/** 表单数据 */
const form = reactive({
  roleName: '',
  roleCode: '',
  systemId: undefined as string | undefined,
  description: '',
  status: 1,
})

/** 校验规则 */
const rules: FormRules = {
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  roleCode: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
  systemId: [{ required: true, message: '请选择所属系统', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

/** 加载系统列表 */
async function fetchSystemList() {
  try {
    const res = await request.get('/zgapi/v1/auth/system/list')
    systemList.value = res.data ?? []
  } catch {
    systemList.value = []
  }
}

/** 加载已有数据（编辑模式） */
async function loadData() {
  const id = route.params.id as string
  if (!id) {
    isEdit.value = false
    return
  }
  isEdit.value = true
  editId.value = id
  try {
    const res = await request.get(`/zgapi/v1/admin/role/${editId.value}`)
    const data = res.data
    if (data) {
      Object.assign(form, {
        roleName: data.roleName ?? '',
        roleCode: data.roleCode ?? '',
        systemId: data.systemId,
        description: data.description ?? '',
        status: data.status ?? 1,
      })
      setTimeout(() => formRef.value?.clearValidate(), 0)
    }
  } catch {
    ElMessage.error('加载角色信息失败')
    router.back()
  }
}

function handleBack() {
  router.back()
}

async function handleSubmit() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return

  submitLoading.value = true
  try {
    if (isEdit.value) {
      await request.put(`/zgapi/v1/admin/role/${editId.value}`, form)
      ElMessage.success('编辑成功')
    } else {
      await request.post('/zgapi/v1/admin/role', form)
      ElMessage.success('新增成功')
    }
    router.back()
  } catch {
    // 错误由拦截器处理
  } finally {
    submitLoading.value = false
  }
}

onMounted(async () => {
  await fetchSystemList()
  await loadData()
  setTimeout(() => formRef.value?.clearValidate(), 0)
})
</script>

<style scoped>
.form-page {
  display: flex;
  flex-direction: column;
  gap: 0;
}

:deep(.el-page-header) {
  margin-bottom: 4px;
}

:deep(.el-page-header + .el-divider) {
  margin: 0 0 20px 0;
}

.form-card {
  max-width: 700px;
  margin: 0 auto;
  width: 100%;
}

.form-section-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .form-card { max-width: 100%; }
  .form-footer { flex-direction: column; }
  .form-footer .el-button { width: 100%; }
  :deep(.el-form-item__label) { width: 70px !important; }
}
</style>
