<template>
	<div>
		<my-card title="搜索条件" search>
			<n-form label-placement="top" class="flex gap-2" style="display: flex; flex-wrap: wrap">
				<n-form-item label="工单类型">
					<n-select
						v-model:value="searchForm.taskType"
						placeholder="请选择工单类型"
						class="w-160px"
						:options="processOptions"
						:style="{ width: formItemWidth }"
						@update-value="selectTaskType"
					></n-select>
				</n-form-item>
				<n-form-item label="生产工单号">
					<n-input
						v-model:value="searchForm.taskSn"
						type="text"
						placeholder="生产工单号"
						:style="{ width: formItemWidth }"
					/>
				</n-form-item>
				<n-form-item label="机台">
					<n-select
						v-model:value="searchForm.workstationId"
						placeholder="请选择机台"
						:options="machineList"
						class="w-160px"
						:style="{ width: formItemWidth }"
					></n-select>
				</n-form-item>
				<n-form-item label="报工时间">
					<n-date-picker v-model:value="range" type="datetimerange" clearable />
				</n-form-item>
				<n-form-item label="批号">
					<n-input
						v-model:value="searchForm.batchCode"
						placeholder="请输入批号"
						:style="{ width: formItemWidth }"
					></n-input>
				</n-form-item>
				<n-form-item label="规格">
					<n-input
						v-model:value="searchForm.itemSpecification"
						placeholder="请输入规格"
						:style="{ width: formItemWidth }"
					></n-input>
				</n-form-item>
				<!-- <n-form-item label="贸易商">
					<n-select
						v-model:value="ingredientsId"
						placeholder="请选择贸易商"
						:filterable="true"
						:options="merchantList"
						:style="{ width: formItemWidth }"
						@update-value="(val, item: any) => {
								searchForm.ingredientsName = item.label;
							}
							"
					></n-select>
				</n-form-item>
				<n-form-item label="规格">
					<n-select
						v-model:value="itemId"
						placeholder="选择规格"
						:filterable="true"
						:options="specificationList"
						:style="{ width: formItemWidth }"
						@update-value="(val, item: any) => {
								searchForm.itemSpecification = item.label;
							}
							"
					></n-select>
				</n-form-item>
				<n-form-item label="材料厂家">
					<n-select
						v-model:value="manufacturerId"
						placeholder="选择材料厂家"
						:filterable="true"
						:options="manufacturerList"
						@update-value="(val, item: any) => {
								searchForm.manufacturerName = item.label;
							}
							"
					></n-select>
				</n-form-item>
				<n-form-item label="称重时间">
					<n-date-picker
						v-model:formatted-value="searchForm.weightTime"
						type="date"
						:style="{ width: formItemWidth }"
						clearable
					/>
				</n-form-item> -->
				<n-form-item label="投料二维码">
					<n-input
						v-model:value="searchForm.inputSn"
						placeholder="请输入投料二维码"
						:style="{ width: formItemWidth }"
					></n-input>
				</n-form-item>
				<n-form-item label="报工二维码">
					<n-input
						v-model:value="searchForm.outputSn"
						placeholder="请输入报工二维码"
						:style="{ width: formItemWidth }"
					></n-input>
				</n-form-item>
				<n-form-item>
					<component :is="useSearchBtn(search, resetThen)"></component>
				</n-form-item>
			</n-form>
		</my-card>

		<my-card title="报工记录">
			<template #right>
				<div style="display: flex">
					<!-- <n-button type="info" size="small" style="margin-right: 10px" @click="lookReport">查看报表</n-button> -->
					<CxColumns v-if="searchForm.taskType === 0" v-model:columns="lsColumns" />
					<CxColumns v-else v-model:columns="qbColumns" />
				</div>
			</template>
			<n-data-table
				:loading="loading"
				:columns="searchForm.taskType === 0 ? lsColumns : qbColumns"
				:data="data"
				:scroll-x="dataTableConfig.scrollWidth(columns)"
				:max-height="dataTableConfig.maxHeight"
			></n-data-table>
			<my-pagination v-model:search-form="searchForm" @init="init"></my-pagination>
		</my-card>
	</div>
