<template>
  <div class="app-container">
    <Filter
      v-model="filterData"
      :config="filterConfig"
      @handleAction="handleFilterData"
      @updateSchool="hanldeUpdateSchool"
      @focusTreeSelect="handleFocusTreeSelect"
    />
    <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/staff/ht/insertBatch"
          :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:sex="scope">
        <span>{{ scope.row.sex === 0 ? "男" : "女" }}</span>
      </template>
      <template v-slot:operation="scope">
        <el-button
          link
          type="primary"
          icon="Edit"
          @click="handleUpdate(scope.row)"
          >编辑</el-button
        >
        <el-button
          link
          type="primary"
          @click="handleResetPwd(scope.row)"
          icon="Edit"
          >重置密码</el-button
        >
        <el-button
          link
          type="danger"
          icon="Delete"
          @click="handleDelete(scope.row)"
          >删除</el-button
        >
      </template>
    </Table>
    <StaffDia
      v-model="open"
      :detailInfo="detailInfo"
      :selectOption="selectConfig"
      @success="handleSuccessDia"
      @cancel="handleCancelDia"
    />
  </div>
</template>

<script setup name="staffManage">
import { ElMessage } from "element-plus";
import Filter from "@/views/smartCampus/components/Filter/index.vue";
import Table from "@/views/smartCampus/components/Table/index.vue";
import StaffDia from "./staffDia.vue";
import {
  getStaffListApi,
  deleteStaffApi,
  getDeptListApi,
} from "@/api/smartCampus/index";
import { resetStaffPasswordApi } from "@/api/login";
import { getSelectDownData } from "@/utils/dropDownData";
import useUserStore from "@/store/modules/user";
const { proxy } = getCurrentInstance();

const open = ref(false);
const detailInfo = ref({}); //详情
const ids = ref([]); //批量删除ids
const multiple = ref(true); //批量删除按钮
const filterData = ref({}); //过滤
const selectConfig = ref({
  deptOption: [],
  sexOption: [],
  subjectOption: [],
});
const filterConfig = computed(() => {
  return [
    {
      comName: "admin",
      label: "学校名称",
      prop: "tenantId",
      placeholder: "请选择",
      clearable: true,
    },
    {
      comName: "el-tree-select",
      label: "部门",
      prop: "deptId",
      clearable: true,
      options: selectConfig.value.deptOption,
      selectConfig: {
        label: "deptName",
        value: "id",
        children: "children",
      },
    },
    {
      comName: "el-input",
      label: "教职工号",
      prop: "staNo",
      placeholder: "请输入",
      clearable: true,
    },

    {
      comName: "el-select",
      label: "性别",
      placeholder: "请输入",
      prop: "sex",
      clearable: true,
      options: selectConfig.value.sexOption,
      selectConfig: {
        label: "label",
        value: "value",
      },
    },
    {
      comName: "el-input",
      label: "联系电话",
      prop: "phone",
      placeholder: "请输入",
      clearable: true,
    },
    {
      comName: "el-input",
      label: "老师姓名",
      prop: "name",
      placeholder: "请输入",
      clearable: true,
    },
  ];
});
const xbTable = ref({
  loading: false,
  columns: [
    { type: "selection" },
    { prop: "name", label: "姓名" },
    { prop: "staNo", label: "教职工号" },
    { prop: "deptName", label: "部门" },
    { prop: "phone", label: "联系电话" },
    { prop: "sex", label: "性别", slot: "sex" },
    { label: "操作", slot: "operation" },
  ],
  tableData: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  },
});
// 导入
function handleSuccessUplaod(val) {
  proxy.$modal.msgSuccess("导入成功");
  getList();
}
// 下载导入模版
function handleImportTemplate() {
  proxy.download(
    "/sc/staff/ht/getStaffTemplate",
    {},
    `teacher_template_${new Date().getTime()}.xlsx`
  );
}
// 过滤按钮
function handleFilterData(type) {
  switch (type.value) {
    case "search":
      getList();
      break;
    case "reset":
      xbTable.value.pagination.pageNum = 1;
      if (useUserStore().showAllTenant) {
        selectConfig.value.deptOption = [];
      }
      getList();
      break;
  }
}
// 筛选学校
function hanldeUpdateSchool() {
  filterData.value.deptId = "";
  if (filterData.value.tenantId) {
    fetchSchoolDeptList();
  } else {
    selectConfig.value.deptOption = [];
  }
}
// 部门选择框
function handleFocusTreeSelect() {
  if (useUserStore().showAllTenant && !filterData.value.tenantId) {
    ElMessage.warning("请选择学校名称");
  }
}
/** 查询列表 */
function getList() {
  xbTable.value.loading = true;
  getStaffListApi({ ...xbTable.value.pagination, ...filterData.value })
    .then((res) => {
      xbTable.value.tableData = res.rows;
      xbTable.value.loading = false;
      xbTable.value.pagination.total = res.total;
    })
    .catch((err) => {
      xbTable.value.loading = false;
    });
}
// 表格勾选
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 handleAdd() {
  open.value = true;
  detailInfo.value = {};
}
/** 取消按钮 */
function cancel() {
  open.value = false;
}
// 编辑或新增成功
function handleSuccessDia(val) {
  open.value = val;
  getList();
}
function handleCancelDia(val) {
  open.value = val;
  detailInfo.value = {};
}
/** 删除按钮操作 */
function handleDelete(row) {
  const deleteId = row.id || ids.value;
  proxy.$modal
    .confirm("是否确认删除？")
    .then(() => {
      xbTable.value.loading = true;
      return deleteStaffApi(deleteId);
    })
    .then(() => {
      xbTable.value.loading = false;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .finally(() => {
      xbTable.value.loading = false;
    });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  detailInfo.value = row;
  open.value = true;
}
/** 重置密码 */
function handleResetPwd(row) {
  proxy.$modal
    .confirm("确定重置该用户的登录密码吗？")
    .then(() => {
      return resetStaffPasswordApi({ id: row.id });
    })
    .then(() => {
      proxy.$modal.msgSuccess("重置成功");
    });
}
// 获取对应学校部门
function fetchSchoolDeptList() {
  getDeptListApi({ tenantId: filterData.value.tenantId }).then((res) => {
    if (res.code === 200) {
      selectConfig.value.deptOption = res.data;
    }
  });
}
// 获取下拉数据
async function getSelectOption() {
  selectConfig.value.sexOption = await getSelectDownData("sex");
  selectConfig.value.subjectOption = await getSelectDownData("subject");
  if (!useUserStore().showAllTenant) {
    fetchSchoolDeptList();
  }
}
// 超管
function handleAdminRole() {
  if (useUserStore().showAllTenant) {
    xbTable.value.columns.splice(1, 0, {
      prop: "tenantName",
      label: "学校名称",
    });
  }
}
// async function handleDifferentRole() {
//   if (useUserStore().showAllTenant) {
//     // 超管
//     setTimeout(() => {
//       let schoolList = useUserStore().schoolList;
//       filterData.value.tenantId = schoolList.length > 0 ? schoolList[0].id : "";
//       getList();
//     }, 200);
//   } else {
//     getList();
//   }
// }
handleAdminRole();
getSelectOption();
getList();
</script>
