<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">
        <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-dialog
      :title="title"
      v-model="open"
      width="600px"
      append-to-body
      :before-close="cancel"
    >
      <el-form ref="diaRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item
          v-if="useUserStore().showAllTenant"
          label="学校名称"
          prop="tenantId"
        >
          <SchoolSelect
            v-model="form.tenantId"
            @updateData="handleFormUpdateSchool"
          />
        </el-form-item>
        <el-form-item label="年级" prop="gradeId">
          <el-select v-model="form.gradeId" placeholder="请选择" clearable>
            <el-option
              v-for="dict in formSelectConfig.gradeOption"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input
            v-model="form.className"
            placeholder="请输入"
            clearable
            maxlength="50"
            @keyup="keyup"
          />
        </el-form-item>
        <el-form-item label="班主任姓名" prop="headTecId">
          <el-select
            v-model="form.headTecId"
            placeholder="请选择"
            clearable
            style="width: 200px"
            filterable
            remote
            reserve-keyword
            remote-show-suffix
          >
            <el-option
              v-for="dict in formSelectConfig.headTecOption"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            >
              <span>{{ dict.staNo }}-{{ dict.label }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="form.sort"
            :min="1"
            :precision="0"
            controls-position="right"
          />
        </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="classManage">
import Filter from "@/views/smartCampus/components/Filter/index.vue";
import Table from "@/views/smartCampus/components/Table/index.vue";
import useUserStore from "@/store/modules/user";
import {
  getGradeListApi,
  getStaffListApi,
  getClassListApi,
  addClassApi,
  updateClassApi,
  deleteClassApi,
} from "@/api/smartCampus/index";

const { proxy } = getCurrentInstance();
const selectConfig = ref({ gradeOption: [], headTecOption: [] });
const formSelectConfig = ref({ gradeOption: [], headTecOption: [] });
const filterData = ref({}); //过滤
const filterConfig = computed(() => {
  return [
    {
      comName: "admin",
      label: "学校名称",
      prop: "tenantId",
      placeholder: "请选择",
      clearable: true,
    },
    {
      comName: "el-select",
      label: "年级",
      prop: "gradeId",
      clearable: true,
      options: selectConfig.value.gradeOption,
      selectConfig: {
        label: "label",
        value: "value",
      },
    },
    {
      comName: "el-input",
      label: "班级",
      placeholder: "请输入",
      prop: "className",
      clearable: true,
    },
    {
      comName: "el-select",
      label: "班主任姓名",
      prop: "headTecId",
      clearable: true,
      options: selectConfig.value.headTecOption,
      selectConfig: {
        label: "label",
        value: "value",
      },
    },
  ];
});
const title = ref(""); //弹窗标题
const open = ref(false); //弹窗开关
// 弹窗数据
const data = reactive({
  form: {},
  rules: {
    tenantId: [
      { required: true, message: "学校名称不能为空", trigger: "change" },
    ],
    gradeId: [{ required: true, message: "年级不能为空", trigger: "blur" }],
    className: [
      { required: true, message: "班级名称不能为空", trigger: "blur" },
    ],
    headTecId: [
      { required: true, message: "班主任不能为空", trigger: "change" },
    ],
    sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
  },
});
const { form, rules } = toRefs(data);
const multiple = ref(true); //批量删除
const ids = ref([]); //批量删除的id
const xbTable = ref({
  loading: false,
  columns: [
    { type: "selection" },
    { prop: "gradeName", label: "年级" },
    { prop: "className", label: "班级" },
    { prop: "totalNum", label: "班级人数" },
    { prop: "headTecName", label: "班主任姓名" },
    { prop: "sort", label: "排序" },
    { label: "操作", slot: "operation" },
  ],
  tableData: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  },
});
// 检查英文符号
function replaceChineseBracketsInString(input) {
  const reg = /[\（\）]/g; // 中文括号的正则表达式
  const replacedString = input.replace(reg, function (match) {
    if (match === "（") {
      return "(";
    } else if (match === "）") {
      return ")";
    }
  });

  return replacedString;
}

