﻿<template>
	<div class="mesPickingHead-container">
		<el-dialog v-model="state.isShowDialog" v-if="state.isShowDialog" :width="1100" draggable="" :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<!--<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>-->
					<span>{{ props.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="state.ruleForm.id" />
					</el-form-item>
					<el-col :xs="12" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
						<el-form-item label="原材料编码" prop="materialCode">
                            <el-input v-model="state.ruleForm.materialCode" placeholder="请选择原材料编码" readonly="true"  maxlength="100" show-word-limit clearable >
                        <template #append >
                            <el-button @click="openChoose" >选择</el-button>
                        </template>
                            </el-input>
					    </el-form-item>
					</el-col>
					<el-col :xs="12" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
						<el-form-item label="原材料名称" prop="materialName">
							<el-input v-model="state.ruleForm.materialName" readonly="true" placeholder="请输入原材料名称" maxlength="100" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="12" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
						<el-form-item label="原材料规格" prop="cInvStd">
							<el-input v-model="state.ruleForm.cInvStd" readonly="true" placeholder="请输入原材料规格" maxlength="100" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="12" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
						<el-form-item label="原材料批次" prop="materialbatch">
							<el-input v-model="state.ruleForm.materialbatch" readonly="true" placeholder="请输入原材料批次" maxlength="100" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="12" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
						<el-form-item label="单位编码" prop="cComUnitCode">
							<el-input v-model="state.ruleForm.cComUnitCode" readonly="true" placeholder="请输入单位编码" maxlength="100" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="12" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
						<el-form-item label="单位名称" prop="cComUnitName">
							<el-input v-model="state.ruleForm.cComUnitName" readonly="true" placeholder="请输入单位名称" maxlength="100" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<!-- <el-col :xs="12" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
						<el-form-item label="批次重量" prop="pickingPlanNum">
							<el-input v-model="state.ruleForm.pickingPlanNum" @input="handleInput3(state.ruleForm.pickingPlanNum)"  placeholder="请输入批次重量" show-word-limit  />
							
						</el-form-item>
						
					</el-col> -->
					<el-col :xs="12" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
						<el-form-item label="计划领料" prop="actualNumber">
							<el-input-number v-model="state.ruleForm.actualNumber" readonly="true"  placeholder="请输入计划领料"  show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>

					<!-- <el-col :xs="12" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
						<el-form-item label="计划退料数" prop="actualTNumber">
							<el-input-number v-model="state.ruleForm.actualTNumber" readonly="true"  placeholder="计划退料数"  show-word-limit clearable />
							
						</el-form-item>
						
					</el-col> -->
					
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
			<template v-if="props.title=='添加领料单'">
                <el-tabs v-model="tabActive">
                <el-tab-pane label="领料工单" name="item"></el-tab-pane>
                </el-tabs>
                <el-table :data="detailList" >
				<el-table-column type="index" label="序号" width="55" align="center" />
                <!-- <el-table-column prop="produceWorkOrderNo" label="工单号" width="130" align="center" show-overflow-tooltip="" /> -->
				<el-table-column prop="productCode" label="MES编码" width="120" align="center" show-overflow-tooltip="" />
				<el-table-column prop="productName" label="MES名称" width="120" align="center" show-overflow-tooltip="" />
				<el-table-column prop="chargeMaterialTypeCodes" label="原材料编码" width="120" align="center" show-overflow-tooltip="" />
				<el-table-column prop="chargeMaterialTypeNames" label="原材料名称" width="120" align="center" show-overflow-tooltip="" />
				<el-table-column prop="batchNo" label="批次号" width="210" align="center"  show-overflow-tooltip="" />
				<el-table-column prop="planNum" label="数量" width="80" align="center" show-overflow-tooltip="" />
				<el-table-column prop="unitUse" label="定额" align="center" width="120" show-overflow-tooltip="" >
                  <template  #default="scope">
                    <el-input v-model="scope.row.unitUse" @input="handleInput1(scope.row)"  />
                  </template>
                </el-table-column>
				<el-table-column prop="planNumber" label="计划领料" align="center" width="120" show-overflow-tooltip="">
                  <template  #default="scope">
                    <el-input v-model="scope.row.planNumber" @input="handleInput2(scope.row)"  />
                  </template>
                </el-table-column>
            </el-table>
            </template>
			<!-- <template v-if="props.title=='添加领料单主表'">
                <el-tabs v-model="tabActive">
                <el-tab-pane label="U8原材料库存信息" name="item"></el-tab-pane>
                </el-tabs>
                <MesQiInspTempItem></MesQiInspTempItem>
            </template> -->
		</el-dialog>
		<choose-material title="选择原材料" ref="chooseMaterialRef" :is-any="false" @finish="onChooseMaterialFinish"></choose-material>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
    import { ref,onMounted, reactive ,computed ,nextTick} from "vue";
	import { ElMessage ,ElMessageBox} from "element-plus";
	import type { FormRules } from "element-plus";
	import { addMesPickingHead, updateMesPickingHead, Scan } from "/@/api/simple/mesPickingHead";
	import { pageMesPickingHead, deleteMesPickingHead } from '/@/api/simple/mesPickingHead';
	import MesQiInspTempItem from "/@/views/simple/ViewCurrentStockEntity/index.vue";
  	import { formatDate } from '/@/utils/formatTime';
	import ChooseMaterial from "/@/views/simple/mesPickingCreate/component/choosu8stock.vue";
 // 子表
 const detailList = ref([]);
 const id = ref();
 const tabActive = ref('item');
	//父级传递来的参数
	var props = defineProps({
		title: {
		type: String,
		default: "",
	},
	});
	//父级传递来的函数，用于回调
	const emit = defineEmits(["reloadTable"]);
	const ruleFormRef = ref();
    const state = reactive({
    isShowDialog: false,
    ruleForm: {} as any,
});

	//自行添加其他规则
	const rules = ref<FormRules>({
	});

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

	});

	// 打开弹窗
	const openDialog = async (_options: any) => {
		// state.ruleForm = JSON.parse(JSON.stringify(row));
		// 改用detail获取最新数据来编辑
		//let rowData = JSON.parse(JSON.stringify(row));
		const id = _options.id;
		detailList.value=[];
		let  res = await Scan({
        packCode:id,
      })
      let datas = res.data.result ?? [];
		 detailList.value.push(...datas);

		 state.ruleForm.materialCode=datas[0].chargeMaterialTypeCodes;
		 state.ruleForm.materialName=datas[0].chargeMaterialTypeNames;
		 const totalQuantity = computed(() => {
          return detailList.value.reduce((sum, item) => sum + item.planNumber, 0);
          });
		  state.ruleForm.cInvStd = undefined;
	     state.ruleForm.materialbatch = undefined;
	     state.ruleForm.pickingPlanNum=undefined;
	     state.ruleForm.cComUnitCode= undefined;
	      state.ruleForm.cComUnitName=undefined;
	      state.ruleForm.stock= undefined;
		  //state.ruleForm.pickingPlanNum=totalQuantity.value;
		  state.ruleForm.actualNumber=totalQuantity.value;
		state.isShowDialog = true;
	};

	// 关闭弹窗
	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) {
				let values = state.ruleForm;
				values.data=detailList.value;
				state.ruleForm.pickingPlanNum=0;
				state.ruleForm.actualTNumber=0;
				// if(state.ruleForm.pickingPlanNum==undefined || state.ruleForm.pickingPlanNum=="" ||state.ruleForm.pickingPlanNum==null)
				// 	{
				// 		return ElMessage({
                //     message: `批次重量不可以为空！`,
                //     type: "error",
                //     });
				// 	}
					var result=(await addMesPickingHead(values)).data.result;
			     	if(result=="添加成功")
			     	 closeDialog();
			     	else
			     	{
			     		ElMessage({
			     	message: `${result}`,
			     	type: "error",
			     });
			     	}
				// ElMessageBox.confirm(`是否创建检验任务单?`, '提示', {
				// 		confirmButtonText: '确定',
				// 		cancelButtonText: '取消',
				// 		type: 'warning',
				// 	})
				// 	.then(async () => {
				// 		await addMesPickingHead(values);
				// 		closeDialog();
				// 	})
				// 	.catch(() => {});
			} else {
				ElMessage({
					message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
					type: "error",
				});
			}
		});
	};

	const chooseMaterialRef = ref();
    const openChoose = ()=>{
      chooseMaterialRef.value.openDialog({materialCode:state.ruleForm.materialCode})
    }
    const onChooseMaterialFinish = (row:any)=>{
      state.ruleForm.materialCode = row?.cInvCode;
      state.ruleForm.materialName = row?.cInvName;
	  state.ruleForm.cInvStd = row?.cInvStd;
	  state.ruleForm.materialbatch = row?.cBatch;
	  state.ruleForm.pickingPlanNum= row?.iQuantity;
	  state.ruleForm.cComUnitCode= row?.cComUnitCode;
	  state.ruleForm.cComUnitName= row?.cComUnitName;
	  state.ruleForm.stock= row?.cWhCode+"-"+row?.cWhName;
	  state.ruleForm.actualTNumber=-(parseFloat(row?.iQuantity)-parseFloat(state.ruleForm.actualNumber));
      // state.ruleForm.productNo = row?.materialNo;
	  console.log(row);
	  if(row==undefined)
	  {
		 state.ruleForm.materialCode=detailList.value[0].chargeMaterialTypeCodes;
		 state.ruleForm.materialName=detailList.value[0].chargeMaterialTypeNames;
	  }
	  else if(row.length<=0)
	  {
		 state.ruleForm.materialCode=detailList.value[0].chargeMaterialTypeCodes;
		 state.ruleForm.materialName=detailList.value[0].chargeMaterialTypeNames
	  }
    }

