<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="用户ID" prop="userId">-->
<!--        <el-input-->
<!--          v-model="queryParams.userId"-->
<!--          placeholder="请输入用户ID"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="代理商" prop="agentId">
        <IeAgentSelect v-model="queryParams.agentId" placeholder="请选择代理商" filterable clearable style="width: 240px" />
      </el-form-item>
      <el-form-item label="教师姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入教师姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所在学校" prop="schoolId">
        <el-select
                v-model="queryParams.schoolId"
                placeholder="请选择或输入学校名称"
                filterable
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
        >
          <el-option
                  v-for="item in schoolOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
          />
        </el-select>
      </el-form-item>
        <el-form-item label="培训校区" prop="campusId">
            <el-select
                    v-model="queryParams.campusId"
                    placeholder="请选择或输入校区名称"
                    filterable
                    clearable
                    style="width: 240px"
                    @keyup.enter="handleQuery"
            >
                <el-option
                        v-for="item in campusOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                />
            </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-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['dz:teacher:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dz:teacher:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dz:teacher:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['dz:teacher:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="teacherList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="教师ID/账号" align="center" prop="teacherId" />
      <el-table-column label="密码" align="center" prop="password2" />
      <el-table-column label="教师姓名" align="center" prop="name" />
      <el-table-column label="代理商" align="center" prop="agentName" />
      <el-table-column label="所在学校" align="center" prop="schoolName" />
      <el-table-column label="所在学校班级" align="center" prop="schoolClass" />
      <el-table-column label="培训校区" align="center" prop="campusName" />
      <el-table-column label="培训校区班级" align="center" prop="campusClass" />
      <el-table-column label="所在机构" align="center" prop="deptName" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="禁用状态" align="center" key="status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="" @click="handleUpdateTeacherClass(scope.row)" v-hasPermi="['dz:teacher:edit']">学校班级</el-button> -->
          <!-- <el-button link type="primary" icon="" @click="handleUpdateCampusClass(scope.row)" v-hasPermi="['dz:teacher:edit']">校区班级</el-button> -->
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['dz:teacher:edit']">修改</el-button>
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['dz:teacher:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改老师对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="teacherRef" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="用户ID" prop="userId">-->
<!--          <el-input v-model="form.userId" placeholder="请输入用户ID" />-->
<!--        </el-form-item>-->
        <el-form-item label="代理商" prop="agentId">
          <IeAgentSelect v-model="form.agentId" placeholder="请选择代理商" filterable clearable style="width: 100%" />
        </el-form-item>
        <el-form-item label="教师姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入教师姓名" />
        </el-form-item>
        <el-form-item label="所在学校" prop="schoolId">
          <el-select v-model="form.schoolId" placeholder="请选择所在学校" style="width: 100%" filterable clearable :disabled="!form.teacherId && !!form.campusId" @change="handleSchoolChange">
            <el-option
                    v-for="item in schoolOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学校班级" prop="schoolClassIds">
          <el-select v-model="form.schoolClassIds" multiple placeholder="请选择学校班级" style="width: 100%" filterable clearable :disabled="!form.schoolId">
            <el-option
                    v-for="item in schoolClassOptions"
                    :key="item.classId"
                    :label="item.name"
                    :value="item.classId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="培训校区" prop="campusId">
          <el-select v-model="form.campusId" placeholder="请选择培训校区" style="width: 100%" filterable clearable :disabled="!form.teacherId && !!form.schoolId" @change="handleCampusChange">
            <el-option
                    v-for="item in campusOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="校区班级" prop="campusClassIds">
          <el-select v-model="form.campusClassIds" multiple placeholder="请选择校区班级" style="width: 100%" filterable clearable :disabled="!form.campusId">
            <el-option
                    v-for="item in campusClassOptions"
                    :key="item.classId"
                    :label="item.name"
                    :value="item.classId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

      <!-- 关联班级 -->
      <el-dialog :title="titleTeacherClass" v-model="openTeacherClass" width="500px" append-to-body>
          <el-form ref="teacherClassRef" :model="formTeacherClass" :rules="rulesTeacherClass" label-width="80px">
<!--              <el-form-item label="教师ID" v-show="false" prop="teacherId">-->
<!--                  <el-input v-model="formTeacherClass.teacherId" placeholder="请输入教师ID" disabled/>-->
<!--              </el-form-item>-->
              <el-form-item label="教师姓名" prop="name">
                  <el-input v-model="formTeacherClass.name" placeholder="请输入教师姓名" disabled/>
              </el-form-item>
              <el-form-item label="学校校区" prop="name">
                  <el-input v-model="formTeacherClass.schoolName" placeholder="请输入教师姓名" disabled/>
              </el-form-item>
              <el-form-item label="关联班级" prop="classIds">
                  <el-select v-model="formTeacherClass.classIds" multiple placeholder="请选择班级" style="width: 100%">
                      <el-option
                              v-for="item in classOptions"
                              :key="item.classId"
                              :label="item.name"
                              :value="item.classId"
                      />
                  </el-select>
              </el-form-item>
          </el-form>
          <template #footer>
              <div class="dialog-footer">
                  <el-button type="primary" @click="submitFormTeacherClass">确 定</el-button>
                  <el-button @click="cancelTeacherClass">取 消</el-button>
              </div>
          </template>
      </el-dialog>

      <!-- 关联校区班级 -->
      <!-- <el-dialog :title="titleCampusClass" v-model="openCampusClass" width="500px" append-to-body>
          <el-form ref="campusClassRef" :model="formCampusClass" :rules="rulesCampusClass" label-width="80px">
              <el-form-item label="教师姓名" prop="name">
                  <el-input v-model="formCampusClass.name" placeholder="请输入教师姓名" disabled/>
              </el-form-item>
              <el-form-item label="培训校区" prop="campusId">
                  <el-select
                          v-model="formCampusClass.campusId"
                          placeholder="请选择培训校区"
                          style="width: 100%"
                          @change="handleCampusClassChange"
                  >
                      <el-option
                              v-for="item in campusOptions"
                              :key="item.id"
                              :label="item.name"
                              :value="item.id"
                      />
                  </el-select>
              </el-form-item>
              <el-form-item label="关联班级" prop="classIds">
                  <el-select
                          v-model="formCampusClass.classIds"
                          multiple
                          placeholder="请选择班级"
                          style="width: 100%"
                          :disabled="!formCampusClass.campusId"
                  >
                      <el-option
                              v-for="item in campusClassOptions"
                              :key="item.classId"
                              :label="item.name"
                              :value="item.classId"
                      />
                  </el-select>
              </el-form-item>
          </el-form>
          <template #footer>
              <div class="dialog-footer">
                  <el-button type="primary" @click="submitFormCampusClass">确 定</el-button>
                  <el-button @click="cancelCampusClass">取 消</el-button>
              </div>
          </template>
      </el-dialog> -->
  </div>
</template>

<script setup name="Teacher">
import { listTeacher, getTeacher, delTeacher, addTeacher, updateTeacher } from "@/api/dz/teacher"
import {listAllSchool} from "@/api/dz/school"
import {listCampus} from "@/api/dz/campus"
import { listAllClass, getClassesBySchoolId, getClassesByCampusId } from "@/api/dz/classes"
import { batchBindTeacherClass,listAllTeacherClass } from "@/api/dz/teacherclass"
import {getCampusSchoolList} from "@/api/dz/cards.js";
import { changeUserStatus } from "@/api/system/user"
import IeAgentSelect from '@/components/IeAgentSelect/index.vue'

const { proxy } = getCurrentInstance()

const teacherList = ref([])
const schoolOptions = ref([])
const campusOptions = ref([])
const classOptions = ref([])
const campusClassOptions = ref([])
const schoolClassOptions = ref([])
const open = ref(false)
const openTeacherClass = ref(false)
const openCampusClass = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const titleTeacherClass = ref("")
const titleCampusClass = ref("")

const data = reactive({
  form: {},
  formTeacherClass: {
      teacherId: null,
      schoolId: null,
      schoolName: null,
      name: null,
      classIds: []
  },
  formCampusClass: {
      teacherId: null,
      schoolId: null,
      campusId: null,
      name: null,
      classIds: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    agentId: null,
    schoolId: null,
    campusId: null,
    name: null
  },
  rules: {
  },
  rulesTeacherClass: {
      // 可以添加验证规则
      classIds: [
          { required: true, message: "请选择至少一个班级", trigger: "change" }
      ]
  },
  rulesCampusClass: {
      campusId: [
          { required: true, message: "请选择培训校区", trigger: "change" }
      ],
      classIds: [
          { required: true, message: "请选择至少一个班级", trigger: "change" }
      ]
  }
})

const { queryParams, form, formTeacherClass, formCampusClass, rules, rulesTeacherClass, rulesCampusClass } = toRefs(data)

/** 查询老师列表 */
function getList() {
  loading.value = true
  listTeacher(queryParams.value).then(response => {
    teacherList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 查询校区列表 */
function getSchoolList() {
  listAllSchool({
    pageNum: 1,
    pageSize: 9999,
  }).then(response => {
    schoolOptions.value = response.data || []
  })
}
/** 查询校区列表 */
function getCampusList() {
  listCampus().then(response => {
    campusOptions.value = response.rows || []
  })
}


// function getClassListBySchool() {
//     listAll().then(response => {
//         classOptions.value = response.data || []
//     })
// }

// 取消按钮
function cancel() {
  open.value = false
  reset()
}


// 表单重置
function reset() {
  form.value = {
    teacherId: null,
    userId: null,
    deptId: null,
    agentId: null,
    schoolId: null,
    campusId: null,
    name: null,
    schoolClassIds: [],
    campusClassIds: []
  }
  schoolClassOptions.value = []
  campusClassOptions.value = []
  proxy.resetForm("teacherRef")
}

// 取消按钮
function cancelTeacherClass() {
    openTeacherClass.value = false
    resetTeacherClass()
}

// 表单重置
function resetTeacherClass() {
    formTeacherClass.value = {
        teacherId: null,
        schoolId: null,
        schoolName: null,
        classIds: [],
        name: null
    }
    classOptions.value = []
    proxy.resetForm("teacherClassRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.teacherId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  getSchoolList()
  getCampusList()
  open.value = true
  title.value = "添加老师"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  getSchoolList()
  getCampusList()
  const _teacherId = row.teacherId || ids.value
  getTeacher(_teacherId).then(response => {
    form.value = response.data
    // 初始化班级ID数组
    form.value.schoolClassIds = []
    form.value.campusClassIds = []

    // 先加载班级列表，然后获取已关联的班级并回显
    const loadPromises = []

    if (form.value.schoolId) {
      loadPromises.push(
        getClassesBySchoolId({ schoolId: form.value.schoolId }).then(response => {
          schoolClassOptions.value = response.data || []
        })
      )
    }

    if (form.value.campusId) {
      loadPromises.push(
        getClassesByCampusId({ campusId: form.value.campusId }).then(response => {
          campusClassOptions.value = response.data || []
        })
      )
    }

    // 获取该老师已关联的所有班级
    Promise.all([
      ...loadPromises,
      listAllTeacherClass({ teacherId: _teacherId })
    ]).then((results) => {
      const teacherClassResponse = results[results.length - 1]
      const teacherClasses = teacherClassResponse.data || []

      // 根据班级所属的学校/校区，分别设置到对应的数组中
      teacherClasses.forEach(tc => {
        if (tc.classId) {
          // 检查该班级是否属于学校
          const schoolClass = schoolClassOptions.value.find(c => c.classId === tc.classId)
          if (schoolClass && form.value.schoolId && schoolClass.schoolId === form.value.schoolId) {
            if (!form.value.schoolClassIds) {
              form.value.schoolClassIds = []
            }
            if (!form.value.schoolClassIds.includes(tc.classId)) {
              form.value.schoolClassIds.push(tc.classId)
            }
          }

          // 检查该班级是否属于校区（校区班级的schoolId等于campusId）
          const campusClass = campusClassOptions.value.find(c => c.classId === tc.classId)
          if (campusClass && form.value.campusId && campusClass.schoolId === form.value.campusId) {
            if (!form.value.campusClassIds) {
              form.value.campusClassIds = []
            }
            if (!form.value.campusClassIds.includes(tc.classId)) {
              form.value.campusClassIds.push(tc.classId)
            }
          }
        }
      })
    })

    open.value = true
    title.value = "修改老师"
  })
}

/** 学校变化处理 */
function handleSchoolChange() {
  // 如果选择了学校，清空校区
  if (form.value.schoolId) {
    form.value.campusId = null
    form.value.campusClassIds = []
    campusClassOptions.value = []
  } else {
    // 如果清空了学校，清空学校班级
    form.value.schoolClassIds = []
    schoolClassOptions.value = []
    return
  }
  // 如果是编辑模式，不清空已选班级，只更新选项列表
  if (!form.value.teacherId) {
    form.value.schoolClassIds = []
  }
  schoolClassOptions.value = []
  if (form.value.schoolId) {
    getClassesBySchoolId({ schoolId: form.value.schoolId }).then(response => {
      schoolClassOptions.value = response.data || []
      // 如果是编辑模式，需要重新匹配已关联的班级
      if (form.value.teacherId) {
        loadTeacherClassesForEdit()
      }
    })
  }
}

/** 校区变化处理 */
function handleCampusChange() {
  // 如果选择了校区，清空学校
  if (form.value.campusId) {
    form.value.schoolId = null
    form.value.schoolClassIds = []
    schoolClassOptions.value = []
  } else {
    // 如果清空了校区，清空校区班级
    form.value.campusClassIds = []
    campusClassOptions.value = []
    return
  }
  // 如果是编辑模式，不清空已选班级，只更新选项列表
  if (!form.value.teacherId) {
    form.value.campusClassIds = []
  }
  campusClassOptions.value = []
  if (form.value.campusId) {
    getClassesByCampusId({ campusId: form.value.campusId }).then(response => {
      campusClassOptions.value = response.data || []
      // 如果是编辑模式，需要重新匹配已关联的班级
      if (form.value.teacherId) {
        loadTeacherClassesForEdit()
      }
    })
  }
}

/** 编辑模式下加载已关联的班级 */
function loadTeacherClassesForEdit() {
  if (!form.value.teacherId) return

  listAllTeacherClass({ teacherId: form.value.teacherId }).then(response => {
    const teacherClasses = response.data || []

    // 重置班级ID数组
    form.value.schoolClassIds = []
    form.value.campusClassIds = []

    // 根据班级所属的学校/校区，分别设置到对应的数组中
    teacherClasses.forEach(tc => {
      if (tc.classId) {
        // 检查该班级是否属于学校
        const schoolClass = schoolClassOptions.value.find(c => c.classId === tc.classId)
        if (schoolClass && form.value.schoolId && schoolClass.schoolId === form.value.schoolId) {
          if (!form.value.schoolClassIds) {
            form.value.schoolClassIds = []
          }
          if (!form.value.schoolClassIds.includes(tc.classId)) {
            form.value.schoolClassIds.push(tc.classId)
          }
        }

        // 检查该班级是否属于校区（校区班级的schoolId等于campusId）
        const campusClass = campusClassOptions.value.find(c => c.classId === tc.classId)
        if (campusClass && form.value.campusId && campusClass.schoolId === form.value.campusId) {
          if (!form.value.campusClassIds) {
            form.value.campusClassIds = []
          }
          if (!form.value.campusClassIds.includes(tc.classId)) {
            form.value.campusClassIds.push(tc.classId)
          }
        }
      }
    })
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["teacherRef"].validate(valid => {
    if (valid) {
      if (form.value.teacherId != null) {
        updateTeacher(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addTeacher(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _teacherIds = row.teacherId || ids.value
  proxy.$modal.confirm('是否确认删除老师编号为"' + _teacherIds + '"的数据项？').then(function() {
    return delTeacher(_teacherIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('dz/teacher/export', {
    ...queryParams.value
  }, `teacher_${new Date().getTime()}.xlsx`)
}

/** 用户状态修改  */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "禁用"
  proxy.$modal.confirm('确认要"' + text + '""' + row.name + '"用户吗?').then(function () {
    return changeUserStatus(row.userId, row.status)
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功")
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0"
  })
}

/** 关联老师班级,按钮操作 */
function handleUpdateTeacherClass(row) {
    resetTeacherClass()
    // 先清空班级选项和已选班级
    classOptions.value = []
    formTeacherClass.value.classIds = []

    // const _schoolId = row.schoolId
    const submitData = {
        schoolId: row.schoolId,
        teacherId: row.teacherId
    }

    // 设置基本数据
    formTeacherClass.value.teacherId = row.teacherId
    formTeacherClass.value.schoolId = row.schoolId
    formTeacherClass.value.name = row.name
    formTeacherClass.value.schoolName = row.schoolName

    // 先打开弹窗
    openTeacherClass.value = true
    titleTeacherClass.value = "关联班级"

    // 加载班级列表和已关联的班级
    Promise.all([
        listAllClass(submitData),
        listAllTeacherClass(submitData)
    ]).then(([classResponse, teacherClassResponse]) => {
        classOptions.value = classResponse.data || []
        formTeacherClass.value.classIds = (teacherClassResponse.data || []).map(item => item.classId)
    })
}

/** 关联老师班级，提交按钮 */
function submitFormTeacherClass() {
    proxy.$refs["teacherClassRef"].validate(valid => {
        if (valid) {
            // 构建提交参数
            const submitData = {
                teacherId: formTeacherClass.value.teacherId,
                schoolId: formTeacherClass.value.schoolId,
                classIds: formTeacherClass.value.classIds
            }
            // console.log("submitData"+submitData)

            // 调用关联班级的API
            // 假设API函数名为 updateTeacherClassRelation
            batchBindTeacherClass(submitData).then(response => {
                proxy.$modal.msgSuccess("关联成功")
                openTeacherClass.value = false
                getList()
            }).catch(() => {
                proxy.$modal.msgError("关联失败")
            })
        }
    })
}

/** 关联校区班级，按钮操作 */
function handleUpdateCampusClass(row) {
    resetCampusClass()
    // 先清空班级选项和已选班级
    campusClassOptions.value = []
    formCampusClass.value.classIds = []

    // 设置数据
    formCampusClass.value.teacherId = row.teacherId
    formCampusClass.value.schoolId = row.campusId
    formCampusClass.value.name = row.name

    // 先打开弹窗
    openCampusClass.value = true
    titleCampusClass.value = "关联校区班级"

    // 如果有培训校区，默认选中并加载该校区的班级列表
    if (row.campusId) {
        formCampusClass.value.campusId = row.campusId
        // 加载该校区的班级列表
        loadCampusClasses(row.campusId, row.teacherId)
    }
}

/** 校区班级弹窗中校区选择变化时，加载该校区的班级列表 */
function handleCampusClassChange(campusId) {
    if (campusId) {
        loadCampusClasses(campusId, formCampusClass.value.teacherId)
        // 清空已选择的班级
        formCampusClass.value.classIds = []
    } else {
        campusClassOptions.value = []
        formCampusClass.value.classIds = []
    }
}

/** 加载校区的班级列表 */
function loadCampusClasses(campusId, teacherId) {
    const submitData = {
        schoolId: campusId,
        teacherId: teacherId
    }
    // 使用Promise.all确保两个请求都完成后再设置数据
    Promise.all([
        listAllClass(submitData),
        listAllTeacherClass(submitData)
    ]).then(([classResponse, teacherClassResponse]) => {
        campusClassOptions.value = classResponse.data || []
        formCampusClass.value.classIds = (teacherClassResponse.data || []).map(item => item.classId)
    })
}

/** 关联校区班级，提交按钮 */
function submitFormCampusClass() {
    proxy.$refs["campusClassRef"].validate(valid => {
        if (valid) {
            // 构建提交参数
            const submitData = {
                teacherId: formCampusClass.value.teacherId,
                schoolId: formCampusClass.value.schoolId,
                classIds: formCampusClass.value.classIds
            }
            // 调用关联班级的API
            batchBindTeacherClass(submitData).then(response => {
                proxy.$modal.msgSuccess("关联成功")
                openCampusClass.value = false
                getList()
            }).catch(() => {
                proxy.$modal.msgError("关联失败")
            })
        }
    })
}

// 取消按钮
function cancelCampusClass() {
    openCampusClass.value = false
    resetCampusClass()
}

// 表单重置
function resetCampusClass() {
    formCampusClass.value = {
        teacherId: null,
        schoolId: null,
        campusId: null,
        name: null,
        classIds: []
    }
    campusClassOptions.value = []
    if (proxy.$refs["campusClassRef"]) {
        proxy.$refs["campusClassRef"].resetFields()
    }
}

onMounted(() => {
  getSchoolList()
  getCampusList()
  getList()
  // getClassListBySchool()
})

</script>
