<template>
	<div class="sys-workforce-number-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent>
				<el-form-item label="关键词" prop="Keyword">
					<el-input v-model="state.queryParams.Keyword" placeholder="班次名称" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
					<el-button @click="resetQuery(ruleFormRef)" class="default-button" :loading="state.loading">
						<SvgIcon name="ele-Refresh" class="mr5" />重置
					</el-button>
				</el-form-item>
			</el-form>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
			>
				<template #buttons>
					<el-button type="primary" @click="onAdd" v-auth="'system:workforce:number:add'" :loading="state.loading"
						><SvgIcon name="ele-Plus" class="mr5" />新增班次
					</el-button>
					<el-button
						type="danger"
						@click="onDeleteMultiple"
						v-auth="'system:workforce:number:deleteMultiple'"
						:disabled="isChecked"
						:loading="state.loading"
						><SvgIcon name="ele-Delete" class="mr5" />删除
					</el-button>
				</template>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					border
					:loading="state.loading"
					:data="state.tableData"
					:column-config="{ resizable: true }"
					:row-config="{ isCurrent: true, isHover: true, height: 30,useKey: true }"
					ref="tableRef"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 100 }"
					id="systemWorkforceNumber"
					:custom-config="{ storage: true }"
					showHeaderOverflow
					@checkbox-all="selectAllChangeEvent"
					@checkbox-change="selectChangeEvent"
				>
					<vxe-column type="checkbox" width="50" align="center"></vxe-column>
					<vxe-column field="name" title="班次名称" min-width="200"></vxe-column>

					<vxe-column field="workingTime" title="上班时间" min-width="200"></vxe-column>
					<vxe-column field="offDutyTime" title="下班时间" min-width="200"></vxe-column>
					<vxe-column field="creationTime" title="创建时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="120" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onEdit(row)" title="编辑班次" v-auth="'system:workforce:number:edit'"> 编辑 </el-button>
							<el-button link type="danger" @click="onDelete(row)" title="查看日志明细" v-auth="'system:workforce:number:delete'"> 删除 </el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
			<pagination
				@pagination="queryList"
				:total="state.total"
				v-model:current-page="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
				:disabled="state.loading"
			/>
		</div>
		<!-- 新增修改班次 -->
		<number-edit ref="numberEditRef" @updateList="queryList" />
	</div>
</template>

<script lang="tsx" setup name="systemWorkforceNumber">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { getWorkforceClassList, deleteWorkforceClass } from '@/api/system/workforce';

// 引入组件
const NumberEdit = defineAsyncComponent(() => import('@/views/system/workforce/components/Number-edit.vue')); // 新增修改班次
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

// 定义变量内容
const state = reactive({
	queryParams: {
		PageIndex: 1, // 当前页
		PageSize: 20, // 每页条数
		Keyword: null, // 关键字
	},
	tableData: [], // 列表数据
	loading: false, // 加载
	total: 0, // 总条数
});
const ruleFormRef = ref<FormInstance>(); // 表单ref
/** 搜索按钮操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
/** 班次列表 */
const queryList = async () => {
	state.loading = true;
	try {
		const response = await getWorkforceClassList(state.queryParams);
		state.tableData = response.result?.items ?? [];
		state.total = response.result?.total ?? 0;
		state.loading = false;
	} catch (e) {
		state.loading = false;
		console.log(e);
	}
};
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
// 新增班次
const numberEditRef = ref<RefType>();
const onAdd = () => {
	numberEditRef.value.openDialog();
};
// 编辑班次
const onEdit = (row: any) => {
	numberEditRef.value.openDialog(row.id);
};
// 删除班次
const onDelete = (row: any) => {
	ElMessageBox.confirm(`确定删除【${row.name}】该班次？若当前班次已排班，删除后该班次将替换为休息日！是否确定删除？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
	})
		.then(() => {
			deleteWorkforceClass({ ids: [row.id] }).then(() => {
				queryList();
				ElMessage.success('删除成功');
			});
		})
		.catch(() => {
			console.log('取消删除');
		});
};
// 批量删除班次
const onDeleteMultiple = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	ElMessageBox.confirm(`确定删除选中的班次？若当前班次已排班，删除后该班次将替换为休息日！是否确定删除？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
	})
		.then(() => {
			deleteWorkforceClass({ ids }).then(() => {
				queryList();
				ElMessage.success('删除成功');
			});
		})
		.catch(() => {
			console.log('取消删除');
		});
};
const tableRef = ref<RefType>();
const checkTable = ref<EmptyArrayType>([]);
const selectAllChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !Boolean(checkTable.value.length);
});
const toolbarRef = ref<RefType>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