//改定额计划领料数根据改变
	const handleInput1=(value:any) =>{
	
	const allowedValues = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','.','-','－','．', '０', '１', '２', '３', '４', '５', '６', '７', '８', '９'];
	const currentChar = value.unitUse.slice(-1);
	if (allowedValues.includes(currentChar))
	{
		value.unitUse = ToCDB(value.unitUse.toUpperCase());
        const number=parseFloat(value.unitUse)*parseFloat(value.planNum);
        if(number>parseFloat(value.planNum))
	    {
	    	value.planNumber=value.planNum;
			value.unitUse=parseFloat(value.planNum)/parseFloat(value.planNumber);
	    }
		else{
			//if(parseFloat(value.planNumber)>0)
	        //{
	        //	state.ruleForm.actualNumber=parseFloat(state.ruleForm.actualNumber)-parseFloat(value.planNumber);
			//	value.isPlanNumber=value.planNumber;
	        //}
		     value.planNumber=parseFloat(value.unitUse)*parseFloat(value.planNum);
			 const numbers=ref(0);
		     for(let index=0;index<detailList.value.length;index++) {
                    if(detailList.value[index].produceWorkOrderNo!=value.produceWorkOrderNo)
	                {
	                	const profitLoss = detailList.value[index].planNumber;
					    if(profitLoss!=null )
				        {
					    	const parsedValue = parseFloat(profitLoss);
                            numbers.value += parsedValue;
				        }
	                }
			}
            state.ruleForm.actualNumber=numbers.value+parseFloat(value.planNumber);
		    // if(parseFloat(value.planNumber)>0)
	        //{
	        //	state.ruleForm.actualNumber=parseFloat(state.ruleForm.actualNumber)+parseFloat(value.planNumber);
			//	value.isPlanNumber=value.planNumber;
	        //}
			//if(state.ruleForm.pickingPlanNum!=undefined || state.ruleForm.pickingPlanNum!="" || state.ruleForm.pickingPlanNum!=null)
			//{
			//	state.ruleForm.actualTNumber=-(parseFloat(state.ruleForm.pickingPlanNum)-parseFloat(state.ruleForm.actualNumber));
            //}
		}
		
	}
	else{
		nextTick(() => {
			value.unitUse = undefined;
			value.planNumber = undefined;
        });
	}
	
}
	
