package com.fjhx.service.order.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.constants.SystemConfigKeyConstant;
import com.fjhx.entity.logistics.LogisticsInfo;
import com.fjhx.entity.order.OrderDetails;
import com.fjhx.entity.order.OrderInfo;
import com.fjhx.enums.stock.OutTypeEnum;
import com.fjhx.mapper.order.OrderDetailsMapper;
import com.fjhx.params.order.IssueVo;
import com.fjhx.params.order.OrderDetailsEx;
import com.fjhx.params.order.OrderDetailsVo;
import com.fjhx.params.stock.ChangeProduct;
import com.fjhx.params.stock.StockChangeVo;
import com.fjhx.params.stock.StockTransferAddVo;
import com.fjhx.service.logistics.LogisticsInfoService;
import com.fjhx.service.order.OrderDetailsService;
import com.fjhx.service.order.OrderInfoService;
import com.fjhx.service.stock.StockService;
import com.fjhx.service.stock.StockTransferService;
import com.fjhx.service.system.SystemConfigService;
import com.fjhx.uitl.kd100.KD100Util;
import com.fjhx.utils.Assert;
import com.fjhx.utils.wrapperUtil.IWrapper;
import org.springblade.core.log.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 销售订单明细表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-12-13
 */
@Service
public class OrderDetailsServiceImpl extends ServiceImpl<OrderDetailsMapper, OrderDetails> implements OrderDetailsService {

    @Lazy
    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private LogisticsInfoService logisticsInfoService;

    @Autowired
    private StockService stockService;

    @Autowired
    private StockTransferService stockTransferService;

    @Autowired
    private SystemConfigService systemConfigService;


    @Override
    public Page<OrderDetails> getPage(Map<String, Object> condition) {

        IWrapper<OrderDetails> wrapper = IWrapper.getWrapper(condition);

        return page(condition, wrapper);
    }

    @Override
    public void add(OrderDetailsVo orderDetailsVo) {
        save(orderDetailsVo);
    }

    @Override
    public void edit(OrderDetailsVo orderDetailsVo) {
        updateById(orderDetailsVo);
    }

    @Override
    public void delete(OrderDetailsVo orderDetailsVo) {
        removeById(orderDetailsVo.getId());
    }

