package com.trade.service.trade.purchaseorder.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.trade.common.utils.ConstantUtil;
import com.trade.service.filestorage.enums.FileTypeEnum;
import com.trade.service.filestorage.service.BusinessRelateFileBaseService;
import com.trade.service.system.domain.InvoiceTypeMapping;
import com.trade.service.system.service.InvoiceTypeMappingService;
import com.trade.service.trade.purchaseorder.domain.PurchaseOrderCommodity;
import com.trade.service.trade.purchaseorder.domain.PurchaseOrderInvoice;
import com.trade.service.trade.purchaseorder.domain.PurchaseOrderInvoiceCommodity;
import com.trade.service.trade.purchaseorder.dto.InvoiceCommodityDto;
import com.trade.service.trade.purchaseorder.dto.PurchaseOrderInvoiceDocumentSearchDto;
import com.trade.service.trade.purchaseorder.dto.PurchaseOrderInvoiceSearchDto;
import com.trade.service.trade.purchaseorder.mapper.PurchaseOrderInvoiceMapper;
import com.trade.service.trade.purchaseorder.service.PurchaseOrderCommodityService;
import com.trade.service.trade.purchaseorder.service.PurchaseOrderInvoiceCommodityService;
import com.trade.service.trade.purchaseorder.service.PurchaseOrderInvoiceService;
import com.trade.service.trade.purchaseorder.vo.PurchaseOrderInvoiceDetailsVo;
import com.trade.service.trade.purchaseorder.vo.PurchaseOrderInvoiceDocumentVo;
import com.trade.service.trade.purchaseorder.vo.PurchaseOrderInvoiceVo;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 销售订单-发票信息 服务实现类
 * </p>
 *
 * @author wl
 * @since 2024-09-14
 */
@Service
public class PurchaseOrderInvoiceServiceImpl extends ServiceImpl<PurchaseOrderInvoiceMapper, PurchaseOrderInvoice> implements PurchaseOrderInvoiceService {

    @Resource
    private BusinessRelateFileBaseService businessRelateFileBaseService;
    @Resource
    private PurchaseOrderInvoiceCommodityService purchaseOrderInvoiceCommodityService;
    @Resource
    private PurchaseOrderCommodityService purchaseOrderCommodityService;
    @Resource
    private InvoiceTypeMappingService invoiceTypeMappingService;

    /**
     * 根据订单id获取发票信息
     *
     * @param orderId 订单id
     * @return 发票信息
     */
    @Override
    public List<PurchaseOrderInvoice> getByOrderId(Long orderId) {
        return this.baseMapper
                .selectList(new QueryWrapper<PurchaseOrderInvoice>().eq("order_id", orderId).eq("deleted", 0));
    }

    @Override
    public PurchaseOrderInvoice getByCodeAndNumber(String code, String number) {
        return this.baseMapper.selectOne(new QueryWrapper<PurchaseOrderInvoice>().eq("invoice_code", code)
                .eq("invoice_number", number).eq("deleted", 0));
    }

    @Override
    public List<PurchaseOrderInvoice> getByInvoiceStatus(String invoiceStatus, List<Long> invoiceIds) {
        if (CollectionUtil.isEmpty(invoiceIds)) {
            return this.lambdaQuery().eq(PurchaseOrderInvoice::getInvoiceStatus, invoiceStatus)
                    .eq(PurchaseOrderInvoice::getDeleted, 0).eq(PurchaseOrderInvoice::getPullState, 0).list();
        } else {
            return this.lambdaQuery().eq(PurchaseOrderInvoice::getInvoiceStatus, invoiceStatus)
                    .eq(PurchaseOrderInvoice::getDeleted, 0).eq(PurchaseOrderInvoice::getPullState, 0)
                    .in(PurchaseOrderInvoice::getId, invoiceIds).list();
        }
    }

    @Override
    public List<PurchaseOrderInvoiceVo> queryByCondition(PurchaseOrderInvoiceSearchDto invoiceSearchDto) {
        List<PurchaseOrderInvoiceVo> invoiceVos = this.baseMapper.selectByCondition(invoiceSearchDto);
        for (PurchaseOrderInvoiceVo invoiceVo : invoiceVos) {
            businessRelateFileBaseService.fillBizObjFiles(invoiceVo, invoiceVo.getId(), ConstantUtil.PURCHASE_ORDER,
                    FileTypeEnum.PURCHASE_ORDER_INVOICE.getCode());
            // 发票类型映射
            InvoiceTypeMapping invoiceTypeMapping = invoiceTypeMappingService
                    .getInvoiceCode(invoiceVo.getInvoiceType());
            if (invoiceTypeMapping != null) {
                invoiceVo.setInvoiceType(invoiceTypeMapping.getKjtCode());
            }
            List<InvoiceCommodityDto> commodityDtos = purchaseOrderInvoiceCommodityService
                    .getByInvoiceId(invoiceVo.getId());
            BigDecimal allNumber = commodityDtos.stream().filter(commodityDto -> commodityDto.getNumber() != null)
                    .map(InvoiceCommodityDto::getNumber).reduce(BigDecimal.ZERO, BigDecimal::add);
            invoiceVo.setNumber(allNumber);
        }
        return invoiceVos;
    }

