﻿<template>
	<div class="mesInStore-container">
		<el-dialog v-model="state.isShowDialog" v-if="state.isShowDialog" width="80%" draggable="" :close-on-click-modal="false" :show-close="true" @close="cancel">
			<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="inStoreNo">-->
<!--							<el-input v-model="state.ruleForm.inStoreNo" placeholder="请输入入库单号" maxlength="100" 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="inStoreType">
							<el-select clearable v-model="state.ruleForm.inStoreType" placeholder="请选择入库类型">
								<el-option v-for="(item,index) in dl('InStoreType')"  :key="index" :value="item.value" :label="`${item.name} [${item.value}]`"></el-option>

							</el-select>

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="入库仓库" prop="inStoreCode">
							<el-input v-model="state.ruleForm.inStoreCode" placeholder="请输入入库仓库" maxlength="100" show-word-limit clearable disabled />

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="客户" prop="customerCode">
<!--							<el-select clearable filterable v-model="state.ruleForm.customerCode" placeholder="请选择客户">-->
<!--								<el-option v-for="(item,index) in mesCustomerCustomerCodeDropdownList" :key="index" :value="item.value" :label="item.label" />-->

<!--							</el-select>-->
              <el-autocomplete v-model="state.ruleForm.customerCode"  maxlength="100" show-word-limit :fetch-suggestions="autoCustomerList" @select="autoCustomerSelect">
                <template #append>
                  <el-button @click="openChooseCustome">选择</el-button>
                </template>
                <template #default="{ item }">
      <div class="value">{{ item }}</div>
    </template>
              </el-autocomplete>
						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="生产订单号" prop="produceOrderNo">
