<template>
	<div class="mesBusLog-container">
		<el-dialog v-model="state.isShowDialog" v-if="state.isShowDialog" width="50%" draggable="" :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<span>{{ props.title }}</span>
				</div>
			</template>
			<div style="width: 100%">
				<el-form :model="ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules" @submit.native.prevent>
					<el-row :gutter="35">
						<el-col :span="24" class="mb20">
							<el-form-item label="扫描物料条码" prop="materialCode">
								<el-input v-model="ruleForm.materialCode" placeholder=" " clearable @keyup.enter.stop="submit" style="width: 100%">
									<template #append>
										<el-icon class="el-input__icon" style="cursor: pointer" @click="submit">
											<ele-FullScreen />
										</el-icon>
									</template>
								</el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<div style="margin-bottom: 10px">
					<el-tag v-for="(item, idx) in chargeMaterialTypeCodes">[{{ item }}]{{ chargeMaterialTypeNames[idx] }}</el-tag>
				</div>

				<div>
					<el-table :data="tableData" style="width: 100%" v-loading="loading" tooltip-effect="light" row-key="id" border="">
						<!-- <el-table-column type="selection" width="55" /> -->
						<el-table-column type="index" label="序号" width="55" align="center" />
						<el-table-column prop="materialCode" label="MES编码" show-overflow-tooltip="" />
						<el-table-column prop="materialName" label="MES名称" show-overflow-tooltip="" />
						<el-table-column prop="specs" label="规格型号" show-overflow-tooltip="" />
						<el-table-column prop="batchNo" label="批号" show-overflow-tooltip="" />
						<el-table-column label="操作" width="120" align="center" fixed="right">
							<template #default="scope">
								<el-button icon="ele-Delete" size="small" type="primary" @click="subDelete(scope.row, scope.$index)"> 删除 </el-button>
							</template>
						</el-table-column>
					</el-table>
					<!-- <el-pagination v-model:currentPage="tableParams.page" v-model:page-size="tableParams.pageSize" :total="tableParams.total" :page-sizes="[10, 20, 50, 100, 200, 500]" small="" background="" @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper" /> -->
				</div>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="relMaterialHandle">确 定</el-button>
				</span>
			</template>
		</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, ElMessageBox } from 'element-plus';
import type { FormRules } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { relMaterial, scanMaterial } from '/@/api/mes/mesControlBoard';

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

//自行添加其他规则
const rules = ref<FormRules>({
	materialCode: [{ required: true, message: '请扫码物料编码！', trigger: 'blur' }],
});

const subDelete = (i) => {
	tableData.splice(i, 1);
};

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

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

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

const processform = ref({});
const chargeMaterialTypeCodes = ref([]);
const chargeMaterialTypeNames = ref([]);
// 打开弹窗
const openDialog = async (row: any) => {
	// 改用detail获取最新数据来编辑
	let rowData = JSON.parse(JSON.stringify(row.processform.value));
	processform.value = rowData;
	state.isShowDialog = true;
	console.log(processform.value);
	chargeMaterialTypeCodes.value = processform.value.chargeMaterialTypeCodes?.split(',') || [];
	chargeMaterialTypeNames.value = processform.value.chargeMaterialTypeNames?.split(',') || [];
};

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

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

const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			var len = ruleForm.value.materialCode.length;
			var batchNo = '';
			var materialCode = '';
			if (len > 16) {
				//解析条码
				let flowid = ruleForm.value.materialCode.substring(len - 8, len);
				batchNo = ruleForm.value.materialCode.substring(len - 14, len - 8);
				materialCode = ruleForm.value.materialCode.substring(0, len - 14);
				// console.log(flowid,batchNo,materialCode)
			}

			let res =
				(
					await scanMaterial({
						materialCode: materialCode || ruleForm.value.materialCode,
						workOrderrNo: props.produceWorkOrderNo,
						ChargeType: 0,
					})
				)?.data?.result || {};
			if (batchNo) res.batchNo = batchNo;

			if (res.isExist == false) {
				ElMessageBox.confirm(`不是预设的上料物料，确定继续上料?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'success',
				})
					.then(async () => {
						tableData.value.push({
							...res,
							produceWorkOrderNo: props.produceWorkOrderNo,
						});
					})
					.catch(() => {});
			} else {
				tableData.value.push({
					...res,
					produceWorkOrderNo: props.produceWorkOrderNo,
				});
			}
		}
	});
};

const relMaterialHandle = () => {
	if (tableData.value.length == 0) return ElMessage.warning('请添加物料后操作');
	relMaterial({
		produceWorkOrderNo: props.produceWorkOrderNo,
		items: tableData.value,
	});
	ElMessage.success('操作成功');
	closeDialog();
};

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