package com.ximai.mes.od.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.ximai.common.constant.UserConstants;
import com.ximai.common.utils.data.DateUtils;
import com.ximai.mes.od.domain.*;
import com.ximai.mes.od.mapper.OdPurchaseOrderDetailMapper;
import com.ximai.mes.od.mapper.OdPurchaseOrderMapper;
import com.ximai.mes.od.service.IOdPurchaseOrderService;
import com.ximai.mes.od.vo.PurchaseOrderDto;
import com.ximai.mes.qt.domain.QtFactoryQuote;
import com.ximai.mes.qt.mapper.QtFactoryQuoteMapper;
import com.ximai.system.strategy.AutoCodeUtil;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户采购订单Service业务层处理
 *
 * @author yinjinlu
 * @date 2024-01-22
 */
@Service
@AllArgsConstructor
public class OdPurchaseOrderServiceImpl implements IOdPurchaseOrderService {
    @Resource
    private OdPurchaseOrderMapper odPurchaseOrderMapper;

    @Resource
    private OdPurchaseOrderDetailMapper odPurchaseOrderDetailMapper;

    @Resource
    private QtFactoryQuoteMapper qtFactoryQuoteMapper;

    @Autowired
    private AutoCodeUtil autoCodeUtil;

    /**
     * 查询客户采购订单列表
     *
     * @param odPurchaseOrder 客户采购订单
     * @return 客户采购订单
     */
    @Override
    public List<OdPurchaseOrder> selectOdPurchaseOrderList(OdPurchaseOrder odPurchaseOrder) {
        return odPurchaseOrderMapper.selectOdPurchaseOrderList(odPurchaseOrder);
    }


    @Override
    public OdSalesOrder getSalesOrder(Long id) {
        OdPurchaseOrder odPurchaseOrder = odPurchaseOrderMapper.selectOdPurchaseOrderById(id);
        if (!"0".equals(odPurchaseOrder.getState())) {
            throw new RuntimeException("该采购单单已生成销售订单");
        }
        OdPurchaseOrderDetail purchaseQuery = new OdPurchaseOrderDetail();
        purchaseQuery.setOrderId(id);
        OdSalesOrder odSalesOrder = new OdSalesOrder();
        odSalesOrder.setPurchaseNo(odPurchaseOrder.getOrderNo());
        odSalesOrder.setOrderNo(autoCodeUtil.genSerialCode(UserConstants.SALES_ORDER, null));
        odSalesOrder.setPurchaseDate(odPurchaseOrder.getCreateTime());
        odSalesOrder.setDeliveryDate(odPurchaseOrder.getDeliveryDate());
        odSalesOrder.setClientNo(odPurchaseOrder.getClientNo());
        odSalesOrder.setClientId(odPurchaseOrder.getClientId());
        odSalesOrder.setOrgNo("1000");
        odSalesOrder.setState("0");
        odSalesOrder.setMerchandiser("E00002");

        List<OdPurchaseOrderDetail> purchaseDetailList = odPurchaseOrderDetailMapper.selectOdPurchaseOrderDetailList(purchaseQuery);
        odSalesOrder.setDetailList(buildOdSalesOrderDetail(purchaseDetailList, odPurchaseOrder.getClientId()));
        return odSalesOrder;
    }

    /**
     * 新增客户采购订单
     *
     * @param odPurchaseOrder 客户采购订单
     * @return 结果
     */
    @Override
    public int insertOdPurchaseOrder(OdPurchaseOrder odPurchaseOrder) {
        odPurchaseOrder.setCreateTime(DateUtils.getNowDate());
        return odPurchaseOrderMapper.insertOdPurchaseOrder(odPurchaseOrder);
    }

    /**
     * 批量删除客户采购订单
     *
     * @param ids 需要删除的客户采购订单主键
     * @return 结果
     */
    @Override
    public int deleteOdPurchaseOrderByIds(String[] ids) {
        return odPurchaseOrderMapper.deleteOdPurchaseOrderByIds(ids);
    }


    @Override
    public int batchInsert(List<PurchaseOrderDto> purchaseOrderDtoList) {
        Date now = new Date();
        PurchaseOrderDto dto = purchaseOrderDtoList.get(0);
        OdPurchaseOrder odPurchaseOrder = savePurchaseOrder(now, dto);

        List<OdPurchaseOrderDetail> purchaseOrderList = purchaseOrderDtoList.stream().map(this::buildOdPurchaseOrderItem)
                .peek(item -> item.setOrderId(odPurchaseOrder.getId())).collect(Collectors.toList());
        return odPurchaseOrderDetailMapper.batchInsert(purchaseOrderList);
    }

