﻿<template>
	<div class="mesWeekSalePlan-container">
		<el-dialog v-model="state.isShowDialog" v-if="state.isShowDialog" :width="1500" 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-row>
			</el-form>
			<el-tabs :model-value="'item'">
                 <el-tab-pane label="批量添加周生产计划" name="item"></el-tab-pane>
            </el-tabs>
			<el-button type="primary" icon="ele-Plus" @click="subAdd" > 从月计划中新增  </el-button>
			<el-button type="primary" icon="ele-Plus" @click="subAddMonth" > 从周销售计划中新增</el-button>
			<el-table :data="detailList">
				<el-table-column type="index" label="序号" width="55" align="center" />
				<!-- <el-table-column prop="orderCode" label="月生产计划"  show-overflow-tooltip="" /> -->
                <el-table-column prop="partCode" label="产品ERP编码" align="center" width="120"  show-overflow-tooltip="" />
                <el-table-column prop="partName" label="产品名称" align="center" width="120"  show-overflow-tooltip="" />
                <el-table-column prop="partModel" label="产品规格型号" align="center" width="100"  show-overflow-tooltip="" />
				<el-table-column prop="month" label="月份" align="center" show-overflow-tooltip="" width="100">
                  <template  #default="scope">
					<el-date-picker v-model="monthvalue" type="month"  placeholder="请输入月份" disabled="true" :default-value="new Date(2024,10)"  show-word-limit clearable />
                  </template>
                </el-table-column>
                <el-table-column :label="weekLabelfirst" prop="firstWeek" align="center"  width="120" show-overflow-tooltip=""  >
                  <template  #default="scope">
                    <el-input-number type="number"  min="0" v-model="scope.row.firstWeek" :precision="0" />
                  </template>
                </el-table-column>
				<el-table-column prop="tuesday" :label="weekLabeltwo" align="center" width="120" show-overflow-tooltip="" >
                  <template  #default="scope">
                    <el-input-number type="number"  min="0" v-model="scope.row.tuesday" :precision="0" />
                  </template>
                </el-table-column>
				<el-table-column prop="threeWeek" :label="weekLabelthree" align="center" width="120" show-overflow-tooltip="" >
                  <template  #default="scope">
                    <el-input-number type="number"  min="0" v-model="scope.row.threeWeek" :precision="0"/>
                  </template>
                </el-table-column>
				<el-table-column prop="fourWeek" :label="weekLabelfour" align="center" width="120" show-overflow-tooltip="" >
                  <template  #default="scope">
                    <el-input-number type="number"  min="0" v-model="scope.row.fourWeek" :precision="0"/>
                  </template>
                </el-table-column>
				<el-table-column prop="fiveWeek" :label="weekLabelfive" align="center" width="120"  v-if="weeklabel>4==true"  show-overflow-tooltip="" >
                  <template  #default="scope">
                    <el-input-number type="number"  min="0" v-model="scope.row.fiveWeek" :precision="0"/>
                  </template>
                </el-table-column>
				<el-table-column prop="saleNumber" label="销售未完成数量" align="center" width="100"  show-overflow-tooltip="" />
				<el-table-column prop="planOrderNumber" label="生产未完成数量" align="center" width="100"  show-overflow-tooltip="" />
				<el-table-column prop="remark" label="备注" align="center"  show-overflow-tooltip="" >
                  <template  #default="scope">
                    <el-input type="text" v-model="scope.row.remark" ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" 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>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<ChooseMaterialApplyType title="选择月生产计划" ref="chooseMaterialRefApplyType" :is-any="true" @finish="onChooseMaterialFinishApplyType"></ChooseMaterialApplyType>
		<ChooseWeekSalePlanPlan title="选择周销售计划" ref="chooseRefApplyType" :is-any="true" @finish="onChooseFinishApplyType"></ChooseWeekSalePlanPlan>

	</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 { addMesWeekProducePlanBatch, detailMesWeekProducePlan } from "/@/api/simple/mesWeekProducePlan";
	import ChooseMaterialApplyType from "/@/views/simple/mesWeekProducePlan/component/chooseMonnthProductPlan.vue";
	import ChooseWeekSalePlanPlan from "/@/views/simple/mesWeekProducePlan/component/chooseWeekSalePlanPlan.vue";
  	import { formatDate } from '/@/utils/formatTime';
	const monthvalue=ref(new Date());//获取当前月份
	//父级传递来的参数
	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 detailList = ref([]);

