﻿<template>
	<div class="mesequipmentpartoutapply-container">
		<el-dialog v-model="state.isShowDialog" v-if="state.isShowDialog" :width="800" 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="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="申请单据号" prop="applyCode">
							<el-input v-model="state.ruleForm.applyCode" readonly="true" placeholder="请输入申请单据号" maxlength="50" 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="applyTypeId">
							<el-input v-model="state.ruleForm.applyTypeId" placeholder="请输入申请类型主键" maxlength="0" 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="applyTypeCode">
							<el-input v-model="state.ruleForm.applyTypeCode" placeholder="请输入申请类型编号" maxlength="50" 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="applyTypeCode">
                            <el-input v-model="state.ruleForm.applyTypeCode" readonly="true" placeholder="请选择申请类型编号" maxlength="100" show-word-limit clearable >
                               <template #append v-if="props.title=='编辑备件出库申请'==false"> 
                               <el-button @click="openChooseApplyType">选择</el-button>
                               </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="applyTypeName">
							<el-input v-model="state.ruleForm.applyTypeName" readonly="true" placeholder="请输入申请类型名称" maxlength="50" 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="warehouseId">
							<el-input v-model="state.ruleForm.warehouseId" placeholder="请输入仓库主键" maxlength="0" 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="warehouseCode">
							<el-input v-model="state.ruleForm.warehouseCode" placeholder="请输入仓库编号" maxlength="50" 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="warehouseCode">
                            <el-input v-model="state.ruleForm.warehouseCode" readonly="true" placeholder="请选择仓库" maxlength="100" show-word-limit clearable >
                               <template #append v-if="props.title=='编辑备件出库申请'==false">
                               <el-button @click="openChooseStock">选择</el-button>
                               </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="warehouseName">
							<el-input v-model="state.ruleForm.warehouseName" readonly="true" placeholder="请输入仓库名称" maxlength="50" 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="applyReason">
							<el-input v-model="state.ruleForm.applyReason" placeholder="请输入出库原因" maxlength="255" 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="recrdState">
							<el-switch v-model="state.ruleForm.recrdState" active-text="是" inactive-text="否" />
							
						</el-form-item>
						
					</el-col> -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="申请时间" prop="applyDate">
							<el-date-picker v-model="state.ruleForm.applyDate" type="date" placeholder="申请时间" />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="出库时间" prop="outDate">
							<el-date-picker v-model="state.ruleForm.outDate" type="date" placeholder="出库时间" />
							
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="创建时间" prop="createOn">
							<el-date-picker v-model="state.ruleForm.createOn" type="datetime" placeholder="创建时间" />
							
						</el-form-item>
						
					</el-col>
					<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="排序" prop="sortCode">
							<el-input-number v-model="state.ruleForm.sortCode" placeholder="请输入排序" 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="remark">
							<el-input v-model="state.ruleForm.remark"  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="partCode">
							<el-input v-model="state.ruleForm.partCode" placeholder="请输入备件编码" maxlength="0" 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="partName">
							<el-input v-model="state.ruleForm.partName" placeholder="请输入备件名称" maxlength="0" 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="partBarCode">
							<el-input v-model="state.ruleForm.partBarCode" placeholder="请输入备件批次" maxlength="0" 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="applyNum">
							<el-input v-model="state.ruleForm.applyNum" placeholder="请输入申请数量" maxlength="0" show-word-limit clearable />
							
						</el-form-item>
						
					</el-col> -->
				</el-row>
			</el-form>
			<el-tabs :model-value="'item'" v-if="props.title=='编辑备件出库申请'==false">
                 <el-tab-pane label="出库单明细" name="item"></el-tab-pane>
            </el-tabs>
			<el-button type="primary" icon="ele-Plus" @click="subAdd" v-if="props.title=='编辑备件出库申请'==false"> 新增 </el-button>
			<el-table :data="detailList" v-if="props.title=='编辑备件出库申请'==false">
				<el-table-column type="index" label="序号" width="55" align="center" />
                <!-- <el-table-column prop="applyCode" label="入库单号"  show-overflow-tooltip="" /> -->
                <el-table-column prop="partCode" label="备件编号" align="center"  show-overflow-tooltip="" />
                <el-table-column prop="partName" label="备件名称" align="center"  show-overflow-tooltip="" />
                <!-- <el-table-column prop="partBarCode" label="备件批次"  show-overflow-tooltip="" /> -->
			    <el-table-column prop="partBarCode" label="备件批次" align="center"  show-overflow-tooltip="" />
                <el-table-column prop="applyNum" label="出库数量"  align="center" show-overflow-tooltip="" >
                  <template  #default="scope">
                    <el-input-number v-model="scope.row.applyNum"  min="1" :precision="0"/>
                  </template>
                </el-table-column>
                <!-- <el-table-column prop="remark" label="备注"  show-overflow-tooltip="" /> -->
                <el-table-column label="操作" align="center" width="140">
                  <template #default="scope">
                    <!-- <el-button @click="deleteRow(scope.$index)" icon="ele-Delete" size="small" text="" type="primary">删除</el-button> -->
					<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>
		<choose-material-stock title="选择仓库" ref="chooseMaterialRefStock" :is-any="false" @finish="onChooseMaterialFinishStock"></choose-material-stock>
		<ChooseMaterialApplyType title="选择出库类型" ref="chooseMaterialRefApplyType" :is-any="false" @finish="onChooseMaterialFinishApplyType"></ChooseMaterialApplyType>
		<choose-user title="选择库存" ref="chooseUserRef" :is-any="true" @finish="onChooseFinish"></choose-user>
	</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 { addMesequipmentpartoutapply, updateMesequipmentpartoutapply, detailMesequipmentpartoutapply } from "/@/api/simple/mesequipmentpartoutapply";
	import { pageMesequipmentpartoutapply, deleteMesequipmentpartoutapply } from '/@/api/simple/mesequipmentpartoutapply';
	import ChooseMaterialStock from "/@/businessComponents/chooseStock.vue";
	import ChooseMaterialApplyType from "/@/views/simple/mesequipmentpartoutapply/component/chooseOutboundType.vue";
  	import { formatDate } from '/@/utils/formatTime';
	import ChooseUser from "/@/views/simple/mesequipmentpartoutapply/component/chooseInventory.vue";
	import { scanlist } from '/@/api/simple/dmsstockinfo';
	import { scanlists } from '/@/api/simple/mesOutboundType';
	//父级传递来的参数
	var props = defineProps({
		title: {
		type: String,
		default: "",
	},
	});
	//父级传递来的函数，用于回调
	const emit = defineEmits(["reloadTable"]);
	const ruleFormRef = ref();
    const state = reactive({
    isShowDialog: false,
    ruleForm: {} as any,
});