<!--							<el-input v-model="state.ruleForm.produceOrderNo" placeholder="请输入生产订单号" maxlength="100" show-word-limit clearable />-->
              <el-autocomplete v-model="state.ruleForm.produceOrderNo" placeholder="请选择生产订单号" maxlength="100" show-word-limit  :fetch-suggestions="autoProduceOrderList" @select="autoProduceOrderSelect" >
                <template #append>
                  <el-button @click="openChooseProduceOrderNo">选择</el-button>
                </template>
                <template #default="{ item }">
      <div class="value">{{ item }}</div>
    </template>
              </el-autocomplete>
						</el-form-item>

					</el-col>

          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="生产订单总数量" prop="totalNum">
							<el-input-number v-model="state.ruleForm.totalNum" placeholder="生产订单总数量" disabled />
						</el-form-item>
					</el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="剩余未入库数量" prop="noInStoreNum">
							<el-input-number v-model="state.ruleForm.noInStoreNum" placeholder="剩余未入库数量" disabled />
						</el-form-item>
					</el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="已抛转U8总数量" prop="toU8Num">
              <el-input-number v-model="state.ruleForm.toU8Num" placeholder="已抛转U8总数量" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="本次入库总数量" prop="num">
              <el-input-number v-model="state.ruleForm.num" placeholder="本次入库总数量" clearable disabled />
            </el-form-item>

          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="扫描条码" prop="flowBarcode">
              <el-input v-model="state.ruleForm.flowBarcode" placeholder="条码号" clearable @keyup.enter="scanCode"  >
                <template #append>
                  <el-icon  @click="scanCode"><ele-FullScreen /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
				</el-row>
			</el-form>
      <el-tabs :model-value="'item'">
        <el-tab-pane label="入库单明细" name="item"></el-tab-pane>
      </el-tabs>
      <el-table
          :data="detailList"
      >
        <el-table-column prop="inStoreNo" label="入库单号"  show-overflow-tooltip="" />
        <el-table-column prop="produceOrderNo" label="生产单号"  show-overflow-tooltip="" />
        <el-table-column prop="flowBarcode" label="条码流水号"  show-overflow-tooltip="" />
        <el-table-column prop="parseMaterialName" label="解析条码物料名称"  show-overflow-tooltip="" />
        <el-table-column prop="materialName" label="U8存货名称"  show-overflow-tooltip="" />
        <el-table-column prop="materialCode" label="U8存货编码"  show-overflow-tooltip="" />
        <el-table-column prop="materialNo" label="U8存货代码"  show-overflow-tooltip="" />
        <el-table-column prop="batchNo" label="批号"  show-overflow-tooltip="" />
        <el-table-column prop="num" label="数量"  show-overflow-tooltip="" >
          <template  #default="scope">
            <el-input type="number" v-model="scope.row.num" min="1"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注"  show-overflow-tooltip="" />
        <el-table-column label="操作" width="140">
          <template #default="scope">
            <el-button @click="deleteRow(scope.$index)" icon="ele-Delete" size="small" text="" type="primary">删除</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-customer title="选择客户" ref="chooseCustomerRef" :is-any="false" @finish="onChooseCustomerFinish"></choose-customer>
    <choose-order title="选择订单" ref="chooseProduceOrderRef" :is-any="false" @finish="onChooseProduceOrderFinish" ></choose-order>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
    import { ref,onMounted, reactive,watchEffect } from "vue";
	import { ElMessage } from "element-plus";
	import type { FormRules } from "element-plus";
    import {addMesInStore, updateMesInStore, detailMesInStore, GetSysConfig, Scan} from "/@/api/mes/mesInStore";
	import { pageMesInStore, deleteMesInStore } from '/@/api/mes/mesInStore';
	import { getMesCustomerCustomerCodeDropdown } from '/@/api/mes/mesInStore';

	import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
  	import { formatDate } from '/@/utils/formatTime';
    import ChooseCustomer from "/@/businessComponents/chooseCustomer.vue";
    import ChooseOrder from "/@/businessComponents/chooseOrder.vue";
    import {pageMesProduceOrderProduct} from "/@/api/mes/mesProduceOrderProduct";
    import {getAutoCustomers} from '/@/api/mes/mesCustomer'
    import {getAutoList} from '/@/api/mes/mesProduceOrder'

	//父级传递来的参数
	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>({
		// inStoreNo: [{required: true, message: '请输入入库单号！', trigger: 'blur',},],
		inStoreType: [{required: true, message: '请选择入库类型！', trigger: 'change',},],
		inStoreCode: [{required: true, message: '请输入入库仓库！', trigger: 'blur',},],
		produceOrderNo: [{required: true, message: '请输入生产订单号！', trigger: 'blur',},],
		num: [{required: true, message: '请输入入库数量！', trigger: 'blur',},],
		// checkStatus: [{required: true, message: '请输入审核状态！', trigger: 'blur',},],
		// syncStatus: [{required: true, message: '请输入同步到u8状态！', trigger: 'blur',},],
	});

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

	});

  // 扫码
    const scanCode = async ()=>{
      if(!state.ruleForm.flowBarcode) return ElMessage({
        message: `请补充条码信息`,
        type: "error",
      });
      if(!state.ruleForm.produceOrderNo) return ElMessage({
        message: `请补充生产订单号信息`,
        type: "error",
      });
      if(!state.ruleForm.customerCode) return ElMessage({
        message: `请补充客户信息`,
        type: "error",
      });
      if(detailList.value.find((u:any)=> { return u.orgBarcode == state.ruleForm.flowBarcode })){
        return ElMessage({
        message: `该条码不能重复扫码`,
        type: "error",
      });
      }
      // alert('todo')
      // detailList.value.push({
      //   num:1000
      // })
      let  res = await Scan({
        barcode:state.ruleForm.flowBarcode,
        produceOrderNo:state.ruleForm.produceOrderNo,
        customerCode:state.ruleForm.customerCode,
      })
      let data = res.data.result || {};
      // 标记新添加的数据
      data.id = 0;
      if(data instanceof Array){
        detailList.value.push(...data.map(item=>({...item,id:0})))
      } else if(data instanceof Object){
        data.id = 0;
        detailList.value.push(data)
      }
      state.ruleForm.flowBarcode = "";
    }

  // 删除行
  const deleteRow = (i)=>{
      let current = detailList.value[i];
      // 只标记已存储过的数据，新增的数据被删除不记录
      if(current?.id != 0){
        delList.value.push(current.id);
      }
      detailList.value.splice(i,1);

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

  const chooseProduceOrderRef = ref();
  const openChooseProduceOrderNo = ()=>{
    chooseProduceOrderRef.value.openDialog({})
  }
  const onChooseProduceOrderFinish = async (row)=>{
    state.ruleForm.produceOrderNo = row?.produceOrderNo;
    // 查询明细
    let res = await pageMesProduceOrderProduct({
      produceOrderNo:state.ruleForm.produceOrderNo,
      page:1,
      pageSize:9999,
    })
    let dataList = res.data.result?.items ?? [];
    // 数量相关字段计算
    // *
    // state.ruleForm.num = detailList.value.reduce((prev, cur)=>prev + Number(cur.num),0);

    // -生产订单总数量
    state.ruleForm.totalNum = dataList.reduce((prev, cur)=>prev + Number(cur.num),0);
    // -剩余未入库数量
    var inNum = dataList.reduce((prev, cur)=>prev + Number(cur.inStoreNum1),0);
    state.ruleForm.noInStoreNum = state.ruleForm.totalNum - inNum;
    // -已抛转U8总数量
    state.ruleForm.toU8Num = dataList.reduce((prev, cur)=>prev + Number(cur.toU8Num),0);
    // -本次入库数量
    // state.ruleForm.num = 0;

  }

    const chooseCustomerRef = ref();
    const openChooseCustome = ()=>{
      chooseCustomerRef.value.openDialog({})
    }
    const onChooseCustomerFinish = (row)=>{
      // console.log(row)
      state.ruleForm.customerName = row?.customerName;
      state.ruleForm.customerCode = row?.customerCode;
    }


	// 打开弹窗
  const delList = ref([]) // 标记删除子表明细
	const openDialog = async (row: any) => {

    delList.value = [];

		// state.ruleForm = JSON.parse(JSON.stringify(row));
		// 改用detail获取最新数据来编辑

    // 查询系统参数 -仓库
    getStoreInfo();
		let rowData = JSON.parse(JSON.stringify(row));
		if (rowData.id){
      state.ruleForm = (await detailMesInStore(rowData.id)).data.result;
      detailList.value = state.ruleForm?.inStoreDetailList || []
      if(rowData.produceOrderNo){
        onChooseProduceOrderFinish({produceOrderNo:rowData.produceOrderNo})
      }
    } else{
      state.ruleForm = rowData;
    }
		state.isShowDialog = true;
	};
  const getStoreInfo = async ()=>{
    let res = await GetSysConfig({code:'U8InStoreCode'});
    console.log(res)
    state.ruleForm.inStoreCode = res.data.result || '';
  }
    watchEffect(() => {
      console.log('数组变化了', detailList);
      // 自动更新 表单内的 本次入库数量字段
      state.ruleForm.num = detailList.value.reduce((prev, cur)=>prev + Number(cur.num),0);
    });
	// 关闭弹窗
	const closeDialog = () => {
    detailList.value = [];
		emit("reloadTable");
		state.isShowDialog = false;
	};

	// 取消
	const cancel = () => {
    detailList.value = [];
    state.isShowDialog = false;
	};

	// 提交
	const submit = async () => {
		ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
			if (isValid) {
				let values = state.ruleForm;
        values.inStoreDetailList = (detailList.value || []).map(item=>({
          ...item,
          inStoreNo:state.ruleForm.inStoreNo,
        }))
        // 标记已经删除的数据id
        // 只记录被删除的数据(防止数据删掉又新增扫码)
        let deleteList = delList.value.filter(id=>!values.inStoreDetailList.find(el=>el.id == id))
        values.delList = deleteList || [];
        if(detailList.value.length == 0) return  ElMessage({
          message: `请扫码添加入库单明细`,
          type: "error",
        });
        if(detailList.value.some(item=>Number(item?.num || 0) < 1)) return  ElMessage({
          message: `入库数量最小为1`,
          type: "error",
        });
				if (state.ruleForm.id == undefined || state.ruleForm.id == null || state.ruleForm.id == "" || state.ruleForm.id == 0) {
					await addMesInStore(values);
				} else {
					await updateMesInStore(values);
				}
				closeDialog();
			} else {
				ElMessage({
					message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
					type: "error",
				});
			}
		});
	};

	const mesCustomerCustomerCodeDropdownList = ref<any>([]);
	const getMesCustomerCustomerCodeDropdownList = async () => {
		let list = await getMesCustomerCustomerCodeDropdown();
		mesCustomerCustomerCodeDropdownList.value = list.data.result ?? [];
	};
	getMesCustomerCustomerCodeDropdownList();


  const autoCustomerList = (queryString: string, cb:(arg:any)=>void)=>{
    getAutoCustomers({CustomerCode:queryString}).then((res:any)=>{
      cb(res.data.result);
    });
  }
  const autoCustomerSelect = (item:any)=>{
    state.ruleForm.customerCode = item;
  }

  
  const autoProduceOrderList = (queryString: string, cb:(arg:any)=>void)=>{
    getAutoList({produceOrderNo:queryString}).then((res:any)=>{
      cb(res.data.result);
    });
  }
  const autoProduceOrderSelect = (item:any)=>{
    state.ruleForm.produceOrderNo = item;
  }

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




