﻿<template>
	<div class="mesMonthProducePlan-container">
		<el-dialog v-model="state.isShowDialog" v-if="state.isShowDialog" width="60%" 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-table :data="detailList">
				<el-table-column type="index" label="序号" width="55" align="center" />
                <el-table-column prop="partCode" label="产品MES编码" align="center" show-overflow-tooltip="" width="120"/>
                <el-table-column prop="partName" label="产品名称" align="center"  show-overflow-tooltip="" width="120"/>
                <el-table-column prop="partModel" label="产品规格型号" align="center" show-overflow-tooltip="" width="140"/>
				<el-table-column prop="monthvalue" label="月份" align="center" show-overflow-tooltip="" width="120">
                  <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 prop="planNumber" label="计划数量" align="center" min="0" show-overflow-tooltip=""  width="140">
                  <template  #default="scope">
                    <el-input-number type="number"  v-model="scope.row.planNumber" :precision="0" />
                  </template>
                </el-table-column>
				<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>
	</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 { addMesMonthProducePlanBatch, detailMesMonthProducePlan } from "/@/api/simple/mesMonthProducePlan";
	import ChooseMaterialApplyType from "/@/views/simple/mesMonthProducePlan/component/chooseSalePlan.vue";
  	import { formatDate } from '/@/utils/formatTime';
	const monthvalue=ref(new Date());//获取当前月份
	//父级传递来的参数
	var props = defineProps({
		title: {
		type: String,
		default: "",
		monthvalue:String,
	},
	});
	//父级传递来的函数，用于回调
	const emit = defineEmits(["reloadTable"]);
	const ruleFormRef = ref();
    const state = reactive({
    isShowDialog: false,
    ruleForm: {} as any,
});

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

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

	});

 // 子表
 const detailList = ref([]);
 const complentNum=ref();//用来存单独接受的完工数
 const chooseMaterialRefApplyType = ref();
    const subAdd = () => {
		var monthvalues=monthvalue.value.getFullYear()+"-"+('0' + (monthvalue.value.getMonth() + 1)).slice(-2);
	    state.ruleForm.month=monthvalues;
		console.log(monthvalues);
		if(!state.ruleForm.month) return ElMessage.warning('请选择月份');
		chooseMaterialRefApplyType.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,
        partCode: item.partCode,
        partName: item.partName,
		partModel: item.partModel,
		planNumber: item.compleNumber,
		compleNumber: 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: `产品${list[0].partCode}不可以重复添加`,
        type: "error",
      });
      }
	}
      detailList.value.push(...list);
	  if(detailList.value.length<=0)
	    {
			closeDialog();
	    	return;
	    }
    };

	// 打开弹窗
	const openDialog = async (row: any) => {
		// 改用detail获取最新数据来编辑
		detailList.value = [];
		let rowData = JSON.parse(JSON.stringify(row));
		if (rowData.id)
		{
			state.ruleForm = (await detailMesMonthProducePlan(rowData.id)).data.result;
		}
		else
		{
			state.ruleForm = rowData;
			monthvalue.value=new Date(rowData.monthvalue+"-01");
			subAdd();
		}
		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.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.planNumber = detailList.value.map((item: any) => item.planNumber).join(',');
				values.remark = detailList.value.map((item: any) => item.remark).join(',');

				//获取完工数
				const stock=detailList.value.map((item: any) => item.compleNumber).join(',');
				const stocknumber=stock.split(',');
				if(values.planNumber==""){
                 return ElMessage({
                  message: `请添加生产计划！`,
                  type: "error",
                });
                }
				//循环判断计划数量是否为空
				var num=false;
				const numbers=values.planNumber.split(',')
				for(let index=0;index<numbers.length;index++) {
					if(numbers[index]=='' && numbers[index]==0)
				    {
						ElMessage({
					     message: `第${index+1}行计划数量不可以为空`,
					     type: "error",
				        });
						num=false;
						break;
					}
					else
					{
						if(numbers[index]<=0)
						{
							ElMessage({
					     message: `第${index+1}行计划数量不可以为0`,
					     type: "error",
				        });
						num=false;
						break;
						}
						else
						{
							if(numbers[index]>parseFloat(stocknumber[index])*1.1)
						    {
								ElMessage({
					                message: `第${index+1}行计划数量不可以超过产品预投未完工数上限10%`,
					                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)
				    {
						var result=(await addMesMonthProducePlanBatch(values)).data.result;
					if(result=="添加成功")
					 closeDialog();
					else
					{
						ElMessage({
					message: `${result}`,
					type: "error",
				});
					}
					}
				 	
				 } 
				 
			} else {
				ElMessage({
					message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
					type: "error",
				});
			}
		});
	};




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