</template>

<script setup lang="tsx">
import { ref, onMounted } from 'vue';
import type { Ref } from 'vue';
import { hiprint } from 'vue-plugin-hiprint';
import type { DataTableColumns } from 'naive-ui';
import { getWorkbenchWiredrawingList } from '@/service/api/md/workbench/wiredrawing';
import { getWorkbenchEnamellingList, getMdPrintData } from '@/service/api/md/workbench/enamelling';
// import { getMaterialList } from '@/service/api/md/itemlist/index';
// import { getIngredientsTradersList } from '@/service/api/md/ingredients/traders';
// import { getIngredientsManufacturerList } from '@/service/api/md/ingredients/manufacturer';
import { dataTableConfig } from '@/config/dataTableConfig';
import { useSearchBtn } from '~/src/hooks/common/useBtn';
import { useLoading } from '~/src/hooks';
import { getOutputLog } from '~/src/service/api/produre/workRecords/index';
import { formatDate } from '~/src/utils/form/rule';
import { useResetSearch } from '~/src/utils/common/searchReset';
const { loading, startLoading, endLoading } = useLoading();

const { searchForm, reset } = useResetSearch({
	taskSn: '', // 生产工单号
	workstationId: null, // 机台
	taskType: 0, // 工单类型
	orderSn: '', // 订单编号
	pageNum: 1,
	pageSize: 10,
	total: 0,
	batchCode: '',
	ingredientsName: '',
	manufacturerName: '',
	itemSpecification: '',
	weightTime: null,
	outputSn: '',
	inputSn: ''
});

const ingredientsId = ref<number | null>(null);
const manufacturerId = ref<number | null>(null);
const itemId = ref<number | null>(null);

const processOptions = [
	{
		value: 0,
		label: '金属'
	},
	{
		value: 1,
		label: '板材'
	}
];

const machineList = ref<{ label: string; value: number }[]>([]);

const wiredrawingList = ref<{ label: string; value: number }[]>([]);
const range = ref<[number, number] | null>(null);
const enamellingList = ref<{ label: string; value: number }[]>([]);
// const specificationList = ref<{ label: string; value: number }[]>([]);
// const merchantList = ref<{ label: string; value: number }[]>([]);
// const manufacturerList = ref<{ label: string; value: number }[]>([]);
const isGetWiredrawingList = ref<boolean>(false);

const isGetEnamelCoverList = ref<boolean>(false);
const formItemWidth = ref<string>('200px');
const columnsFilterData = ref<Array<string>>(['alexPositionNumber', 'alexLot']);
const data = ref<workRecords.TabelList[]>([]);

