<script setup lang="ts">
import { reactive, onMounted, ref, nextTick } from "vue";
import { getDepartmentTree, getDepartmentList, removeDepartment } from "@/api/department";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessage, ElMessageBox } from "element-plus";
import DepartmentDialog from "./dialog.vue";

defineOptions({ name: "AdminDepartment" });

const queryRef = ref();
const tableRef = ref();
const dialogRef = ref();
const treeRef = ref();

const state = reactive({
  formQuery: {
    name: "",
    parent: null as number | null
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false,
    columns: [
      { label: "部门名称", prop: "name", width: 160 },
      { label: "上级部门", prop: "parentName", width: 160 },
      { label: "部门全称", prop: "fullName", width: 200 },
      { label: "部门层级", prop: "level", width: 100 },
      { label: "排序", prop: "weight", width: 80 },
      { label: "更新时间", prop: "updateAt", width: 180 }
    ]
  },
  treeData: [] as any[],
  filterText: "",
  selectedNode: null as any
});

onMounted(() => {
  loadTreeData();
  loadData();
  nextTick(() => {
    const bodyHeight = document.body.clientHeight;
    const queryHeight = queryRef.value?.$el?.clientHeight || 0;
    state.tableData.height = bodyHeight - queryHeight - 250;
  });
});

const loadTreeData = () => {
  getDepartmentTree().then((res: any) => {
    state.treeData = res || [];
  });
};

const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  getDepartmentList({
    ...state.formQuery,
    ...state.pageQuery
  })
    .then((res: any) => {
      const { list, total } = res || {};
      state.tableData.data = list || [];
      state.pageQuery.total = total || 0;
    })
    .catch(() => {
      state.tableData.data = [];
    })
    .finally(() => {
      state.tableData.loading = false;
    });
};

const handleNodeClick = (data: any) => {
  if (state.selectedNode?.id === data.id) {
    state.selectedNode = null;
    state.formQuery.parent = null;
  } else {
    state.selectedNode = data;
    state.formQuery.parent = data.id;
  }
  loadData(true);
};

const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name?.includes(value);
};

const handleFilterChange = () => {
  treeRef.value?.filter(state.filterText);
};

const handleSizeChange = (size: number) => {
  state.pageQuery.pageSize = size;
  loadData(true);
};

const handleCurrentChange = (page: number) => {
  state.pageQuery.pageNum = page;
  loadData();
};

const handleSearch = () => {
  loadData(true);
};

const handleReset = () => {
  state.formQuery = {
    name: "",
    parent: null
  };
  state.selectedNode = null;
  loadData(true);
};

const handleAdd = () => {
  dialogRef.value?.open("add");
};

const handleEdit = (row: any) => {
  dialogRef.value?.open("edit", row);
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除部门『${row.name}』吗？`,
    "提示",
    { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
  ).then(() => {
    removeDepartment(row.id).then(() => {
      ElMessage.success("删除成功");
      loadTreeData();
      loadData(true);
    });
  }).catch(() => {});
};
</script>

<template>
  <div class="page-container">
    <el-row :gutter="15">
      <el-col :span="6">
        <el-card shadow="hover" class="tree-card">
          <el-input
            v-model="state.filterText"
            placeholder="搜索部门"
            clearable
            @input="handleFilterChange"
            class="mb-3"
          />
          <el-tree
            ref="treeRef"
            :data="state.treeData"
            :props="{ label: 'name', children: 'children' }"
            node-key="id"
            highlight-current
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card shadow="hover">
          <el-form ref="queryRef" :model="state.formQuery" inline class="search-form">
            <el-form-item label="部门名称">
              <el-input
                v-model="state.formQuery.name"
                placeholder="请输入部门名称"
                clearable
                style="width: 160px"
                @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :icon="useRenderIcon('ri/search-line')"
                @click="handleSearch"
              >
                查询
              </el-button>
              <el-button
                :icon="useRenderIcon('ri/refresh-line')"
                @click="handleReset"
              >
                重置
              </el-button>
              <el-button
                type="success"
                :icon="useRenderIcon('ri/add-line')"
                @click="handleAdd"
              >
                新增部门
              </el-button>
            </el-form-item>
          </el-form>

          <el-table
            ref="tableRef"
            v-loading="state.tableData.loading"
            :data="state.tableData.data"
            :height="state.tableData.height"
            border
            stripe
          >
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
            <el-table-column
              v-for="col in state.tableData.columns"
              :key="col.prop"
              :prop="col.prop"
              :label="col.label"
              :width="col.width"
              show-overflow-tooltip
            />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link size="small" @click="handleEdit(row)">修改</el-button>
                <el-button
                  type="danger"
                  link
                  size="small"
                  :disabled="row.parent === 0"
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="state.pageQuery.pageNum"
              v-model:page-size="state.pageQuery.pageSize"
              :total="state.pageQuery.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <DepartmentDialog ref="dialogRef" @refresh="() => { loadTreeData(); loadData(true); }" />
  </div>
</template>

<style scoped lang="scss">
.page-container {
  padding: 15px;
}

.tree-card {
  height: 100%;

  :deep(.el-tree) {
    .el-tree-node__content {
      height: 36px;
    }
  }
}

.search-form {
  margin-bottom: 15px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.mb-3 {
  margin-bottom: 12px;
}
</style>
