<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 右边班级树状 -->
      <el-col :span="6">
        <el-card class="box-card grade_tree">
          <el-tree
            :data="gradeDataTree"
            :props="defaultProps"
            node-key="id"
            v-loading="treeLoading"
            :default-expanded-keys="[defaultExpandedId]"
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>
      <!-- 左边小组 -->
      <el-col :span="18">
        <Filter
          v-model="filterData"
          :config="filterConfig"
          @handleAction="handleFilterData"
          @updateSchool="hanldeUpdateSchool"
        />
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              >添加学生分组</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              @click="handleDelete"
              :disabled="multiple"
              >批量删除</el-button
            >
          </el-col>
        </el-row>
        <!-- 表格 -->
        <Table
          :xbTable="xbTable"
          @tablePageChange="handleTablePageChange"
          @selectionChange="handleSelectionChange"
        >
          <template v-slot:operation="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button
              link
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </Table>
      </el-col>
    </el-row>
    <!-- 编辑新增弹窗 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="800px"
      append-to-body
      :before-close="cancel"
    >
      <el-form ref="diaRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="小组名称" prop="groupName">
          <el-input
            v-model="form.groupName"
            placeholder="请输入"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="form.sort"
            :min="0"
            :precision="0"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item class="class_member">
          <el-transfer
            v-if="open"
            filterable
            filter-placeholder="请输入学号或学生姓名"
            :filter-method="filterStudentsMethod"
            :titles="['班级成员', '小组成员']"
            :button-texts="['删除', '添加']"
            v-model="form.stuIds"
            :data="classStudents"
            :props="{
              key: 'id',
            }"
          >
            <template #default="{ option }">
              <span>{{ option.stuNo }}/{{ option.stuName }}</span>
            </template>
          </el-transfer>
        </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>
  </div>
</template>

<script setup name="groupManage">
import Filter from "@/views/smartCampus/components/Filter/index.vue";
import Table from "@/views/smartCampus/components/Table/index.vue";
import {
  getGradeClassTreeApi,
  getTenantGradeClassTreeApi,
  getGroupListApi,
  addGroupApi,
  updateGroupApi,
  getGroupDetailsApi,
  deleteGroupApi,
  getAlreadyAddStuApi,
  getNotJoinStuInfoApi,
} from "@/api/smartCampus/index";
import useUserStore from "@/store/modules/user";
import { nextTick } from "vue";
const { proxy } = getCurrentInstance();
const title = ref(""); //弹窗title
const open = ref(false);
const ids = ref([]); //批量删除ids
const multiple = ref(true); //批量删除按钮
const filterData = ref({}); //过滤
const filterClassOrGradeId = ref({ gradeId: "", classId: "" }); //点击树状图筛选
const chooseClass = ref({ gradeId: "", classId: "" }); //选择的班级
const classStudents = ref([]); //班级学生
const Transferloading = ref(false); //穿梭框加载
const filterConfig = computed(() => {
  return [
    {
      comName: "admin",
      label: "学校名称",
      prop: "tenantId",
      placeholder: "请选择",
      clearable: true,
    },
    {
      comName: "el-select",
      label: "学科",
      prop: "subject",
      clearable: true,
      options: [{ label: "英语", value: "英语" }],
      selectConfig: {
        label: "label",
        value: "value",
      },
    },
    {
      comName: "el-input",
      label: "学生姓名",
      placeholder: "请输入",
      prop: "stuName",
      clearable: true,
    },
  ];
});
const xbTable = ref({
  loading: false,
  columns: [
    { type: "selection" },
    { prop: "groupName", label: "小组名称" },
    { prop: "groupMember", label: "小组成员" },
    { prop: "groupNum", label: "小组人数" },
    { prop: "sort", label: "排序" },
    { label: "操作", slot: "operation" },
  ],
  tableData: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  },
});
const data = reactive({
  form: {},
  rules: {
    groupName: [
      { required: true, message: "小组名称不能为空", trigger: "blur" },
    ],
    sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
  },
});

const { form, rules } = toRefs(data);
const defaultProps = {
  children: "children",
  label: "label",
};

const treeLoading = ref(false);
const defaultExpandedId = ref(""); // 默认展开
const gradeDataTree = ref([]);
// 树状图点击
const handleNodeClick = (data) => {
  if (!data.tenantId) {
    // 全校
    filterClassOrGradeId.value.classId = "";
    filterClassOrGradeId.value.gradeId = "";
    chooseClass.value.classId = "";
    chooseClass.value.gradeId = "";
    filterData.value.tenantId = data.id;
  } else if (data.id && !data.gradeId) {
    // 年级
    filterData.value.tenantId = data.tenantId;
    filterClassOrGradeId.value.gradeId = data.id;
    filterClassOrGradeId.value.classId = "";
    chooseClass.value.classId = "";
    chooseClass.value.gradeId = data.id;
  } else if (data.id && data.gradeId) {
    // 班级
    filterData.value.tenantId = data.tenantId;
    filterClassOrGradeId.value.classId = data.id;
    filterClassOrGradeId.value.gradeId = "";
    chooseClass.value.classId = data.id;
    chooseClass.value.gradeId = data.gradeId;
  }
  xbTable.value.pagination.pageNum = 1;
  getList();
};
/** 查询列表 */
function getList() {
  xbTable.value.loading = true;
  getGroupListApi({
    ...xbTable.value.pagination,
    ...filterData.value,
    ...filterClassOrGradeId.value,
  }).then((res) => {
    xbTable.value.tableData = res.rows;
    xbTable.value.loading = false;
    xbTable.value.pagination.total = res.total;
  });
}
// 表格勾选
function handleSelectionChange(val) {
  ids.value = val.map((item) => item.id);
  multiple.value = !val.length;
}
// 表格分页
function handleTablePageChange(val) {
  xbTable.value.pagination.pageSize = val.limit;
  xbTable.value.pagination.pageNum = val.page;
  getList();
}
/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    subject: "英语",
    groupName: undefined,
    classId: undefined,
    gradeId: undefined,
    stuIds: [],
    sort: 1,
  };
  classStudents.value = [];
  proxy.resetForm("diaRef");
}
// 过滤按钮
function handleFilterData(type) {
  switch (type.value) {
    case "search":
      getList();
      break;
    case "reset":
      xbTable.value.pagination.pageNum = 1;
      getList();
      break;
  }
}
// 更新学校
function hanldeUpdateSchool() {
  filterClassOrGradeId.value.classId = "";
  filterClassOrGradeId.value.gradeId = "";
  fetchGradeTree();
  getList();
}

