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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
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.file.utils.ObsFileUtil;
import com.fjhx.purchase.entity.invoice.dto.InvoiceSelectDto;
import com.fjhx.purchase.entity.invoice.po.Invoice;
import com.fjhx.purchase.entity.invoice.po.InvoiceDetails;
import com.fjhx.purchase.entity.invoice.vo.InvoiceDetailsVo;
import com.fjhx.purchase.entity.invoice.vo.InvoiceVo;
import com.fjhx.purchase.mapper.invoice.InvoiceMapper;
import com.fjhx.purchase.service.invoice.InvoiceDetailsService;
import com.fjhx.purchase.service.invoice.InvoiceService;
import com.fjhx.supply.entity.supplier.po.SupplierInfo;
import com.fjhx.supply.service.supplier.SupplierInfoService;
import com.ruoyi.common.annotation.LogicIgnore;
import com.ruoyi.common.annotation.TenantIgnore;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.ruoyi.common.utils.wrapper.SqlField;
import lombok.experimental.Delegate;
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.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 发票管理 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-04-12
 */
@DS(SourceConstant.PURCHASE)
@Service
public class InvoiceServiceImpl extends ServiceImpl<InvoiceMapper, Invoice> implements InvoiceService {

    @Autowired
    private InvoiceDetailsService invoiceDetailsService;

    @Autowired
    private SupplierInfoService supplierInfoService;

    /**
     * 分页
     * @param dto
     * @return
     */
    @Override
    public Page<InvoiceVo> getPage(InvoiceSelectDto dto) {
        IWrapper<Invoice> wrapper = getWrapper();
        wrapper.orderByDesc("t1", Invoice::getCreateTime);
        if(ObjectUtils.isNotEmpty(dto.getInvoiceType())){
            wrapper.eq("t1", Invoice::getType,dto.getInvoiceType());
        }
        if(StringUtils.isNotEmpty(dto.getKeyword())){
            wrapper.keyword(dto.getKeyword(), new SqlField("t1.purchaseCodes"));
        }
        Page<InvoiceVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        List<InvoiceVo> list = page.getRecords();
        if(CollectionUtils.isNotEmpty(list)){
            List<Long> supplyIds = list.stream().map(InvoiceVo::getSupplyId).collect(Collectors.toList());
            List<SupplierInfo> supplierInfoList = supplierInfoService.list(Wrappers.<SupplierInfo>query().lambda().in(SupplierInfo::getId,supplyIds));
            Map<Long,List<SupplierInfo>> supplyMap = supplierInfoList.stream().distinct().collect(Collectors.groupingBy(SupplierInfo::getId));
            if(MapUtils.isNotEmpty(supplyMap)){
                for(InvoiceVo p:list){
                    List<SupplierInfo> supplys = supplyMap.getOrDefault(p.getSupplyId(),null);
                    p.setSupplyName(supplys==null?null:supplys.get(0).getName());
                }
            }
        }
        return page;
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public InvoiceVo detail(Long id) {
        Invoice Invoice = this.getById(id);
        InvoiceVo result = BeanUtil.toBean(Invoice, InvoiceVo.class);
        List<InvoiceDetailsVo> invoiceDetailsVos = invoiceDetailsService.getDetail(id);
        List<Long> ids = invoiceDetailsVos.stream().distinct().map(InvoiceDetailsVo::getPurchaseId).collect(Collectors.toList());
        List<InvoiceDetailsVo> invoiceDetailsList = invoiceDetailsService.getSumMoneyByPurchaseIds(ids);
        Map<Long, BigDecimal> invoiceMap = invoiceDetailsList.stream().collect(Collectors.toMap(InvoiceDetailsVo::getPurchaseId,InvoiceDetailsVo::getSumMoney));
        for(InvoiceDetailsVo p:invoiceDetailsVos){
            if(MapUtils.isNotEmpty(invoiceMap)){
                p.setSumMoney(invoiceMap.getOrDefault(p.getPurchaseId(), BigDecimal.ZERO));
            }else{
                p.setSumMoney(BigDecimal.ZERO);
            }
        }
        result.setInvoiceDetailsVoList(invoiceDetailsVos);
        return result;
    }

    /**
     * 新增
     * @param invoice
     */
    @Override
    @DSTransactional
    public void add(Invoice invoice) {
        this.save(invoice);
        List<InvoiceDetails> invoiceDetailsList = invoice.getInvoiceDetailsList();
        if(CollectionUtils.isNotEmpty(invoiceDetailsList)){

            invoiceDetailsList = invoiceDetailsList.stream()
                    .peek(item -> item.setInvoiceId(invoice.getId()))
                    .filter(item -> item.getMoney() != null && item.getMoney().compareTo(BigDecimal.ZERO) > 0)
                    .collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(invoiceDetailsList)) {
                invoiceDetailsService.saveBatch(invoiceDetailsList);
            }

        }

        ObsFileUtil.saveFile(invoice.getFileList(),invoice.getId());
    }

    /**
     * 修改
     * @param invoice
     */
    @Override
    @DSTransactional
    @LogicIgnore
    public void edit(Invoice invoice) {
        this.updateById(invoice);
        invoiceDetailsService.remove(Wrappers.<InvoiceDetails>query().lambda().eq(InvoiceDetails::getInvoiceId,invoice.getId()));
        List<InvoiceDetails> invoiceDetailsList = invoice.getInvoiceDetailsList();
        if(CollectionUtils.isNotEmpty(invoiceDetailsList)){
            for(InvoiceDetails d:invoiceDetailsList){
                d.setInvoiceId(invoice.getId());
            }
            invoiceDetailsService.saveBatch(invoiceDetailsList);
        }
        //修改
        ObsFileUtil.editFile(invoice.getFileList(),invoice.getId());
    }

    /**
     * 删除
     * @param id
     */
    @Override
    @DSTransactional
    public void delete(Long id) {
        this.removeById(id);
        invoiceDetailsService.remove(Wrappers.<InvoiceDetails>query().lambda().eq(InvoiceDetails::getInvoiceId,id));
        ObsFileUtil.removeFile(id);
    }

}