function keyup(e) {
  e.target.value = replaceChineseBracketsInString(e.target.value);
}
/** 查询列表 */
function getList() {
  xbTable.value.loading = true;
  getClassListApi({ ...xbTable.value.pagination, ...filterData.value }).then(
    (res) => {
      xbTable.value.tableData = res.rows;
      xbTable.value.loading = false;
      xbTable.value.pagination.total = res.total;
    }
  );
}
// 过滤按钮
function handleFilterData(type) {
  switch (type.value) {
    case "search":
      getList();
      break;
    case "reset":
      xbTable.value.pagination.pageNum = 1;
      getList();
      if (useUserStore().showAllTenant) getSelectOption();
      break;
  }
}
// 超管
function handleUpdateSchool() {
  filterData.value.gradeId = "";
  filterData.value.headTecId = "";
  getSelectOption();
}
function handleFormUpdateSchool() {
  form.value.headTecId = "";
  form.value.gradeId = "";
  getFormSelectOption();
}
// 筛选条件下拉框数据
function getSelectOption() {
  selectConfig.value.gradeOption = [];
  selectConfig.value.headTecOption = [];
  // 年级
  getGradeListApi({ tenantId: filterData.value.tenantId }).then((res) => {
    if (res.code === 200 && res.total > 0) {
      for (let i in res.rows) {
        selectConfig.value.gradeOption.push({
          value: res.rows[i].id,
          label: res.rows[i].gradeName,
        });
      }
    }
  });
  // 班主任
  getStaffListApi({ tenantId: filterData.value.tenantId }).then((res) => {
    if (res.code === 200 && res.total > 0) {
      for (let i in res.rows) {
        selectConfig.value.headTecOption.push({
          value: res.rows[i].id,
          label: res.rows[i].name,
          staNo: res.rows[i].staNo,
        });
      }
    }
  });
}
// 表单内下拉框
function getFormSelectOption() {
  formSelectConfig.value.gradeOption = [];
  formSelectConfig.value.headTecOption = [];
  // 年级
  getGradeListApi({ tenantId: form.value.tenantId }).then((res) => {
    if (res.code === 200 && res.total > 0) {
      for (let i in res.rows) {
        formSelectConfig.value.gradeOption.push({
          value: res.rows[i].id,
          label: res.rows[i].gradeName,
        });
      }
    }
  });
  // 班主任
  getStaffListApi({ tenantId: form.value.tenantId }).then((res) => {
    if (res.code === 200 && res.total > 0) {
      for (let i in res.rows) {
        formSelectConfig.value.headTecOption.push({
          value: res.rows[i].id,
          label: res.rows[i].name,
          staNo: res.rows[i].staNo,
        });
      }
    }
  });
}
/** 表单重置 */
function reset() {
  form.value = {
    gradeId: undefined,
    className: undefined,
    headTecId: undefined,
    headTecName: undefined,
    sort: 1,
  };
  proxy.resetForm("diaRef");
}
// 添加按钮
function handleAdd() {
  reset();
  title.value = "班级管理/添加";
  open.value = true;
  getFormSelectOption();
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
// 表格勾选
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 handleUpdate(row) {
  reset();
  title.value = "班级管理/编辑";
  form.value = { ...row };
  open.value = true;
  getFormSelectOption();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const deleteId = row.id || ids.value;
  proxy.$modal
    .confirm("是否确认删除？")
    .then(() => {
      xbTable.value.loading = true;
      return deleteClassApi(deleteId);
    })
    .then(() => {
      xbTable.value.loading = false;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .finally(() => {
      xbTable.value.loading = false;
    });
}
/** 提交按钮 */
function submitForm() {
  form.value.className = replaceChineseBracketsInString(form.value.className);
  proxy.$refs["diaRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateClassApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addClassApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
// 超管
function handleAdminRole() {
  if (useUserStore().showAllTenant) {
    xbTable.value.columns.splice(1, 0, {
      prop: "tenantName",
      label: "学校名称",
    });
  }
}
handleAdminRole();
getList();
getSelectOption();
</script>
<style lang="scss" scoped></style>