    @Override
    public List<OrderDetailsEx> listByOrderSalesId(Long orderId) {
        Assert.notEmpty(orderId, "订单id不能为空");
        QueryWrapper<Object> wrapper = Wrappers.query().eq("od.order_id", orderId);
        return baseMapper.listByOrderSalesId(wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void issue(IssueVo issueVo) {
        Long orderId = issueVo.getOrderId();
        Assert.notEmpty(orderId, "订单id不能为空");

        List<IssueVo.IssueDetails> orderDetailsList = issueVo.getOrderDetailsList();

        Map<Long, BigDecimal> map = orderDetailsList.stream().collect(Collectors.toMap(
                IssueVo.IssueDetails::getOrderDetailsId,
                IssueVo.IssueDetails::getChangeQuantity
        ));

        // 变更订单明细未出库数量
        synchronized (this) {
            List<OrderDetails> list = list(q -> q.eq(OrderDetails::getOrderId, orderId));

            for (OrderDetails orderDetails : list) {
                Long id = orderDetails.getId();
                BigDecimal changeQuantity = map.get(id);
                if (changeQuantity == null || changeQuantity.compareTo(BigDecimal.ZERO) == 0) {
                    continue;
                }

                BigDecimal notIssuedQuantity = orderDetails.getNotIssuedQuantity();

                if (notIssuedQuantity.compareTo(changeQuantity) < 0) {
                    throw new ServiceException("出库数量超过待出库数量，操作失败");
                }

                // 重新赋值未出库数量
                orderDetails.setNotIssuedQuantity(notIssuedQuantity.subtract(changeQuantity));
            }
            updateBatchById(list);

            // 修改订单状态
            OrderInfo orderInfo = orderInfoService.getById(orderId);

            // 如果是京东出库
            if (issueVo.getOutTypeEnum().equals(OutTypeEnum.JD)) {
                orderInfo.setStatus(2);
                orderInfo.setIssueStatus(3);
            }
            // 如果是退换货或者补发，出库一次算完成
            else if (orderInfo.getType() == 5) {
                orderInfo.setIssueStatus(3);
                // 补发跟进中变已补发
                if (orderInfo.getAfterSalesStatus() == 1) {
                    orderInfo.setAfterSalesStatus(2);
                }
            }
            // 如果是线下退换货
            else if (orderInfo.getType() == 6) {
                orderInfo.setIssueStatus(3);
                switch (orderInfo.getAfterSalesStatus()) {
                    // 未补发未收到退货变已补发未收到退货
                    case 1:
                        orderInfo.setAfterSalesStatus(5);
                        break;
                    // 未补发已收到退货变已补发已收到退货
                    case 2:
                        orderInfo.setAfterSalesStatus(3);
                        break;
                }
            }
            // 如果未出库数量全为0，修改订单完成状态
            else {
                long count = list.stream().filter(item -> item.getNotIssuedQuantity().compareTo(BigDecimal.ZERO) > 0).count();
                orderInfo.setId(orderId);
                if (count == 0) {
                    orderInfo.setStatus(2);
                    orderInfo.setIssueStatus(3);
                } else {
                    orderInfo.setIssueStatus(2);
                }
            }
            orderInfoService.updateById(orderInfo);
        }

        // 保存物流消息
        LogisticsInfo logisticsInfo = new LogisticsInfo();
        logisticsInfo.setBusinessId(orderId);
        logisticsInfo.setBusinessType(2);
        logisticsInfo.setCode(issueVo.getLogisticsCode());
        logisticsInfo.setLogisticsCompanyCode(issueVo.getLogisticsCompanyCode());
        logisticsInfo.setWarehouseId(issueVo.getWarehouseId());
        //查询快递100的物流信息
        Integer logisticsStatus = KD100Util.getLogisticsStatus(logisticsInfo.getLogisticsCompanyCode(), logisticsInfo.getCode());
        logisticsInfo.setLogisticsStatus(logisticsStatus);
        logisticsInfo.setStatus(0);
        logisticsInfoService.save(logisticsInfo);

        // 变更库存添加流水记录
        StockChangeVo stockChangeVo = new StockChangeVo();
        stockChangeVo.setDefaultBusinessId(orderId);
        stockChangeVo.setDefaultWarehouseId(issueVo.getWarehouseId());
        stockChangeVo.setTypeEnum(issueVo.getOutTypeEnum());
        stockChangeVo.setChangeDetailsList(orderDetailsList);

        // 京东出库新增调仓
        if (issueVo.getOutTypeEnum().equals(OutTypeEnum.JD)) {
            // 获取京东仓库id
            Long jdWarehouseId = systemConfigService.getValue(SystemConfigKeyConstant.JD_WAREHOUSE_ID, Long.class);

            StockTransferAddVo stockTransferAddVo = new StockTransferAddVo();
            stockTransferAddVo.setOutWarehouseId(issueVo.getWarehouseId());
            stockTransferAddVo.setInWarehouseId(jdWarehouseId);
            stockTransferAddVo.setRemark("京东出库");
            // ChangeProduct.

            List<ChangeProduct> changeProductList = issueVo.getOrderDetailsList().stream().map(item -> {
                ChangeProduct changeProduct = new ChangeProduct();
                changeProduct.setProductId(item.getProductId());
                changeProduct.setQuantity(item.getChangeQuantity());
                return changeProduct;
            }).collect(Collectors.toList());

            stockTransferAddVo.setChangeProductList(changeProductList);
            stockTransferService.add(stockTransferAddVo);
        }

        stockService.changeQuantity(stockChangeVo);
    }

}
