<template>
	<div class="barcodemain-container">
		<el-card shadow="hover" :body-style="{ padding: '20px 20px 16px 10px', display: 'flex', width: '100%', height: '100%', alignItems: 'start' }">
			<el-form  ref="queryForm" :show-message="false" :inlineMessage="true" label-width="auto" style="flex: 1 1 0%" >
				<el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb5">
						<el-form-item label="MES批次" prop="batchNo" :required="true">
              <el-input v-model="state.ruleForm.flow" placeholder="扫描MES批次" clearable @keyup.enter="scanList"  >
                  <template #append>
                      <el-icon  @click="scanList"><ele-FullScreen /></el-icon>
                  </template>
              </el-input>
              <el-input v-model="state.ruleForm.batchNo" placeholder="MES批次" readonly="true" maxlength="100" show-word-limit clearable >
                  <template #append>
                  <el-button @click="openChooseApplyType">选择</el-button>
                  </template>
              </el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb5">
						<el-form-item label="MES编码" prop="productCode">
							<el-input v-model="state.ruleForm.productCode" readonly="true" placeholder="请输入MES编码" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb5" >
						<el-form-item label="MES名称" prop="productName">
							<el-input v-model="state.ruleForm.productName" readonly="true" placeholder="请输入MES名称" clearable />
						</el-form-item>
					</el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb5">
						<el-form-item label="主计量单位编码" prop="unitGroupName">
							<el-input v-model="state.ruleForm.unitGroupName" readonly="true" placeholder="请输入主计量单位编码" clearable  />
						</el-form-item>
					</el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb5">
						<el-form-item label="包装箱数" prop="packageNum" :required="true">
							<el-input v-model="state.ruleForm.packageNum" placeholder="请输入包装箱数" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb5" >
						<el-form-item label="每箱数量" prop="number" :required="true">
							<el-input v-model="state.ruleForm.number" placeholder="请输入每箱数量" clearable  />
						</el-form-item>
					</el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb5">
						<el-form-item label="MES入库批次" prop="code" :required="true">
							<el-input v-model="state.ruleForm.code" placeholder="请输入MES入库批次" @input="handleInput" clearable  />
						</el-form-item>
					</el-col>
        
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb5">
						<el-form-item label="总数量" prop="sumNumber">
							<el-input v-model="state.ruleForm.sumNumber" readonly="true" placeholder="请输入总数量" clearable  />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<el-divider style="height: calc(100% - 5px); margin: 0 12px" direction="vertical" />

			<el-row :gutter="12">
				<el-col :span="14">
					<el-button-group> 
						<el-button icon="ele-CopyDocument" left-padding="2px" @click="generate"> 生成 </el-button> 
						<el-button icon="ele-Refresh"  left-padding="2px" @click="resetQuery"  > 重置 </el-button>
					</el-button-group>
				</el-col>
        <el-col :span="14">
					<el-button-group>
						<el-button icon="ele-EditPen"  @click="batchsave"> 保存 </el-button>
						<el-button icon="ele-Printer" @click="batchprint"> 打印 </el-button>
					</el-button-group>
				</el-col>
			</el-row>
		</el-card>

		<el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table :data="detailList" >
				<el-table-column type="index" label="序号" header-align="center" width="55" align="center" />
                <el-table-column prop="barCode" header-align="center" width="200" label="条码"  show-overflow-tooltip="" />
                <el-table-column prop="cInvCode" label="ERP编码" width="140" header-align="center" show-overflow-tooltip="" />
                <el-table-column prop="cInvName" label="ERP名称" width="140" header-align="center" show-overflow-tooltip="" />
                <!-- <el-table-column prop="qty" label="数量"  show-overflow-tooltip="" >
                  <template  #default="scope">
                    <el-input-number  v-model="scope.row.qty"  :precision="0" min="1"/>
                  </template>
                </el-table-column> -->
                <el-table-column prop="pLot" label="批次" width="90" header-align="center"  show-overflow-tooltip="" />
                <el-table-column prop="qty" label="数量" width="80" header-align="center" show-overflow-tooltip="" />
                <el-table-column prop="cComUnitName" label="主计量单位" width="100" header-align="center" show-overflow-tooltip="" />
                <el-table-column prop="barCodeRule" label="规则编码" width="90" header-align="center"  show-overflow-tooltip="" />
                <el-table-column prop="barCodeName" label="规则名称" width="90" header-align="center" show-overflow-tooltip="" />
                <el-table-column prop="cLabelCode" label="标签代码" width="90" header-align="center" show-overflow-tooltip="" />
                <el-table-column prop="cLabelName" label="标签名称" width="90" header-align="center" show-overflow-tooltip="" />
                <el-table-column label="操作" header-align="center"  width="140">
                  <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>
            <ChooseMaterialApplyType title="选择MES计划" ref="chooseMaterialRefApplyType" :is-any="false" @finish="onChooseMaterialFinishApplyType"></ChooseMaterialApplyType>
    </el-card>


	</div>