const columns: Ref<DataTableColumns<workRecords.TabelList>> = ref([
	{
		title: '序号',
		key: 'index',
		align: 'center',
		width: 70,
		render: (_row, index) => (searchForm.value.pageNum - 1) * searchForm.value.pageSize + index + 1
	},
	{
		title: '工单类型',
		align: 'center',
		key: 'taskType',
		width: 100,
		render: row => {
			return row.taskType === '0' ? '金属' : '板材';
		}
	},
	{
		title: '机台',
		align: 'center',
		key: 'workstationCode',
		width: 100
	},
	{
		title: '轴位置数',
		align: 'center',
		key: 'alexPositionNumber',
		width: 100
	},
	{
		title: '批次',
		align: 'center',
		key: 'alexLot',
		width: 100
	},
	{
		title: '订单类型',
		align: 'center',
		key: 'orderType',
		width: 100,
		render: row => {
			return row.orderType === '0' ? '客户订单' : '备库订单';
		}
	},
	{
		title: '客户',
		align: 'center',
		key: 'clientName',
		width: 150,
		ellipsis: {
			tooltip: true
		}
	},
	{
		title: '生产工单号',
		align: 'center',
		key: 'taskSn',
		width: 140,
		ellipsis: {
			tooltip: true
		}
	},
	{
		title: '投料二维码',
		align: 'center',
		key: 'inputSn',
		width: 140,
		render: row => {
			return (
				<n-space>
					<n-ellipsis line-clamp="1">{row.inputSn}</n-ellipsis>
				</n-space>
			);
		}
	},
	{
		title: '报工二维码',
		align: 'center',
		key: 'outputSn',
		width: 140,
		render: row => {
			return (
				<n-space>
					<n-ellipsis line-clamp="1">{row.outputSn}</n-ellipsis>
				</n-space>
			);
		}
	},
	{
		title: '产品型号',
		align: 'center',
		key: 'productModel',
		width: 100
	},
	{
		title: '产品规格',
		align: 'center',
		key: 'productSpecification',
		width: 100
	},
	{
		title: '报工数量（副）',
		align: 'center',
		key: 'outputWeight',
		width: 100
	},
	{
		title: '报工规格',
		align: 'center',
		key: 'itemSpecification',
		width: 100
	},
	{
		title: '单位',
		align: 'center',
		key: 'measureName',
		width: 100
	},
	{
		title: '报工时间',
		align: 'center',
		key: 'createTime',
		width: 180
	},
	{
		title: '报工人',
		align: 'center',
		key: 'createBy',
		width: 100
	},
	{
		title: '报工工号',
		align: 'center',
		key: 'jobNumber',
		width: 100
	},
	{
		title: '批号',
		align: 'center',
		key: 'batchCode',
		width: 100
	},
	{
		title: '操作',
		key: 'action',
		fixed: 'right',
		width: 100,
		render(row) {
			return (
				<n-button
					type="primary"
					size="tiny"
					onClick={() => {
						printTemp(row);
					}}
				>
					补打标签
				</n-button>
			);
		}
	}
]);

const lsColumns: Ref<DataTableColumns<workRecords.TabelList>> = ref([]);

const qbColumns: Ref<DataTableColumns<workRecords.TabelList>> = ref([]);

function search(): void {
	if (range.value !== null) {
		searchForm.value['params[beginTime]'] = formatDate(new Date(range.value[0]), 'yyyy-MM-dd');
		searchForm.value['params[endTime]'] = formatDate(new Date(range.value[1]), 'yyyy-MM-dd');
	} else {
		searchForm.value['params[beginTime]'] = null;
		searchForm.value['params[endTime]'] = null;
	}
	init();
}
function resetThen(): void {
	reset();
	ingredientsId.value = null;
	manufacturerId.value = null;
	itemId.value = null;
	range.value = null;
	search();
}

function selectTaskType(value: number) {
	if (value === searchForm.value.taskType) return;
	searchForm.value.taskType = value;
	searchForm.value.workstationId = null;
	init();
	if (searchForm.value.taskType === 0) {
		machineList.value = [];
		wiredrawingList.value.forEach(item => {
			machineList.value.push({
				label: item.label,
				value: item.value
			});
		});
		lsColumns.value = columns.value.filter((item: any) => !columnsFilterData.value.includes(item.key));
	} else {
		qbColumns.value = columns.value.map(item => item);
		if (isGetEnamelCoverList.value) {
			machineList.value = [];
			enamellingList.value.forEach(item => {
				machineList.value.push({
					label: item.label,
					value: item.value
				});
			});
			return;
		}
		getWorkbenchEnamellingList({ pageSize: 999 }).then(res => {
			isGetEnamelCoverList.value = true;
			res.rows.forEach((item: { equipmentCode: any; id: any }) => {
				enamellingList.value.push({
					label: item.equipmentCode,
					value: item.id
				});
			});
			machineList.value = enamellingList.value;
		});
	}
}
// function lookReport() {
//   let url = 'http://huaerda-jimu.24yt.com/jmreport/view/989752370909216768';
//   let searchValue = '';
//   let isAddQuestionMask = false;
//   const filterData = ['pageNum', 'pageSize', 'total', 'params[beginTime]', 'params[endTime]'];
//   for (const key in searchForm.value) {
//     if (searchForm.value[key] && !filterData.includes(key)) {
//       if (!isAddQuestionMask) {
//         searchValue += `?${key}=${searchForm.value[key]}`;
//         isAddQuestionMask = true;
//       } else {
//         searchValue += `&${key}=${searchForm.value[key]}`;
//       }
//     }
//   }
//   if (range.value !== null) {
//     const day = 1000 * 60 * 60 * 24;
//     const beginTime = formatDate(new Date(range.value[0]), 'yyyy-MM-dd');
//     const endTime = formatDate(new Date(new Date(range.value[1]).getTime() + day), 'yyyy-MM-dd');
//     if (isAddQuestionMask) {
//       searchValue += `&beginTime=${beginTime}&endTime=${endTime}`;
//     } else {
//       searchValue = `?beginTime=${beginTime}&endTime=${endTime}`;
//     }
//   }
//   url += searchValue;
//   window.open(url, '_blank');
// }

