﻿<template>
	<div class="mesPack-container">
		<el-card shadow="hover" :body-style="{ padding: '20px 20px 16px 10px', display: 'flex', width: '100%', height: '100%', alignItems: 'start' }">
		
			<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 style="border: 1px solid #cccccc;margin: 10px; padding: 10px;width: 90%; height: calc(100% - 22px)" :gutter="15">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="扫描载具信息" prop="flowBarcode"style="width: 64%">
                            <el-input v-model="state.ruleForm.flowBarcode" placeholder="扫描载具编码" clearable @keyup.enter="scanCode" style="width: 40%" >
                                <template #append>
                                    <el-icon  @click="scanCode"><ele-FullScreen /></el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="8" class="mb20">
						<el-form-item label="载具编码" prop="packCode">
							<el-input v-model="state.ruleForm.packCode" readonly="true" placeholder="" maxlength="100"  clearable disabled />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="8" class="mb20">
						<el-form-item label="载具名称" prop="packName">
							<el-input v-model="state.ruleForm.packName" readonly="true" placeholder="" maxlength="100"  clearable disabled />
							
						  </el-form-item>
						
					</el-col>
					<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="最大载容量" prop="maxNum">
							<el-input-number v-model="state.ruleForm.maxNum" readonly="true" placeholder="请输入最大载容量" clearable />
							
						</el-form-item>
						
					</el-col> -->
					<el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="8" class="mb20">
						<el-form-item label="当前装载量" prop="num">
							<el-input-number v-model="state.ruleForm.num" min="0" :precision="0" placeholder="请输入装载量" clearable />
							
						</el-form-item>
						
					</el-col>
			
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="24" :gutter="200" class="mb20"  >
						<el-form-item label="产品ERP编码"  prop="partCode" style="width: 70%">
                            <el-input v-model="state.ruleForm.partCode" placeholder="请选择产品ERP编码" readonly="true"  maxlength="100" show-word-limit clearable >
                        <template #append v-if="props.title=='编辑月销售计划'==false">
                            <el-button @click="openChoose" >选择</el-button>
                        </template>
                            </el-input>
					    </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8" class="mb20" >
						<el-form-item label="产品名称" prop="partName">
							<el-input v-model="state.ruleForm.partName" readonly="true"   maxlength="100" show-word-limit clearable disabled />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8" class="mb20">
						<el-form-item label="选择零件" prop="productCode">
							<!-- <el-cascader style="width: 100%" @change="onBomChange" :options="bomTreeData" :props="{ checkStrictly: true }" :collapse-tags-tooltip="true"> </el-cascader> -->
							<el-tree-select v-model="addForm.productBomId" :data="bomTreeData" clearable :check-strictly="true" :render-after-expand="false" @change="onBomChange" style="width: 100%" />
						</el-form-item>
					</el-col>
					<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" 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="24" :sm="12" :md="12" :lg="12" :xl="8" class="mb20">
						<el-form-item label="批次号" prop="batchNo">
							<el-input v-model="state.ruleForm.batchNo" placeholder="请输入批次号" maxlength="100" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="8" :md="24" :lg="24" :xl="24" class="mb20" >
                        <el-form-item label="扫描人员信息" prop="flowBarcode"style="width: 64%">
							<el-input v-model=" state.ruleForm.peopleCode" placeholder="扫描人员编码" clearable @keyup.enter.stop="onScanAccounts" style="width: 40%">
									  <template #append>
									     <el-icon class="el-input__icon" style="cursor: pointer" @click="onScanAccounts">
										     <ele-FullScreen />
									     </el-icon>
									  </template>
							</el-input>{{ state.ruleForm.people }}
                        </el-form-item>
                    </el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="8" class="mb20">
						<el-form-item label="人员编码" prop="nickPeople">
							<el-input v-model="state.ruleForm.nickPeople" readonly="true" placeholder="" maxlength="100" show-word-limit clearable disabled />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="8" class="mb20">
						<el-form-item label="人员名称" prop="nickPeopleName">
							<el-input v-model="state.ruleForm.nickPeopleName" readonly="true" placeholder="" maxlength="100" show-word-limit clearable disabled />
							
						</el-form-item>
						
					</el-col>

					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" style="margin-top: 10px;">
                        <el-form-item label="扫描工位/库位" prop="flow" style="width: 64%">
                            <el-input v-model="state.ruleForm.flow" placeholder="扫描工位/库位" clearable @keyup.enter="scanCodes" style="width: 40%" >
                                <template #append>
                                    <el-icon  @click="scanCodes"><ele-FullScreen /></el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
					<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="仓库编码" prop="storeCode">
							<el-input v-model="state.ruleForm.storeCode" readonly="true" placeholder="请输入仓库编码" maxlength="100" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="仓库名称" prop="storeName">
							<el-input v-model="state.ruleForm.storeName" readonly="true" placeholder="请输入仓库名称" maxlength="100" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col> -->
					<el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="8" class="mb20">
						<el-form-item label="位置编码" prop="storeSiteCode">
							<el-input v-model="state.ruleForm.storeSiteCode" readonly="true" placeholder="" maxlength="100" show-word-limit clearable disabled/>
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="8" class="mb20">
						<el-form-item label="位置名称" prop="storeSiteName">
							<el-input v-model="state.ruleForm.storeSiteName" readonly="true" placeholder="" maxlength="100" show-word-limit clearable disabled/>
							
						</el-form-item>
						
					</el-col>
					
					<el-col  :xs="12" :sm="12" :md="16" :lg="12" :xl="16" class="mb20">
						<el-form-item label="备注" prop="remank" >
							<el-input type="textarea"
							:rows="4" v-model="state.ruleForm.remank" placeholder="请输入备注" maxlength="100" show-word-limit clearable />
							
						</el-form-item>
					</el-col>
					
					<el-col  :xs="12" :sm="12" :md="{ span: 24, offset: 22 }" :lg="12" :xl="{ span: 24, offset: 23 }" class="mb20">
						<el-button type="primary" style="" @click="submit" >确定</el-button><!--@click="scanShow" size="large" -->
					</el-col>
					
				</el-row>
					<!-- <div class="card-footer" style="display: flex; justify-content: flex-end;">
                   <el-button type="primary" style="margin-left: 10px;" @click="submit">确 定</el-button>
                </div> -->
			</el-form>
		
           	 <!-- 卡片底部内容 -->
			


		</el-card>
		<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 } from "vue";
	import { ElMessage } from "element-plus";
	import type { FormRules } from "element-plus";
	//import { addMesPack, updateMesPack, detailMesPack } from "/@/api/simple/mesPack";
	//import { pageMesPack, deleteMesPack } from '/@/api/simple/mesPack';
	import { Scan } from "/@/api/simple/mesPackTransferLog";
	import { ScanStock } from "/@/api/simple/mesBarcodeInfo";
	import ChooseMaterial from "/@/views/simple/mesMonthSalePlan/component/chooseMaterial.vue";
  	import { formatDate } from '/@/utils/formatTime';
	import {  getPartMakeNum, genProduceBatchNo } from '/@/api/mes/mesProducePlan';
	import { getBomList } from '/@/api/mes/mesProduct';
	import { updateMesPack } from '/@/api/simple/mesCreatePackLog';
	import { getPersonByAccount } from '/@/api/mes/mesControlBoard';
	//父级传递来的参数
	var props = defineProps({
		title: {
		type: String,
		default: "",
	},
	});
	//父级传递来的函数，用于回调
	const emit = defineEmits(["reloadTable"]);
	const ruleFormRef = ref();
    const state = reactive({
    isShowDialog: false,
    ruleForm: {} as any,
});

