<!--
  会员编辑弹窗
  @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="regionIds">
              <el-cascader
                v-model="form.regionIds"
                :options="regionTree"
                :props="{ value: 'id', label: 'label', children: 'children', checkStrictly: false }"
                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.schoolId" :label="item.schoolName" :value="item.schoolId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属年级" prop="schoolGradeId">
              <el-select v-model="form.schoolGradeId" placeholder="请选择年级" clearable style="width: 100%" @change="handleGradeChange">
                <el-option v-for="item in gradeList" :key="item.id" :label="item.gradeName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属班级" prop="schoolClassId">
              <el-select v-model="form.schoolClassId" placeholder="请选择班级" clearable style="width: 100%">
                <el-option v-for="item in classList" :key="item.id" :label="item.className" :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="studentName" 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="{ row, $index }">
            <el-popconfirm
              title="确认解绑该学生吗？"
              @confirm="handleUnbindStudent(row, $index)"
            >
              <template #reference>
                <el-button link type="danger" size="small">解绑</el-button>
              </template>
            </el-popconfirm>
          </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>

    <!-- 学生选择弹窗 -->
    <StudentBindDialog
      v-model:visible="studentDialogVisible"
      :identity-type="form.identityType"
      :school-id="form.schoolId"
      :exclude-ids="form.students.map(s => s.studentId)"
      @confirm="handleStudentBind"
    />
  </el-dialog>
</template>

<script setup>
import { 
  addMember, 
  updateMember, 
  getMember, 
  getRegionTree, 
  getSchoolListByRegion, 
  getGradeListBySchool, 
  getClassListByGrade,
  bindStudent,
  unbindStudent
} from '@/api/member'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, reactive, ref, watch } from 'vue'
import StudentBindDialog from './StudentBindDialog.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({
  memberId: null,
  phone: '',
  nickname: '',
  gender: '0',
  birthday: '',
  identityType: '1',
  status: '0',
  regionIds: [],
  regionId: null,
  schoolId: null,
  schoolGradeId: null,
  schoolClassId: null,
  students: []
})

// 表单验证规则
const rules = reactive({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  identityType: [
    { required: true, message: '请选择身份类型', trigger: 'change' }
  ],
  regionIds: [
    { 
      required: true, 
      message: '请选择所属区域', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.identityType === '2' && (!value || value.length === 0)) {
          callback(new Error('请选择所属区域'))
        } else {
          callback()
        }
      }
    }
  ],
  schoolId: [
    { 
      required: true, 
      message: '请选择所属学校', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.identityType === '2' && !value) {
          callback(new Error('请选择所属学校'))
        } else {
          callback()
        }
      }
    }
  ],
  schoolGradeId: [
    { 
      required: true, 
      message: '请选择所属年级', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.identityType === '2' && !value) {
          callback(new Error('请选择所属年级'))
        } else {
          callback()
        }
      }
    }
  ],
  schoolClassId: [
    { 
      required: true, 
      message: '请选择所属班级', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.identityType === '2' && !value) {
          callback(new Error('请选择所属班级'))
        } else {
          callback()
        }
      }
    }
  ]
})

// 下拉选项数据
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.code === 200 && res.data) {
        const data = res.data
        form.memberId = data.memberId
        form.phone = data.phoneFull || data.phone
        form.nickname = data.nickname
        form.gender = data.gender || '0'
        form.birthday = data.birthday
        form.identityType = data.identityType
        form.status = data.status
        form.regionId = data.regionId
        form.schoolId = data.schoolId
        form.schoolGradeId = data.schoolGradeId
        form.schoolClassId = data.schoolClassId
        form.students = data.students || []
        
        // 教师需要加载关联数据
        if (data.identityType === '2' && data.regionId) {
          form.regionIds = [data.regionId]
          await loadSchoolList(data.regionId)
          
          if (data.schoolId) {
            await loadGradeList(data.schoolId)
          }
          if (data.schoolGradeId) {
            await loadClassList(data.schoolGradeId)
          }
        }
      }
    } catch (e) {
      console.error('加载会员数据失败:', e)
    }
  } else {
    resetForm()
  }
}

/**
 * 重置表单
 */
const resetForm = () => {
  form.memberId = null
  form.phone = ''
  form.nickname = ''
  form.gender = '0'
  form.birthday = ''
  form.identityType = '1'
  form.status = '0'
  form.regionIds = []
  form.regionId = null
  form.schoolId = null
  form.schoolGradeId = null
  form.schoolClassId = null
  form.students = []
  schoolList.value = []
  gradeList.value = []
  classList.value = []
}

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

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

/**
 * 加载班级列表
 */
const loadClassList = async (schoolGradeId) => {
  try {
    const res = await getClassListByGrade(schoolGradeId)
    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.schoolGradeId = null
  form.schoolClassId = null
  schoolList.value = []
  gradeList.value = []
  classList.value = []
  if (form.regionId) {
    loadSchoolList(form.regionId)
  }
}

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

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

// 学生绑定弹窗
const studentDialogVisible = ref(false)

/**
 * 打开学生选择弹窗
 */
const handleAddStudent = () => {
  studentDialogVisible.value = true
}

/**
 * 学生绑定确认
 */
const handleStudentBind = async (students) => {
  for (const student of students) {
    // 检查是否已绑定
    if (form.students.some(s => s.studentId === student.studentId)) {
      continue
    }
    
    // 编辑模式下调用接口绑定
    if (form.memberId) {
      try {
        await bindStudent(form.memberId, student.studentId)
      } catch (error) {
        ElMessage.error(`绑定学生${student.studentName}失败`)
        continue
      }
    }
    
    // 添加到列表
    form.students.push(student)
  }
  ElMessage.success('绑定成功')
}

/**
 * 解绑学生
 */
const handleUnbindStudent = async (row, index) => {
  // 编辑模式下调用接口解绑
  if (form.memberId) {
    try {
      await unbindStudent(form.memberId, row.studentId)
    } catch (error) {
      ElMessage.error('解绑失败')
      return
    }
  }
  
  // 从列表移除
  form.students.splice(index, 1)
  ElMessage.success('解绑成功')
}

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

  submitLoading.value = true
  try {
    const submitData = {
      ...form,
      // 新增时带上要绑定的学生ID列表
      studentIds: form.memberId ? undefined : form.students.map(s => s.studentId)
    }
    
    const res = form.memberId
      ? await updateMember(submitData)
      : await addMember(submitData)
    
    if (res.code === 200) {
      ElMessage.success(form.memberId ? '修改成功' : '新增成功')
      visible.value = false
      emit('success')
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

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