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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.common.constant.SourceConstant;
import com.fjhx.item.entity.product.vo.ProductInfoVo;
import com.fjhx.item.service.product.ProductClassifyService;
import com.fjhx.item.service.product.ProductInfoService;
import com.fjhx.purchase.entity.arrival.dto.ArrivalDetailDto;
import com.fjhx.purchase.entity.arrival.dto.ArrivalDetailSelectDto;
import com.fjhx.purchase.entity.arrival.po.ArrivalDetail;
import com.fjhx.purchase.entity.arrival.vo.ArrivalDetailVo;
import com.fjhx.purchase.entity.purchase.po.PurchaseDetail;
import com.fjhx.purchase.mapper.arrival.ArrivalDetailMapper;
import com.fjhx.purchase.service.arrival.ArrivalDetailService;
import com.fjhx.purchase.service.quality.QualityDetailService;
import com.fjhx.supply.service.supplier.SupplierInfoService;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.wrapper.SqlField;
import org.apache.commons.collections4.MapUtils;
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>
 *
 * @author 
 * @since 2023-04-07
 */
@DS(SourceConstant.PURCHASE)
@Service
public class ArrivalDetailServiceImpl extends ServiceImpl<ArrivalDetailMapper, ArrivalDetail> implements ArrivalDetailService {

    @Autowired
    private SupplierInfoService supplierInfoService;

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ProductClassifyService productClassifyService;

    @Autowired
    private QualityDetailService qualityDetailService;

    /**
     * 分页
     *
     * @param dto
     * @return
     */
    @Override
    public Page<ArrivalDetailVo> getPage(ArrivalDetailSelectDto dto) {
        IWrapper<ArrivalDetail> wrapper = getWrapper();
        if(StringUtils.isNotEmpty(dto.getStatus())){
            wrapper.eq("t1", PurchaseDetail::getStatus,dto.getStatus());
        }
        if(StringUtils.isNotEmpty(dto.getKeyword())){
            wrapper.keyword(dto.getKeyword(),new SqlField("t2.code"));
        }
        wrapper.eq("t1", PurchaseDetail::getStatus, dto.getStatus());
        wrapper.orderByDesc("t1", ArrivalDetail::getCreateTime);
        wrapper.groupBy("t1.id");
        Page<ArrivalDetailVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        List<ArrivalDetailVo> list = page.getRecords();
        if (CollectionUtils.isNotEmpty(list)) {

            // 赋值供应商名称
            supplierInfoService.attributeAssign(list, ArrivalDetailVo::getSupplyId, (item, supplier) -> {
                item.setSupplyName(supplier.getName());
            });

            // 赋值产品属性
            productInfoService.attributeAssign(list, ArrivalDetail::getBussinessId, (item, product) -> {
                item.setProductCode(product.getCode());
                item.setProductUnit(product.getUnit());
                item.setProductType(product.getType());
                item.setProductName(product.getName());
                item.setProductSpec(product.getSpec());
                item.setProductCategoryId(product.getProductClassifyId());
            });

            // 赋值产品分类名称
            productClassifyService.attributeAssign(list, ArrivalDetailVo::getProductCategoryId, (item, productClassify) -> {
                item.setProductCategory(productClassify.getName());
            });

        }
        return page;
    }

    /**
     * 详情--
     * @param ids
     * @return
     */
    @Override
    public List<ArrivalDetailVo> detail(List<Long>  ids) {
        List<ArrivalDetail> arrivalDetailList = this.list(Wrappers.<ArrivalDetail>query().lambda().in(ArrivalDetail::getId,ids));
        List<ArrivalDetailVo> results = new ArrayList<>();
        //查询产品
        List<Long> productIds = arrivalDetailList.stream().map(ArrivalDetail::getBussinessId).collect(Collectors.toList());
        List<ProductInfoVo> productInfoVos = productInfoService.getListByProductIds(productIds);
        Map<Long, List<ProductInfoVo>> productMap = productInfoVos.stream().collect(Collectors.groupingBy(ProductInfoVo::getId));
        if(MapUtils.isNotEmpty(productMap)) {
            for(ArrivalDetail s:arrivalDetailList){
                //查询出当前这款到货明细的质检总数
                ArrivalDetailVo result = BeanUtil.toBean(s, ArrivalDetailVo.class);
                ProductInfoVo p = productMap.get(s.getBussinessId()).get(0);
                result.setSumQualityCount(qualityDetailService.getSumQualityCount(s.getId()));
                result.setProductCategory(p.getClassifyName());
                result.setProductCode(p.getCode());
                result.setProductUnit(p.getUnit());
                result.setProductType(p.getType());
                result.setProductName(p.getName());
                result.setProductSpec(p.getSpec());
                results.add(result);
            }
        }
        return results;
    }

    @Override
    public void add(ArrivalDetailDto arrivalDetailDto) {
        this.save(arrivalDetailDto);
    }

    @Override
    public void edit(ArrivalDetailDto arrivalDetailDto) {
        this.updateById(arrivalDetailDto);
    }

    @Override
    public void delete(Long id) {
        this.removeById(id);
    }

    /**
     * 统计到货明细总数
     * @param purchaseDetailId
     * @param businessId
     * @return
     */
    @Override
    public BigDecimal getSumCount(Long purchaseDetailId, Long businessId) {
        return baseMapper.getSumCount(purchaseDetailId,businessId);
    }

    @Override
    public List<ArrivalDetailVo> getArrivalDetail(IWrapper<ArrivalDetail> wrapper1) {
        return baseMapper.getArrivalDetail(wrapper1);
    }

}
