<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-wrapper">
      <el-form :model="queryParams" :inline="true">
        <el-form-item label="区域名称">
          <el-input v-model="queryParams.regionName" placeholder="请输入区域名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 100px">
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button type="info" :icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card shadow="never" style="margin-top: 12px">
      <el-row :gutter="10" style="margin-bottom: 12px">
        <el-col :span="1.5">
          <el-button type="primary" :icon="Plus" @click="handleAdd()" v-hasPermi="['business:region:add']">新增</el-button>
        </el-col>
      </el-row>

      <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="tableData"
        row-key="regionId"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        border
        stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column prop="regionName" label="区域名称" min-width="200" />
        <el-table-column prop="regionCode" label="区域编码" width="120" />
        <el-table-column prop="level" label="层级" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="['', 'primary', 'success', 'warning'][row.level] || 'info'">
              {{ ['', '省', '市', '区/县'][row.level] || row.level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderNum" label="排序" width="80" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === '0' ? 'success' : 'danger'">
              {{ row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" link :icon="Plus" @click="handleAdd(row)" v-hasPermi="['business:region:add']">新增下级</el-button>
            <el-button type="primary" link :icon="Edit" @click="handleEdit(row)" v-hasPermi="['business:region:edit']">编辑</el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelete(row)" v-hasPermi="['business:region:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" :close-on-click-modal="false" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级区域" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="regionOptions"
            :props="{ value: 'regionId', label: 'regionName', children: 'children' }"
            value-key="regionId"
            placeholder="选择上级区域"
            check-strictly
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="区域名称" prop="regionName">
          <el-input v-model="form.regionName" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" active-value="0" inactive-value="1" active-text="正常" inactive-text="停用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/**
 * 区域管理页面
 * @author pangu
 */
import { Delete, Edit, Plus, Refresh, Search, Sort } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { nextTick, onMounted, ref } from 'vue'
import request from '@/utils/request'
import useBaseDataStore from '@/store/modules/baseData'

const baseDataStore = useBaseDataStore()

const loading = ref(false)
const tableData = ref([])
const regionOptions = ref([])
const refreshTable = ref(true)
const isExpandAll = ref(false) // 默认折叠，避免渲染大量节点

const queryParams = ref({
  regionName: '',
  status: ''
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const form = ref({
  regionId: null,
  parentId: 0,
  regionName: '',
  orderNum: 0,
  status: '0'
})

const rules = {
  regionName: [{ required: true, message: '请输入区域名称', trigger: 'blur' }]
}

// 获取区域列表（树形）- 使用 Store 缓存
const getList = async () => {
  loading.value = true
  try {
    // 使用 Store，自动缓存
    const data = await baseDataStore.fetchRegionTree()
    tableData.value = data || []
  } finally {
    loading.value = false
  }
}

// 获取区域树选项（用于下拉选择）
const getRegionOptions = async () => {
  const data = await baseDataStore.fetchRegionTree()
  regionOptions.value = [{ regionId: 0, regionName: '顶级区域', children: data || [] }]
}

// 展开/折叠
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

// 搜索
const handleQuery = () => {
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.value = { regionName: '', status: '' }
  getList()
}

// 新增
const handleAdd = (row) => {
  dialogTitle.value = row ? '新增下级区域' : '新增区域'
  form.value = {
    regionId: null,
    parentId: row ? row.regionId : 0,
    regionName: '',
    orderNum: 0,
    status: '0'
  }
  getRegionOptions()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑区域'
  form.value = { ...row }
  getRegionOptions()
  dialogVisible.value = true
}

// 提交
const handleSubmit = async () => {
  await formRef.value?.validate()
  const isEdit = !!form.value.regionId
  const res = isEdit
    ? await request.put('/business/region', form.value)
    : await request.post('/business/region', form.value)
  if (res.code === 200) {
    baseDataStore.clearRegionTree() // 清除区域缓存
    ElMessage.success(isEdit ? '修改成功' : '新增成功')
    dialogVisible.value = false
    getList()
  }
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除区域"${row.regionName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await request.delete(`/business/region/${row.regionId}`)
    if (res.code === 200) {
      baseDataStore.clearRegionTree() // 清除区域缓存
      ElMessage.success('删除成功')
      getList()
    }
  }).catch(() => {})
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 16px;
}
.search-wrapper {
  margin-bottom: 0;
}
</style>
