<template>
	<div class="px-2 sm:px-4 pt-6 sm:rounded-lg">
		<div class="mb-4 sm:mb-6 col-span-full">
			<Breadcrumbs :names="['用户管理', '绑定部门']" :routes="[Routes.USERVIEW.fullPath()]" />
			<h1 class="text-xl sm:text-2xl mb-4 sm:mb-6 font-semibold text-gray-900">绑定部门</h1>
		</div>

		<TableFilterForm :filters="filterConfig" :initialValues="filterValues" @search="handleSearch"
			@update:values="updateFilterValues">
			<template #actions>
				<div class="flex gap-x-2">
					<TableButton variant="primary" @click="() => {
              if (checkedDepartmentIds.length === 0) {
                alertStore.showAlert({
                  content: '没有选择部门',
                  level: 'error',
                });
              } else {
                departmentBindModal?.show();
              }
            }">
						绑定
					</TableButton>
					<TableButton variant="danger" @click="() => {
              if (checkedDepartmentIds.length === 0) {
                alertStore.showAlert({
                  content: '没有选择部门',
                  level: 'error',
                });
              } else {
                departmentUnbindModal?.show();
              }
            }">
						解绑
					</TableButton>
				</div>
			</template>
		</TableFilterForm>

		<!-- 移动端卡片布局 -->
		<div class="md:hidden space-y-4">
			<MobileCardListWithCheckbox :items="departments || []" v-model="checkedDepartmentIds">
				<template #title="{ item }">
					{{ item.name }}
				</template>
				<template #status="{ item }">
					<div class="flex items-center">
						<div class="h-2.5 w-2.5 rounded-full me-2" :class="item.isBound ? 'bg-green-500' : 'bg-red-500'"></div>
						<span class="text-sm">{{ item.isBound === true ? "已绑定" : "未绑定" }}</span>
					</div>
				</template>
				<template #content="{ item }">
					<div>
						<p class="text-xs font-medium text-gray-600">上级部门</p>
						<p class="text-sm text-gray-900 mt-0.5">{{ !item.parentName ? '无' : item.parentName }}</p>
					</div>
				</template>
			</MobileCardListWithCheckbox>
		</div>

		<!-- PC端表格布局 -->
		<div class="hidden md:block">
			<TableFormLayout :items="departments || []" :columns="columns" :hasCheckbox="true" v-model="checkedDepartmentIds"
				@all-checked-change="allChecked = $event">
				<template #parentName="{ item }">
					{{ !item.parentName ? '无' : item.parentName }}
				</template>
				<template #name="{ item }">
					{{ item.name }}
				</template>
				<template #bindState="{ item }">
					<div class="flex items-center">
						<div class="h-2.5 w-2.5 rounded-full me-2" :class="item.isBound ? 'bg-green-500' : 'bg-red-500'"></div>
						{{ item.isBound === true ? "已绑定" : "未绑定" }}
					</div>
				</template>
			</TableFormLayout>
		</div>
		<TablePagination :pageChange="handlePageChange" :total="total" />
		<BindModal :id="'department-bind-modal'" :closeModal="() => {
    departmentBindModal!.hide();
  }" :onSubmit="handleBindDepartmentSubmit" title="绑定选中的部门吗"></BindModal>
		<UnModal :id="'department-unbind-modal'" :closeModal="() => {
    departmentUnbindModal!.hide();
  }" :onSubmit="handleUnbindDepartmentSubmit" title="解绑选中的部门吗"></UnModal>
	</div>

</template>

<script setup lang="ts">
import Breadcrumbs from "@/components/layout/Breadcrumbs.vue";
import BindModal from "@/components/modals/ConfirmationDialog.vue";
import UnModal from "@/components/modals/ConfirmationDialog.vue";
import MobileCardListWithCheckbox from "@/components/tables/MobileCardListWithCheckbox.vue";
import TableButton from "@/components/tables/TableButton.vue";
import TableFilterForm from "@/components/tables/TableFilterForm.vue";
import type { FilterItem } from "@/components/tables/TableFilterForm.vue";
import TableFormLayout from "@/components/tables/TableFormLayout.vue";
import TablePagination from "@/components/tables/TablePagination.vue";
import { useDepartmentBind } from "@/composables/department/useDepartmentBind";
import { useDepartmentQuery } from "@/composables/department/useDepartmentQuery";
import { useActionExcStore } from "@/composables/store/useActionExcStore";
import useAlertStore from "@/composables/store/useAlertStore";
import { Routes } from "@/router/constants";
import { Modal, type ModalInterface, initFlowbite } from "flowbite";
import { onMounted, reactive, ref, watch } from "vue";
import { useRoute } from "vue-router";