const addForm = ref({
	productCode: null,
	batchNo: null,
	productBomId:null,
});

state.isShowDialog=true;
	//自行添加其他规则
	const rules = ref<FormRules>({
		packCode: [{required: true, message: '请输入载具编码！', trigger: 'blur',},],
		packName: [{required: true, message: '请输入载具名称！', trigger: 'blur',},],
		maxNum: [{required: true, message: '请输入最大载容量！', trigger: 'blur',},],
		num: [{required: true, message: '请输入当前装载量！', trigger: 'blur',},],
		batchNo: [{required: true, message: '请输入批次号！', trigger: 'blur',},],
		nickPeople: [{required: true, message: '请输入人员！', trigger: 'blur',},],
		productBomId: [{required: true, message: '请选择零件！', trigger: 'blur',},],
		// partCode: [{required: true, message: '请选择产品！', trigger: 'blur',},],
	});

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

	});

	// 打开弹窗
	const openDialog = async (row: any) => {
		// state.ruleForm = JSON.parse(JSON.stringify(row));
		// 改用detail获取最新数据来编辑
		let rowData = JSON.parse(JSON.stringify(row));
		//if (rowData.id)
			//state.ruleForm = (await detailMesPack(rowData.id)).data.result;
		//else
			state.ruleForm = rowData;
		state.isShowDialog = true;
	};

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

	// 取消
	const cancel = () => {
		state.isShowDialog = false;
	};
	const bomTreeData = ref([]);
	// 提交
	const submit = async () => {
		ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
			if (isValid) {
				if(addForm.value.productBomId==undefined)
                 {
  	               return ElMessage({
                   message: `请先选择零件！`,
                   type: "error",
                 });
                 }
				 if(state.ruleForm.num<=0)
                 {
  	               return ElMessage({
                   message: `数量不可以为0！`,
                   type: "error",
                 });
                 }
				let values = state.ruleForm;
				
				
			     await updateMesPack(values);
				 ElMessage.success('新增成功');
				 clears();
				
			} else {
				ElMessage({
					message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
					type: "error",
				});
			}
		});
	};