</template>

<script lang="ts" setup name="dmsstockinfo">
import { onMounted, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage } from "element-plus";
import { auth } from '/@/utils/authFunction';
import ChooseMaterialApplyType from "/@/views/simple/barCodeMain/component/chooseProductPlan.vue";
import { VxeGridInstance, VxeGridListeners, VxeGridPropTypes } from 'vxe-table';
import { useVxeTable } from '/@/hooks/useVxeTableOptionsHook';
import { Local } from '/@/utils/storage';

import { formatDate } from '/@/utils/formatTime';
import { getAPI } from '/@/utils/axios-utils';
import { SysPrintApi } from '/@/api-services/api';
import { hiprint } from 'vue-plugin-hiprint';
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import MesRuleProcessProdCycleDetail from '/@/views/simple/dmsStockPosInfo/index.vue'
import { getItemCodeDropdown,pageHyBarCodeMainList ,batchsavestore} from '/@/api/simple/hyBarCodeMain';;
const datastate=ref(0);//数据流状态，0是初始（生成）状态，1是保存状态，2是打印状态
// 变量
const state = reactive({
  ruleForm: {} as any,
	visible: false,
	title: '',
});



// 本地存储参数
const localPageParamKey = 'localPageParam:barcodemain';

// 页面初始化
onMounted(() => {});

// 重置操作
const resetQuery = async () => {
	state.ruleForm.flow = undefined;
	state.ruleForm.batchNo = undefined;
	state.ruleForm.productCode = undefined;
	state.ruleForm.productName = undefined;
	state.ruleForm.unitGroupName = undefined;
	state.ruleForm.packageNum = undefined;
	state.ruleForm.number = undefined;
	state.ruleForm.code = undefined;
  state.ruleForm.sumNumber = undefined;
  state.ruleForm.unitName = undefined;
  detailList.value=[];
};


// 子表
const detailList = ref([]);

//删除
const subDelete = (row: any, index: number) => {
     if(row.datastate==1)
      {
      return ElMessage({
          message: `已保存的数据不允许进行删除！`,
          type: "error",
        });
      }
        state.ruleForm.sumNumber=parseFloat(state.ruleForm.sumNumber)-parseFloat(row.qty);
        detailList.value.splice(index, 1);
    };

// 扫码条码
const scanList = async ()=>{
      
      if(state.ruleForm.flow==undefined)
      {
      return ElMessage({
          message: `请先扫描MES批次码`,
          type: "error",
        });
      }
     let  res = await getItemCodeDropdown({
      barCode:state.ruleForm.flow,
     })
     let data = res.data.result || {};
     console.log(data);
     if(data==undefined && data==null && data=="")
     {
		   state.ruleForm.flow=undefined;
  	   return ElMessage({
       message: `当前批次码不存在，请重新扫描！`,
       type: "error",
     });
     }

     if(data.length<=0)
     {
		   state.ruleForm.flow=undefined;
  	   return ElMessage({
       message: `当前批次码不存在，请重新扫描！`,
       type: "error",
     });
     }
     resetQuery();

     state.ruleForm.producePlanNo=data[0].producePlanNo;
     state.ruleForm.batchNo=data[0].batchNo;
     state.ruleForm.productCode=data[0].productCode;
     state.ruleForm.productName=data[0].productName;
     state.ruleForm.unitGroupName=data[0].unitGroupName;
     state.ruleForm.unitName=data[0].unitName;
     const times = new Date();//当前时间
     const barcode=times.getFullYear().toString().slice(-2)+('0' + (times.getMonth() + 1)).slice(-2)+times.getDate().toString().padStart(2, '0');
     state.ruleForm.code=barcode;
     state.ruleForm.flow = "";
}
  