// 定义筛选配置
const filterConfig: FilterItem[] = [
	{
		type: "input",
		name: "departmentName",
		placeholder: "部门名",
	},
	{
		type: "select",
		name: "bindState",
		options: [
			{ value: "BIND", label: "已绑定" },
			{ value: "UNBIND", label: "未绑定" },
			{ value: "ALL", label: "全部" },
		],
	},
];

// 筛选值
const filterValues = reactive<{
	departmentName: string;
	bindState: "BIND" | "ALL" | "UNBIND";
}>({
	departmentName: "",
	bindState: "ALL",
});

// 更新筛选值
const updateFilterValues = (
	values: Record<string, string | number | boolean | Date[] | undefined>,
) => {
	if (values.departmentName !== undefined) {
		filterValues.departmentName = values.departmentName as string;
	}
	if (values.bindState !== undefined) {
		filterValues.bindState = values.bindState as "BIND" | "ALL" | "UNBIND";
	}
};

const checkedDepartmentIds = ref<number[]>([]);
const departmentBindModal = ref<ModalInterface>();
const departmentUnbindModal = ref<ModalInterface>();
const allChecked = ref<boolean>(false);
const $route = useRoute();

const alertStore = useAlertStore();
const actionExcStore = useActionExcStore();
const { total, departments, fetchDepartmentWith } = useDepartmentQuery();

const { bindDepartment, unbindDepartment } = useDepartmentBind();

// 定义表格列配置
const columns = [
	{ title: "上级部门", field: "parentName" },
	{ title: "部门名称", field: "name" },
	{ title: "绑定状态", field: "bindState" },
];

const handleBindDepartmentSubmit = async () => {
	await bindDepartment(
		Number($route.params.userId),
		checkedDepartmentIds.value,
	);
	clearCheckedDepartment();
	allChecked.value = false;
	departmentBindModal.value?.hide();
	alertStore.showAlert({
		content: "操作成功",
		level: "success",
	});
	await fetchDepartmentWith({
		name: filterValues.departmentName,
		userId: Number($route.params.userId),
		bindState: filterValues.bindState,
	});
};

const handleUnbindDepartmentSubmit = async () => {
	await unbindDepartment(
		Number($route.params.userId),
		checkedDepartmentIds.value,
	);
	clearCheckedDepartment();
	allChecked.value = false;
	departmentUnbindModal.value?.hide();
	alertStore.showAlert({
		content: "操作成功",
		level: "success",
	});
	await fetchDepartmentWith({
		name: filterValues.departmentName,
		userId: Number($route.params.userId),
		bindState: filterValues.bindState,
	});
};

onMounted(async () => {
	await fetchDepartmentWith({
		name: filterValues.departmentName,
		userId: Number($route.params.userId),
		bindState: filterValues.bindState,
	});
	initFlowbite();
	const $bindModalElement: HTMLElement | null = document.querySelector(
		"#department-bind-modal",
	);
	if ($bindModalElement) {
		departmentBindModal.value = new Modal($bindModalElement, {});
	}
	const $unbindModalElement: HTMLElement | null = document.querySelector(
		"#department-unbind-modal",
	);
	departmentUnbindModal.value = new Modal($unbindModalElement, {});
	actionExcStore.setCallback((result) => {
		if (result) {
			handleSearch();
		}
	});
});

const handleSearch = async () => {
	await fetchDepartmentWith({
		name: filterValues.departmentName,
		userId: Number($route.params.userId),
		bindState: filterValues.bindState,
	});
};

const handlePageChange = async (page: number, pageSize: number) => {
	await fetchDepartmentWith(
		{
			name: filterValues.departmentName,
			userId: Number($route.params.userId),
			bindState: filterValues.bindState,
		},
		page,
		pageSize,
	);
};

watch(allChecked, async () => {
	if (allChecked.value) {
		checkedDepartmentIds.value = departments.value?.map((r) => r.id!) ?? [];
	} else {
		checkedDepartmentIds.value = [];
	}
});

const clearCheckedDepartment = () => {
	checkedDepartmentIds.value = [];
};
</script>

<style scoped></style>