//改计划领料数定额根据边根据改变
const handleInput2=(value:any) =>{
	
	const allowedValues = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','.','-','－','．', '０', '１', '２', '３', '４', '５', '６', '７', '８', '９'];
	const currentChar = value.planNumber.slice(-1);
	if (allowedValues.includes(currentChar))
	{
		value.planNumber = ToCDB(value.planNumber.toUpperCase());
		if(value.planNumber>parseFloat(value.planNum))
	    {
	    	value.planNumber=value.planNum;
			value.unitUse=parseFloat(value.planNum)/parseFloat(value.planNumber);
	    }
		else{
			//if(parseFloat(value.planNumber)>=0)
	        //{
	        //	state.ruleForm.actualNumber=parseFloat(state.ruleForm.actualNumber)-parseFloat(value.isPlanNumber);
	        //}
		   const numbers=ref(0);
		   for(let index=0;index<detailList.value.length;index++) {
                    if(detailList.value[index].produceWorkOrderNo!=value.produceWorkOrderNo)
	                {
	                	const profitLoss = detailList.value[index].planNumber;
					    if(profitLoss!=null )
				        {
					    	const parsedValue = parseFloat(profitLoss);
                            numbers.value += parsedValue;
				        }
	                }
			}
		    value.unitUse=parseFloat(value.planNumber)/parseFloat(value.planNum);
            state.ruleForm.actualNumber=numbers.value+parseFloat(value.planNumber);
		    //if(parseFloat(value.planNumber)>=0)
	        //{
	        //	state.ruleForm.actualNumber=parseFloat(state.ruleForm.actualNumber)+parseFloat(value.planNumber);
		    //	value.isPlanNumber=value.planNumber;
	        //}
			//if(state.ruleForm.pickingPlanNum!=undefined || state.ruleForm.pickingPlanNum!="" || state.ruleForm.pickingPlanNum!=null)
			//{
			//	state.ruleForm.actualTNumber=-(parseFloat(state.ruleForm.pickingPlanNum)-parseFloat(state.ruleForm.actualNumber));
			//}
		}
	}
	else{
		nextTick(() => {
			value.unitUse = undefined;
			value.planNumber = undefined;
        });
	}
	
}

	//全角转半角
