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

import com.github.pagehelper.PageHelper;
import com.prolog.cs.biz.outbound.dao.BarcodeHMapper;
import com.prolog.cs.biz.outbound.dao.OutboundHandoverMapper;
import com.prolog.cs.biz.outbound.dao.PickTaskHMapper;
import com.prolog.cs.biz.outbound.model.OutboundHandover;
import com.prolog.cs.biz.outbound.model.dto.HandoverDetailDTO;
import com.prolog.cs.biz.outbound.model.dto.OutboundHandoverDTO;
import com.prolog.cs.biz.outbound.model.entity.BarcodeHDO;
import com.prolog.cs.biz.outbound.service.OutboundHandoverService;
import com.prolog.framework.authority.core.dto.UserDTO;
import com.prolog.framework.authority.user.UserTemplate;
import com.prolog.framework.bz.core.model.ModelUtils;
import com.prolog.framework.core.exception.PrologException;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Order;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.framework.dao.util.PageUtils;
import com.prolog.framework.utils.AssertUtils;
import com.prolog.framework.utils.MapUtils;
import com.prolog.framework.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author zzz
 * @desc
 * @date 2021/6/29
 */
@Service
public class OutboundHandoverServiceImpl implements OutboundHandoverService {

    @Autowired
    private OutboundHandoverMapper mapper;

    @Autowired
    private PickTaskHMapper pickTaskHMapper;

    @Autowired
    private UserTemplate userTemplate;

    @Autowired
    private BarcodeHMapper barcodeHMapper;
    
    /**
     * 分页查询出库交接记录
     * @param billGroupId
     * @param srcCode
     * @param shipperName
     * @param warehouseId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Page<OutboundHandover> getPage(String billGroupId, String srcCode, String shipperName, String warehouseId, Integer pageNum, Integer pageSize) {
        UserDTO userDTO = userTemplate.getUserDTO();
        String enterpriseId = userDTO.getEnterpriseId();
        Criteria crt = Criteria.forClass(OutboundHandover.class);
        Restriction r1 = StringUtils.isBlank(billGroupId)? null : Restrictions.eq("billGroupId", billGroupId);
        Restriction r2 = StringUtils.isBlank(srcCode)? null : Restrictions.like("srcCodes", "%"+srcCode+"%");
        Restriction r3 = StringUtils.isBlank(shipperName)? null : Restrictions.like("shipperName", "%"+shipperName+"%");
        Restriction r4 = Restrictions.eq("warehouseId", warehouseId);
        Restriction r5 = Restrictions.eq("enterpriseId", enterpriseId);
        crt.setRestriction(Restrictions.and(r1, r2, r3,r4,r5));
        crt.setOrder(Order.newInstance().desc("gmtCreate"));
        PageHelper.startPage(pageNum, pageSize);
        List<OutboundHandover> list = mapper.findByCriteria(crt);
        //组合id
        for (int i = 0; i < list.size(); i++) {
            OutboundHandover outboundHandover = list.get(i);
            outboundHandover.setStatus("已交接");
        }
        return PageUtils.getPage(list);
    }

    /**
     * 新增出库交接记录
     * @param model
     */
    @Override
    public void add(OutboundHandover model) {
        AssertUtils.isNotBlank(model.getBillGroupId(), "订单号不能为空");
        AssertUtils.isNotNull(model.getLclQty(), "箱数不能为空");
        AssertUtils.isNotNull(model.getUomQty(), "件数不能为空");
        AssertUtils.isNotBlank(model.getLicensePlateNum(), "车牌号不能为空");
        AssertUtils.isNotBlank(model.getDriverName(), "司机名称不能为空");

        UserDTO userDTO = userTemplate.getUserDTO();
        String enterpriseId = userDTO.getEnterpriseId();
        long count = mapper.findCountByMap(MapUtils.put("enterpriseId",enterpriseId).put("billGroupId",model.getBillGroupId()).put("warehouseId",model.getWarehouseId()).getMap(),OutboundHandover.class);
        if(count>0)
            throw new PrologException("该订单已出库交接，请勿重复操作！");
        ModelUtils.generateBaseData(model, userTemplate::getUserDTO);
        model.setHandoverDate(new Date());
        model.setStatus("0");
        List<String> omsBillIds = barcodeHMapper.getOmsBillIds(model.getBillGroupId(),enterpriseId);
        if(omsBillIds.size()>0){
            String srcCodes = omsBillIds.stream().collect(Collectors.joining(","));
            model.setSrcCodes(srcCodes);
            model.setWarehouseId(model.getWarehouseId());
        }
        mapper.save(model);
    }

    /**
     * 根据订单号查询条码列表
     * @param billGroupId
     * @param warehouseId
     * @return
     */
    @Override
    public OutboundHandoverDTO getBarcodeDetail(String billGroupId, String warehouseId) {
        AssertUtils.isNotBlank(billGroupId, "条码不能为空");
        UserDTO userDTO = userTemplate.getUserDTO();
        String enterpriseId = userDTO.getEnterpriseId();
        List<BarcodeHDO> barcodeHList = barcodeHMapper.findByMap(MapUtils.put("barcode",billGroupId).put("warehouseId",warehouseId).getMap(),BarcodeHDO.class);
        if(barcodeHList.size()==0)
            throw new PrologException("未找到对应订单!");
        if(!"5".equals(barcodeHList.get(0).getCheckStatus()))
            throw new PrologException("该条码未外复核!");
        billGroupId = barcodeHList.get(0).getBillGroupId();
        List<OutboundHandover> handoverList = mapper.findByMap(MapUtils.put("billGroupId",billGroupId).put("warehouseId",warehouseId).getMap(),OutboundHandover.class);
        if(handoverList.size()>0)
            throw new PrologException("该订单已出库交接!");
        OutboundHandoverDTO dto = pickTaskHMapper.getLclDetail(billGroupId,warehouseId,enterpriseId);
        if(dto!=null && dto.getBillGroupId()!=null) {
            List<HandoverDetailDTO> list = pickTaskHMapper.getBarcodeDList(billGroupId, warehouseId, enterpriseId);
            dto.setDetailList(list);
            if(list.size()>0){
                BigDecimal totUomQty = BigDecimal.ZERO;
                BigDecimal totLclQty = BigDecimal.ZERO;
                for (HandoverDetailDTO detail : list) {
                    totUomQty = totUomQty.add(detail.getUomQty());
                    totLclQty = totLclQty.add(detail.getLclQty());
                }
                dto.setTotUomQty(totUomQty);
                dto.setTotLclQty(totLclQty);
            }
        }else{
            throw new PrologException("此订单号数据不存在！");
        }
        return dto;
    }

    @Override
    public List<OutboundHandoverDTO> getBarcodeDetails(String billGroupId, String warehouseId) {
        AssertUtils.isNotBlank(billGroupId, "订单号不能为空");
        UserDTO userDTO = userTemplate.getUserDTO();
        String enterpriseId = userDTO.getEnterpriseId();
        List<OutboundHandoverDTO> dtoList = pickTaskHMapper.getLclDetails(billGroupId,warehouseId,enterpriseId);
        return dtoList;
    }

}