//选择装配生产批计划
	const chooseMaterialRefApplyType = ref();
    const openChooseApplyType = ()=>{
		chooseMaterialRefApplyType.value.openDialog({
		})
    }
    const onChooseMaterialFinishApplyType = (row:any)=>{
      resetQuery();

      state.ruleForm.producePlanNo=row.producePlanNo;
      state.ruleForm.batchNo=row.batchNo;
      state.ruleForm.productCode=row.productCode;
      state.ruleForm.productName=row.productName;
      state.ruleForm.unitGroupName=row.unitGroupName;
      state.ruleForm.unitName=row.unitName;
      const times = new Date();//当前时间
      const barcode=times.getFullYear().toString().slice(-2)+('0' + (times.getMonth() + 1)).slice(-2)+times.getDate().toString().padStart(2, '0');
      state.ruleForm.code=barcode;
    }


  const handleInput=(value:any) =>{
      // 使用正则表达式限制只能输入6位数字
      state.ruleForm.code = value.replace(/[^\d]/g, '');
      // 限制输入长度为6位
      if (state.ruleForm.code.length > 6) {
        state.ruleForm.code =  state.ruleForm.code.slice(0, 6);
      }
    }
    const barcodenumber=ref(1000001);//初始流水号
    //生成按钮
  const generate = async() =>{
     if(state.ruleForm.batchNo==undefined)
     {
      return ElMessage({
          message: `生成装箱码时MES批次不可以为空！`,
          type: "error",
        });
     }
     if(state.ruleForm.code==undefined)
     {
      return ElMessage({
          message: `ERP入库批次不可以为空！`,
          type: "error",
        });
     }
     if(state.ruleForm.code.length<6)
     {
      return ElMessage({
          message: `ERP入库批次不可以小于6位！`,
          type: "error",
        });
     }
     if(state.ruleForm.packageNum>0 && state.ruleForm.number>0)
     {
        //调用U8查询数据查看今天是否存在当前批次
        let  res = await pageHyBarCodeMainList({
         barCode:state.ruleForm.code,productCode:state.ruleForm.productCode,
         })
         let data = res.data.result || {};
         const barcode=ref(1000001);////初始流水号
         console.log(data);
         if(data.length>0)
         {
            const num=data[0].barCode.substring(data[0].barCode.length-7);
            const number=parseFloat(num)+1;
            barcode.value=number;
         }
         if(detailList.value.length>0)
         {
          if(detailList.value[detailList.value.length-1].pLot==state.ruleForm.code)
          {
           barcode.value=barcodenumber.value+1;
          }
         }
         
        for(let index=0;index<state.ruleForm.packageNum;index++)
        {
          const datalist=ref([{
            barCode:state.ruleForm.productCode+state.ruleForm.code+(barcode.value+index),
            cInvCode:state.ruleForm.productCode,
            cInvName:state.ruleForm.productName,
            qty:state.ruleForm.number,
            pLot:state.ruleForm.code,
            cComUnitName:state.ruleForm.unitName,
            barCodeRule:"001",
            barCodeName:"产品",
            cLabelCode:"01",
            datastate:datastate.value,
            cLabelName:"产品"
          }]);
          barcodenumber.value=barcode.value+index;
          detailList.value.push(...datalist.value);
        }
        if(state.ruleForm.sumNumber==undefined && detailList.value.length>0)
        state.ruleForm.sumNumber=parseFloat(state.ruleForm.packageNum)*parseFloat(state.ruleForm.number);
        else
        state.ruleForm.sumNumber=parseFloat(state.ruleForm.sumNumber)+parseFloat(state.ruleForm.packageNum)*parseFloat(state.ruleForm.number);
     }
     else{
      return ElMessage({
          message: `生成装箱码请先输入包装箱数和每箱数量！`,
          type: "error",
        });
     }
}

//保存按钮
const batchsave=async()=>{
   if(detailList.value.length>0)
   {
      //查找生成的条码的数据
      const list=detailList.value.filter(item=>item.datastate===0);
      console.log(list);
      if(list.length>0)
      {
				let values = state.ruleForm;
        values.data=list;
				var result=(await batchsavestore(values)).data.result;
				if(result=="添加成功")
         {
          ElMessage({
          message: `保存成功`,
          type: "success",
        });
        // 使用map替换状态（保存后进行替换已保存的状态，改为保存状态，用于方便打印）
       const updatedList = detailList.value.map(item => {
       if (item.datastate === 0) {
          return { ...item, datastate: 1 };
         }
         return item;
       });
      // 更新detailList.value
       detailList.value = updatedList;  
       console.log(detailList);  

         }
				else
				{
						ElMessage({
					message: `${result}`,
					type: "error",
				  });
				}
      }
      else
      {
        return ElMessage({
          message: `当前页面无可保存数据`,
          type: "error",
        });
      }
   }else{
    return ElMessage({
          message: `当前页面无数据，不可以进行保存`,
          type: "error",
        });
   }
};
const printTitle = ref('');
const batchprint=async()=>{
      //查找保存的的条码的数据
      if(detailList.value.length>0)
      {
        const list=detailList.value.filter(item=>item.datastate===1);
      console.log(list);
      if(list.length>0)
      {
				let printRes = await getAPI(SysPrintApi).apiSysPrintPrintNameGet('装箱码打印40');
	      let template = JSON.parse(printRes.data.result?.template);
	       printTitle.value = '包装箱信息打印';
	       let templates: any = [];
	       list.forEach((el: any) => {
	       	templates.push({ template: new hiprint.PrintTemplate({ template: template }), data: el });
	       });
	       hiprint.print({
	       	templates: templates,
	       });
      }
      else
      {
        return ElMessage({
          message: `请先保存在打印！`,
          type: "error",
        });
      }
      }
      else
      {
        return ElMessage({
          message: `当前页面可以打印数据！`,
          type: "error",
        });
      }
};

</script>

<style lang="scss" scoped>
:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
