<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="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="请选择所在学校"
                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="请选择培训校区"
                    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="name" />
      <el-table-column label="所在学校" align="center" prop="schoolName" />
      <el-table-column label="培训校区" align="center" prop="campusName" />
      <el-table-column label="所在机构" align="center" prop="deptName" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <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="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="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%">
            <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="form.campusId" placeholder="请选择培训校区" style="width: 100%">
            <el-option
                    v-for="item in campusOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
            />
          </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>
  </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 } from "@/api/dz/classes"
import { batchBindTeacherClass,listAllTeacherClass } from "@/api/dz/teacherclass"
import {getCampusSchoolList} from "@/api/dz/cards.js";

const { proxy } = getCurrentInstance()

const teacherList = ref([])
const schoolOptions = ref([])
const campusOptions = ref([])
const classOptions = ref([])
const open = ref(false)
const openTeacherClass = 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 data = reactive({
  form: {},
  formTeacherClass: {
      teacherId: null,
      schoolName: null,
      name: null,
      classIds: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    schoolId: null,
    campusId: null,
    name: null
  },
  rules: {
  },
  rulesTeacherClass: {
      // 可以添加验证规则
      classIds: [
          { required: true, message: "请选择至少一个班级", trigger: "change" }
      ]
  }
})

const { queryParams, form, formTeacherClass, rules, rulesTeacherClass } = 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() {
  getCampusSchoolList({
    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,
    schoolId: null,
    campusId: null,
    name: null
  }
  proxy.resetForm("teacherRef")
}

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

// 表单重置
function resetTeacherClass() {
    formTeacherClass.value = {
        teacherId: null,
        schoolName: null,
        classIds: [],
        name: null
    }
    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()
  open.value = true
  title.value = "添加老师"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _teacherId = row.teacherId || ids.value
  getTeacher(_teacherId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改老师"
  })
}

/** 提交按钮 */
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 handleUpdateTeacherClass(row) {
    resetTeacherClass()
    // const _schoolId = row.schoolId
    const submitData = {
        schoolId: row.schoolId,
        teacherId: row.teacherId
    }
    listAllClass(submitData).then(response => {
        classOptions.value = response.data || []

        // 然后设置数据
        formTeacherClass.value.teacherId = row.teacherId
        formTeacherClass.value.name = row.name
        formTeacherClass.value.schoolName = row.schoolName

        listAllTeacherClass(submitData).then(response => {
            formTeacherClass.value.classIds = (response.data || []).map(item => item.classId)
        })

        openTeacherClass.value = true
        titleTeacherClass.value = "关联班级"
    })
}

/** 关联老师班级，提交按钮 */
function submitFormTeacherClass() {
    proxy.$refs["teacherClassRef"].validate(valid => {
        if (valid) {
            // 构建提交参数
            const submitData = {
                teacherId: formTeacherClass.value.teacherId,
                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("关联失败")
            })
        }
    })
}

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

</script>
