package com.pj.tb_orders;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pj.tb_demand_quotation.TbDemandQuotation;
import com.pj.tb_demand_quotation.TbDemandQuotationService;
import com.pj.tb_goods_demand.TbGoodsDemand;
import com.pj.tb_goods_demand.TbGoodsDemandService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 二级市场订单-抽取方法公共类
 * @Author lbl
 * @Date 2023 08 09
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class MethodOrdersService {
    @Autowired
    private TbGoodsDemandService goodsDemandService;
    @Autowired
    private TbDemandQuotationService demandQuotationService;

    // 公共方法：TbOrders数据封装成TbOrdersDto
    List<TbOrdersDto> getTbOrdersDto(List<TbOrders> orderList) {

        List<TbOrdersDto> ordersDtoList = new ArrayList<>();

        orderList.forEach(order -> {
            TbOrdersDto ordersDto = new TbOrdersDto();
            BeanUtils.copyProperties(order,ordersDto);


            // 需求表主键Id
            Long goodsDemandId = ordersDto.getFkGoodsDemandId();
            // 获取订单关联的需求表信息
            TbGoodsDemand goodsDemand = goodsDemandService.getById(goodsDemandId);
            ordersDto.setGoodsImg(goodsDemand.getGoodsImg());
            ordersDto.setGoodsQuantity(goodsDemand.getGoodsQuantity());
            ordersDto.setRemark(goodsDemand.getRemark());
            ordersDto.setGoodsUnit(goodsDemand.getGoodsUnit());
            ordersDto.setGoodsNo(goodsDemand.getGoodsNo());
            ordersDto.setGoodsQuantity(goodsDemand.getGoodsQuantity());
            ordersDto.setAcquirerName(goodsDemand.getCreateName());
            ordersDto.setGoodsDemandTime(goodsDemand.getCreateTime());


            // 根据需求表主键Id，获取报价表信息
            LambdaQueryWrapper<TbDemandQuotation> wrapper = new LambdaQueryWrapper();
            wrapper.eq(TbDemandQuotation::getDemandId, goodsDemandId);
            wrapper.eq(TbDemandQuotation::getQuotationResult, 1);
            wrapper.orderByDesc(TbDemandQuotation::getCreateTime);
            List<TbDemandQuotation> demandQuotationList = demandQuotationService.list(wrapper);
            if(demandQuotationList.size()>0) {
                // 商品报价
                ordersDto.setQuotation(demandQuotationList.get(0).getQuotation());
                // 商品报价人
                ordersDto.setQuotationPerson(demandQuotationList.get(0).getCreateName());
            }

            ordersDtoList.add(ordersDto);
        });

        return ordersDtoList;
    }
}