//成功后清空页面
const clears=async()=>{
	state.ruleForm.packCode=undefined;
	state.ruleForm.packName=undefined;
	state.ruleForm.maxNum=undefined;
	state.ruleForm.num=undefined;
	state.ruleForm.partCode=undefined;
	state.ruleForm.partName=undefined;
	addForm.value.productBomId=null;
	state.ruleForm.materialName=undefined;
	state.ruleForm.batchNo=undefined;
	state.ruleForm.materialNames=undefined;
	state.ruleForm.materialCodes=undefined;
	state.ruleForm.flow=undefined;
	state.ruleForm.storeCode=undefined;
	state.ruleForm.storeName=undefined;
	state.ruleForm.storeSiteCode=undefined;
	state.ruleForm.peopleCode=undefined;
	state.ruleForm.nickPeople=undefined;
	state.ruleForm.nickPeopleName=undefined;
	state.ruleForm.remank=undefined;
}


	// 扫码载具转移前条码
	const scanCode = async ()=>{
   
      let  res = await Scan({
        packCode:state.ruleForm.flowBarcode,
      })
      let data = res.data.result || {};
	  console.log(data);
	  if(data.packCode==undefined)
     {
  	   return ElMessage({
       message: `当前载具系统不存在！`,
       type: "error",
     });
     }
	if(data.packStatus==1)
     {
  	   return ElMessage({
       message: `载具状态不可以是使用中的载具！`,
       type: "error",
     });
     }
	 if(data.packStatus==2)
     {
  	   return ElMessage({
       message: `载具状态不可以是装载完成中的载具！`,
       type: "error",
     });
     }
     
      state.ruleForm.packCode=data.packCode;
	  state.ruleForm.packName=data.packName;
	  state.ruleForm.maxNum=data.maxNum;
	  state.ruleForm.num=data.num;
      state.ruleForm.flowBarcode = "";
    }

	  // 扫码仓库库位
const scanCodes = async ()=>{
      
      let  res = await ScanStock({
        stockPosCode:state.ruleForm.flow,
      })
      let data = res.data.result || {};
	  if(data.stockCode==undefined)
	  {
		return ElMessage({
        message: `系统中不存在当前库区库位`,
        type: "error",
      });
	  }
      state.ruleForm.storeCode=data.stockCode;
      state.ruleForm.storeName=data.stockName;
	  state.ruleForm.storeSiteCode=data.code;
      state.ruleForm.storeSiteName=data.name;
      state.ruleForm.flow = "";
    }

	const chooseMaterialRef = ref();
    const openChoose = ()=>{
      chooseMaterialRef.value.openDialog({})
    }
    const onChooseMaterialFinish = async(row)=>{
      state.ruleForm.partName = row?.materialName;
      state.ruleForm.partCode = row?.materialCode;
	  state.ruleForm.partModel = row?.specs;
	  state.ruleForm.partId = row?.id;

	  
	var res = await getBomList({ productCode: row?.materialCode });
	console.log(res);
	var treeData = res.data.result.filter((u: any) => u.pid == 0); //&& u.processList && u.processList.length>0

	treeData.forEach((el: any) => {
		el.value = el.id;
		el.label = `${el.materialName}[${el.materialCode}]`;
		el.disabled = !el.processList || el.processList.length == 0;
		recBom(res.data.result, el);
	});
	bomTreeData.value = treeData;
	bomTreeList.value = res.data.result;

 }

 const recBom = (bomList: any[], row: any) => {
	if (bomList) {
		var list = bomList.filter((u: any) => u.pid == row.productBomId); //&& u.processList && u.processList.length>0
		row.children = list;
		list.forEach((el: any) => {
			el.value = el.id;
			el.label = `${el.materialName}[${el.materialCode}]`;
			el.disabled = !el.processList || el.processList.length == 0;
			recBom(bomList, el);
		});
	}
};

	const bomTreeList = ref([]);
	const partMakeNum = ref('');
	const onBomChange = async (e: any) => {
		debugger
	addForm.value.productBomId = e;

	var node = bomTreeList.value.find((u: any) => u.id == e);
	state.ruleForm.materialCodes=node?.materialCode;
	state.ruleForm.materialNames=node?.materialName;
	var res = await getPartMakeNum({ partCode: node?.materialCode });
	partMakeNum.value = res.data.result;

	var genRes = await genProduceBatchNo({ partCode: node?.materialCode });
	if(genRes.data.result.length>6)
	{
		genRes.data.result= genRes.data.result.slice(0, -6)
	}
	state.ruleForm.batchNo = genRes.data.result;
};


//获取人员信息
const onScanAccounts = async () => {
	var res = await getPersonByAccount({ account: state.ruleForm.peopleCode });
	let data = res.data.result || {};
	state.ruleForm.nickPeople = data.account;
	state.ruleForm.nickPeopleName=data.realName;
	state.ruleForm.peopleCode=undefined;
	ElMessage.success('扫描成功');
};

</script>




