<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="01" />
          <el-option label="初中" value="02" />
          <el-option label="高中" value="03" />
          <el-option label="完全中学" value="04" />
          <el-option label="其他" value="99" />
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="form.address" type="textarea" :rows="2" placeholder="请输入详细地址" />
      </el-form-item>
      <el-form-item label="联系人" prop="contactPerson">
        <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
      </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 { addSchool, updateSchool, getSchoolDetail } from '@/api/school'
import { ElMessage } from 'element-plus'
import { computed, ref } from 'vue'

// 接收父组件传递的区域树
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({
  schoolId: null,
  schoolName: '',
  schoolType: '',
  regionId: null,
  regionIds: [],
  regionName: '',
  address: '',
  contactPerson: '',
  contactPhone: '',
  status: '0'
})

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

// 表单验证规则
const rules = {
  schoolName: [
    { required: true, message: '请输入学校名称', trigger: 'blur' },
    { max: 100, message: '学校名称长度不能超过100个字符', trigger: 'blur' }
  ],
  schoolType: [
    { required: true, message: '请选择学校类型', trigger: 'change' }
  ],
  regionId: [
    { required: true, message: '请选择所属区域', trigger: 'change' }
  ],
  address: [
    { max: 255, message: '详细地址长度不能超过255个字符', trigger: 'blur' }
  ],
  contactPerson: [
    { max: 50, message: '联系人长度不能超过50个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 获取区域完整路径名称
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 = async (row) => {
  dialogVisible.value = true
  isEdit.value = !!row
  
  if (row) {
    // 编辑模式：获取详情
    try {
      const res = await getSchoolDetail(row.schoolId)
      if (res.code === 200 && res.data) {
        form.value = {
          schoolId: res.data.schoolId,
          schoolName: res.data.schoolName,
          schoolType: res.data.schoolType,
          regionId: res.data.regionId,
          regionIds: getRegionIdPath(res.data.regionId),
          regionName: res.data.regionPath || '',
          address: res.data.address || '',
          contactPerson: res.data.contactPerson || '',
          contactPhone: res.data.contactPhone || '',
          status: res.data.status
        }
      }
    } catch (error) {
      console.error('获取学校详情失败:', error)
    }
  } else {
    // 新增模式：重置表单
    form.value = {
      schoolId: null,
      schoolName: '',
      schoolType: '',
      regionId: null,
      regionIds: [],
      regionName: '',
      address: '',
      contactPerson: '',
      contactPhone: '',
      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>
