package com.prolog.cs.biz.outbound.service.impl;

import com.alibaba.fastjson.JSON;
import com.prolog.cs.basic.common.model.BaseCommonDict;
import com.prolog.cs.biz.outbound.dao.WmsRepPreMapper;
import com.prolog.cs.biz.outbound.model.WmsRepPre;
import com.prolog.cs.biz.outbound.resource.CommonClient;
import com.prolog.cs.biz.outbound.resource.OperateResource;
import com.prolog.cs.biz.outbound.service.WmsRepPreService;

import com.prolog.cs.biz.outbound.utils.SearchApi;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.utils.MapUtils;
import com.prolog.framework.utils.StringUtils;
import com.prolog.framework.utils.UUIDUtils;
import com.prolog.upcloud.base.wh.operate.vo.ReplenishUrgentSaveDetailVO;
import com.prolog.upcloud.base.wh.operate.vo.ReplenishUrgentSaveVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WmsRepPreServiceImpl implements WmsRepPreService {

    @Autowired
    private WmsRepPreMapper wmsRepPreMapper;

    @Autowired
    private SearchApi searchApi;

    @Autowired
    private OperateResource operateResource;

    @Autowired
    private CommonClient commonClient;

    @Override
    public void autoRep() {

        int times;

        RestMessage<List<BaseCommonDict>> retryTimes = commonClient.getDictBasicListByCodes("auto_rep_times", null);
        if(retryTimes == null || !retryTimes.isSuccess() || retryTimes.getData() == null || retryTimes.getData().size() <= 0){
            times = 1;
        }else {
            times = Integer.parseInt(retryTimes.getData().get(0).getDictName());
        }

        List<WmsRepPre> wmsRepPres = wmsRepPreMapper.getUnPres(times);
        if(wmsRepPres == null || wmsRepPres.size() <= 0){
            return;
        }

        ReplenishUrgentSaveVO replenishUrgentSaveVO = new ReplenishUrgentSaveVO();
        replenishUrgentSaveVO.setWarehouseId(wmsRepPres.get(0).getWarehouseId());
        List<ReplenishUrgentSaveDetailVO> details = new ArrayList<>();

        List<String> itemIds = wmsRepPres.stream().map(WmsRepPre :: getItemId).distinct().collect(Collectors.toList());
        for (int i = 0; i < itemIds.size(); i++) {

            String itemId = itemIds.get(i);

            List<Map> searchForMap = null;
            try {
                searchForMap = searchApi.searchForMap("querylocator", MapUtils.put("warehouseId",wmsRepPres.get(0).getWarehouseId())
                        .put("itemId",itemId)
                        .put("currentUser.enterpriseId",wmsRepPres.get(0).getEnterpriseId())
                        .put("auto","1").getMap());
            }catch (Exception e){
                e.printStackTrace();
                log.info("调用查询服务：querylocator失败!");
            }
            log.info("自动补货，查询A品库存返回结果:{}", JSON.toJSONString(searchForMap));
            if(searchForMap == null || searchForMap.size() <= 0){
                List<WmsRepPre> repPres = wmsRepPres.stream().filter(item -> item.getItemId().equals(itemId)).collect(Collectors.toList());
                for (WmsRepPre repPre : repPres) {
                    if(StringUtils.isBlank(repPre.getAttrStr1()) || Integer.valueOf(repPre.getAttrStr1()) < times){
                        wmsRepPreMapper.updateMapById(repPre.getId(),MapUtils.put("attrStr1",repPre.getAttrStr1() == null ? 1 : Integer.valueOf(repPre.getAttrStr1()) + 1).put("gmtModified",new Date()).getMap(),WmsRepPre.class);
                    }else {
                        wmsRepPreMapper.updateMapById(repPre.getId(),MapUtils.put("status","2").put("gmtModified",new Date()).getMap(),WmsRepPre.class);
                    }
                }
                continue;
            }
            Map map = searchForMap.get(0);
            ReplenishUrgentSaveDetailVO detailVO = new ReplenishUrgentSaveDetailVO();
            detailVO.setCargoOwnerId((String) (map.get("cargoOwnerId")));
            detailVO.setItemId(itemId);
            detailVO.setPieceQuantity(new BigDecimal((Double) map.get("avlQuantity")));
            detailVO.setToWhLocatorId((String) map.get("sjLocatorId"));
            detailVO.setWhLocatorId((String) map.get("locatorId"));
            detailVO.setBatchId((String) map.get("batchId"));
            detailVO.setContainerCode((String) map.get("containerCode"));

            details.add(detailVO);
        }

        replenishUrgentSaveVO.setDetails(details);
        if(details.size() > 0){
            //调用紧急补货生成补货任务
            RestMessage<String> restMessage = operateResource.replenishUrgent(replenishUrgentSaveVO);
            if(restMessage != null && restMessage.isSuccess()){
                List<String> itemIdList = details.stream().map(ReplenishUrgentSaveDetailVO::getItemId).collect(Collectors.toList());
                for (WmsRepPre wmsRepPre : wmsRepPres) {
                    if(itemIdList.contains(wmsRepPre.getItemId())){
                        wmsRepPreMapper.updateMapById(wmsRepPre.getId(),MapUtils.put("status","1").put("gmtModified",new Date()).getMap(),WmsRepPre.class);
                    }
                }
            }
        }

    }

    @Override
    public void save(WmsRepPre wmsRepPre) {
        wmsRepPreMapper.save(wmsRepPre);
    }
}