    @Override
    public int batchSave(List<PurchaseOrderDto> odPurchaseOrder) {
        odPurchaseOrder.get(0).setFilePath("金库");
        return batchInsert(odPurchaseOrder);
    }


    private OdPurchaseOrder savePurchaseOrder(Date now, PurchaseOrderDto dto) {
        OdPurchaseOrder odPurchaseOrder = new OdPurchaseOrder();
        odPurchaseOrder.setOrderNo(autoCodeUtil.genSerialCode(UserConstants.PURCHASE_ORDER, null));
        odPurchaseOrder.setClientId(dto.getCustomerId());
        odPurchaseOrder.setDeliveryDate(dto.getDeliveryDate());
        odPurchaseOrder.setState("0");
        odPurchaseOrder.setSource(dto.getFilePath());
        odPurchaseOrder.setCreateBy("1");
        odPurchaseOrder.setCreateTime(now);
        odPurchaseOrder.setUpdateBy("1");
        odPurchaseOrder.setUpdateTime(now);
        odPurchaseOrderMapper.insertOdPurchaseOrder(odPurchaseOrder);
        return odPurchaseOrder;
    }


    public OdPurchaseOrderDetail buildOdPurchaseOrderItem(PurchaseOrderDto dto) {
        OdPurchaseOrderDetail detail = new OdPurchaseOrderDetail();
        detail.setItemId(dto.getProductId());
        detail.setNum(dto.getOrderNumber());
        detail.setState("0");
        detail.setSpecJson(JSONUtil.toJsonStr(dto.getProductProperties().stream().map(PurchaseOrderDto::convert).collect(Collectors.toList())));
        detail.setProductName(dto.getCustomerName());
        detail.setPoProductName(dto.getCustomerProductName());
        detail.setPoProductNo(dto.getCustomerCode());
        detail.setPoColor(dto.getColor());
        detail.setPoColorNo(dto.getColorCode());
        detail.setRegion(dto.getRegion());
        detail.setSizeGroup(dto.getSizeGroup());
        detail.setSize(dto.getSize());
        detail.setWholeYard(dto.getHalf());
        detail.setSpecialSize(dto.getSpecialSize());
        detail.setFeatureNo(dto.getTypeNumber());
        detail.setCmdNo(dto.getInstruct());
        detail.setOrderNum(dto.getOrderNumber());
        detail.setProductSize(dto.getProductSpecifications());
        detail.setDeliveryDate(dto.getDeliveryDate());
        detail.setPoKg(dto.getWeight());
        detail.setPoOrderNo(dto.getCustomerNo());
        detail.setCustomerUnit(dto.getCustomerUnit());
        detail.setSigner(dto.getSignee());
        detail.setSalePath(dto.getSalesLine());
        detail.setSegment(dto.getDan());
        detail.setLayout(dto.getFace());
        detail.setQuarter(dto.getQuarter());
        detail.setPoNo(dto.getPoCode());
        detail.setWipNo(dto.getWipCode());
        detail.setPackingNum(dto.getPacking());
        detail.setCycle(dto.getCycle());
        detail.setSkNo(dto.getSkNo());
        detail.setPatentNo(dto.getPatentNumber());
        detail.setMaterialDesc(dto.getMaterialDesc());
        detail.setShipToId(dto.getShipTOId());
        detail.setBarCode(dto.getBarCode());
        detail.setPrintingDirection(dto.getPrintDirection());
        detail.setCreateBy("1");
        detail.setCreateTime(new Date());
        detail.setRemark(dto.getRemark());
        return detail;
    }

