package com.storlead.sales.service.impl.sku;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.storlead.framework.common.constant.CodeGenerateInterface;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.util.generate.CodeGenerate;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.mybatis.entity.SysBaseField;
import com.storlead.sales.pojo.entity.customer.BusinessEntity;
import com.storlead.sales.pojo.entity.customer.LiaisonEntity;
import com.storlead.sales.pojo.entity.customer.OrderFormEntity;
import com.storlead.sales.pojo.dto.sku.QuotationPriceDTO;
import com.storlead.sales.pojo.vo.sku.*;
import com.storlead.sales.pojo.dto.sku.QuotationAddDTO;
import com.storlead.sales.pojo.dto.sku.QuotationListDTO;
import com.storlead.sales.pojo.dto.sku.QuotationSearchDTO;
import com.storlead.sales.pojo.entity.sku.QuotationEntity;
import com.storlead.sales.pojo.entity.sku.SkuDetailEntity;
import com.storlead.sales.service.customer.*;
import com.storlead.sales.mapper.sku.QuotationMapper;
import com.storlead.sales.service.sku.QuotationService;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.sales.service.sku.SkuDetailService;
import com.storlead.sales.service.sku.SsdSkuService;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 报价单表 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2024-08-09
 */
@Service
public class QuotationServiceImpl extends MyBaseServiceImpl<QuotationMapper, QuotationEntity> implements QuotationService {