const ToCDB=(str:any) =>{
        // 全角转半角
        var tmp = void 0;
        if (str) {
            tmp = '';
            for (var i = 0; i < str.length; i++) {
                if (str.charCodeAt(i) == 12288) {
                    tmp += String.fromCharCode(32);
                } else if (str.charCodeAt(i) == 160) {
                    tmp += String.fromCharCode(32); // 处理下Unicode为160的特殊空格
                } else if (str.charCodeAt(i) > 65248 && str.charCodeAt(i) < 65375) {
                    tmp += String.fromCharCode(str.charCodeAt(i) - 65248);
                } else {
                    tmp += str[i];
                }
            }
        } else {
            tmp = str;
        }
        return tmp;
      }

	  //计算退料数
	const handleInput3=(value:any) =>{
	
	const allowedValues = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','.','-','－','．', '０', '１', '２', '３', '４', '５', '６', '７', '８', '９'];
	const currentChar = value.slice(-1);
	if (allowedValues.includes(currentChar))
	{debugger
		value = ToCDB(value.toUpperCase());
		if(parseFloat(value)>=0)
	    {
	    	state.ruleForm.actualTNumber=-(parseFloat(value)-parseFloat(state.ruleForm.actualNumber));
	    }
	}
	else{
		nextTick(() => {
			state.ruleForm.pickingPlanNum = 0;
			state.ruleForm.actualTNumber = 0;
        });
	}
	
}
	
	//将属性或者函数暴露给父组件
	defineExpose({ openDialog });
</script>