    private List<OdSalesOrderDetail> buildOdSalesOrderDetail(List<OdPurchaseOrderDetail> purchaseDetailList, Long clientId) {
        List<OdSalesOrderDetail> list = new ArrayList<>();

        Map<Long, List<OdPurchaseOrderDetail>> listMap = purchaseDetailList.stream().collect(Collectors.groupingBy(OdPurchaseOrderDetail::getItemId));

        QtFactoryQuote qtFactoryQuote = new QtFactoryQuote();
        qtFactoryQuote.setClientId(clientId);
        for (Map.Entry<Long, List<OdPurchaseOrderDetail>> entry : listMap.entrySet()) {
            Long itemId = entry.getKey();
            List<OdPurchaseOrderDetail> detailList = entry.getValue();

            qtFactoryQuote.setItemId(itemId);
            QtFactoryQuote factoryQuotes = qtFactoryQuoteMapper.selectOne(qtFactoryQuote);
            OdPurchaseOrderDetail detail0 = detailList.get(0);

            OdSalesOrderDetail detail = new OdSalesOrderDetail();
            detail.setSapItemNo(detail0.getSapItemCode());
            detail.setPrice(factoryQuotes != null ? factoryQuotes.getPrice() : null);
//            detail.setShipmentPointNo();
//            detail.setStoreAddr();
//            detail.setBatchNo();
//            detail.setActualDeliveryDate();
//            detail.setPricingVal();
//            detail.setOfferUnit();
//            detail.setSaleUnit();
//            detail.setSizeUnit();
            detail.setSaleFactory("1000");
//            detail.setPackingNum();
            detail.setDeliveryDate(detail.getDeliveryDate());
//            detail.setProdSpec();
//            detail.setPlantCode();
//            detail.setPackMode();
            detail.setItemId(detail0.getItemId());
            detail.setItemNo(detail0.getItemNo());
            detail.setItemName(detail0.getItemName());
            detail.setTotalNum(detail0.getTotalNum());
            detail.setLossNum(0);
            detail.setPoOrderNo(detail0.getPoOrderNo());
            detail.setClientItemNo(detail0.getPoProductNo());
            detail.setClientItemName(detail0.getPoProductName());
            detail.setClientSizeUnit(detail0.getCustomerUnit());
            detail.setClientCmd(detail0.getCmdNo());
            detail.setTypeNo(detail0.getFeatureNo());
            detail.setColorNo(detail0.getPoColorNo());
            detail.setColor(detail0.getPoColor());
            detail.setClientKg(detail0.getPoKg());
            detail.setSalePath(detail0.getSalePath());
            detail.setSegment(detail0.getSegment());
            detail.setLayout(detail0.getLayout());
            detail.setQuarter(detail0.getQuarter());
            detail.setWholeSize(detail0.getWholeYard());
            detail.setSpecSize(detail0.getSpecialSize());
            detail.setPoNo(detail0.getPoNo());
            detail.setWipNo(detail0.getWipNo());
            detail.setPackingNum(detail0.getPackingNum());
            detail.setCycle(detail0.getCycle());
            detail.setSkNo(detail0.getSkNo());
            detail.setPatentNo(detail0.getPatentNo());
            detail.setMaterialDesc(detail0.getMaterialDesc());
            detail.setSigner(detail0.getSigner());
            detail.setShipToId(detail0.getShipToId());
            detail.setDeliveryDate(detail0.getDeliveryDate());
            detail.setSizeGroup(detail0.getSizeGroup());
            detail.setSize(detail0.getSize());
            detail.setOrderNum(0);
            detail.setBarCode(detail0.getBarCode());
            detail.setPrintingDirection(detail0.getPrintingDirection());
            detail.setProdSpec(detail0.getProductSize());
            detail.setState("0");
            detail.setRemark(detail0.getRemark());

            List<OdSalesOrderDetailItem> itemList = new ArrayList<>();
            for (OdPurchaseOrderDetail detailSize : detailList) {
                OdSalesOrderDetailItem item = new OdSalesOrderDetailItem();
                item.setSize(detailSize.getSize());
                item.setNum(detailSize.getOrderNum());
                item.setLossNum(detailSize.getLossNum());
                item.setRemark(detailSize.getRemark());
                item.setSpecJson(detailSize.getSpecJson());
                itemList.add(item);
                detail.setOrderNum(detail.getOrderNum() + ObjectUtil.defaultIfNull(detailSize.getOrderNum(), 0));
                detail.setLossNum(detail.getLossNum() + ObjectUtil.defaultIfNull(detailSize.getLossNum(), 0));
                detail.setNum(detail.getOrderNum());
            }

            detail.setTotalNum(detail.getLossNum() + detail.getNum());
            detail.setItemList(itemList);
            list.add(detail);
        }

        return list;
    }

}
