package com.casic.missiles.service.Impl.finance;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.finance.SettlementInfoDetailResponse;
import com.casic.missiles.dto.finance.SettlementInfoListRequest;
import com.casic.missiles.dto.finance.SettlementInfoListResponse;
import com.casic.missiles.dto.finance.SettlementSampleDTO;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.business.BusinessOrderSampleRelationMapper;
import com.casic.missiles.mapper.finance.FinanceBusinessSettlementInfoMapper;
import com.casic.missiles.model.business.BusinessOrderSampleRelation;
import com.casic.missiles.model.finance.FinanceBusinessSettlementInfo;
import com.casic.missiles.service.finance.IFinanceBusinessSettlementInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务结算表-未在合同里的委托书收款信息 服务实现类
 * </p>
 *
 * @author wangpeng
 * @since 2023-03-31
 */
@Service
public class FinanceBusinessSettlementInfoServiceImpl extends ServiceImpl<FinanceBusinessSettlementInfoMapper, FinanceBusinessSettlementInfo> implements IFinanceBusinessSettlementInfoService {
    @Autowired
    private FinanceBusinessSettlementInfoMapper settlementInfoMapper;
    @Autowired
    private BusinessOrderSampleRelationMapper sampleRelationMapper;

    @Override
    public Page<SettlementInfoListResponse> listPage(SettlementInfoListRequest request, Page<SettlementInfoListResponse> page) {
        Page<SettlementInfoListResponse> infoPage = settlementInfoMapper.selectListPage(page, request);
        if(Objects.isNull(infoPage) || CollectionUtils.isEmpty(infoPage.getRecords())){
            return new Page<>();
        }
        calculateTarget(infoPage.getRecords());
        return infoPage;
    }

    @Override
    public List<SettlementInfoListResponse> list(SettlementInfoListRequest request) {
        List<SettlementInfoListResponse> infoList = settlementInfoMapper.selectList(request);
        if(CollectionUtils.isEmpty(infoList)){
            return new ArrayList<>();
        }
        calculateTarget(infoList);
        return infoList;
    }

    @Override
    @Transactional
    public ReturnDTO addSettlement(FinanceBusinessSettlementInfo settlementInfo) {
        if(settlementInfoMapper.insert(settlementInfo) > 0){
            sampleRelationMapper.updatePriceBatchById(settlementInfo.getSamplePriceList());
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    @Transactional
    public ReturnDTO updateSettlement(FinanceBusinessSettlementInfo settlementInfo) {
        if(settlementInfoMapper.updateById(settlementInfo) > 0){
            sampleRelationMapper.updatePriceBatchById(settlementInfo.getSamplePriceList());
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public ReturnDTO settlementDetail(Long id) {
        SettlementInfoDetailResponse detailResponse = settlementInfoMapper.selectDetailById(id);
        Long orderId = detailResponse.getOrderId();
        List<SettlementSampleDTO> sampleDTOS = sampleRelationMapper.selectSampleListForSettlement(orderId);
        //标价
        Integer price = sampleDTOS.stream().collect(Collectors.summingInt(SettlementSampleDTO::getPostedPrice));
        detailResponse.setPostedPrice(price);
        if(Objects.nonNull(price) && Objects.nonNull(detailResponse.getSuggestedDiscount())){
            //建议价格，四舍五入取整数分
            BigDecimal bigDecimal = new BigDecimal(price);
            BigDecimal suggestedPrice = bigDecimal.multiply(BigDecimal.valueOf(detailResponse.getSuggestedDiscount()))
                    .divide(BigDecimal.valueOf(100)).setScale(0, BigDecimal.ROUND_HALF_UP);
            detailResponse.setSuggestedPrice(suggestedPrice.intValue());
            if(Objects.nonNull(detailResponse.getExtraCharge())){
                //总计结算费用
                detailResponse.setTotalSettlement(detailResponse.getExtraCharge() + suggestedPrice.intValue());
            }
        }
        detailResponse.setSampleList(sampleDTOS);
        return ReturnUtil.success(detailResponse);
    }

    @Override
    public List<SettlementInfoListResponse> listBySettlementIds(List<Long> ids) {
        List<SettlementInfoListResponse> infoList = settlementInfoMapper.selectListByIds(ids);
        if(CollectionUtils.isEmpty(infoList)){
            return new ArrayList<>();
        }
        calculateTarget(infoList);
        return infoList;
    }

    @Override
    public Integer selectCompleteAmount(String dimension) {
        List<SettlementInfoListResponse> list = settlementInfoMapper.selectListByDimension(dimension);
        if(CollectionUtils.isEmpty(list)){
            return 0;
        }
        calculateTarget(list);
        int sum = list.stream().mapToInt(SettlementInfoListResponse::getTotalSettlement).sum();
        return sum;
    }

    private void calculateTarget(List<SettlementInfoListResponse> list) {
        //委托书样品数量
        List<BusinessOrderSampleRelation> orderSampleList = sampleRelationMapper.selectList(null);
        Map<Long, List<BusinessOrderSampleRelation>> orderSampleMap = orderSampleList.stream().collect(
                Collectors.groupingBy(BusinessOrderSampleRelation::getOrderId)
        );
        list.forEach(orderSettlement -> {
            orderSettlement.setSampleCount(orderSampleMap.containsKey(orderSettlement.getOrderId()) ? orderSampleMap.get(orderSettlement.getOrderId()).size() : 0);
            List<BusinessOrderSampleRelation> orderSampleRelations = orderSampleMap.get(orderSettlement.getOrderId());
            //所有样品标价和
            Integer price = orderSampleRelations.stream().collect(Collectors.summingInt(BusinessOrderSampleRelation::getPostedPrice));
            orderSettlement.setPostedPrice(price);
            if(Objects.nonNull(price) && Objects.nonNull(orderSettlement.getSuggestedDiscount())){
                //建议价格，四舍五入取整数分
                BigDecimal bigDecimal = new BigDecimal(price);
                BigDecimal suggestedPrice = bigDecimal.multiply(BigDecimal.valueOf(orderSettlement.getSuggestedDiscount()))
                        .divide(BigDecimal.valueOf(100)).setScale(0, BigDecimal.ROUND_HALF_UP);
                orderSettlement.setSuggestedPrice(suggestedPrice.intValue());
                if(Objects.nonNull(orderSettlement.getExtraCharge())){
                    orderSettlement.setTotalSettlement(orderSettlement.getExtraCharge() + suggestedPrice.intValue());
                }
            }
        });
    }

}
