<template>
  <div class="app-container">
    <Filter
      v-model="filterData"
      :config="filterConfig"
      @handleAction="handleFilterData"
      @updateSchool="handleUpdateSchool"
    />
    <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">
        <FileUpload
          uploadUrl="/sc/stu/ht/import"
          :isShowTip="false"
          buttonText="导入"
          @handleSuccessUplaod="handleSuccessUplaod"
        />
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain @click="handleImportTemplate"
          >下载导入模板</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:grade="scope">
        <span v-for="i in selectConfig.gradeOption" :key="i.value">
          {{ scope.row.gradeId === i.id ? i.gradeName : "" }}
        </span>
      </template>
      <template v-slot:class="scope">
        <span v-for="i in selectConfig.classOption" :key="i.value">
          {{ scope.row.classId === i.id ? i.className : "" }}
        </span>
      </template>
      <template v-slot:sex="scope">
        <span v-if="scope.row.sex === 0">男</span>
        <span v-if="scope.row.sex === 1">女</span>
      </template>
      <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>
    <StudentDia
      v-model="open"
      :detailInfo="detailInfo"
      :selectOption="selectConfig"
      :gradeClassTree="gradeClassTree"
      @success="handleSuccessDia"
      @cancel="handleCancelDia"
    />
  </div>
</template>

<script setup name="studentsManage">
import Filter from "@/views/smartCampus/components/Filter/index.vue";
import Table from "@/views/smartCampus/components/Table/index.vue";
import StudentDia from "./studentDia.vue";
import {
  getSelectDownData,
  useFetchGradeClassTree,
} from "@/utils/dropDownData";
import {
  getStudentListApi,
  getClassListApi,
  getGradeListApi,
  deleteStudentApi,
} from "@/api/smartCampus/index";
import useUserStore from "@/store/modules/user";
const { proxy } = getCurrentInstance();
const open = ref(false);
const ids = ref([]); //批量删除ids
const multiple = ref(true); //批量删除按钮
const studentFile = ref(); //导入文件
const filterData = ref({}); //过滤
const detailInfo = ref({}); //点击学生数据
const gradeClassTree = ref([]);
const selectConfig = ref({
  relationOption: [], //家长称谓
  gradeOption: [],
  classOption: [],
  sexOption: [],
  gradeDataTree: [],
  educationDict: [], //学段
});
const filterConfig = computed(() => {
  return [
    {
      comName: "admin",
      label: "学校名称",
      prop: "tenantId",
      placeholder: "请选择",
      clearable: true,
    },
    {
      comName: "el-tree-select",
      label: "班级",
      placeholder: "请选择",
      prop: "search",
      clearable: true,
      options: selectConfig.value.gradeDataTree,
      selectConfig: {
        label: "name",
        value: "name",
        children: "children",
      },
    },
    {
      comName: "el-select",
      label: "性别",
      placeholder: "请输入",
      prop: "sex",
      clearable: true,
      options: selectConfig.value.sexOption,
      selectConfig: {
        label: "label",
        value: "value",
      },
    },
    {
      comName: "el-input",
      label: "学号",
      prop: "stuNo",
      placeholder: "请输入",
      clearable: true,
    },
    {
      comName: "el-input",
      label: "学生姓名",
      prop: "stuName",
      placeholder: "请输入",
      clearable: true,
    },
  ];
});
const xbTable = ref({
  loading: false,
  columns: [
    { type: "selection" },
    { prop: "gradeId", label: "年级", slot: "grade" },
    { prop: "classId", label: "班级", slot: "class" },
    { prop: "stuNo", label: "学号" },
    { prop: "stuName", label: "姓名" },
    { prop: "sex", label: "性别", slot: "sex" },
    { label: "操作", slot: "operation" },
  ],
  tableData: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  },
});

// 过滤按钮
function handleFilterData(type) {
  switch (type.value) {
    case "search":
      getList();
      break;
    case "reset":
      xbTable.value.pagination.pageNum = 1;
      getList();
      break;
  }
}

/** 查询列表 */
function getList() {
  xbTable.value.loading = true;
  getStudentListApi({ ...xbTable.value.pagination, ...filterData.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 handleSuccessUplaod(val) {
  proxy.$modal.msgSuccess("导入成功");
  getList();
}
// 下载导入模版
function handleImportTemplate() {
  proxy.download(
    "/sc/stu/ht/getImportTemplate",
    {},
    `student_template_${new Date().getTime()}.xlsx`
  );
}
/** 新增按钮操作 */
function handleAdd() {
  open.value = true;
  detailInfo.value = {};
}

/** 删除按钮操作 */
function handleDelete(row) {
  const deleteId = row.id || ids.value;
  proxy.$modal
    .confirm("是否确认删除？")
    .then(() => {
      xbTable.value.loading = true;
      return deleteStudentApi(deleteId);
    })
    .then(() => {
      xbTable.value.loading = false;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .finally(() => {
      xbTable.value.loading = false;
    });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  open.value = true;
  detailInfo.value = row;
}
// 编辑或新增成功
function handleSuccessDia(val) {
  open.value = val;
  getList();
}
function handleCancelDia(val) {
  open.value = val;
  detailInfo.value = {};
}
function handleTree(data) {
  let arr = data[0]?.children;
  gradeClassTree.value = arr;
  console.log("handleTree", data, gradeClassTree.value);
}
// 获取下拉数据
async function getSelectOption() {
  selectConfig.value.relationOption = await getSelectDownData("relation");
  selectConfig.value.sexOption = await getSelectDownData("sex");
  selectConfig.value.gradeDataTree = await getSelectDownData("gradeClassTree");
  handleTree(selectConfig.value.gradeDataTree);
  let dictObj = await getSelectDownData("dict", "sc_education");
  selectConfig.value.educationDict = dictObj[0].sysDictData;

  // 年级
  getGradeListApi().then((res) => {
    if (res.code === 200) {
      selectConfig.value.gradeOption = res.rows;
    }
  });
  // 班级
  getClassListApi().then((res) => {
    if (res.code === 200) {
      selectConfig.value.classOption = res.rows;
    }
  });
}

// 超管
async function handleUpdateSchool() {
  filterData.value.search = "";
  selectConfig.value.gradeDataTree = await useFetchGradeClassTree({
    tenantId: filterData.value.tenantId,
  });
}
function handleAdminRole() {
  if (useUserStore().showAllTenant) {
    xbTable.value.columns.splice(1, 0, {
      prop: "tenantName",
      label: "学校名称",
    });
  }
}
handleAdminRole();
getSelectOption();
getList();
</script>