// function getList() {
// getMaterialList({ pageSize: 999 }).then(res => {
//   if (res.code === 200) {
//     res.rows.forEach(item => {
//       if (item.workstageName === ' ') {
//         specificationList.value.push({ label: item.specification, value: item.id });
//       }
//     });
//   }
// });
// getIngredientsTradersList({ pageSize: 999 }).then(res => {
//   if (res.code === 200) {
//     res.rows.forEach(item => {
//       merchantList.value.push({ label: item.tradersName, value: item.id });
//     });
//   }
// });
// getIngredientsManufacturerList({ pageSize: 999 }).then(res => {
//   if (res.code === 200) {
//     res.rows.forEach(item => {
//       manufacturerList.value.push({ label: item.manufacturerName, value: item.id, ...item });
//     });
//   }
// });
// }

function printTemp(row: any) {
	let printData = row.printObj;
	// eslint-disable-next-line @typescript-eslint/ban-ts-comment
	// @ts-ignore
	if (window.hiwebSocket.opened || window.hiwebSocket.printerList.length) {
		if (!printData) {
			window.$message?.error('补打数据为空，不可打印！');
			return;
		}
		let livePrint = printData.livePrint;
		console.log("livePrint",livePrint);

		if(!livePrint){
			// eslint-disable-next-line @typescript-eslint/ban-ts-comment
			// @ts-ignore
			let printerList = window.hiwebSocket.printerList.map(item => {
				return {
					label: item.name,
					value: item.name
				};
			});
			if (printerList && printerList.length) {
				livePrint = this.$ls.get('livePrint') || printerList.find(item => item.name.indexOf("ZDesigner ZD888") > -1).value;
				console.log("livePrint2",livePrint);
			}
		}

		const hiprintTemplate = new hiprint.PrintTemplate({ template: JSON.parse(printData?.templateJson) });
		hiprintTemplate.print2(JSON.parse(printData?.templateData), { printer: livePrint});
	} else {
		window.$message?.error('客户端未连接,无法直接打印');
	}
}

function init() {
	startLoading();
	getOutputLog({ ...searchForm.value }).then(res => {
		if (res.code === 200) {
			data.value = res.rows;
			searchForm.value.total = res.total;
		}
		endLoading();
	});
	if (isGetWiredrawingList.value) return;
	getWorkbenchWiredrawingList({ pageSize: 999 }).then(res => {
		if (res.code === 200) {
			isGetWiredrawingList.value = true;
			res.rows.forEach((item: { equipmentCode: any; id: any }) => {
				wiredrawingList.value.push({
					label: item.equipmentCode,
					value: item.id
				});
			});
			machineList.value = wiredrawingList.value;
		}
	});
}
onMounted(() => {
	init();
	// getList();
	lsColumns.value = columns.value.filter((item: any) => !columnsFilterData.value.includes(item.key));
});
</script>

<style scoped></style>
