<template>
	<div>
		<!-- 左侧树形结构 -->
		<el-container>

			<layout-sider :resize-directions="['right']" :width="220" style="margin-right: 10px;">
				<div class="JKWTree-tree" style="height: 70vh;">
					<h3>机台生产日报表附加维护</h3>
					<el-tree :data="treeData" highlight-current @node-click="handleNodeClick" />
				</div>

			</layout-sider>
			<el-container>
				<el-main>
					<!-- 按钮区域 -->
					<div class="gva-table-box">
						<el-form-item>
							<el-input v-model="searchInfo" placeholder="输入工单编号或产品名称" style="width: 180px;" />
							<el-button type="primary" class="search" icon="search" @click="onSearch"></el-button>
							<el-button type="primary" class="bt" icon="plus" @click="onAdd">新增</el-button>
							<el-button type="primary" class="bt" icon="delete" @click="onDel">删除</el-button>
							<div style="margin-left: auto;">
								<el-button type="primary" class="bt" icon="download"
									@click="exportExcel">导出到Excel</el-button>
							</div>
						</el-form-item>
						<!-- 数据展示 -->
						<el-table ref="multipleTable" style="width: 100%" tooltip-effect="dark" :data="tableData"
							row-key="ID" highlight-current-row="true" border :row-style="{ height: '0px' }"
							:header-row-style="{ height: '20px' }" :header-cell-style="{ padding: '0px' }"
							@selection-change="handleSelectionChange" @row-click="Click" :show-overflow-tooltip="true"
							@row-dblclick="doubleClick">
							<!-- <el-table-column type="selection" width="55" /> -->
							<el-table-column align="left" sortable label="生产日期" prop="sczl_rq" width="105" />
							<el-table-column align="left" sortable label="设备编号" prop="sczl_jtbh" width="105" />
							<el-table-column align="left" sortable label="设备名称" prop="sczl_sbmc" width="250" />
							<el-table-column align="left" sortable label="班组编号" prop="sczl_bzdh" width="105" />
							<el-table-column align="left" sortable label="排班工时" prop="sczl_设备运行工时" width="105" />
							<el-table-column align="left" sortable label="备注" prop="sczl_desc" width="120" />
							<el-table-column align="left" sortable label="创建用户" prop="sys_id" width="120" />
							<el-table-column align="left" sortable label="创建时间" prop="sys_rq" width="160" />
							<el-table-column align="left" sortable label="修改时间" prop="mod_rq" width="160" />
							<el-table-column align="left" sortable label="UNIQID" prop="UniqId" width="120" />
						</el-table>
						<!-- 分页 -->
						<div class="gva-pagination">
							<el-pagination layout="total, sizes, prev, pager, next, jumper" :current-page="page"
								:page-size="limit" :page-sizes="[10, 30, 50, 100]" :total="total"
								@current-change="handleCurrentChange" @size-change="handleSizeChange" />
						</div>
					</div>
					<!-- 弹出框 -->
					<el-dialog v-model="dialogFormVisible" :before-close="closeDialog"
						:title="type === 'create' ? '新增' : '修改'" destroy-on-close width="700px">
						<!-- <el-scrollbar height="500px"> -->
						<el-form :model="formData" label-position="right" ref="elFormRef" :rules="rule"
							label-width="80px">

							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item label="日期" prop="name" class="mab">
										<el-input v-model="formData.sczl_rq" type="date" max="9999-12-31" id="日期"
											@focus="rqHandleFocus()" @keydown="ent($event, '备注', '日期', '机器')"
											placeholder="" />
									</el-form-item>
								</el-col>
							</el-row>

							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item label="机器" prop="id" class="mab">
										<el-input v-model="formData.sczl_jtbh" id="机器"
											@keydown="ent($event, '日期', '机器', '组别')" @blur="getJTsubmit()"
											style="width: 200px; " placeholder="Enter回车" />
									</el-form-item>
								</el-col>
								<el-col :span="16">
									<el-input v-model="formData.设备名称" id="设备名称" :readonly=true style="width: 400px;"
										placeholder="" />
								</el-col>
							</el-row>

							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item label="组别" prop="id" class="mab">
										<el-input v-model="formData.sczl_bzdh" id="组别"
											@keydown="ent($event, '机器', '组别', '通电时间')" @blur="getBzsubmit()"
											style="width: 150px;" placeholder="Enter回车" />
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item label="通电时间" prop="id" label-width="133px" class="mab">
										<el-input v-model="formData.sczl_设备运行工时" id="通电时间"
											@keydown="ent($event, '组别', '通电时间', '备注')" style="width: 200px;"
											placeholder="" />
									</el-form-item>
								</el-col>
							</el-row>

							<el-row :gutter="24">
								<el-col :span="21">
									<el-form-item label="备注" prop="id" class="mab">
										<el-input type="textarea" rows="3" cols="50" v-model="formData.sczl_desc"
											id="备注" @keydown="ent($event, '通电时间', '备注', '日期')" :clearable="true"
											placeholder="" />
									</el-form-item>
								</el-col>
							</el-row>

						</el-form>
						<!-- </el-scrollbar> -->
						<template #footer>
							<div class="dialog-footer">
								<el-button @click="dialogFormVisible=false">取 消</el-button>
								<el-button type="primary" @click="enterDialog">确 定</el-button>
							</div>
						</template>
					</el-dialog>


					<el-dialog v-model="GetjtbhVisible" title="选择" destroy-on-close width="600px">
						<el-input v-model="searchGetjtbh" placeholder="" style="width: 400px;"></el-input>
						<el-button type="primary" icon="search" @click="GetjtbhSubmit" class="search"></el-button>

						<el-tree :data="GetJTtreeData" :props="defaultProps" highlight-current="true"
							style="width: 500px;" @node-click="GetMachineDedhhandleNodeClick"
							@node-dblclick="handleNodeDoubleClick"></el-tree>
					</el-dialog>
					<el-dialog v-model="BzVisible" title="选择" destroy-on-close width="200px"
						@keydown="selectBZ($event)">
						<el-table tooltip-effect="dark" :data="selectDataBz" row-key="ID" highlight-current-row="true"
							border style="width:100%" ref="table2" @row-dblclick="SelectClickBz">
							<el-table-column prop="sczl_bzdh" label="班组" width="150" />
						</el-table>
					</el-dialog>
				</el-main>
			</el-container>
		</el-container>

	</div>
