﻿<template>
	<div class="mesequipmentpartinapply-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" disabled="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="applyOrganCode">
							<el-input v-model="state.ruleForm.applyOrganCode"  disabled="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="applyOrganName">
							<el-input v-model="state.ruleForm.applyOrganName"  disabled="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="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="inDate">
							<el-date-picker v-model="state.ruleForm.inDate" 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="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="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-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="" >
                  <template  #default="scope">
                    <el-input type="text" v-model="scope.row.partBarCode" min="1"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="applyNum" label="入库数量" align="center"  show-overflow-tooltip="" >
                  <template  #default="scope">
                    <el-input-number  v-model="scope.row.applyNum"  :precision="0" min="1"/>
                  </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>
		<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 { addMesequipmentpartinapply, updateMesequipmentpartinapply, detailMesequipmentpartinapply, Scan } from "/@/api/simple/mesequipmentpartinapply";
	import { pageMesequipmentpartinapply, deleteMesequipmentpartinapply } from '/@/api/simple/mesequipmentpartinapply';
	import ChooseMaterialStock from "/@/businessComponents/chooseStock.vue";
  	import { formatDate } from '/@/utils/formatTime';//choosePart
	//import ChooseUser from "/@/views/simple/mesequipmentpartstock/component/chooseMaterial.vue";
	import ChooseUser from "/@/views/simple/mesequipmentpartinapply/component/chooseMaterial.vue";//"/@/businessComponents/chooseMaterial.vue";
	import { detailMesequipmentpartinapplydetail } from '/@/api/simple/mesequipmentpartinapplydetail';
import { title } from "process";
import { scanlist } from '/@/api/simple/dmsstockinfo';
	//父级传递来的参数
	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({});
    };

    const onChooseFinish = (data: any) => {
      console.log(data);
      let list: any[] = (data?.rows || []).map((item: any) => ({
        ...item,
        partCode: item.materialCode,
        partName: item.materialName,
		partId: item.id,
      }));
	  console.log(list);
      detailList.value.push(...list);
    };

	   
	//自行添加其他规则
	const rules = ref<FormRules>({
		//remark: [{required: true, message: '请输入描述！', trigger: 'blur',},],
		 warehouseCode: [{required: true, message: '请选择仓库！', trigger: 'blur',},],
		 applyDate: [{required: true, message: '请选择申请时间！', trigger: 'blur',},],
		 inDate: [{required: true, message: '请选择入库时间！', trigger: 'blur',},],
		 createOn: [{required: true, message: '请选择创建时间！', trigger: 'blur',},],
	});

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

	});

	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 openDialog = async (row: any) => {
		// state.ruleForm = JSON.parse(JSON.stringify(row));
		// 改用detail获取最新数据来编辑
		detailList.value = [];
		
		let rowData = JSON.parse(JSON.stringify(row));
		
		if (rowData.id)
	    {
	    	//state.ruleForm = (await detailMesequipmentpartinapply(rowData.id)).data.result;
			let data = (await detailMesequipmentpartinapply(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] || '',
            };
            });
	    }
			
		else
		{
			state.ruleForm = rowData;
			let  res = await scanlist();
            let datas = res.data.result || {};
			console.log(datas);
			if(datas.code!=undefined)
			{
				state.ruleForm.warehouseId=datas.id;
				state.ruleForm.warehouseCode=datas.code;
				state.ruleForm.warehouseName=datas.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.inDate==undefined)
	        {
	    	  return ElMessage({
              message: `请选择入库时间！`,
              type: "error",
            });
	        }
			if(state.ruleForm.createOn==undefined)
	        {
	    	  return ElMessage({
              message: `请选择创建日期！`,
              type: "error",
            });
	        }
			if (isValid && detailList.value.length>0) {
				let values = state.ruleForm;
				if (state.ruleForm.id == undefined || state.ruleForm.id == null || state.ruleForm.id == "" || state.ruleForm.id == 0)
				{
				// 备件绑定
				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 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;
						return true;
					}
					else
					{
						if(numbers[index]<=0)
						{
							ElMessage({
					     message: `第${index+1}行入库数量不可以为0`,
					     type: "error",
				        });
						num=false;
						return true;
						}else
						num=true;
					}
					
				};
				
				debugger
				if(barcodes && num)
				{
					//await addMesequipmentpartinapply(values);
					var result=(await addMesequipmentpartinapply(values)).data.result;
				    if(result=="添加成功"){
						closeDialog();
					}
				    else
				    {
				    	ElMessage({
				    message: `${'添加失败'}`,
				    type: "error",
				     });
				    }
				}
				else {
				if(detailList.value.length>0)
			    {
				    ElMessage({
					     message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
					     type: "error",
				    });
			    }else{
				    ElMessage({
					message: `入库明细无数据，请添加入库明细数据`,
					type: "error",
				});
			}
				
			}
			} 
			else {
					 //await updateMesequipmentpartinapply(values);
					var result=(await updateMesequipmentpartinapply(values)).data.result;
				    if(result=="修改成功"){
						closeDialog();
					}
				    else
				    {
				    	ElMessage({
				    message: `${'修改失败'}`,
				    type: "error",
				     });
				    }
				}
				   
			
		}
		else{
			if(detailList.value.length>0)
			    {
				    ElMessage({
					     message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
					     type: "error",
				    });
			    }else{
				    ElMessage({
					message: `入库明细无数据，请添加入库数据`,
					type: "error",
				});
			}
		}
		
		});
	};
	//将属性或者函数暴露给父组件
	defineExpose({ openDialog });
</script>