    @Override
    public PurchaseOrderInvoiceDetailsVo getDetails(Long id) {
        PurchaseOrderInvoiceDetailsVo purchaseOrderInvoiceDetailsVo = this.baseMapper.selectByInvoiceId(id);
        if (purchaseOrderInvoiceDetailsVo != null) {
            businessRelateFileBaseService.fillBizObjFiles(purchaseOrderInvoiceDetailsVo, id,
                    ConstantUtil.PURCHASE_ORDER, FileTypeEnum.PURCHASE_ORDER_INVOICE.getCode());
            // 商品信息
            // List<InvoiceCommodityDto> invoiceCommodityDtos = purchaseOrderInvoiceCommodityService.getByInvoiceId(id);
            List<PurchaseOrderInvoiceCommodity> invoiceCommoditys = purchaseOrderInvoiceCommodityService
                    .getInfoByInvoiceId(id);
            // 发票类型映射
            InvoiceTypeMapping invoiceTypeMapping = invoiceTypeMappingService
                    .getInvoiceCode(purchaseOrderInvoiceDetailsVo.getInvoiceType());
            if (invoiceTypeMapping != null) {
                purchaseOrderInvoiceDetailsVo.setInvoiceType(invoiceTypeMapping.getKjtCode());
            }
            // 采购订单商品
            List<PurchaseOrderCommodity> commodities = purchaseOrderCommodityService.lambdaQuery()
                    .eq(PurchaseOrderCommodity::getPurchaseOrderId, purchaseOrderInvoiceDetailsVo.getOrderId()).list();
            List<InvoiceCommodityDto> invoiceCommodityDtos = new ArrayList<>();
            for (PurchaseOrderInvoiceCommodity invoiceCommodity : invoiceCommoditys) {
                InvoiceCommodityDto invoiceCommodityDto = BeanUtil.copyProperties(invoiceCommodity,
                        InvoiceCommodityDto.class);
                invoiceCommodityDto.setTotalAmount(invoiceCommodity.getAmount().add(invoiceCommodity.getTaxAmount()));
                String commodityName = invoiceCommodity.getName();
                if (commodityName.contains("*")) {
                    commodityName = commodityName.substring(commodityName.lastIndexOf("*") + 1);
                }
                String finalCommodityName = commodityName;
                PurchaseOrderCommodity purchaseOrderCommodity = commodities.stream()
                        .filter(commodity -> commodity.getDeclarationName().equals(finalCommodityName)).findAny()
                        .orElse(null);
                if (purchaseOrderCommodity != null) {
                    invoiceCommodityDto.setPriceUnit(purchaseOrderCommodity.getPriceUnit());
                    invoiceCommodityDto.setDeclarationName(purchaseOrderCommodity.getDeclarationName());
                } else {
                    invoiceCommodityDto.setDeclarationName(finalCommodityName);
                }
                invoiceCommodityDtos.add(invoiceCommodityDto);
            }
            purchaseOrderInvoiceDetailsVo.setInvoiceCommodityList(invoiceCommodityDtos);
        }
        return purchaseOrderInvoiceDetailsVo;
    }

    @Override
    public PurchaseOrderInvoice getByPurchaseVoucherNo(String purchaseVoucherNo) {
        return this.baseMapper.selectOne(
                new QueryWrapper<PurchaseOrderInvoice>().eq("purchase_voucher_no", purchaseVoucherNo).eq("deleted", 0));
    }

    @Override
    public List<PurchaseOrderInvoice> selectByInvoiceStatus(String invoiceStatus) {
        return this.baseMapper.selectByInvoiceStatus(invoiceStatus);
    }

    @Override
    public List<PurchaseOrderInvoiceDocumentVo> queryPurchaseOrderInvoiceDocument(
            PurchaseOrderInvoiceDocumentSearchDto documentSearchDto) {
        List<PurchaseOrderInvoiceDocumentVo> documentVos = this.baseMapper
                .selectPurchaseOrderInvoiceDocument(documentSearchDto);
        for (PurchaseOrderInvoiceDocumentVo documentVo : documentVos) {
            businessRelateFileBaseService.fillBizObjFiles(documentVo, documentVo.getId(), ConstantUtil.PURCHASE_ORDER,
                    FileTypeEnum.PURCHASE_ORDER_INVOICE.getCode());
            // 发票类型映射
            InvoiceTypeMapping invoiceTypeMapping = invoiceTypeMappingService
                    .getInvoiceCode(documentVo.getInvoiceType());
            if (invoiceTypeMapping != null) {
                documentVo.setInvoiceType(invoiceTypeMapping.getKjtCode());
            }
            List<InvoiceCommodityDto> commodityDtos = purchaseOrderInvoiceCommodityService
                    .getByInvoiceId(documentVo.getId());
            BigDecimal allNumber = commodityDtos.stream().filter(commodityDto -> commodityDto.getNumber() != null)
                    .map(InvoiceCommodityDto::getNumber).reduce(BigDecimal.ZERO, BigDecimal::add);
            documentVo.setNumber(allNumber);
        }
        return documentVos;
    }
}
