<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="600px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="学校名称" prop="schoolName">
        <el-input v-model="form.schoolName" placeholder="请输入学校名称" />
      </el-form-item>
      <el-form-item label="学校类型" prop="schoolType">
        <el-select v-model="form.schoolType" placeholder="请选择学校类型" style="width: 100%">
          <el-option label="小学" value="小学" />
          <el-option label="初中" value="初中" />
          <el-option label="高中" value="高中" />
          <el-option label="九年一贯制" value="九年一贯制" />
          <el-option label="完全中学" value="完全中学" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属区域" prop="regionId">
        <el-cascader
          v-model="form.regionIds"
          :options="regionTree"
          :props="{
            value: 'regionId',
            label: 'regionName',
            children: 'children',
            checkStrictly: true
          }"
          placeholder="请选择所属区域"
          clearable
          style="width: 100%"
          @change="handleRegionChange"
        />
      </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" :loading="submitLoading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 * 学校新增/编辑弹窗
 * @author pangu
 */
import { ElMessage } from 'element-plus'
import { computed, ref } from 'vue'
import { addSchool, updateSchool } from '@/api/school'

// 接收父组件传递的区域树
const props = defineProps({
  regionTree: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const submitLoading = ref(false)
const formRef = ref(null)
const isEdit = ref(false)

// 表单数据
const form = ref({
  id: null,
  schoolName: '',
  schoolType: '',
  regionId: null,
  regionIds: [],
  regionName: '',
  status: '0'
})

// 弹窗标题
const dialogTitle = computed(() => isEdit.value ? '编辑学校' : '新增学校')

// 表单验证规则
const rules = {
  schoolName: [
    { required: true, message: '请输入学校名称', trigger: 'blur' }
  ],
  schoolType: [
    { required: true, message: '请选择学校类型', trigger: 'change' }
  ],
  regionId: [
    { required: true, message: '请选择所属区域', trigger: 'change' }
  ]
}

// 获取区域完整路径名称
const getRegionPath = (ids, tree) => {
  const names = []
  const findPath = (nodes, targetId, path) => {
    for (const node of nodes) {
      if (ids.includes(node.regionId)) {
        path.push(node.regionName)
      }
      if (node.children) {
        findPath(node.children, targetId, path)
      }
    }
  }
  findPath(tree, ids[ids.length - 1], names)
  return names.join('/')
}

// 区域选择变化
const handleRegionChange = (value) => {
  if (value && value.length > 0) {
    form.value.regionId = value[value.length - 1]
    form.value.regionName = getRegionPath(value, props.regionTree)
  } else {
    form.value.regionId = null
    form.value.regionName = ''
  }
}

// 打开弹窗
const open = (row) => {
  dialogVisible.value = true
  isEdit.value = !!row
  
  if (row) {
    // 编辑模式：回显数据
    form.value = {
      id: row.id,
      schoolName: row.schoolName,
      schoolType: row.schoolType,
      regionId: row.regionId,
      regionIds: getRegionIdPath(row.regionId),
      regionName: row.regionName,
      status: row.status
    }
  } else {
    // 新增模式：重置表单
    form.value = {
      id: null,
      schoolName: '',
      schoolType: '',
      regionId: null,
      regionIds: [],
      regionName: '',
      status: '0'
    }
  }
}

// 根据区域ID获取完整的ID路径（用于级联选择器回显）
const getRegionIdPath = (regionId) => {
  if (!regionId) return []
  
  const id = regionId.toString()
  const path = []
  
  // 省级ID（1位）
  if (id.length >= 1) {
    path.push(parseInt(id.charAt(0)))
  }
  // 市级ID（2位）
  if (id.length >= 2) {
    path.push(parseInt(id.substring(0, 2)))
  }
  // 区级ID（3位）
  if (id.length >= 3) {
    path.push(parseInt(id))
  }
  
  return path
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      const submitData = {
        ...form.value,
        regionIds: undefined // 不提交级联选择器的数组
      }
      
      const res = isEdit.value 
        ? await updateSchool(submitData)
        : await addSchool(submitData)
        
      if (res.code === 200) {
        ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
        dialogVisible.value = false
        emit('success')
      }
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      submitLoading.value = false
    }
  })
}

// 暴露方法给父组件
defineExpose({ open })
</script>
