package com.fjhx.sale.service.arrival.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.common.enums.CodingRuleEnum;
import com.fjhx.common.service.coding.CodingRuleService;
import com.fjhx.common.utils.Assert;
import com.fjhx.sale.entity.arrival.dto.ArrivalDto;
import com.fjhx.sale.entity.arrival.dto.ArrivalSelectDto;
import com.fjhx.sale.entity.arrival.po.Arrival;
import com.fjhx.sale.entity.arrival.po.ArrivalDetail;
import com.fjhx.sale.entity.arrival.vo.ArrivalVo;
import com.fjhx.sale.entity.purchase.po.EhsdPurchase;
import com.fjhx.sale.entity.purchase.po.EhsdPurchaseProduct;
import com.fjhx.sale.mapper.arrival.ArrivalMapper;
import com.fjhx.sale.service.arrival.ArrivalDetailService;
import com.fjhx.sale.service.arrival.ArrivalService;
import com.fjhx.sale.service.purchase.EhsdPurchaseProductService;
import com.fjhx.sale.service.purchase.EhsdPurchaseService;
import com.fjhx.wms.entity.stock.emums.JournalType;
import com.fjhx.wms.entity.stock.po.StockWait;
import com.fjhx.wms.entity.stock.po.StockWaitDetails;
import com.fjhx.wms.service.stock.StockWaitDetailsService;
import com.fjhx.wms.service.stock.StockWaitService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.wrapper.IWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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


/**
 * <p>
 * 到货 服务实现类
 * </p>
 *
 * @since 2024-02-01
 */
@Service
public class ArrivalServiceImpl extends ServiceImpl<ArrivalMapper, Arrival> implements ArrivalService {

    private final CodingRuleService codingRuleService;
    private final EhsdPurchaseProductService purchaseProductService;
    private final EhsdPurchaseService purchaseService;
    private final ArrivalDetailService arrivalDetailService;
    private final StockWaitService stockWaitService;
    private final StockWaitDetailsService stockWaitDetailsService;

    @Autowired
    public ArrivalServiceImpl(CodingRuleService codingRuleService, EhsdPurchaseService purchaseService, EhsdPurchaseProductService purchaseProductService, ArrivalDetailService arrivalDetailService, StockWaitService stockWaitService, StockWaitDetailsService stockWaitDetailsService) {
        this.codingRuleService = codingRuleService;
        this.purchaseService = purchaseService;
        this.purchaseProductService = purchaseProductService;
        this.arrivalDetailService = arrivalDetailService;
        this.stockWaitService = stockWaitService;
        this.stockWaitDetailsService = stockWaitDetailsService;
    }


    @Override
    public Page<ArrivalVo> getPage(ArrivalSelectDto dto) {
        IWrapper<Arrival> wrapper = getWrapper();
        wrapper.orderByDesc("a", Arrival::getId);
        return this.baseMapper.getPage(dto.getPage(), wrapper);
    }

    @Override
    public ArrivalVo detail(Long id) {
        Arrival Arrival = this.getById(id);
        return BeanUtil.toBean(Arrival, ArrivalVo.class);
    }

    @DSTransactional
    @Override
    public void add(ArrivalDto dto) {
        Assert.notEmpty(dto.getPurchaseId(), "采购id不能为空");

        EhsdPurchase purchase = purchaseService.getById(dto.getPurchaseId());
        Assert.notEmpty(purchase, "查询不到采购信息");

        //赋值到货编号
        dto.setCode(codingRuleService.createCode(CodingRuleEnum.ARRIVAL.getKey(), null));
        this.save(dto);

        List<ArrivalDetail> arrivalDetailList = dto.getArrivalDetailList();

        //过滤数量为空为0的数据
        arrivalDetailList = arrivalDetailList.stream()
                .filter(item -> ObjectUtil.isNotEmpty(item.getQuantity()) && item.getQuantity().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());

        if (ObjectUtil.isEmpty(arrivalDetailList)) {
            throw new ServiceException("到货列表不能为空");
        }

        //生成待入库数据
        StockWait stockWait = new StockWait();
        stockWait.setCompanyId(SecurityUtils.getCompanyId());
        stockWait.setType(1);
        stockWait.setBusinessType(JournalType.PURCHASE_IN.getDetailType());
        stockWait.setBusinessId(purchase.getId());
        stockWait.setBusinessCode(purchase.getCode());
        stockWait.setStatus(0);
        stockWait.setPurchaseId(purchase.getId());
        stockWait.setContractId(purchase.getDataResourceId());
        stockWaitService.save(stockWait);
        List<StockWaitDetails> stockWaitDetailsList = new ArrayList<>();

        List<Long> pdIds = arrivalDetailList.stream().map(ArrivalDetail::getPurchaseDetailId).collect(Collectors.toList());
        Map<Long, EhsdPurchaseProduct> pdMap = purchaseProductService.mapKEntity(EhsdPurchaseProduct::getId, q -> q.in(EhsdPurchaseProduct::getId, pdIds));
        for (ArrivalDetail arrivalDetail : arrivalDetailList) {
            arrivalDetail.setId(IdWorker.getId());
            arrivalDetail.setArrivalId(dto.getId());
            EhsdPurchaseProduct ehsdPurchaseProduct = pdMap.get(arrivalDetail.getPurchaseDetailId());
            arrivalDetail.setProductId(ehsdPurchaseProduct.getProductId());

            arrivalDetail.setPurchaseId(dto.getPurchaseId());

//            //更新到货数量
//            purchaseProductService.update(q -> q
//                    .eq(EhsdPurchaseProduct::getId, ehsdPurchaseProduct.getId())
//                    .setSql("arrival_quantity = arrival_quantity + " + arrivalDetail.getQuantity())
//                    .set(BasePo::getUpdateTime, new Date())
//                    .set(BasePo::getUpdateUser, SecurityUtils.getUserId())
//            );

            //生成待入库明细
            StockWaitDetails stockWaitDetails = new StockWaitDetails();
            stockWaitDetails.setStockWaitId(stockWait.getId());
            stockWaitDetails.setBusinessDetailsId(arrivalDetail.getId());
            stockWaitDetails.setPurchaseDetailId(arrivalDetail.getPurchaseDetailId());

            stockWaitDetails.setProductId(arrivalDetail.getProductId());
            stockWaitDetails.setQuantity(arrivalDetail.getQuantity());
            stockWaitDetails.setStatus(0);

            stockWaitDetailsList.add(stockWaitDetails);
        }
        arrivalDetailService.saveBatch(arrivalDetailList);

        //保存待入库明细
        stockWaitDetailsService.saveBatch(stockWaitDetailsList);

        //更新到货状态
        purchaseService.updateArrivalStatus(dto.getPurchaseId());

    }

}