</template>

<script setup>
	import {
		getproductionaddList,
		getproductionaddCount,
		adddel,
		addedit,
		addgetJtbh,
		addgetInfo,
		reportadd
	} from '@/api/jixiaoguanli/jitairibaobiao'

	// 全量引入格式化工具 请按需保留
	import {
		getDictFunc,
		formatDate,
		formatBoolean,
		filterDict,
		ReturnArrImg,
		onDownloadFile
	} from '@/utils/format'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		Search,
		Refresh,
		Download
	} from '@element-plus/icons-vue'
	import {
		ref,
		reactive,
		onMounted,
		onBeforeMount
	} from 'vue'
	import {
		getPackingSideTable,
		getPackingTable
	} from '@/api/mes_api_gty/myapi'
	import {
		Layout,
		LayoutContent,
		LayoutHeader,
		LayoutSider
	} from '@arco-design/web-vue'
	import {
		useUserStore
	} from '@/pinia/modules/user'
	const userStore = useUserStore()
	const sys_id = '[' + userStore.userInfo.userName + '/' + userStore.userInfo.nickName + ']'
	defineOptions({
		name: '06-packingDocuments'
	})

	// 侧边栏数据请求
	const treeData = reactive([]);

	const getTabdata = async () => {
		//接口调用函数
		const response = await getproductionaddCount();

		const transformedData = response.data.map(item => ({
			label: `${item.date.replace(/-/g, '.')}【单据数: ${item.counts}张】`,
			children: item.sys.map(sysItem => ({
				label: `${sysItem.sys_id} 【记录数: ${sysItem.count}张】`,
				params: {
					date: item.date.replace(/\./g, '-'),
					sys_id: sysItem.sys_id,
					total: sysItem.count,
				},
			})),
		}));
		treeData.splice(0, treeData.length, ...transformedData);


	}

	getTabdata();

	// 自动化生成的字典（可能为空）以及字段
	const formData = ref({
		sczl_rq: '',
		sczl_jtbh: '',
		设备名称: '',
		sczl_bzdh: '',
		sczl_设备运行工时: '0.00',
		sczl_desc: '',
		sys_id: sys_id,
	})
	const initFormData = () => {
		formData.value = {
			sczl_rq: '',
			sczl_jtbh: '',
			设备名称: '',
			sczl_bzdh: '',
			sczl_设备运行工时: '0.00',
			sczl_desc: '',
			sys_id: sys_id,
		};
	}

	// 验证规则
	const rule = reactive({})

	const elFormRef = ref()
	const elSearchFormRef = ref()

	// =========== 表格控制部分 ===========
	const tableData = reactive([])
	const detailData = reactive([])
	const total = ref(0)
	const page = ref(1)
	const limit = ref(10)
	const searchInfo = ref('')
	const searchGetjtbh = ref('')
	const params = {
		date: '',
		sys_id: '',
		page: page.value.toString(),
		limit: limit.value.toString(),
	}

	// 分页设置
	const handleSizeChange = (val) => {
		limit.value = val;
		params.limit = val.toString();
		getTableData();
	}

	// 页面跳转
	const handleCurrentChange = (val) => {
		page.value = val
		params.page = val.toString();
		getTableData()
	}

	const getTableData = async () => {
		const response = await getproductionaddList(params);
		if (response.code === 0) {
			tableData.splice(0, tableData.length, ...response.data.rows);
		}
	}

	const handleNodeClick = (node, check) => {
		if (node.params) {
			params.date = node.params.date;
			params.sys_id = node.params.sys_id;
			total.value = node.params.total;
			handleCurrentChange(1);
		}
	}

	// 搜索
	function onSearch() {

	}
	// ============== 表格控制部分结束 ===============

	// 获取需要的字典 可能为空 按需保留
	const setOptions = async () => {}

	// 获取需要的字典 可能为空 按需保留
	setOptions()

	// 多选数据
	const multipleSelection = ref([])
	// 多选
	const handleSelectionChange = (val) => {
		// multipleSelection.value = val
		if (val.length > 0) {
			multipleSelection.value = val
			const lenth = val.length
			// ScrapFactor.gdbh=val[lenth-1].combinedProp.split('-')[0];
			// const parts = val[lenth-1].combinedProp2.split('-')
			// ScrapFactor.yjno=parts[0];
			// ScrapFactor.gxh=parts[1];
			// ScrapFactor.type=val[lenth-1].sczl_检验类别
			// console.log(ScrapFactor)
			lastCellValue = val[lenth - 1].UniqId

			val.splice(0, val.length); // 清空 val 数组	
		}
	}

	// 批量删除控制标记
	const deleteVisible = ref(false)

	// 多选删除
	const onDelete = async () => {
		const ids = []
		if (multipleSelection.value.length === 0) {
			ElMessage({
				type: 'warning',
				message: '请选择要删除的数据'
			})
			return
		}
		multipleSelection.value &&
			multipleSelection.value.map(item => {
				ids.push(item.ID)
			})
		const res = await deleteCompanyByIds({
			ids
		})
		if (res.code === 0) {
			ElMessage({
				type: 'success',
				message: '删除成功'
			})
			if (tableData.value.length === ids.length && page.value > 1) {
				page.value--
			}
			deleteVisible.value = false
			getTableData()
		}
	}

	// 行为控制标记（弹窗内部需要增还是改）
	const type = ref('')

	// 更新行
	const updateCompanyFunc = async (row) => {
		const res = await findCompany({
			ID: row.ID
		})
		type.value = 'update'
		if (res.code === 0) {
			formData.value = res.data.recompany
			dialogFormVisible.value = true
		}
	}

	// 弹窗控制标记
	const dialogFormVisible = ref(false)

	// 打开弹窗
	const openDialog = () => {
		type.value = 'create'
		dialogFormVisible.value = true
	}

	// 关闭弹窗
	const closeDialog = () => {
		dialogFormVisible.value = false
		formData.value = {
			address: '',
			image: '',
			name: '',
		}
	}

	const rqHandleFocus = () => {
		if (formData.value.sczl_rq == '') {
			formData.value.sczl_rq = new Date().toISOString().split('T')[0]
		}
	}

	const enterDialog1 = (event) => {
		if (event.keyCode === 13 || event.keyCode === 40) { // Enter 或向下箭头
			//弹窗提示确认
			ElMessageBox.confirm('数据存盘?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				enterDialog()
			})
		} else if (event.keyCode === 39) { // 向右箭头
			//弹窗提示确认
			ElMessageBox.confirm('数据存盘?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				enterDialog()
			})
		}

	}
	// 弹窗确定
	const enterDialog = async () => {
		//弹窗提示确认
		ElMessageBox.confirm('数据存盘?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {

			if (formData.value.sczl_rq == '') {
				ElMessage({
					type: 'error',
					message: '请填写日期'
				});
				document.getElementById('日期').focus()
				document.getElementById('日期').select()
				return;
			}
			if (formData.value.sczl_jtbh == '') {
				ElMessage({
					type: 'error',
					message: '请选择机器'
				});
				document.getElementById('机器').focus()
				document.getElementById('机器').select()
				return;
			}
			if (formData.value.sczl_bzdh == '') {
				ElMessage({
					type: 'error',
					message: '请选择班组'
				});
				document.getElementById('组别').focus()
				document.getElementById('组别').select()
				return;
			}
			if (formData.value.sczl_设备运行工时 == '') {
				ElMessage({
					type: 'error',
					message: '请填写通电时间'
				});
				document.getElementById('通电时间').focus()
				document.getElementById('通电时间').select()
				return;
			}
			updateDetailData()
		});

	}
	let table = ref(5);
	let lastCellValue = ref()
	// 双击表格操作
	function doubleClick(row, column, event) {
		type.value = 'update';
		lastCellValue = row['UniqId'];
		table.value = lastCellValue
		dialogFormVisible.value = true

		AddgetInfo(table.value)
	}
	// 单击表格操作
	function Click(row, column, event) {
		lastCellValue = row['UniqId'];
	}
	//获取详细信息
	const AddgetInfo = async (value) => {
		const response = await addgetInfo({
			UniqId: value
		});
		if (response.code === 0) {
			formData.value = response.data[0];
		}
	}

	//机台回车事件
	const getJTsubmit = (event, inputName) => {
		addgetJtbh({
			sys_mc: ''
		}).then(response => {
			if (response.code == 0) {
				var flag = 0;
				for (const arr of response.data[0]['使用部门']) {
					if (!flag) {
						for (const arr1 of response.data[0][arr]) {
							if (arr1['jtbh'] == formData.value.sczl_jtbh) {
								flag = 1
								break;
							}
						}
					} else {
						break;
					}
				}
				if (!flag) {
					// 遍历接口返回的数据，构建父子关系
					GetJTtreeData.splice(0, GetJTtreeData.length);
					response.data.forEach(item => {
						const departments = item["使用部门"];
						departments.forEach(department => {
							const departmentData = {
								label: department,
								value: department,
								children: item[department].map(device => {
									return {
										label: device["jtbh"] + '/' + device[
											"设备名称"],
										value: device["jtbh"]
									};
								})
							};
							GetJTtreeData.push(departmentData);
						});
					});
					GetjtbhVisible.value = true
				}
				return


			}
		})
	}
	const GetjtbhSubmit = () => {
		addgetJtbh({
			sys_mc: searchGetjtbh.value
		}).then(response => {
			if (response.code == 0) {
				// 遍历接口返回的数据，构建父子关系
				GetJTtreeData.splice(0, GetJTtreeData.length);
				response.data.forEach(item => {
					const departments = item["使用部门"];
					departments.forEach(department => {
						const departmentData = {
							label: department,
							value: department,
							children: item[department].map(device => {
								return {
									label: device["jtbh"] + '/' + device["设备名称"],
									value: device["jtbh"]
								};
							})
						};
						GetJTtreeData.push(departmentData);
					});
				});
			}
		})
	}
	const GetjtbhVisible = ref(false)
	let GetJTtreeData = reactive([]);
	const GetMachineDedhhandleNodeClick = (node, check, nodeData) => {
		if (!node.children) {
			// 点击的是子节点
			// 执行相应的子节点单击事件处理逻辑
			const splitIndex = node.label.indexOf('/');
			formData.value.sczl_jtbh = node.label.substring(0, splitIndex);
			formData.value.设备名称 = node.label.substring(splitIndex + 1);
			GetjtbhVisible.value = false
		}
	}

	//班组失去焦点事件
	const getBzsubmit = () => {
		//弹出选择
		const data = [{
			'sczl_bzdh': 'A班'
		}, {
			'sczl_bzdh': 'B班'
		}]
		selectDataBz.splice(0, selectDataBz.length, ...data)
		if (!GetjtbhVisible.value) {
			BzVisible.value = true
			setCurrent(selectDataBz[0])
		}


	}
	const table2 = ref()
	const setCurrent = (row) => {
		setTimeout(() => {
			table2.value?.setCurrentRow(row)
			// SelectClick(row)
			// console.log(row)
			// console.log(table)
			const {
				sczl_bzdh
			} = row
			formData.value.sczl_bzdh = row.sczl_bzdh
			console.log(row)
		})
	}
	//班组选择
	const selectDataBz = reactive([])
	const BzVisible = ref(false)
	const SelectClickBz = (row, column, event) => {
		const {
			sczl_bzdh
		} = row

		formData.value.sczl_bzdh = row.sczl_bzdh

		BzVisible.value = false
	}
	const selectBZ = (event) => {
		// console.log(selectDataBz.length);
		if (event.keyCode === 40) { // Enter 或向下箭头
			setCurrent(selectDataBz[1]);

		} else if (event.keyCode === 38) {
			setCurrent(selectDataBz[0]);

		} else if (event.keyCode === 13) {
			BzVisible.value = false
		}
	}

	// 更新数据
	const updateDetailData = async () => {
		const restoredData = {
			UniqId: lastCellValue,
			sczl_rq: formData.value.sczl_rq,
			sczl_jtbh: formData.value.sczl_jtbh,
			sczl_bzdh: formData.value.sczl_bzdh,
			sczl_设备运行工时: formData.value.sczl_设备运行工时,
			sczl_desc: formData.value.sczl_desc,
			sys_id: sys_id,
		}
		if (ADD.value == '新增') {
			const response = await reportadd(restoredData);
			// ADD.value='1'
			// console.log(ADD.value)
			ADD.value = '0'
			if (response.code == 0) {
				ElMessage({
					type: 'success',
					message: '新增成功',
				})
				dialogFormVisible.value = false
				//刷新侧边栏
				getTabdata()
				if (params.date != '') {
					//刷新页面
					getTableData()
				}
			}

		} else {
			const response = await addedit(restoredData);
			if (response.code == 0) {
				ElMessage({
					type: 'success',
					message: '修改成功',
				})
			}
			dialogFormVisible.value = false
		}
	}
	//键盘 input框跳转
	const ent = (event, id1, id2, id3) => {

		if (event.keyCode === 13 || event.keyCode === 40) { // Enter 或向下箭头
			if (id3 != '') {
				if (id2 == '备注') {
					document.getElementById(id3).focus()
					document.getElementById(id3).select();
					enterDialog1()
				} else {
					document.getElementById(id3).focus()
					document.getElementById(id3).select()
				}
			}
		} else if (event.keyCode === 38) { // 向上箭头
			if (id1 != '') {
				document.getElementById(id1).focus()
				document.getElementById(id1).select()
			}
		} else if (event.keyCode === 8) { // 删除箭头
			if (id1 != '' && document.getElementById(id2).value == '') {
				document.getElementById(id1).focus()
				document.getElementById(id1).setSelectionRange(0, 0)
			}
		} else if (event.keyCode === 37) { // 向左箭头
			if (id1 != '' && document.getElementById(id2).selectionStart == 0) {
				document.getElementById(id1).focus()
				document.getElementById(id1).select()
			}
		} else if (event.keyCode === 39) { // 向右箭头
			if (id3 != '' && document.getElementById(id2).selectionStart == document.getElementById(id2).value
				.length) {
				if (id2 == '备注') {
					document.getElementById(id3).focus()
					document.getElementById(id3).select()
					enterDialog1()
				} else {
					document.getElementById(id3).focus()
					document.getElementById(id3).select()
				}
			}
		}
	}
	const AddDel = (value) => {
		if (typeof(lastCellValue) == 'object') {
			ElMessage({
				type: 'warning',
				message: '未选中记录',
			})
			return
		}
		ElMessageBox.confirm(
			`确认删除这条数据么?`,
			'警告', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(async () => {
			const response = await adddel({
				UniqId: lastCellValue
			});
			if (response.code === 0) {
				ElMessage({
					type: 'success',
					message: '删除成功',
				})
				//刷新侧边栏
				getTabdata()
				//刷新页面
				getTableData()
			}
		})
	}
	const ADD = ref('0')
	//新增
	const onAdd = () => {
		type.value = 'create'
		ADD.value = '新增'
		initFormData()
		dialogFormVisible.value = true
		// Productionadd()
	}
	//新增
	const Reportadd = async () => {
		const response = await reportadd();
		if (response.code === 0) {}
		getTableData()
	}
	//删除
	function onDel() {
		AddDel()
	}
	// 导出excel
	function exportExcel() {
		console.log('导出到excel');
	}

	// 生命周期钩子
	onMounted(async () => {});
</script>

<style>
	.JKWTree-container {
		display: flex;
	}

	.JKWTree-tree {
		width: 300px;
		background-color: #fff;
		padding: 10px;
		margin-right: 20px;
	}

	.JKWTree-tree h3 {
		font-size: 15px;
		font-weight: 700;
		margin: 10px 0;
	}

	.JKWTree-content {
		flex: 1;
	}

	/* 选中某行时的背景色*/
	.el-table__body tr.current-row>td {
		background: #ff80ff !important;
		/* 背景颜色 */
	}
</style>
<style scoped>
	:deep(.el-table td .cell) {
		line-height: 20px !important;
	}

	:deep(.el-tabs__header) {
		margin-bottom: 0;
	}

	.search {
		margin-left: 0px !important;
		margin-right: 10px !important;
	}

	.bt {
		margin-left: 2px !important;
		padding: 3px !important;
		font-size: 12px;
	}

	.el-tabs__header {
		margin: 0px !important;
	}

	.gva-table-box {
		padding: 0px !important;
	}

	.mab {
		margin-bottom: 5px;
	}
</style>