package com.prolog.eis.service.shelves.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.prolog.eis.dto.item.ItemSyncVO;
import com.prolog.eis.dto.shelves.GoodsInfoDTO;
import com.prolog.eis.service.shelves.ShelvesGoodsInfoService;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.PrologException;
import com.prolog.upcloud.base.inventory.model.BatchNumberSync;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @author zhanghan
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ShelvesShelvesGoodsInfoServiceImpl implements ShelvesGoodsInfoService {

    @Value("${prolog.goods.wms-lotNo-url:}")
    private String wmsLotNoUrl;

    @Value("${prolog.goods.wms-item-url:}")
    private String wmsItemUrl;
    
    @Value("${cfg.upSystemItemCategoryCode:false}")
    private boolean upSystemItemCategoryCode;

    @Value("${cfg.eisItemCategoryCode:001}")
    private String eisItemCategoryCode;

    @Override
    public List<GoodsInfoDTO> getGoodsInfo(List<GoodsInfoDTO> result) {
        List<String> lotIds = result.stream().map(GoodsInfoDTO::getLotId).filter(lotId -> !StringUtils.isEmpty(lotId))
                .distinct().collect(Collectors.toList());
        List<String> goodsIds = result.stream().map(GoodsInfoDTO::getGoodsId)
                .filter(goodsId -> !StringUtils.isEmpty(goodsId)).distinct().collect(Collectors.toList());
        List<BatchNumberSync> batchNumberSyncList = null;
        List<ItemSyncVO> itemSyncVOS = null;

        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        JSONObject jsonObj = new JSONObject();
        RestTemplate jjlsRestTemplate = new RestTemplate();
        if (!lotIds.isEmpty()) {
            jsonObj.put("batchIds",lotIds);
            HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
            RestMessage<List<BatchNumberSync>> restMessage = jjlsRestTemplate.postForObject(wmsLotNoUrl, formEntity, RestMessage.class);
            if(!restMessage.isSuccess()){
                throw new PrologException("调用WMS查询批次服务出现错误!");
            }
            batchNumberSyncList = JSONArray.parseArray(JSONObject.toJSONString(restMessage.getData()), BatchNumberSync.class);
        }
        if (!goodsIds.isEmpty()) {
            jsonObj.put("itemIds",goodsIds);
            HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
            RestMessage<List<ItemSyncVO>> restMessage = jjlsRestTemplate.postForObject(wmsItemUrl, formEntity, RestMessage.class);
            if(!restMessage.isSuccess()){
                throw new PrologException("调用WMS查询商品服务出现错误！");
            }
            if (null == restMessage.getData() || restMessage.getData().isEmpty()) {
                throw new PrologException(goodsIds + "查询商品不存在");
            }
            itemSyncVOS = JSONArray.parseArray(JSONObject.toJSONString(restMessage.getData()), ItemSyncVO.class);
            if (!upSystemItemCategoryCode) {
                itemSyncVOS.stream().forEach(p -> {
                    p.setItemCategoryCode(eisItemCategoryCode);
                    p.setItemHealthCategory(eisItemCategoryCode);
                });
            }
        }
        List<GoodsInfoDTO> list = Lists.newArrayList();
        for (GoodsInfoDTO GoodsInfoDTO : result) {
            if (null != itemSyncVOS) {
                ItemSyncVO itemSyncVO = itemSyncVOS.stream()
                        .filter(x -> !Objects.isNull(x.getItemId()) && x.getItemId().equals(GoodsInfoDTO.getGoodsId()))
                        .findFirst().orElse(new ItemSyncVO());
                if (!Objects.isNull(itemSyncVO)) {
                    GoodsInfoDTO.setItemCode(itemSyncVO.getItemCode());
                    GoodsInfoDTO.setPieceBarcode(itemSyncVO.getPieceBarcode());
                    GoodsInfoDTO.setItemName(itemSyncVO.getItemName());
                    GoodsInfoDTO.setManufacturerId(itemSyncVO.getManufacturerId());
                    GoodsInfoDTO.setItemHealthApprovalNbr(itemSyncVO.getItemHealthApprovalNbr());
                    GoodsInfoDTO.setCargoOwnerName(itemSyncVO.getCargoOwnerName());
                    GoodsInfoDTO.setPieceConversionRate(itemSyncVO.getPieceConversionRate());
                    GoodsInfoDTO.setItemHealthCategory(itemSyncVO.getItemHealthCategory());
                    GoodsInfoDTO.setSpecification(itemSyncVO.getSpecification());
                    GoodsInfoDTO.setItemHealthCategoryName(itemSyncVO.getItemHealthCategoryName());
                    GoodsInfoDTO.setSingleVolume(
                            null == itemSyncVO.getUomList() || itemSyncVO.getUomList().isEmpty() ? BigDecimal.ZERO
                                    : Objects.isNull(itemSyncVO.getUomList().get(0).getVolume()) ? new BigDecimal(0) : itemSyncVO.getUomList().get(0).getVolume().divide(itemSyncVO.getUomList().get(0).getConversionRate(),2,BigDecimal.ROUND_DOWN));
                }
            }
            if (null != batchNumberSyncList) {
                BatchNumberSync batchNumberSync = batchNumberSyncList.stream()
                        .filter(v -> !Objects.isNull(v.getBatchId()) && v.getBatchId().equals(GoodsInfoDTO.getLotId()))
                        .findFirst().orElse(new BatchNumberSync());
                if (!Objects.isNull(batchNumberSync)) {
                    GoodsInfoDTO.setManufacturerLotNum(batchNumberSync.getManufacturerLotNum());
                    GoodsInfoDTO.setBatchExpiredDate(batchNumberSync.getBatchExpiredDate());
                    GoodsInfoDTO.setBatchProductionDate(batchNumberSync.getBatchProductionDate());
                    GoodsInfoDTO.setBatchExpiredDateShow(batchNumberSync.getBatchExpiredDateShow());
                    GoodsInfoDTO.setBatchProductionDateShow(batchNumberSync.getBatchProductionDateShow());
                }
            }
            list.add(GoodsInfoDTO);
        }
        return list;
    }
    
}