//从月计划选择
 const chooseMaterialRefApplyType = ref();
    const subAdd = () => {
		var monthvalues=monthvalue.value.getFullYear()+"-"+('0' + (monthvalue.value.getMonth() + 1)).slice(-2);
	    state.ruleForm.month=monthvalues;
		if(!state.ruleForm.month) return ElMessage.warning('请选择月份');
		chooseMaterialRefApplyType.value.openDialog({
			month:state.ruleForm.month
		})
    };

	//从周计划选择
	const chooseRefApplyType = ref();
    const subAddMonth = () => {
		var monthvalues=monthvalue.value.getFullYear()+"-"+('0' + (monthvalue.value.getMonth() + 1)).slice(-2);
	    state.ruleForm.month=monthvalues;
		if(!state.ruleForm.month) return ElMessage.warning('请选择月份');
		chooseRefApplyType.value.openDialog({
			month:state.ruleForm.month
		})
    };

    //删除选中行
	const subDelete = (row: any, index: number) => {
        detailList.value.splice(index, 1);
    };

	//从月计划选择后赋值
	const onChooseMaterialFinishApplyType = (data: any) => {
      let list: any[] = (data?.rows || []).map((item: any) => ({
        ...item,
		sourceCode:item.orderCode,
        partCode: item.partCode,
        partName: item.partName,
		partModel: item.partModel,
		firstWeek: item.planNumber,
		tuesday: 0,
		threeWeek: 0,
		fourWeek: 0,
		fiveWeek: 0,
		sumPlanNuber: item.planNumber,
		saleNumber:item.number,
		planOrderNumber: item.compleNumber,
      }));
	  for(let index=0;index<list.length;index++) {
		if(detailList.value.find((u:any)=> { return u.partCode == list[index].partCode })){
        return ElMessage({
        message: `产品不可以重复添加！`,
        type: "error",
      });
      }
	  }
	  
      detailList.value.push(...list);
	  if(detailList.value.length<=0)
	  {
		closeDialog();
	  }
    };

	//从周销售计划选择后赋值
	const onChooseFinishApplyType = (data: any) => {
      let list: any[] = (data?.rows || []).map((item: any) => ({
        ...item,
		sourceCode:item.orderCode,
        partCode: item.partCode,
        partName: item.partName,
		partModel: item.partModel,
		firstWeek: item.firstWeek,
		tuesday: item.tuesday,
		threeWeek: item.threeWeek,
		fourWeek: item.fourWeek,
		fiveWeek: item.fiveWeek,
		sumPlanNuber: item.sumPlanNuber,
		saleNumber:item.saleNumber,
		planOrderNumber: item.planOrderNumber,
      }));
	  for(let index=0;index<list.length;index++) {
		if(detailList.value.find((u:any)=> { return u.partCode == list[index].partCode })){
        return ElMessage({
        message: `产品不可以重复添加！`,
        type: "error",
      });
      }
	  }
	  
      detailList.value.push(...list);
	  if(detailList.value.length<=0)
	  {
		closeDialog();
	  }
    };

	// 打开弹窗
	const openDialog = async (row: any) => {
		// 改用detail获取最新数据来编辑
		detailList.value = [];
		let rowData = JSON.parse(JSON.stringify(row));
		if (rowData.id)
		{
			state.ruleForm = (await detailMesWeekProducePlan(rowData.id)).data.result;
		}
		else
		{
			state.ruleForm = rowData;
			monthvalue.value=new Date(rowData.monthvalue+"-01");
		}
		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;
				var monthvalues=monthvalue.value.getFullYear()+"-"+('0' + (monthvalue.value.getMonth() + 1)).slice(-2);
				state.ruleForm.month=monthvalues;
				values.sourceCode = detailList.value.map((item: any) => item.sourceCode).join(',');
				values.partCode = detailList.value.map((item: any) => item.partCode).join(',');
                values.partName = detailList.value.map((item: any) => item.partName).join(',');
				values.partModel = detailList.value.map((item: any) => item.partModel).join(',');
				values.firstWeek = detailList.value.map((item: any) => item.firstWeek).join(',');
				values.tuesday = detailList.value.map((item: any) => item.tuesday).join(',');
				values.threeWeek = detailList.value.map((item: any) => item.threeWeek).join(',');
				values.fourWeek = detailList.value.map((item: any) => item.fourWeek).join(',');
				values.fiveWeek = detailList.value.map((item: any) => item.fiveWeek).join(',');
				values.sumPlanNuber = detailList.value.map((item: any) => item.sumPlanNuber).join(',');
				values.saleNumber = detailList.value.map((item: any) => item.saleNumber).join(',');
				values.planOrderNumber = detailList.value.map((item: any) => item.planOrderNumber).join(',');
				values.remark = detailList.value.map((item: any) => item.remark).join(',');
				//获取总计划数用于判断
				const stock=detailList.value.map((item: any) => item.sumPlanNuber).join(',');
				const stocknumber=stock.split(',');

				//循环判断计划数量是否为空
				var num=false;
				//获取第一周计划数
				const numbers=values.firstWeek.split(',')
				//获取第二周计划数
				const numbertuw=values.tuesday.split(',')
				//获取第三周计划数
				const numberthree=values.threeWeek.split(',')
				//获取第四周计划数
				const numberfour=values.fourWeek.split(',')
				//获取第五周计划数
				const numberfive=values.fiveWeek.split(',')
				for(let index=0;index<numbers.length;index++) {
					if(sundaysInMonth.length>4)
					{
						if(numberfive[index]=='')
				        {
						ElMessage({
					     message: `第${index+1}行第五周计划数量不可以为空`,
					     type: "error",
				        });
						num=false;
						break;
					    }
					}

					if((numbers[index]=='')||(numbertuw[index]=='' )||(numberthree[index]=='' )||(numberfour[index]=='' ))
				    {
						ElMessage({
					     message: `第${index+1}行计划数量不可以为空`,
					     type: "error",
				        });
						num=false;
						break;
					}
					else
					{
						if((numbers[index]=='')||(numbertuw[index]=='' )||(numberthree[index]=='' )||(numberfour[index]=='' )||numberfive[index]=='')
						{
							numbers[index]=0;
							numbertuw[index]=0;
							numberthree[index]=0;
							numberfour[index]=0;
							numberfive[index]=0;
						}
						
						if((parseFloat(numbers[index])+parseFloat(numbertuw[index])+parseFloat(numberthree[index])+parseFloat(numberfour[index])+parseFloat(numberfive[index]))>parseFloat(stocknumber[index])*1.1)
						{
							ElMessage({
					            message: `第${index+1}行周计划数量总数不可以超过月总计划数上限10%`,
					            type: "error",
				            });
						        num=false;
						        break;
						}
						else if((numbers[index]<0) ||(numbertuw[index]<0 )||(numberthree[index]<0 )||(numberfour[index]<0 )||numberfive[index]<0)
						{
							ElMessage({
					            message: `第${index+1}行周生产计划数量不可以小于0`,
					            type: "error",
				            });
						        num=false;
						        break;
						}
						else{
							num=true;
						}
						
					}
					
				};
				if (state.ruleForm.id == undefined || state.ruleForm.id == null || state.ruleForm.id == "" || state.ruleForm.id == 0) {
					if(num==true)
				    {
						await addMesWeekProducePlanBatch(values);
						closeDialog();
					}
				 	
				 } 
				 
			} else {
				ElMessage({
					message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
					type: "error",
				});
			}
		});
	};


	const weekLabelfirst=ref();//第一周label变量
	const weekLabeltwo=ref();//第二周label变量
	const weekLabelthree=ref();//第三周label变量
	const weekLabelfour=ref();//第四周label变量
	const weekLabelfive=ref();//第五周label变量
	const weeklabel=ref();
	//日期事件
	  //获取月份的年和月
      var monthvalues=monthvalue.value.getFullYear()+"-"+('0' + (monthvalue.value.getMonth() + 1)).slice(-2);
	  console.log(monthvalues);
	  //获取当前月份所有天数
	  const daysInMonth = new Date(monthvalue.value.getFullYear(), (monthvalue.value.getMonth() + 1), 0).getDate();
	  const sundaysInMonth = [];//数组接收需要的所有周
	  //循环当前月所有天	 
      for (let day = 1; day <= daysInMonth; day++) {
        const date = new Date(monthvalue.value.getFullYear(), monthvalue.value.getMonth(), day);//取当前日期
        if (date.getDay() === 0) { // 0 表示周日
			//取本月的周日
	        var last=('0' + (date.getMonth() + 1)).slice(-2)+"."+('0' + (date.getDate())).slice(-2);
			//取本月周日对应的周一事件
			const da = new Date(date);
			da.setDate(date.getDate() - 6);
			//值取月和日
			var first=('0' + (da.getMonth() + 1)).slice(-2)+"."+('0' + (da.getDate())).slice(-2);

            sundaysInMonth.push(first+"-"+last);
        }
      }
	  weeklabel.value=sundaysInMonth.length;
	  if(sundaysInMonth.length<=4)
	  {
		weekLabelfirst.value=sundaysInMonth[0];
		weekLabeltwo.value=sundaysInMonth[1];
		weekLabelthree.value=sundaysInMonth[2];
		weekLabelfour.value=sundaysInMonth[3];
	  }
	  else{
		weekLabelfirst.value=sundaysInMonth[0];
		weekLabeltwo.value=sundaysInMonth[1];
		weekLabelthree.value=sundaysInMonth[2];
		weekLabelfour.value=sundaysInMonth[3];
		weekLabelfive.value=sundaysInMonth[4];
	  }
    



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