    @Resource
    private SkuDetailService skuDetailService;
    @Resource
    private BusinessService businessService;
    @Resource
    private OrderFormService orderFormService;
    @Resource
    private CustomerService customerService;
    @Resource
    private LiaisonService liaisonService;
    @Resource
    private SsdSkuService ssdSkuService;
    @Resource
    private MessageAssembleService assembleService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> addQuotation(QuotationAddDTO quotationAddDTO) {
        if (CollectionUtils.isEmpty(quotationAddDTO.getSsdSkuDetailVOList())){
            return Result.error("产品列表不能为空！");
        }
//        if (ObjectUtils.isEmpty(quotationAddDTO.getBusinessId()) && ObjectUtils.isEmpty(quotationAddDTO.getOrderFormId())){
//            return Result.error("关联业务不能为空！");
//        }
        QuotationEntity quotation = new QuotationEntity();
        BeanUtils.copyProperties(quotationAddDTO,quotation);

        if (!(ObjectUtils.isEmpty(quotationAddDTO.getBusinessId()) && ObjectUtils.isEmpty(quotationAddDTO.getOrderFormId()))) {
            LambdaQueryWrapper<QuotationEntity> queryWrapper = new LambdaQueryWrapper<>();
            if (!ObjectUtils.isEmpty(quotationAddDTO.getBusinessId()) && !ObjectUtils.isEmpty(quotationAddDTO.getOrderFormId())) {
                queryWrapper.and(wrapperT -> wrapperT.eq(QuotationEntity::getBusinessId, quotationAddDTO.getBusinessId())
                        .or()
                        .eq(QuotationEntity::getOrderFormId, quotationAddDTO.getOrderFormId()));
            } else {
                if (!ObjectUtils.isEmpty(quotationAddDTO.getBusinessId())) {
                    queryWrapper.eq(QuotationEntity::getBusinessId, quotationAddDTO.getBusinessId());
                }
                if (!ObjectUtils.isEmpty(quotationAddDTO.getOrderFormId())) {
                    queryWrapper.eq(QuotationEntity::getOrderFormId, quotationAddDTO.getOrderFormId());
                }
            }


            queryWrapper.eq(QuotationEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            Integer count = this.count(queryWrapper);
            if (count > 0) {
                return Result.error("该商机或订单下已存在报价单！");
            }
        }
        quotation.setDataCode(CodeGenerate.generate10Code(CodeGenerateInterface.QUOTATION_CODE));

        boolean hasAddOrUpdate = this.saveOrUpdate(quotation);
        if (!hasAddOrUpdate){
            return Result.error("新增报价单失败！");
        }
        quotationAddDTO.setId(quotation.getId());

        BigDecimal totalOrderAmt = BigDecimal.ZERO;
        BigDecimal productTotalOrderAmt = BigDecimal.ZERO;
        BigDecimal otherAmt = BigDecimal.ZERO;
        BigDecimal totalEarnestAmt = BigDecimal.ZERO;
        Integer totalNumber = 0;
        Integer languageType = 1;
        List<SkuDetailEntity> skuDetailEntityList = new ArrayList<>();
        for (SsdSkuDetailVO ssdSkuDetailVO : quotationAddDTO.getSsdSkuDetailVOList()){
            SkuDetailEntity skuDetailEntity = new SkuDetailEntity();
            skuDetailEntity.setSsdSkuId(ssdSkuDetailVO.getSsdSkuId().longValue());
            skuDetailEntity.setSsdProductTypeId(ssdSkuDetailVO.getSsdProductTypeId());
//            if (!ObjectUtils.isEmpty(ssdSkuDetailVO.getUnitPriceCNY()) && !ssdSkuDetailVO.getUnitPriceCNY().equals(BigDecimal.ZERO)){
//                skuDetailEntity.setUnitPrice(ssdSkuDetailVO.getUnitPriceCNY());
//            }else {
//                skuDetailEntity.setUnitPrice(ssdSkuDetailVO.getUnitPriceUSD());
//            }
//
//            if (!ObjectUtils.isEmpty(ssdSkuDetailVO.getSkuPriceCNY()) && !ssdSkuDetailVO.getSkuPriceCNY().equals(BigDecimal.ZERO)){
//                skuDetailEntity.setOrderAmt(ssdSkuDetailVO.getSkuPriceCNY());
//            }else {
//                skuDetailEntity.setOrderAmt(ssdSkuDetailVO.getSkuPriceUSD());
//            }

//            skuDetailEntity.setUnitPrice(ssdSkuDetailVO.getUnitPriceCNY());
            skuDetailEntity.setUnitPrice(ssdSkuDetailVO.getUnitPriceCNYActual());
//            skuDetailEntity.setOrderAmt(ssdSkuDetailVO.getSkuPriceCNY());
            //如果是海外报价
//            if (!ObjectUtils.isEmpty(quotationAddDTO.getQuotationType()) && quotationAddDTO.getQuotationType().equals(2)){
//                skuDetailEntity.setOrderAmt(ssdSkuDetailVO.getSkuPriceCNYWithNoRateActual());
//            }else {
//                skuDetailEntity.setOrderAmt(ssdSkuDetailVO.getSkuPriceCNYActual());
//            }
            skuDetailEntity.setOrderAmt(ssdSkuDetailVO.getSkuPriceCNYWithNoRateActual());


            skuDetailEntity.setDeliveryDays(ssdSkuDetailVO.getDeliveryDays());
            skuDetailEntity.setProductCount(ssdSkuDetailVO.getProductCount());
            BeanUtils.copyProperties(ssdSkuDetailVO,skuDetailEntity);
            skuDetailEntity.setQuotationId(quotation.getId());
            //ssdSkuDetailVO转为JSON数组的String字符串
            skuDetailEntity.setDetail(JSON.toJSONString(ssdSkuDetailVO));
            skuDetailEntityList.add(skuDetailEntity);
            languageType = ssdSkuDetailVO.getLanguageType();

//            totalOrderAmt = totalOrderAmt.add(ssdSkuDetailVO.getSkuPriceCNY());
            if (!ObjectUtils.isEmpty(quotationAddDTO.getQuotationType()) && quotationAddDTO.getQuotationType().equals(1)){
                totalOrderAmt = totalOrderAmt.add(ssdSkuDetailVO.getSkuPriceCNYActual());
                if (!ObjectUtils.isEmpty(ssdSkuDetailVO.getSsdSkuCode()) && !ssdSkuDetailVO.getSsdSkuCode().equals("其他费用")){
                    productTotalOrderAmt = productTotalOrderAmt.add(ssdSkuDetailVO.getSkuPriceCNYActual());
                }else {
                    otherAmt = otherAmt.add(ssdSkuDetailVO.getSkuPriceCNYActual());
                }
            }else {
                totalOrderAmt = totalOrderAmt.add(ssdSkuDetailVO.getSkuPriceCNYWithNoRateActual());
                if (!ObjectUtils.isEmpty(ssdSkuDetailVO.getSsdSkuCode()) && !ssdSkuDetailVO.getSsdSkuCode().equals("其他费用")){
                    productTotalOrderAmt = productTotalOrderAmt.add(ssdSkuDetailVO.getSkuPriceCNYWithNoRateActual());
                }else {
                    otherAmt = otherAmt.add(ssdSkuDetailVO.getSkuPriceCNYWithNoRateActual());
                }
            }

            totalOrderAmt = totalOrderAmt.setScale(2,  RoundingMode.HALF_UP);
            productTotalOrderAmt = productTotalOrderAmt.setScale(2,  RoundingMode.HALF_UP);
            otherAmt = otherAmt.setScale(2,  RoundingMode.HALF_UP);
//            totalEarnestAmt = totalEarnestAmt.add(ssdSkuDetailVO.getSkuPriceUSD());
            totalEarnestAmt = totalEarnestAmt.add(ssdSkuDetailVO.getSkuPriceUSDActual());
            totalEarnestAmt = totalEarnestAmt.setScale(2,  RoundingMode.HALF_UP);
            if (!ssdSkuDetailVO.getSsdSkuCode().equals("其他费用")) {
//                totalProductCount = totalProductCount + Integer.parseInt(contractData.getProductCount());
                totalNumber = totalNumber + ssdSkuDetailVO.getProductCount();
            }


        }
        quotation.setLanguageType(languageType);
        quotation.setQuotationType(quotationAddDTO.getQuotationType());
        quotation.setTotalOrderAmt(totalOrderAmt);
        quotation.setProductTotalOrderAmt(productTotalOrderAmt);
        quotation.setOtherAmt(otherAmt);
        quotation.setTotalEarnestAmt(totalEarnestAmt);
        quotation.setTotalNumber(totalNumber);
        this.saveOrUpdate(quotation);
        boolean isOk = skuDetailService.saveOrUpdateBatch(skuDetailEntityList);
        if (!isOk){
            return Result.error("保存失败！");
        }
        quotationAddDTO.setTotalOrderAmt(totalOrderAmt);
        //修改商机阶段为产品报价
        if (!ObjectUtils.isEmpty(quotationAddDTO.getBusinessId())){
            BusinessEntity business = new BusinessEntity();
            business.setId(quotationAddDTO.getBusinessId());
            business.setQuotationId(quotation.getId());
            business.setStage("3");
            businessService.updateById(business);
        }
        if (!ObjectUtils.isEmpty(quotationAddDTO.getOrderFormId())){
            OrderFormEntity orderForm = new OrderFormEntity();
            orderForm.setId(quotationAddDTO.getOrderFormId());
            orderForm.setQuotationId(quotation.getId());
            orderForm.setTotalOrderAmt(totalOrderAmt);
            orderFormService.updateById(orderForm);
        }
        quotationAddDTO.setId(quotation.getId());
        quotationAddDTO.setTotalOrderAmt( quotation.getTotalOrderAmt());
        assembleService.sendBusinessEventMessages(quotation.getBusinessId(),"ADD_QUOTE");
        return Result.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> editQuotation(QuotationAddDTO quotationAddDTO) {
        if (CollectionUtils.isEmpty(quotationAddDTO.getSsdSkuDetailVOList())){
            return Result.error("产品列表不能为空！");
        }
//        QuotationEntity quotationOld = getById(quotationAddDTO.getId());

        QuotationEntity quotation = new QuotationEntity();
        BeanUtils.copyProperties(quotationAddDTO,quotation);

        boolean hasAddOrUpdate = this.saveOrUpdate(quotation);
        if (!hasAddOrUpdate){
            return Result.error("修改报价单失败！");
        }
        quotationAddDTO.setId(quotation.getId());
        if (!ObjectUtils.isEmpty(quotationAddDTO.getOrderFormId())){
            OrderFormEntity orderForm = new OrderFormEntity();
            orderForm.setId(quotationAddDTO.getOrderFormId());
            orderForm.setQuotationId(quotation.getId());
            orderFormService.updateById(orderForm);
        }
        BigDecimal totalOrderAmt = BigDecimal.ZERO;
        BigDecimal productTotalOrderAmt = BigDecimal.ZERO;
        BigDecimal otherAmt = BigDecimal.ZERO;
        BigDecimal totalEarnestAmt = BigDecimal.ZERO;
        Integer totalNumber = 0;
        Integer languageType = 1;
        List<SkuDetailEntity> skuDetailEntityList = new ArrayList<>();
        for (SsdSkuDetailVO ssdSkuDetailVO : quotationAddDTO.getSsdSkuDetailVOList()){
            SkuDetailEntity skuDetailEntity = new SkuDetailEntity();
            skuDetailEntity.setSsdSkuId(ssdSkuDetailVO.getSsdSkuId().longValue());
            skuDetailEntity.setSsdProductTypeId(ssdSkuDetailVO.getSsdProductTypeId());
//            if (!ObjectUtils.isEmpty(ssdSkuDetailVO.getUnitPriceCNY()) && !ssdSkuDetailVO.getUnitPriceCNY().equals(BigDecimal.ZERO)){
//                skuDetailEntity.setUnitPrice(ssdSkuDetailVO.getUnitPriceCNY());
//            }else {
//                skuDetailEntity.setUnitPrice(ssdSkuDetailVO.getUnitPriceUSD());
//            }
//
//            if (!ObjectUtils.isEmpty(ssdSkuDetailVO.getSkuPriceCNY()) && !ssdSkuDetailVO.getSkuPriceCNY().equals(BigDecimal.ZERO)){
//                skuDetailEntity.setOrderAmt(ssdSkuDetailVO.getSkuPriceCNYWithNoRateActual());
//            }else {
//                skuDetailEntity.setOrderAmt(ssdSkuDetailVO.getSkuPriceUSDActual());
//            }
            skuDetailEntity.setUnitPrice(ssdSkuDetailVO.getUnitPriceCNY());
            skuDetailEntity.setOrderAmt(ssdSkuDetailVO.getSkuPriceCNYWithNoRateActual());

//            skuDetailEntity.setUnitPrice(ssdSkuDetailVO.getUnitPriceCNY());
//            skuDetailEntity.setOrderAmt(ssdSkuDetailVO.getSkuPriceCNY());
            skuDetailEntity.setDeliveryDays(ssdSkuDetailVO.getDeliveryDays());
            skuDetailEntity.setProductCount(ssdSkuDetailVO.getProductCount());
            BeanUtils.copyProperties(ssdSkuDetailVO,skuDetailEntity);
            skuDetailEntity.setQuotationId(quotation.getId());
            //ssdSkuDetailVO转为JSON数组的String字符串
            skuDetailEntity.setDetail(JSON.toJSONString(ssdSkuDetailVO));
            skuDetailEntityList.add(skuDetailEntity);
            languageType = ssdSkuDetailVO.getLanguageType();

//            totalOrderAmt = totalOrderAmt.add(ssdSkuDetailVO.getSkuPriceCNY());
            if (!ObjectUtils.isEmpty(quotationAddDTO.getQuotationType()) && quotationAddDTO.getQuotationType().equals(1)){
                totalOrderAmt = totalOrderAmt.add(ssdSkuDetailVO.getSkuPriceCNYActual());
                if (!ObjectUtils.isEmpty(ssdSkuDetailVO.getSsdSkuCode()) && !ssdSkuDetailVO.getSsdSkuCode().equals("其他费用")){
                    productTotalOrderAmt = productTotalOrderAmt.add(ssdSkuDetailVO.getSkuPriceCNYActual());
                }else {
                    otherAmt = otherAmt.add(ssdSkuDetailVO.getSkuPriceCNYActual());
                }
            }else {
                totalOrderAmt = totalOrderAmt.add(ssdSkuDetailVO.getSkuPriceCNYWithNoRateActual());
                if (!ObjectUtils.isEmpty(ssdSkuDetailVO.getSsdSkuCode()) && !ssdSkuDetailVO.getSsdSkuCode().equals("其他费用")){
                    productTotalOrderAmt = productTotalOrderAmt.add(ssdSkuDetailVO.getSkuPriceCNYWithNoRateActual());
                }else {
                    otherAmt = otherAmt.add(ssdSkuDetailVO.getSkuPriceCNYWithNoRateActual());
                }
            }

            totalOrderAmt = totalOrderAmt.setScale(2,  RoundingMode.HALF_UP);
            productTotalOrderAmt = productTotalOrderAmt.setScale(2,  RoundingMode.HALF_UP);
            otherAmt = otherAmt.setScale(2,  RoundingMode.HALF_UP);
//            totalEarnestAmt = totalEarnestAmt.add(ssdSkuDetailVO.getSkuPriceUSD());
            totalEarnestAmt = totalEarnestAmt.add(!ObjectUtils.isEmpty(ssdSkuDetailVO.getSkuPriceUSDActual()) ? ssdSkuDetailVO.getSkuPriceUSDActual() : BigDecimal.ZERO);
            totalEarnestAmt = totalEarnestAmt.setScale(2,  RoundingMode.HALF_UP);
            if (!ssdSkuDetailVO.getSsdSkuCode().equals("其他费用")) {
//                totalProductCount = totalProductCount + Integer.parseInt(contractData.getProductCount());
                totalNumber = totalNumber + ssdSkuDetailVO.getProductCount();
            }

        }
        quotation.setLanguageType(languageType);
        quotation.setQuotationType(quotationAddDTO.getQuotationType());
        quotation.setTotalOrderAmt(totalOrderAmt);
        quotation.setProductTotalOrderAmt(productTotalOrderAmt);
        quotation.setOtherAmt(otherAmt);
        quotation.setTotalEarnestAmt(totalEarnestAmt);
        quotation.setTotalNumber(totalNumber);
        this.saveOrUpdate(quotation);
        boolean isOk = skuDetailService.saveOrUpdateBatch(skuDetailEntityList);
        if (!isOk){
            return Result.error("保存失败！");
        }
        quotationAddDTO.setTotalOrderAmt(totalOrderAmt);
        List<Long> skuDetailIds = skuDetailEntityList.stream().map(SkuDetailEntity::getId).collect(Collectors.toList());
        LambdaUpdateWrapper<SkuDetailEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SkuDetailEntity::getQuotationId,quotation.getId());
        updateWrapper.notIn(SkuDetailEntity::getId,skuDetailIds);
        updateWrapper.set(SkuDetailEntity::getIsDelete,CommonConstant.DEL_FLAG_1);
        skuDetailService.update(updateWrapper);

        //修改商机阶段为产品报价
        if (!ObjectUtils.isEmpty(quotationAddDTO.getBusinessId())){
            BusinessEntity business = new BusinessEntity();
            business.setId(quotationAddDTO.getBusinessId());
            business.setQuotationId(quotation.getId());
            business.setStage("3");
            businessService.updateById(business);
        }
        if (!ObjectUtils.isEmpty(quotationAddDTO.getOrderFormId())){
            OrderFormEntity orderForm = new OrderFormEntity();
            orderForm.setId(quotationAddDTO.getOrderFormId());
            orderForm.setQuotationId(quotation.getId());
            orderForm.setTotalOrderAmt(totalOrderAmt);
            orderFormService.updateById(orderForm);
        }
        assembleService.sendBusinessEventMessages(quotation.getBusinessId(),"ADD_QUOTE");
        return Result.ok();
    }

    @Override
    public QuotationDetailVO getQuotationDetailVOById(Long id) {
        QuotationDetailVO quotationDetailVO = new QuotationDetailVO();
        QuotationEntity quotation = this.getById(id);
        if (ObjectUtils.isEmpty(quotation)){
            return quotationDetailVO;
        }

        BeanUtils.copyProperties(quotation,quotationDetailVO);
        LambdaQueryWrapper<SkuDetailEntity> skuWrapper = new LambdaQueryWrapper<>();
        skuWrapper.eq(SkuDetailEntity::getQuotationId,id);
        skuWrapper.eq(SkuDetailEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        List<SkuDetailEntity> skuDetailList = skuDetailService.list(skuWrapper);
        List<SsdSkuDetailVO> ssdSkuDetailVOList = new ArrayList<>();
        for (SkuDetailEntity skuDetailEntity : skuDetailList){
            Gson gson = new Gson();
            SsdSkuDetailVO ssdSkuDetailVO = gson.fromJson(skuDetailEntity.getDetail(),  SsdSkuDetailVO.class);
            ssdSkuDetailVO.setId(skuDetailEntity.getId());
            ssdSkuDetailVOList.add(ssdSkuDetailVO);
        }

        quotationDetailVO.setSsdSkuDetailVOList(ssdSkuDetailVOList);

        return quotationDetailVO;
    }

    @Override
    public QuotationDetailVO getQuotationDetailVO(QuotationSearchDTO quotationSearchDTO) {
        if (!ObjectUtils.isEmpty(quotationSearchDTO.getSkuDetailId())){
            SkuDetailEntity skuDetail = skuDetailService.getById(quotationSearchDTO.getSkuDetailId());
            if (!ObjectUtils.isEmpty(skuDetail)){
                quotationSearchDTO.setId(skuDetail.getQuotationId());
            }
        }
        QuotationDetailVO quotationDetailVO = new QuotationDetailVO();
        LambdaQueryWrapper<QuotationEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuotationEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        wrapper.eq(!ObjectUtils.isEmpty(quotationSearchDTO.getId()),QuotationEntity::getId,quotationSearchDTO.getId());
        wrapper.eq(!ObjectUtils.isEmpty(quotationSearchDTO.getBusinessId()),QuotationEntity::getBusinessId,quotationSearchDTO.getBusinessId());
        wrapper.eq(!ObjectUtils.isEmpty(quotationSearchDTO.getOrderFormId()),QuotationEntity::getOrderFormId,quotationSearchDTO.getOrderFormId());
        wrapper.last("limit 1");
        QuotationEntity quotation = this.getOne(wrapper);
        if (ObjectUtils.isEmpty(quotation)){
            return quotationDetailVO;
        }

        BeanUtils.copyProperties(quotation,quotationDetailVO);
        LambdaQueryWrapper<SkuDetailEntity> skuWrapper = new LambdaQueryWrapper<>();
        skuWrapper.eq(SkuDetailEntity::getQuotationId,quotation.getId());
        skuWrapper.eq(SkuDetailEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (!ObjectUtils.isEmpty(quotationSearchDTO.getSkuDetailId())){
            skuWrapper.eq(SkuDetailEntity::getId,quotationSearchDTO.getSkuDetailId());
        }
        List<SkuDetailEntity> skuDetailList = skuDetailService.list(skuWrapper);
        List<SsdSkuDetailVO> ssdSkuDetailVOList = new ArrayList<>();
        for (SkuDetailEntity skuDetailEntity : skuDetailList){
            Gson gson = new Gson();
            SsdSkuDetailVO ssdSkuDetailVO = gson.fromJson(skuDetailEntity.getDetail(),  SsdSkuDetailVO.class);
            ssdSkuDetailVO.setId(skuDetailEntity.getId());
            ssdSkuDetailVOList.add(ssdSkuDetailVO);
        }

        quotationDetailVO.setSsdSkuDetailVOList(ssdSkuDetailVOList);

        return quotationDetailVO;
    }

    @Override
    public Result<IPage<QuotationListVO>> selectListVO(QuotationListDTO quotationListDTO) {
        if (ObjectUtils.isEmpty(quotationListDTO.getSortMethod())){
            quotationListDTO.setSortMethod("desc");
        }
        if (ObjectUtils.isEmpty(quotationListDTO.getCommonQueryOrderBy())){
            quotationListDTO.setCommonQueryOrderBy("id");
        }
//        CustomerEntity customer = customerService.getById(quotationListDTO.getCustomerId());
        LiaisonEntity liaison = liaisonService.getByCustomerId(quotationListDTO.getCustomerId());

        IPage<QuotationListVO> pageVO = new Page<>(quotationListDTO.getPageIndex(), quotationListDTO.getPageSize());
        IPage<QuotationEntity> page = new Page<>(quotationListDTO.getPageIndex(), quotationListDTO.getPageSize());
        LambdaQueryWrapper<QuotationEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuotationEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (ObjectUtils.isEmpty(quotationListDTO.getCustomerId()) && ObjectUtils.isEmpty(quotationListDTO.getOwnerBy())){
            return Result.result(pageVO);
        }
        wrapper.eq(!ObjectUtils.isEmpty(quotationListDTO.getCustomerId()),QuotationEntity::getCustomerId, quotationListDTO.getCustomerId());
        wrapper.eq(!ObjectUtils.isEmpty(quotationListDTO.getOwnerBy()),QuotationEntity::getOwnerBy,quotationListDTO.getOwnerBy());

        if (!quotationListDTO.getHasOrderForm()){
            wrapper.eq(QuotationEntity::getCustomerId,0);
            wrapper.eq(QuotationEntity::getOrderFormId,0);
            wrapper.eq(QuotationEntity::getBusinessId,0);
        }
        wrapper.eq(!ObjectUtils.isEmpty(quotationListDTO.getCustomerId()),QuotationEntity::getCustomerId, quotationListDTO.getCustomerId());
        wrapper.eq(!ObjectUtils.isEmpty(quotationListDTO.getOwnerBy()),QuotationEntity::getOwnerBy,quotationListDTO.getOwnerBy());
        if (ObjectUtils.isEmpty(quotationListDTO.getCustomerId())) {
            page = pageWithScope(page, wrapper, quotationListDTO, "");
        }else {
            page = page(page, wrapper);
        }
        if (CollectionUtils.isEmpty(page.getRecords())){
            return Result.result(pageVO);
        }

        pageVO = SysBaseField.page(page, QuotationListVO.class);
        //获取商机idList
        List<Long> businessIdList = page.getRecords().stream().filter(quotationEntity -> !ObjectUtils.isEmpty(quotationEntity.getBusinessId()) && !quotationEntity.getBusinessId().equals(0L)).map(QuotationEntity::getBusinessId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(businessIdList)){
            Map<Long, BusinessEntity> businessMap = businessService.getBusinessMap(businessIdList);
            pageVO.getRecords().forEach(quotationListVO -> {
                if (!ObjectUtils.isEmpty(quotationListVO.getBusinessId()) && !quotationListVO.getBusinessId().equals(0L)){
                    if (!ObjectUtils.isEmpty(businessMap.get(quotationListVO.getBusinessId()))) {
                        quotationListVO.setBusinessTitle(businessMap.get(quotationListVO.getBusinessId()).getTitle());
                        quotationListVO.setAbutmentUserId(businessMap.get(quotationListVO.getBusinessId()).getLiaisonId());
                        quotationListVO.setAbutmentUserName(liaisonService.getById(quotationListVO.getAbutmentUserId()).getName());
                    }
                }
            });
        }
        //获取订单idList
        List<Long> orderFormIdList = page.getRecords().stream().filter(quotationEntity -> !ObjectUtils.isEmpty(quotationEntity.getOrderFormId()) && !quotationEntity.getOrderFormId().equals(0L)).map(QuotationEntity::getOrderFormId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(orderFormIdList)){
            Map<Long, OrderFormEntity> orderFormMap = orderFormService.getOrderFormMap(orderFormIdList);
            pageVO.getRecords().forEach(quotationListVO -> {
                if (!ObjectUtils.isEmpty(quotationListVO.getOrderFormId()) && !quotationListVO.getOrderFormId().equals(0L)){
                    quotationListVO.setOrderFormTitle(orderFormMap.get(quotationListVO.getOrderFormId()).getTitle());
                }
            });
        }
        pageVO.getRecords().forEach(quotationListVO -> {
            if (ObjectUtils.isEmpty(quotationListVO.getAbutmentUserId()) && !ObjectUtils.isEmpty(liaison)){
                quotationListVO.setAbutmentUserId(liaison.getId());
                quotationListVO.setAbutmentUserName(liaison.getName());
            }
        });
        SysBaseField.dictFileds(pageVO.getRecords());
        SysBaseField.orgFileds(pageVO.getRecords());
        return Result.result(pageVO);
    }

    @Override
    public Map<Long, QuotationEntity> getQuotationMap(List<Long> quotationIdList) {
        if (!CollectionUtils.isEmpty(quotationIdList)){
            Collection<QuotationEntity> quotationList = listByIds(quotationIdList);
            if (!CollectionUtils.isEmpty(quotationList)){
                Map<Long, QuotationEntity> quotationEntityMap = quotationList.stream().collect(Collectors.toMap(QuotationEntity::getId, quotationEntity -> quotationEntity));
                return quotationEntityMap;
            }
        }
        return null;
    }

    @Override
    public Result<?> getPrice(QuotationPriceDTO quotationPriceDTO) {
        if (ObjectUtils.isEmpty(quotationPriceDTO.getQuotationPricetype())){
            return Result.error("参数异常");
        }
        BigDecimal rate = ssdSkuService.getRate();
        if (ObjectUtils.isEmpty(rate)){
            return Result.error("汇率获取失败");
        }
        quotationPriceDTO.setRete(rate);
        if (quotationPriceDTO.getQuotationPricetype().equals(1)){
            //国内单价（不含税）
            return this.cnyPrice(quotationPriceDTO);
        }
        if (quotationPriceDTO.getQuotationPricetype().equals(2)){
            //海外单价
            return this.usdPrice(quotationPriceDTO);
        }
        if (quotationPriceDTO.getQuotationPricetype().equals(3)){
            //国内总价（不含税）
            return this.cnyPriceTotal(quotationPriceDTO);
        }
        if (quotationPriceDTO.getQuotationPricetype().equals(4)){
            //海外总价
            return this.usdPriceTotal(quotationPriceDTO);
        }
        if (quotationPriceDTO.getQuotationPricetype().equals(5)){
            //国内单价（含税）
            return this.cnyPriceRate(quotationPriceDTO);
        }
        if (quotationPriceDTO.getQuotationPricetype().equals(6)){
            //国内总价（含税）
            return this.cnyPriceTotalRate(quotationPriceDTO);
        }
        return Result.result(new QuotationPriceVO());
    }

    private Result<?> cnyPriceTotalRate(QuotationPriceDTO quotationPriceDTO) {
        QuotationPriceVO quotationPriceVO = new QuotationPriceVO();

        if (!ObjectUtils.isEmpty(quotationPriceDTO.getSkuPriceCNYActual())) {

            //国内总价（含税）
            BigDecimal skuPriceCNYActual = quotationPriceDTO.getSkuPriceCNYActual();
            //国内总价（不含税）
            BigDecimal skuPriceCNYWithNoRateActual = skuPriceCNYActual.divide(BigDecimal.valueOf(1.13),4, RoundingMode.HALF_UP);
            //海外总价
            BigDecimal skuPriceUSDActual = skuPriceCNYWithNoRateActual.divide(quotationPriceDTO.getRete(),4, RoundingMode.HALF_UP);

            quotationPriceVO.setSkuPriceCNYActual(skuPriceCNYActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setSkuPriceCNYWithNoRateActual(skuPriceCNYWithNoRateActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setSkuPriceUSDActual(skuPriceUSDActual.setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        return Result.result(quotationPriceVO);
    }

    private Result<?> cnyPriceRate(QuotationPriceDTO quotationPriceDTO) {


        QuotationPriceVO quotationPriceVO = new QuotationPriceVO();

        if (!ObjectUtils.isEmpty(quotationPriceDTO.getUnitPriceCNYActual()) && !ObjectUtils.isEmpty(quotationPriceDTO.getProductCount())) {
            //获取国内单价（含税）
            BigDecimal unitPriceCNYActual = quotationPriceDTO.getUnitPriceCNYActual();
            //国内单价（不含税）
            BigDecimal unitPriceCNYWithNoRateActual = unitPriceCNYActual.divide(BigDecimal.valueOf(1.13),4, RoundingMode.HALF_UP);
            //国内总价（含税）
            BigDecimal skuPriceCNYActual = unitPriceCNYActual.multiply(BigDecimal.valueOf(quotationPriceDTO.getProductCount()));
            //国内总价（不含税）
            BigDecimal skuPriceCNYWithNoRateActual = unitPriceCNYWithNoRateActual.multiply(BigDecimal.valueOf(quotationPriceDTO.getProductCount()));
            //单价USD不含税（实际）
            BigDecimal unitPriceUSDActual = unitPriceCNYWithNoRateActual.divide(quotationPriceDTO.getRete(),4, RoundingMode.HALF_UP);
            //总价USD不含税（实际）
            BigDecimal skuPriceUSDActual = skuPriceCNYWithNoRateActual.divide(quotationPriceDTO.getRete(),4, RoundingMode.HALF_UP);

            quotationPriceVO.setUnitPriceCNYActual(unitPriceCNYActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setSkuPriceCNYActual(skuPriceCNYActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setUnitPriceCNYWithNoRateActual(unitPriceCNYWithNoRateActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setSkuPriceCNYWithNoRateActual(skuPriceCNYWithNoRateActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setUnitPriceUSDActual(unitPriceUSDActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setSkuPriceUSDActual(skuPriceUSDActual.setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        return Result.result(quotationPriceVO);
    }


    private Result<?> cnyPrice(QuotationPriceDTO quotationPriceDTO) {
        QuotationPriceVO quotationPriceVO = new QuotationPriceVO();

        if (!ObjectUtils.isEmpty(quotationPriceDTO.getUnitPriceCNYWithNoRateActual()) && !ObjectUtils.isEmpty(quotationPriceDTO.getProductCount())) {
            BigDecimal unitPriceCNYWithNoRateActual = quotationPriceDTO.getUnitPriceCNYWithNoRateActual();
            BigDecimal unitPriceCNYActual = unitPriceCNYWithNoRateActual.multiply(BigDecimal.valueOf(1.13));
            BigDecimal skuPriceCNYWithNoRateActual = unitPriceCNYWithNoRateActual.multiply(BigDecimal.valueOf(quotationPriceDTO.getProductCount()));
            BigDecimal skuPriceCNYActual = skuPriceCNYWithNoRateActual.multiply(BigDecimal.valueOf(1.13));
            BigDecimal unitPriceUSDActual = unitPriceCNYWithNoRateActual.divide(quotationPriceDTO.getRete(),4, RoundingMode.HALF_UP);
            BigDecimal skuPriceUSDActual = skuPriceCNYWithNoRateActual.divide(quotationPriceDTO.getRete(),4, RoundingMode.HALF_UP);

            quotationPriceVO.setUnitPriceCNYActual(unitPriceCNYActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setSkuPriceCNYActual(skuPriceCNYActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setUnitPriceCNYWithNoRateActual(unitPriceCNYWithNoRateActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setSkuPriceCNYWithNoRateActual(skuPriceCNYWithNoRateActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setUnitPriceUSDActual(unitPriceUSDActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setSkuPriceUSDActual(skuPriceUSDActual.setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        return Result.result(quotationPriceVO);
    }

    private Result<?> usdPrice(QuotationPriceDTO quotationPriceDTO) {

        QuotationPriceVO quotationPriceVO = new QuotationPriceVO();

        if (!ObjectUtils.isEmpty(quotationPriceDTO.getUnitPriceUSDActual()) && !ObjectUtils.isEmpty(quotationPriceDTO.getProductCount())) {

            BigDecimal unitPriceUSDActual = quotationPriceDTO.getUnitPriceUSDActual();
            BigDecimal skuPriceUSDActual = unitPriceUSDActual.multiply(BigDecimal.valueOf(quotationPriceDTO.getProductCount()));
            BigDecimal unitPriceCNYWithNoRateActual = unitPriceUSDActual.multiply(quotationPriceDTO.getRete());
            BigDecimal unitPriceCNYActual = unitPriceCNYWithNoRateActual.multiply(BigDecimal.valueOf(1.13));
            BigDecimal skuPriceCNYWithNoRateActual = unitPriceCNYWithNoRateActual.multiply(BigDecimal.valueOf(quotationPriceDTO.getProductCount()));
            BigDecimal skuPriceCNYActual = skuPriceCNYWithNoRateActual.multiply(BigDecimal.valueOf(1.13));

            quotationPriceVO.setUnitPriceCNYActual(unitPriceCNYActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setSkuPriceCNYActual(skuPriceCNYActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setUnitPriceCNYWithNoRateActual(unitPriceCNYWithNoRateActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setSkuPriceCNYWithNoRateActual(skuPriceCNYWithNoRateActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setUnitPriceUSDActual(unitPriceUSDActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setSkuPriceUSDActual(skuPriceUSDActual.setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        return Result.result(quotationPriceVO);
    }

    private Result<?> cnyPriceTotal(QuotationPriceDTO quotationPriceDTO) {

        QuotationPriceVO quotationPriceVO = new QuotationPriceVO();

        if (!ObjectUtils.isEmpty(quotationPriceDTO.getSkuPriceCNYWithNoRateActual())) {

            BigDecimal skuPriceCNYWithNoRateActual = quotationPriceDTO.getSkuPriceCNYWithNoRateActual();
            BigDecimal skuPriceCNYActual = skuPriceCNYWithNoRateActual.multiply(BigDecimal.valueOf(1.13));
            BigDecimal skuPriceUSDActual = skuPriceCNYWithNoRateActual.divide(quotationPriceDTO.getRete(),4, RoundingMode.HALF_UP);

            quotationPriceVO.setSkuPriceCNYActual(skuPriceCNYActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setSkuPriceCNYWithNoRateActual(skuPriceCNYWithNoRateActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setSkuPriceUSDActual(skuPriceUSDActual.setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        return Result.result(quotationPriceVO);
    }

    private Result<?> usdPriceTotal(QuotationPriceDTO quotationPriceDTO) {

        QuotationPriceVO quotationPriceVO = new QuotationPriceVO();

        if (!ObjectUtils.isEmpty(quotationPriceDTO.getSkuPriceUSDActual())) {

            BigDecimal skuPriceUSDActual = quotationPriceDTO.getSkuPriceUSDActual();
            BigDecimal skuPriceCNYWithNoRateActual = skuPriceUSDActual.multiply(quotationPriceDTO.getRete());
            BigDecimal skuPriceCNYActual = skuPriceCNYWithNoRateActual.multiply(BigDecimal.valueOf(1.13));

            quotationPriceVO.setSkuPriceCNYActual(skuPriceCNYActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setSkuPriceCNYWithNoRateActual(skuPriceCNYWithNoRateActual.setScale(2, BigDecimal.ROUND_HALF_UP));
            quotationPriceVO.setSkuPriceUSDActual(skuPriceUSDActual.setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        return Result.result(quotationPriceVO);
    }

    @Override
    public Result<?> getPriceUSD(QuotationPriceDTO quotationPriceDTO) {
        QuotationPriceUSDVO quotationPriceVO = new QuotationPriceUSDVO();
        if (!ObjectUtils.isEmpty(quotationPriceDTO.getUnitPriceUSDActual()) && !ObjectUtils.isEmpty(quotationPriceDTO.getProductCount())){
            quotationPriceVO.setUnitPriceUSDActual(quotationPriceDTO.getUnitPriceUSDActual());
            BigDecimal skuPriceUSDActual = quotationPriceDTO.getUnitPriceUSDActual().multiply(BigDecimal.valueOf(quotationPriceDTO.getProductCount()));
            //SkuPriceUSDActual保留两位小数
            skuPriceUSDActual = skuPriceUSDActual.setScale(2, BigDecimal.ROUND_HALF_UP);
            quotationPriceVO.setSkuPriceUSDActual(skuPriceUSDActual);
        }
        return Result.result(quotationPriceVO);
    }

    @Override
    public Result<?> getLastQuotation(QuotationSearchDTO quotationSearchDTO) {
        if (ObjectUtils.isEmpty(quotationSearchDTO.getCreateBy())){
            return Result.error("请传入创建人信息！");
        }
        LambdaQueryWrapper<QuotationEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QuotationEntity::getCreateBy,quotationSearchDTO.getCreateBy());
        queryWrapper.isNull(QuotationEntity::getBusinessId);
        queryWrapper.isNull(QuotationEntity::getOrderFormId);
        queryWrapper.eq(QuotationEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        queryWrapper.orderByDesc(QuotationEntity::getCreateTime);
        queryWrapper.last("limit 1");
        QuotationEntity quotation = baseMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(quotation)){
            return Result.ok();
        }
        Long id = quotation.getId();
        QuotationDetailVO quotationDetailVO = getQuotationDetailVOById(id);
        return Result.result(quotationDetailVO);
    }

    @Override
    public void deleteCustomerId() {
        LambdaUpdateWrapper<QuotationEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(QuotationEntity::getBusinessId,0);
        updateWrapper.eq(QuotationEntity::getOrderFormId,0);
        updateWrapper.ne(QuotationEntity::getCustomerId,0);
        updateWrapper.set(QuotationEntity::getCustomerId,0);
        update(updateWrapper);
    }
}
