﻿<template>
	<div class="mesBusLog-container">
		<el-dialog v-model="state.isShowDialog" v-if="state.isShowDialog" width="90%" draggable="" :close-on-click-modal="false" @close="closeDialog">
			<template #header>
				<div style="color: #fff">
					<span>{{ props.title }}</span>
				</div>
			</template>
			<div style="width: 100%; display: flex; justify-content: space-between">
				<div style="width: 49.5%">
					<el-card style="padding: 5px">
						<el-form :model="ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
							<el-row :gutter="35">
								<el-col :span="24">
									<el-form-item label=" " style="padding-bottom: 20px">
										<el-radio-group v-model="workupTab" size="default">
											<el-radio-button label="按人员上工" :value="1" />
											<!-- <el-radio-button label="按工作组上工" :value="2" /> -->
										</el-radio-group>
									</el-form-item>
								</el-col>
								<template v-if="workupTab == 1">
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
										<el-form-item label="上工工位" prop="workSiteCode">
											<el-select filterable="" v-model="ruleForm.workSiteCode" placeholder="请选择上工工位" clearable @change="getWorkSiteName">
												<el-option v-for="(item, index) in worksiteList" :key="index" :value="item.value" :label="item.label" />
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
										<el-form-item label="人员编码" prop="personCode">
											<el-input v-model="ruleForm.personCode" placeholder="请输入人员编码" clearable @keyup.enter.stop="searchPersonListByPersonCode">
												<template #append>
													<el-icon class="el-input__icon" style="cursor: pointer" @click="searchPersonListByPersonCode">
														<ele-FullScreen />
													</el-icon>
												</template>
											</el-input>
										</el-form-item>
									</el-col>
								</template>
								<!--                <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" class="mb20">-->
								<!--                  <el-form-item label="人员名称" prop="opAccount">-->
								<!--                    <el-input v-model="ruleForm.opAccount" placeholder="请输入人员名称" clearable />-->
								<!--                  </el-form-item>-->
								<!--                </el-col>-->

								<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="workupTab == 2">
									<el-form-item label="工作组" prop="workGroupCode">
										<!--                    <el-input v-model="ruleForm.workGroupCode" placeholder="请输入工作组编号" clearable />-->
										<el-select filterable="" v-model="ruleForm.workGroupCode" placeholder="请选择工作组" clearable>
											<el-option v-for="(item, index) in workGroupList" :key="index" :value="item.value" :label="item.label" />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" class="mb20" v-if="workupTab == 2">
									<el-button @click="ruleForm = {}">重 置</el-button>
									<el-button type="primary" @click="seachPersonByWorkGroup">搜索</el-button>
								</el-col>

								<!--                <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" class="mb20">-->
								<!--                  <el-form-item label="工作组名称" prop="opResult">-->
								<!--                    <el-input v-model="ruleForm.opResult" placeholder="请输入工作组名称" disabled />-->
								<!--                  </el-form-item>-->
								<!--                </el-col>-->
							</el-row>
						</el-form>
						<div>
							<div style="color: var(--el-color-primary); margin-bottom: 10px">人员信息</div>
							<el-table :data="peopletableData" ref="tableRef" style="width: 100%" v-loading="peopleloading" tooltip-effect="light" row-key="id" border="" @selection-change="onSelectionChange">
								<!-- <el-table-column type="selection" width="55" /> -->
								<el-table-column type="index" label="序号" width="55" align="center" />
								<el-table-column prop="workSiteCode" label="工位编码" show-overflow-tooltip="" />
								<el-table-column prop="workSiteName" label="工位名称" show-overflow-tooltip="" />
								<el-table-column prop="personCode" label="人员编码" show-overflow-tooltip="" />
								<el-table-column prop="personName" label="人员名称" show-overflow-tooltip="" />
							</el-table>
							<el-pagination
								v-model:currentPage="peopletableParams.page"
								v-model:page-size="peopletableParams.pageSize"
								:total="peopletableParams.total"
								:page-sizes="[10, 20, 50, 100, 200, 500]"
								small=""
								background=""
								@size-change="peoplehandleSizeChange"
								@current-change="peoplehandleCurrentChange"
								layout="total, sizes, prev, pager, next, jumper"
							/>
						</div>
						<div style="width: 100%; display: flex; flex-direction: column; align-items: center">
							<div style="margin-top: 10px; display: flex; justify-content: space-between; width: 40%">
								<el-button type="primary" :disabled="peopletableData.length == 0" @click="signin">签 到</el-button>
								<!-- <el-button type="primary" :disabled="selectionList.length == 0" @click="signout">签 退</el-button> -->
								<!-- <el-button type="primary" :disabled="selectionList.length == 0" @click="removePerson">移除人员</el-button> -->
							</div>
						</div>
					</el-card>
				</div>
				<div style="width: 49.5%">
					<!-- <el-card style="padding: 5px">
						<div style="color: var(--el-color-primary); margin-bottom: 10px">考勤记录</div>
						<el-table :data="attenTableList" style="width: 100%" v-loading="checkloading" tooltip-effect="light" row-key="id" border="">
							<el-table-column type="index" label="序号" width="55" align="center" />
							<el-table-column prop="workSiteCode" label="工位编码" show-overflow-tooltip="" />
							<el-table-column prop="account" label="上岗人工号" show-overflow-tooltip="" />
							<el-table-column prop="name" label="姓名" show-overflow-tooltip="" />
							<el-table-column prop="onlineDate" label="签到时间" width="140" />
							<el-table-column prop="offlineDate" label="签退时间" width="140" />
							<el-table-column prop="totalTime" label="时长(分)" show-overflow-tooltip="" />
						</el-table>
						           <el-pagination v-model:currentPage="checktableParams.page" v-model:page-size="checktableParams.pageSize" :total="checktableParams.total" :page-sizes="[10, 20, 50, 100, 200, 500]" small="" background="" @size-change="checkhandleSizeChange" @current-change="checkhandleCurrentChange" layout="total, sizes, prev, pager, next, jumper" />
					</el-card> -->
					<el-card style="margin-top: 5px; padding: 5px">
						<div style="color: var(--el-color-primary); margin-bottom: 10px">当前在岗记录</div>
						<el-table :data="presenttableData" style="width: 100%" v-loading="presentloading" tooltip-effect="light" row-key="id" border="">
							<el-table-column type="index" label="序号" width="55" align="center" />
							<el-table-column prop="account" label="人员编码" show-overflow-tooltip="" />
							<el-table-column prop="name" label="人员名称" show-overflow-tooltip="" />
							<el-table-column prop="produceWorkOrderNo" label="在岗计划" show-overflow-tooltip="" />
							<el-table-column prop="productionLineName" label="在岗线体" show-overflow-tooltip="">
								<template #default="scope">
									{{ scope.row.productionLineInfo?.productionLineName }}
								</template>
							</el-table-column>
							<el-table-column prop="workSiteName" label="工位" show-overflow-tooltip="" />
							<el-table-column prop="totalTime" label="工时(分)" show-overflow-tooltip="" />
							<el-table-column prop="workStartTime" label="操作" show-overflow-tooltip="" width="80">
								<template #default="scope">
									<el-button type="primary" @click="signoutOne(scope.row)">下 工</el-button>
								</template>
							</el-table-column>
						</el-table>
						<el-pagination
							v-model:currentPage="presenttableParams.page"
							v-model:page-size="presenttableParams.pageSize"
							:total="presenttableParams.total"
							:page-sizes="[10, 20, 50, 100, 200, 500]"
							small=""
							background=""
							@size-change="presenthandleSizeChange"
							@current-change="presenthandleCurrentChange"
							layout="total, sizes, prev, pager, next, jumper"
						/>
					</el-card>
				</div>
			</div>
		</el-dialog>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormRules } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { getAttenList, getOnlineRecord, getPersonByAccount, getPersonByWorkGroupInfo, getWorkSiteList, personOffline, personOnline } from '/@/api/mes/mesControlBoard';
