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

import cn.hutool.core.bean.BeanUtil;
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.purchase.entity.pay.dto.PayDetailDto;
import com.fjhx.purchase.entity.pay.dto.PayDetailSelectDto;
import com.fjhx.purchase.entity.pay.enums.PayStatusEnum1;
import com.fjhx.purchase.entity.pay.po.Pay;
import com.fjhx.purchase.entity.pay.po.PayDetail;
import com.fjhx.purchase.entity.pay.vo.PayDetailVo;
import com.fjhx.purchase.mapper.pay.PayDetailMapper;
import com.fjhx.purchase.service.pay.PayDetailService;
import com.ruoyi.common.utils.wrapper.IWrapper;
import org.springframework.stereotype.Service;

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


/**
 * <p>
 * 采购付款明细 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-04-13
 */
@Service
public class PayDetailServiceImpl extends ServiceImpl<PayDetailMapper, PayDetail> implements PayDetailService {

    @Override
    public Page<PayDetailVo> getPage(PayDetailSelectDto dto) {
        IWrapper<PayDetail> wrapper = getWrapper();
        wrapper.orderByDesc("pd", PayDetail::getId);
        Page<PayDetailVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        return page;
    }

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

    @Override
    public void add(PayDetailDto payDetailDto) {
        this.save(payDetailDto);
    }

    @Override
    public void edit(PayDetailDto payDetailDto) {
        this.updateById(payDetailDto);
    }

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

    /**
     * 付款
     *
     * @param purchaseIds
     * @return
     */
    @Override
    public List<PayDetailVo> getSumMoneyByPurchaseIds(List<Long> purchaseIds) {
        return baseMapper.getSumMoneyByPurchaseIds(purchaseIds);
    }

    @Override
    public Map<Long, BigDecimal> getPayMoneyCountByPurchaseId(List<Long> purchaseIdList) {

        QueryWrapper<Object> queryWrapper = Wrappers.query()
                .ge("p.status", PayStatusEnum1.PASS.getKey())
                .in("pd.purchase_id", purchaseIdList);

        List<PayDetail> list = baseMapper.getPayMoneyCountByPurchaseId(queryWrapper);

        return list.stream().collect(Collectors.toMap(
                PayDetail::getPurchaseId,
                PayDetail::getMoney,
                BigDecimal::add
        ));
    }

    /**
     * 获取付款总额
     * @param purchaseIds
     * @return
     */
    @Override
    public List<Pay> getSumMoney(List<Long> purchaseIds) {
        return baseMapper.getSumMoney(purchaseIds);
    }


}
