<template>
  <div class="app-container">
    <Filter
      v-model="filterData"
      :config="filterConfig"
      @handleAction="handleFilterData"
    />
    <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-row>
    <!-- 表格 -->
    <Table :xbTable="xbTable" @tablePageChange="handleTablePageChange">
      <template v-slot:status="scope">
        <span>{{ scope.row.status === 0 ? "启用" : "停用" }}</span>
      </template>
      <template v-slot:operation="scope">
        <el-button
          link
          type="primary"
          icon="Edit"
          @click="handleUpdate(scope.row)"
          >编辑</el-button
        >
        <el-button
          v-if="!scope.row.children || !scope.row.children.length"
          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 && title.includes('添加')"
          label="学校名称"
          prop="tenantId"
        >
          <SchoolSelect
            v-model="form.tenantId"
            @updateData="updateChangeSchool"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName">
          <el-input
            v-model="form.deptName"
            placeholder="请输入"
            clearable
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="上级部门" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="schoolDeptList"
            :render-after-expand="false"
            check-strictly
            :props="deptProps"
            placeholder="请选择"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number
            v-model="form.orderNum"
            :min="1"
            :precision="0"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status" class="ml-4">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </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="deptManage">
import Filter from "@/views/smartCampus/components/Filter/index.vue";
import Table from "@/views/smartCampus/components/Table/index.vue";
import {
  getDeptListApi,
  addDeptApi,
  updateDeptApi,
  deleteDeptApi,
  getDeptDetailsApi,
} from "@/api/smartCampus/index";
import useUserStore from "@/store/modules/user";
const { proxy } = getCurrentInstance();
const tableExpands = ref([]); //表单展开项
const filterData = ref({}); //过滤
const schoolDeptList = ref([]);
const filterConfig = computed(() => {
  return [
    {
      comName: "admin",
      label: "学校名称",
      prop: "tenantId",
      placeholder: "请选择",
      clearable: true,
    },
    {
      comName: "el-input",
      label: "部门名称",
      placeholder: "请输入",
      prop: "deptName",
      clearable: true,
    },
  ];
});
const title = ref(""); //弹窗标题
const open = ref(false); //弹窗开关
const deptProps = { label: "deptName", value: "id", children: "children" };
// 弹窗数据
const data = reactive({
  form: {},
  rules: {
    tenantId: [
      { required: true, message: "学校名称不能为空", trigger: "change" },
    ],
    deptName: [
      { required: true, message: "部门名称不能为空", trigger: "blur" },
    ],
    parentId: [
      { required: true, message: "上级部门不能为空", trigger: "blur" },
    ],
    orderNum: [{ required: true, message: "排序不能为空", trigger: "blur" }],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
  },
});
const { form, rules } = toRefs(data);

const xbTable = ref({
  loading: false,
  columns: [
    { prop: "deptName", label: "部门名称" },
    { prop: "orderNum", label: "排序" },
    { prop: "status", label: "状态", slot: "status" },
    { label: "操作", slot: "operation" },
  ],
  tableData: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  },
});
/** 查询列表 */
function getList() {
  xbTable.value.loading = true;
  getDeptListApi({ ...xbTable.value.pagination, ...filterData.value }).then(
    (res) => {
      xbTable.value.tableData = res.data;
      xbTable.value.loading = false;
    }
  );
}
// 表单部门列表
function getFormDeptList(tenantId) {
  getDeptListApi({ tenantId }).then((res) => {
    schoolDeptList.value = res.data;
  });
}
// 过滤按钮
function handleFilterData(type) {
  switch (type.value) {
    case "search":
      getList();
      break;
    case "reset":
      xbTable.value.pagination.pageNum = 1;
      handleDifferentRole();
      break;
  }
}

/** 表单重置 */
function reset() {
  form.value = {
    deptName: undefined,
    parentId: undefined,
    orderNum: 1,
    status: "0",
  };
  proxy.resetForm("diaRef");
}
// 添加按钮
function handleAdd() {
  reset();
  title.value = "部门管理/添加";
  open.value = true;
  form.value.tenantId = filterData.value.tenantId;
  getFormDeptList(form.value.tenantId);
}
function updateChangeSchool() {
  form.value.parentId = "";
  getFormDeptList(form.value.tenantId);
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

// 表格分页
function handleTablePageChange(val) {
  xbTable.value.pagination.pageSize = val.limit;
  xbTable.value.pagination.pageNum = val.page;
  getList();
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  title.value = "部门管理/编辑";
  getDeptDetailsApi(row.id).then((res) => {
    if (res.code === 200) {
      form.value = res.data;
      open.value = true;
      getFormDeptList(form.value.tenantId);
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm("是否确认删除？")
    .then(() => {
      xbTable.value.loading = true;
      return deleteDeptApi(row.id);
    })
    .then(() => {
      xbTable.value.loading = false;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .finally(() => {
      xbTable.value.loading = false;
    });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["diaRef"].validate((valid) => {
    if (valid) {
      if (form.value.deptId != undefined) {
        updateDeptApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDeptApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
async function handleDifferentRole() {
  if (useUserStore().showAllTenant) {
    // 超管
    setTimeout(() => {
      let schoolList = useUserStore().schoolList;
      filterData.value.tenantId = schoolList.length > 0 ? schoolList[0].id : "";
      getList();
    }, 200);
  } else {
    getList();
  }
}
handleDifferentRole();
</script>
<style lang="scss" scoped></style>