import { pageMesWorkGroup } from '/@/api/mes/mesWorkGroup';

//父级传递来的参数
var props = defineProps({
	title: {
		type: String,
		default: '',
	},
	productionLineCode: {
		type: String,
		default: '',
	},
	produceWorkOrderNo: {
		type: String,
		default: '',
	},
});

//自行添加其他规则
const rules = ref<FormRules>({
	workSiteCode: [{ required: true, message: '请选择工位！', trigger: 'blur' }],
	workGroupCode: [{ required: true, message: '请选择工作组！', trigger: 'blur' }],
});

const workupTab = ref(1);

//父级传递来的函数，用于回调
const emit = defineEmits(['reloadTable']);
const ruleFormRef = ref();
const peopletableData = ref<any>([]);
const peopleloading = ref(false);
const peopletableParams = ref({
	page: 1,
	pageSize: 10,
	total: 0,
});
const peoplehandleSizeChange = (val: number) => {
	peopletableParams.value.pageSize = val;
	handleQuery();
};
// 改变页码序号
const peoplehandleCurrentChange = (val: number) => {
	peopletableParams.value.page = val;
	handleQuery();
};

const attenTableList = ref<any>([]);
const checkloading = ref(false);
const checktableParams = ref({
	page: 1,
	pageSize: 10,
	total: 0,
});
const checkSizeChange = (val: number) => {
	peopletableParams.value.pageSize = val;
	handleQuery();
};
// 改变页码序号
const checkCurrentChange = (val: number) => {
	peopletableParams.value.page = val;
	handleQuery();
};

const presenttableData = ref<any>([]);
const presentloading = ref(false);
const presenttableParams = ref({
	page: 1,
	pageSize: 10,
	total: 0,
});
const presentSizeChange = (val: number) => {
	peopletableParams.value.pageSize = val;
	handleQuery();
};
// 改变页码序号
const presentCurrentChange = (val: number) => {
	peopletableParams.value.page = val;
	handleQuery();
};
const handleQuery = () => {};

const ruleForm = ref<any>({});
const state = reactive({
	isShowDialog: false,
});

// 页面加载时
onMounted(() => {});