const subDelete = (row: any, index: number) => {
        detailList.value.splice(index, 1);
    };
    // 子表
	const detailList = ref([]);
	const chooseUserRef = ref();
    const subAdd = () => {
        //chooseUserRef.value.openDialog({});
		if(!state.ruleForm.warehouseCode) return ElMessage.warning('请选择仓库');
        chooseUserRef.value.openDialog({
			warehouseCode:state.ruleForm.warehouseCode
        });
    };

    const onChooseFinish = (data: any) => {
      let list: any[] = (data?.rows || []).map((item: any) => ({
        ...item,
        partCode: item.partCode,
        partName: item.partName,
		partId: item.partId,
		partBarCode: item.partBarCode,
		applyNum: item.stockNum,
      }));
	  for(let index=0;index<list.length;index++) {
	  if(detailList.value.find((u:any)=> { return u.partCode == list[index].partCode && u.partBarCode==list[index].partBarCode })){
        return ElMessage({
        message: `产品${list[0].partCode}的批次号${list[0].partBarCode}不可以重复添加`,
        type: "error",
      });
      }
	}
      detailList.value.push(...list);
    };

	//自行添加其他规则
	const rules = ref<FormRules>({
		 warehouseCode: [{required: true, message: '请选择仓库！', trigger: 'blur',},],
		 applyDate: [{required: true, message: '请选择申请时间！', trigger: 'blur',},],
		 applyTypeCode: [{required: true, message: '请选择申请类型！', trigger: 'blur',},],
	     applyReason: [{required: true, message: '请输入出库原因！', trigger: 'blur',},],
		 outDate: [{required: true, message: '请选择出库时间！', trigger: 'blur',},],
		 createOn: [{required: true, message: '请选择创建时间！', trigger: 'blur',},],
	});

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


	// 打开弹窗
	const openDialog = async (row: any) => {
		// state.ruleForm = JSON.parse(JSON.stringify(row));
		// 改用detail获取最新数据来编辑
		detailList.value = [];
		let rowData = JSON.parse(JSON.stringify(row));
		if (rowData.id)
		{
			let data = (await detailMesequipmentpartoutapply(rowData.id)).data.result;
			state.ruleForm = data;
			// -备件
			detailList.value = (data.partCode || '')
            .split(',')
            .filter((item) => item)
            .map((item, index) => {
             return {
				partCode: item || '',
				partName: (data.partName || '').split(',').filter((item) => item)?.[index] || '',
				partBarCode: (data.partBarCode || '').split(',').filter((item) => item)?.[index] || '',
				applyNum: (data.applyNum || '').split(',').filter((item) => item)?.[index] || '',
            };
            });
		}
			//state.ruleForm = (await detailMesequipmentpartoutapply(rowData.id)).data.result;
		else
		{
			state.ruleForm = rowData;
			let  res = await scanlist();
            let datas = res.data.result || {};
			if(datas.code!=undefined)
			{
				state.ruleForm.warehouseId=datas.id;
				state.ruleForm.warehouseCode=datas.code;
				state.ruleForm.warehouseName=datas.name;
			}

			let  ress = await scanlists();
            let datass = ress.data.result || {};
			if(datass.code!=undefined)
			{
				state.ruleForm.applyTypeId=datass.id;
				state.ruleForm.applyTypeCode=datass.code;
				state.ruleForm.applyTypeName=datass.name;
			}
		}
			
		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(state.ruleForm.warehouseCode==undefined)
	        {
	    	  return ElMessage({
              message: `请选择仓库！`,
              type: "error",
            });
	        }
			if(state.ruleForm.applyDate==undefined)
	        {
	    	  return ElMessage({
              message: `请选择申请时间！`,
              type: "error",
            });
	        }
			if(state.ruleForm.outDate==undefined)
	        {
	    	  return ElMessage({
              message: `请选择出库时间！`,
              type: "error",
            });
	        }
			if(state.ruleForm.createOn==undefined)
	        {
	    	  return ElMessage({
              message: `请选择创建时间！`,
              type: "error",
            });
	        }
			if(state.ruleForm.applyTypeCode==undefined)
	        {
	    	  return ElMessage({
              message: `请选择申请类型！`,
              type: "error",
            });
	        }
			if(state.ruleForm.applyReason==undefined)
	        {
	    	  return ElMessage({
              message: `请输入出库原因！`,
              type: "error",
            });
	        }
			if(props.title=="添加备件出库申请")
			{
				if (isValid && detailList.value.length>0) {
				let values = state.ruleForm;
				values.partId = detailList.value.map((item: any) => item.partId).join(',');
				values.partCode = detailList.value.map((item: any) => item.partCode).join(',');
                values.partName = detailList.value.map((item: any) => item.partName).join(',');
				values.partBarCode = detailList.value.map((item: any) => item.partBarCode).join(',');
				//循环判断入库批次是否为空
				var li=values.partBarCode.split(',')
				var barcodes=false;
				for(let index=0;index<li.length;index++)
			    {
					if(li[index]=='')
				    {
						ElMessage({
							message: `第${index+1}行备件批次不可以为空`,
							type: "error",
						});
						barcodes=false;
						break;
					}
					else
					{
						barcodes=true;
					}
				}
				
				var num=false;
                values.applyNum = detailList.value.map((item: any) => item.applyNum).join(',');
				//截取最初库存数据var
				const stock=detailList.value.map((item: any) => item.stockNum).join(',');
				
				const stocknumber=stock.split(',');
				console.log(stocknumber[0]);
				//循环判断入库数量是否为空
				const numbers=values.applyNum.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]))
						    {
								ElMessage({
					                message: `第${index+1}行出库数量不可以大于库存数量`,
					                type: "error",
				                });
						            num=false;
						            break;
						    }
							else{
								num=true;
							}
						}
					}
					
				};
			
				if(barcodes && num)
				{
					if (state.ruleForm.id == undefined || state.ruleForm.id == null || state.ruleForm.id == "" || state.ruleForm.id == 0) {
					    //await addMesequipmentpartoutapply(values);
						var result=(await addMesequipmentpartoutapply(values)).data.result;
				    if(result=="添加成功"){
						closeDialog();
					}
				    else
				    {
				    	ElMessage({
				    message: `${'添加失败'}`,
				    type: "error",
				     });
				    }
				    } else {
					    await updateMesequipmentpartoutapply(values);
						closeDialog();
				    }
				       
				}
				
			} else {
				if(detailList.value.length>0)
			    {
				    ElMessage({
					     message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
					     type: "error",
				    });
			    }else{
				    ElMessage({
					message: `出库明细无数据，请添加入库数据`,
					type: "error",
				});}
			}
			}
			else
			{
				let values = state.ruleForm;
				//await updateMesequipmentpartoutapply(values);
				var result=(await updateMesequipmentpartoutapply(values)).data.result;
				    if(result=="修改成功"){
						closeDialog();
					}
				    else
				    {
				    	ElMessage({
				    message: `${'修改失败'}`,
				    type: "error",
				     });
				    }
			}
		});
	};

	const chooseMaterialRefStock = ref();
    const openChooseStock = ()=>{
		chooseMaterialRefStock.value.openDialog({})
    }
    const onChooseMaterialFinishStock = (row)=>{
      state.ruleForm.warehouseCode = row?.code;
      state.ruleForm.warehouseName = row?.name;
	  state.ruleForm.warehouseId = row?.id;
      // state.ruleForm.productNo = row?.materialNo;
    }

	const chooseMaterialRefApplyType = ref();
    const openChooseApplyType = ()=>{
		chooseMaterialRefApplyType.value.openDialog({})
    }
    const onChooseMaterialFinishApplyType = (row)=>{
      state.ruleForm.applyTypeId = row?.id;
      state.ruleForm.applyTypeCode = row?.code;
	  state.ruleForm.applyTypeName = row?.name;
      // state.ruleForm.productNo = row?.materialNo;
    }



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




