package com.trade.service.trade.salesorder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.trade.common.constant.HttpStatus;
import com.trade.common.exception.ServiceException;
import com.trade.service.filestorage.dto.FileAbstractDto;
import com.trade.service.filestorage.service.TFileStorageService;
import com.trade.service.trade.salesorder.domain.SalesOrderInvoice;
import com.trade.service.trade.salesorder.mapper.SalesOrderInvoiceMapper;
import com.trade.service.trade.salesorder.service.ISalesOrderGoodsService;
import com.trade.service.trade.salesorder.service.ISalesOrderInvoiceService;
import com.trade.service.trade.salesorder.vo.SalesOrderInvoiceDtlVO;
import com.trade.service.trade.salesorder.vo.SalesOrderInvoiceSearch;
import com.trade.service.trade.salesorder.vo.SalesOrderInvoiceVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 销售订单-发票信息 服务实现类
 * </p>
 *
 * @author zhangchenm
 * @since 2024-09-06
 */
@Service
public class SalesOrderInvoiceServiceImpl extends ServiceImpl<SalesOrderInvoiceMapper, SalesOrderInvoice> implements ISalesOrderInvoiceService {

    @Resource
    private ISalesOrderGoodsService salesOrderGoodsService;
    @Resource
    private TFileStorageService fileStorageService;

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

    /**
     * 发票列表分页查询
     *
     * @param search 查询条件
     * @return 分页结果
     */
    @Override
    public PageInfo<SalesOrderInvoiceVO> queryListBySearch(SalesOrderInvoiceSearch search) {
        PageHelper.startPage(search.getPage(), search.getRows());
        List<SalesOrderInvoiceVO> list = this.baseMapper.queryListBySearch(search);
        return new PageInfo<>(list);
    }

    /**
     * 根据发票号获取发票明细
     *
     * @param invoiceNo 发票号
     * @return 发票明细
     */
    @Override
    public SalesOrderInvoiceDtlVO getDetailByInvoiceNo(String invoiceNo) {
        SalesOrderInvoiceDtlVO vo = this.baseMapper.getDetailByInvoiceNo(invoiceNo);
        if (vo == null) {
            throw new ServiceException("发票信息不存在", HttpStatus.BAD_REQUEST);
        }
        if (null != vo.getFileId()) {
            vo.setFile(new FileAbstractDto(fileStorageService.getFileStorageById(vo.getFileId())));
        }
        vo.setSalesOrderGoodsList(salesOrderGoodsService.listByOrderId(vo.getOrderId()));
        return vo;
    }
}