// 新增-获取班级未组队学生
async function getNoJoinStudentsList(classId, groupId) {
  Transferloading.value = true;
  try {
    const res = await getNotJoinStuInfoApi({
      classId: classId,
      groupId: groupId,
      subject: "英语",
    });
    if (res.code === 200) {
      classStudents.value = res.rows;
      Transferloading.value = false;
    }
  } catch {
    (err) => {
      console.log(err);
    };
  } finally {
    Transferloading.value = false;
  }
}
// 过滤学生
function filterStudentsMethod(query, item) {
  if (query) {
    return (
      item.stuName.indexOf(query) > -1 || String(item.stuNo).indexOf(query) > -1
    );
  } else {
    return item;
  }
}
// 添加按钮
async function handleAdd() {
  reset();
  if (!chooseClass.value.classId) {
    proxy.$modal.msgWarning("请选择班级");
  } else {
    title.value = "分组管理/添加学生分组";
    await getNoJoinStudentsList(chooseClass.value.classId, "");
    open.value = true;
    form.value.classId = chooseClass.value.classId;
    form.value.gradeId = chooseClass.value.gradeId;
    form.value.tenantId = filterData.value.tenantId
      ? filterData.value.tenantId
      : "";
  }
}
/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  title.value = "分组管理/编辑学生分组";
  form.value = { ...row };
  // 获取班级学生
  await getNoJoinStudentsList(row.classId, row.id);
  // 获取已加入的组员
  let res = await getAlreadyAddStuApi({ groupId: row.id });
  form.value.stuIds = res.total > 0 ? res.rows.map((item) => item.id) : [];
  open.value = true;
}
/** 删除按钮操作 */
function handleDelete(row) {
  const deleteId = row.id || ids.value;
  proxy.$modal
    .confirm("是否确认删除？")
    .then(() => {
      xbTable.value.loading = true;
      return deleteGroupApi(deleteId);
    })
    .then(() => {
      xbTable.value.loading = false;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .finally(() => {
      xbTable.value.loading = false;
    });
}
/** 取消按钮 */
function cancel() {
  reset();
  open.value = false;
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["diaRef"].validate((valid) => {
    if (valid) {
      if (form.value.id !== undefined) {
        updateGroupApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          reset();
          getList();
        });
      } else {
        addGroupApi({ ...form.value }).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          reset();
          getList();
        });
      }
    }
  });
}

// 获取年级树状
function fetchGradeTree() {
  gradeDataTree.value = [];
  treeLoading.value = true;
  getTenantGradeClassTreeApi({ tenantId: filterData.value.tenantId }).then(
    (res) => {
      let data = res.data;
      if (data.length > 0) {
        defaultExpandedId.value = data[0].tenantId;
        gradeDataTree.value = data.map((item) => ({
          label: item.tenantName,
          children: item.gradeList,
          id: item.tenantId,
        }));
        for (let i in gradeDataTree.value) {
          gradeDataTree.value[i].children = gradeDataTree.value[i].children.map(
            (item) => ({
              ...item,
              label: item.gradeName,
              children: item.scClassVos,
            })
          );
          let classVos = gradeDataTree.value[i].children;
          for (let j in classVos) {
            classVos[j].children = classVos[j].children
              ? classVos[j].children.map((item) => ({
                  ...item,
                  label: item.className,
                }))
              : [];
          }
        }
      }
      treeLoading.value = false;
    }
  );
}
async function handleDifferentRole() {
  if (useUserStore().showAllTenant) {
    // 超管
    setTimeout(() => {
      let schoolList = useUserStore().schoolList;
      filterData.value.tenantId = schoolList.length > 0 ? schoolList[0].id : "";
      fetchGradeTree();
      getList();
    }, 200);
  } else {
    fetchGradeTree();
    getList();
  }
}
handleDifferentRole();
</script>
<style lang="scss" scoped>
.grade_tree {
  height: 80vh;
  overflow-y: scroll;

  :deep(.el-tree-node.is-current > .el-tree-node__content) {
    background-color: #ddf2fd !important;
    border: 1px solid #3db2f1;
  }
  :deep(.el-tree-node__content) {
    display: block;
    width: 100%;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
}
.class_member {
  :deep(.el-checkbox) {
    margin-right: 0 !important;
  }
}
</style>
