package com.cim.idm.service.Impl;

import com.cim.idm.dao.ToSapDao;
import com.cim.idm.framework.data.EventInfo;
import com.cim.idm.service.AllocateStockInService;
import com.cim.idm.service.impl.ToSAPServiceImpl;
import com.cim.idm.utils.EventInfoUtil;
import com.cim.idm.wmspackage.materialpacking.MaterialPackingServiceProxy;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingKey;
import com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("AllocateStockInService")
@Slf4j
public class AllocateStockInServiceImpl implements AllocateStockInService {

    @Autowired
    private ToSAPServiceImpl toSAPServiceImpl;

    @Autowired
    private ToSapDao toSapDao;
    /**
     * 调拨入库提交
     *
     * @param shipRequestName
     * @param siteName
     * @param user
     * @param erpLocation
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public String allocateStockIn(String shipRequestName, String siteName, String user, String erpLocation,String locationName) throws Exception {
        log.debug("AllocateStockInServiceImpl.allocateStockIn {} {} {} {}", shipRequestName, siteName, user, erpLocation);
        //提交SAP过账
        String undoId = toSAPServiceImpl.AlloctionStockIn(shipRequestName, siteName, user, erpLocation);
        //基于单据获取要操作的Box
        List<MaterialPacking> boxList = toSapDao.getBoxListByShipRequestName(shipRequestName);
        //保存物料凭证
        toSapDao.updateStockState(boxList, "Stocked", undoId);
        //记录出入库流水
        toSapDao.saveUnDoInfo(boxList, undoId, "");
        //更新库存状态和仓库
        List<MaterialPackingKey> mpKeyList = new ArrayList<>();
        for (MaterialPacking box : boxList) {
            mpKeyList.add(new MaterialPackingKey("SDK", box.getMaterialPackingName()));
        }
        EventInfo eventInfo = EventInfoUtil.makeEventInfo("allocateStockIn", user, "调拨入库");
        SetEventInfo setEventInfo = new SetEventInfo();
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("stockState", "Stocked");
        hashMap.put("erpLocation", erpLocation);
        hashMap.put("locationName", locationName);
        hashMap.put("shipRequestName", "");
        hashMap.put("shipRequestDetailName", "");
        setEventInfo.setUserColumns(hashMap);
        MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpKeyList, eventInfo, setEventInfo);
        return "";
    }
}
