package vip.xiaonuo.sale.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import vip.xiaonuo.sale.entity.SaleDeliver;
import vip.xiaonuo.sale.entity.SaleInvoice;
import vip.xiaonuo.sale.entity.vo.SaleInvoiceVo;
import vip.xiaonuo.sale.mapper.SaleInvoiceMapper;
import vip.xiaonuo.sale.param.SaleInvoiceParam;
import vip.xiaonuo.sale.service.ISaleInvoiceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 销售发票 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-13
 */
@Service
public class SaleInvoiceServiceImpl extends ServiceImpl<SaleInvoiceMapper, SaleInvoice> implements ISaleInvoiceService {

    @Autowired
    private SaleInvoiceMapper invoiceMapper;

    @Override
    public List<SaleInvoiceVo> getList(SaleInvoiceParam invoiceParam) {
        String orgId = invoiceParam.getOrgId();
        Integer timeType = invoiceParam.getTimeType();
        QueryWrapper<SaleInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        queryWrapper.select(" count(*) saleInvoiceOrder,create_time createTime,IFNULL(sum(sale_invoice_money),'0') saleInvoiceMoney");
        if (0 == timeType) {
            queryWrapper.groupBy("DATE_FORMAT(create_time,'%Y')");
        } else {
            queryWrapper.groupBy("DATE_FORMAT(create_time,'%Y-%m')");
        }
        queryWrapper.orderByAsc("create_time");
        List<SaleInvoiceVo> list = new ArrayList<>();
        List<SaleInvoice> saleInvoices = invoiceMapper.selectList(queryWrapper);
        BigDecimal math = new BigDecimal("10000");
        if (saleInvoices.size() != 0) {
            for (SaleInvoice saleInvoice : saleInvoices) {
                SaleInvoiceVo vo = new SaleInvoiceVo();
                BigDecimal bg = new BigDecimal(saleInvoice.getSaleInvoiceMoney());
                bg = bg.divide(math, 2, RoundingMode.HALF_UP);
                vo.setCreateTime(saleInvoice.getCreateTime());
                vo.setSaleInvoiceMoney(bg.toString());
                vo.setSaleInvoiceNumber(saleInvoice.getSaleInvoiceOrder());
                list.add(vo);
            }
        }
        return list;
    }

}
