<!--
  会员编辑弹窗
  @author pangu
-->
<template>
  <el-dialog
    v-model="visible"
    :title="memberId ? '编辑会员' : '新增会员'"
    width="700px"
    :close-on-click-modal="false"
    destroy-on-close
    @open="handleOpen"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" maxlength="11" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="form.nickname" placeholder="请输入昵称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio value="1">男</el-radio>
              <el-radio value="2">女</el-radio>
              <el-radio value="0">未知</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birthday">
            <el-date-picker
              v-model="form.birthday"
              type="date"
              placeholder="请选择"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份类型" prop="identityType">
            <el-radio-group v-model="form.identityType">
              <el-radio value="1">家长</el-radio>
              <el-radio value="2">教师</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <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-col>
      </el-row>

      <!-- 教师身份时显示学校信息 -->
      <template v-if="form.identityType === '2'">
        <el-divider content-position="left">学校信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="区域" prop="regionId">
              <el-cascader
                v-model="form.regionIds"
                :options="regionTree"
                :props="{ value: 'id', label: 'label', checkStrictly: true }"
                placeholder="请选择区域"
                clearable
                style="width: 100%"
                @change="handleRegionChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学校" prop="schoolId">
              <el-select v-model="form.schoolId" placeholder="请选择学校" clearable style="width: 100%" @change="handleSchoolChange">
                <el-option v-for="item in schoolList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年级" prop="gradeId">
              <el-select v-model="form.gradeId" placeholder="请选择年级" clearable style="width: 100%" @change="handleGradeChange">
                <el-option v-for="item in gradeList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="classId">
              <el-select v-model="form.classId" placeholder="请选择班级" clearable style="width: 100%">
                <el-option v-for="item in classList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!-- 绑定学生 -->
      <el-divider content-position="left">绑定学生</el-divider>
      <el-row style="margin-bottom: 12px;">
        <el-button type="primary" size="small" :icon="Plus" @click="handleAddStudent">添加学生</el-button>
      </el-row>
      <el-table :data="form.students" border size="small" max-height="200">
        <template #empty>
          <el-empty description="暂无绑定学生" :image-size="60" />
        </template>
        <el-table-column prop="name" label="姓名" min-width="80" />
        <el-table-column prop="studentNo" label="学号" width="120" />
        <el-table-column prop="schoolName" label="学校" min-width="120" show-overflow-tooltip />
        <el-table-column prop="gradeName" label="年级" width="80" />
        <el-table-column prop="className" label="班级" width="60" />
        <el-table-column label="操作" width="80" align="center">
          <template #default="{ $index }">
            <el-button link type="danger" size="small" @click="handleRemoveStudent($index)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { addMember, getClassList, getGradeList, getMember, getRegionTree, getSchoolList, updateMember } from '@/api/pangu/member'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, reactive, ref, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  memberId: {
    type: [Number, null],
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

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

// 表单数据
const form = reactive({
  phone: '',
  nickname: '',
  gender: '0',
  birthday: '',
  identityType: '1',
  status: '0',
  regionIds: [],
  regionId: null,
  schoolId: null,
  gradeId: null,
  classId: null,
  students: []
})

// 表单验证规则
const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ]
}

// 下拉选项数据
const regionTree = ref([])
const schoolList = ref([])
const gradeList = ref([])
const classList = ref([])

/**
 * 弹窗打开时加载数据
 */
const handleOpen = async () => {
  // 加载区域树
  try {
    const res = await getRegionTree()
    regionTree.value = res.data || []
  } catch (e) {
    // 忽略错误
  }

  // 编辑模式加载会员数据
  if (props.memberId) {
    try {
      const res = await getMember(props.memberId)
      if (res.data) {
        Object.assign(form, res.data)
        // 加载关联数据
        if (form.regionId) {
          await loadSchoolList(form.regionId)
        }
        if (form.schoolId) {
          await loadGradeList(form.schoolId)
        }
        if (form.gradeId) {
          await loadClassList(form.gradeId)
        }
      }
    } catch (e) {
      // 忽略错误
    }
  } else {
    resetForm()
  }
}

/**
 * 重置表单
 */
const resetForm = () => {
  form.phone = ''
  form.nickname = ''
  form.gender = '0'
  form.birthday = ''
  form.identityType = '1'
  form.status = '0'
  form.regionIds = []
  form.regionId = null
  form.schoolId = null
  form.gradeId = null
  form.classId = null
  form.students = []
}

/**
 * 加载学校列表
 */
const loadSchoolList = async (regionId) => {
  try {
    const res = await getSchoolList(regionId)
    schoolList.value = res.data || []
  } catch (e) {
    schoolList.value = []
  }
}

/**
 * 加载年级列表
 */
const loadGradeList = async (schoolId) => {
  try {
    const res = await getGradeList(schoolId)
    gradeList.value = res.data || []
  } catch (e) {
    gradeList.value = []
  }
}

/**
 * 加载班级列表
 */
const loadClassList = async (gradeId) => {
  try {
    const res = await getClassList(gradeId)
    classList.value = res.data || []
  } catch (e) {
    classList.value = []
  }
}

/**
 * 区域变更
 */
const handleRegionChange = (val) => {
  form.regionId = val && val.length ? val[val.length - 1] : null
  form.schoolId = null
  form.gradeId = null
  form.classId = null
  schoolList.value = []
  gradeList.value = []
  classList.value = []
  if (form.regionId) {
    loadSchoolList(form.regionId)
  }
}

/**
 * 学校变更
 */
const handleSchoolChange = () => {
  form.gradeId = null
  form.classId = null
  gradeList.value = []
  classList.value = []
  if (form.schoolId) {
    loadGradeList(form.schoolId)
  }
}

/**
 * 年级变更
 */
const handleGradeChange = () => {
  form.classId = null
  classList.value = []
  if (form.gradeId) {
    loadClassList(form.gradeId)
  }
}

/**
 * 添加学生（模拟，实际应该弹出学生选择器）
 */
const handleAddStudent = () => {
  ElMessage.info('请选择要绑定的学生')
}

/**
 * 移除学生
 */
const handleRemoveStudent = (index) => {
  form.students.splice(index, 1)
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
  } catch (e) {
    return
  }

  submitLoading.value = true
  try {
    if (props.memberId) {
      await updateMember({ ...form, id: props.memberId })
      ElMessage.success('修改成功')
    } else {
      await addMember(form)
      ElMessage.success('新增成功')
    }
    visible.value = false
    emit('success')
  } finally {
    submitLoading.value = false
  }
}

// 监听弹窗关闭，重置表单
watch(visible, (val) => {
  if (!val) {
    formRef.value?.resetFields()
  }
})
</script>