// 打开弹窗
const openDialog = async (row: any) => {
	// 改用detail获取最新数据来编辑
	let rowData = JSON.parse(JSON.stringify(row));
	state.isShowDialog = true;
	attenList();
	getonlineList();
	getWorksiteList();
};

// 关闭弹窗
const closeDialog = () => {
	emit('reloadTable');
	state.isShowDialog = false;
};

// 取消
const cancel = () => {
	state.isShowDialog = false;
};

const removePerson = () => {
	if (selectionList.value.length == 0) return;
	peopletableData.value.forEach((item: any) => {
		let i = selectionList.value.findIndex((el) => el.account == item.account);
		if (i == -1) return;
		peopletableData.value.splice(i, 1);
	});
};

// 签到
const signin = async () => {
	// if (selectionList.value.length == 0) return ElMessage.warning('请选择人员');
	if (peopletableData.value.length == 0) return ElMessage.warning('没有可上工人员');
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			await personOnline(
				peopletableData.value.map((item: any) => ({
					account: item.personCode,
					name: item.personName,
					produceWorkOrderNo: props.produceWorkOrderNo,
					productionLineCode: props.productionLineCode,
					productionLineName: props.productionLineName,
					workSiteCode: item.workSiteCode,
					workSiteName: item.workSiteName,
				}))
			);
			ElMessage.success('操作成功');
			attenList();
			getonlineList();
		}
	});
};

// 签退
const signout = async () => {
	if (selectionList.value.length == 0) return ElMessage.warning('请选择人员');
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			await personOffline(
				selectionList.value.map((item: any) => ({
					account: item.personCode,
					name: item.personName,
					produceWorkOrderNo: props.produceWorkOrderNo,
					productionLineCode: props.productionLineCode,
					productionLineName: props.productionLineName,
					workSiteCode: item.workSiteCode,
					workSiteName: item.workSiteName,
				}))
			);
			ElMessage.success('操作成功');
			attenList();
			getonlineList();
		}
	});
};
//单个签退
const signoutOne = async (item:any) => {
	await personOffline([{Account:item.account,Name:item.name,WorkSiteCode:item.workSiteCode,WorkSiteName:item.workSiteName}]);
	ElMessage.success('操作成功');
	attenList();
	getonlineList();
};
// 获取考勤记录
const attenList = async () => {
	let res =
		(
			await getAttenList({
				workOrderNo: props.produceWorkOrderNo,
			})
		)?.data?.result || [];
	attenTableList.value = res;
};

// 获取当前在岗记录
const getonlineList = async () => {
	let res =
		(
			await getOnlineRecord({
				workOrderNo: props.produceWorkOrderNo,
			})
		)?.data?.result || [];
	presenttableData.value = res;
};

const selectionList = ref([]);
const tableRef = ref();
const onSelectionChange = () => {
	selectionList.value = tableRef.value.getSelectionRows();
};

// 获取工位列表
const worksiteList = ref([]);
const getWorksiteList = async () => {
	// if(!props.productionLineCode) return ElMessage.error('工位信息获取失败:该设备未绑定线体信息');
	let WorkSiteList =
		(
			await getWorkSiteList({
				productionLineCode: props.productionLineCode,
			})
		).data?.result || [];
	worksiteList.value = WorkSiteList.map((workSite) => ({
		...workSite,
		value: workSite.workSiteCode,
		label: workSite.workSiteName,
	}));
};

// 根据员工编码获取列表
const searchPersonListByPersonCode = async () => {
	if (!ruleForm.value?.workSiteCode) return ElMessage.warning('请选择工位');
	if (ruleForm.value?.personCode?.trim()?.length > 0) {
		let res =
			(
				await getPersonByAccount({
					account: ruleForm.value.personCode,
				})
			)?.data?.result || {};
		console.log(res);
		peopletableData.value = [
			{
				...res,
				personCode: res.account,
				personName: res.realName,
				workSiteCode: ruleForm.value.workSiteCode,
				workSiteName: ruleForm.value.workSiteName,
			},
		];
	} else {
		ElMessage.warning('请扫描员工编码');
	}
};

// 根据工作组搜索人员
const seachPersonByWorkGroup = () => {
	// if(!ruleForm.value?.workSiteCode) return ElMessage.warning('请选择工位');
	// if(!ruleForm.value?.workGroupCode) return ElMessage.warning('请选择工作组');
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			let res =
				(
					await getPersonByWorkGroupInfo({
						workGroupCode: ruleForm.value.workGroupCode,
					})
				)?.data?.result || [];
			console.log(res);
			peopletableData.value = res;
		}
	});
};

// 获取工位名称
const getWorkSiteName = (value) => {
	ruleForm.value.workSiteName = worksiteList.value.find((item: any) => item.value === value)?.label;
};

// 获取所有工作组
const workGroupList = ref([]);
const getAllWorkGroup = async () => {
	let list =
		(
			await pageMesWorkGroup({
				page: 1,
				pageSize: 99999,
			})
		)?.data?.result?.items ?? [];
	console.log(list);
	workGroupList.value = list.map((workGroup) => ({
		...workGroup,
		label: workGroup.workGroupName,
		value: workGroup.workGroupCode,
	}));
};
getAllWorkGroup();

//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
