package com.gci.boot.modules.statis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Segment;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gci.boot.modules.projects.entity.TbContract;
import com.gci.boot.modules.projects.entity.TbContractVehicle;
import com.gci.boot.modules.projects.entity.TbVehicleCheck;
import com.gci.boot.modules.projects.entity.TbVehicleCheckDetail;
import com.gci.boot.modules.projects.service.ITbContractService;
import com.gci.boot.modules.projects.service.ITbContractVehicleService;
import com.gci.boot.modules.projects.service.ITbVehicleCheckDetailService;
import com.gci.boot.modules.projects.service.ITbVehicleCheckService;
import com.gci.boot.modules.statis.service.VehicleRentalService;
import com.gci.boot.modules.statis.vo.VehicleRentalVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
@Slf4j
public class VehicleRentalServiceImpl implements VehicleRentalService {

    @Autowired
    private ITbContractService contractService;

    @Autowired
    private ITbVehicleCheckService vehicleCheckService;

    @Autowired
    private ITbVehicleCheckDetailService detailService;

    @Autowired
    private ITbContractVehicleService contractVehicleService;

    @Override
    public IPage<VehicleRentalVo> pageBuild(Page<VehicleRentalVo> page, VehicleRentalVo query) {
        List<VehicleRentalVo> recordList = getVehicleRentalList(query);
        PageUtil.setOneAsFirstPageNo();
        int totalPage = PageUtil.totalPage(recordList.size(), Convert.toInt(page.getSize()));
        if (page.getCurrent() > totalPage) {
            page.setCurrent(totalPage);
        }
        page.setTotal(recordList.size());
        page.setPages(totalPage);
        if (page.getSize() == -1) {
            page.setRecords(recordList);
            return page;
        }
        Segment<Integer> integerSegment = PageUtil.toSegment(Convert.toInt(page.getCurrent()), Convert.toInt(page.getSize()));
        Integer endIndex = integerSegment.getEndIndex();
        if (endIndex > recordList.size()) {
            endIndex = recordList.size();
        }
        page.setRecords(recordList.subList(integerSegment.getStartIndex(), endIndex));
        return page;
    }

    private List<VehicleRentalVo> getVehicleRentalList(VehicleRentalVo query) {
        List<VehicleRentalVo> rentalVos = new ArrayList<>();
        BigDecimal wan = new BigDecimal(10000);
        //查询租赁合同
        List<TbContract> contractList = contractService.list(new LambdaQueryWrapper<TbContract>()
                .eq(TbContract::getContractType, '1')
                .like(StrUtil.isNotBlank(query.getContractName()),TbContract::getName,query.getContractName())
        );
        if (contractList.isEmpty()) {
            return rentalVos;
        }
        Map<String, String> contractIdNameMap = contractList.stream().collect(Collectors.toMap(TbContract::getId, TbContract::getName));
        //根据合同查询对应的车型明细
        List<TbContractVehicle> contractVehicleList = contractVehicleService.list(new LambdaQueryWrapper<TbContractVehicle>().in(TbContractVehicle::getContractId, contractIdNameMap.keySet()));
        Map<String, List<TbContractVehicle>> contractVehicleContractIdGroup = contractVehicleList.stream().collect(Collectors.groupingBy(TbContractVehicle::getContractId));

        //根据合同查询已提交的交车单
        List<TbVehicleCheck> vehicleCheckList = vehicleCheckService.list(new LambdaQueryWrapper<TbVehicleCheck>()
                .eq(TbVehicleCheck::getStatus, '1')
                .eq(TbVehicleCheck::getCheckType, '2')
                .in(TbVehicleCheck::getContractId,contractIdNameMap.keySet())
                .and(i->i.eq(TbVehicleCheck::getReceiveStatus,"0.5").or().eq(TbVehicleCheck::getReceiveStatus,'1')));
        if (vehicleCheckList.isEmpty()) {
            return rentalVos;
        }
        Map<String, List<TbVehicleCheck>> vehicleCheckContractIdGroup = vehicleCheckList.stream().collect(Collectors.groupingBy(TbVehicleCheck::getContractId));

        //根据交车单查询收车单
        List<TbVehicleCheck> afterVehicleCheckList = vehicleCheckService.list(new LambdaQueryWrapper<TbVehicleCheck>()
                .in(TbVehicleCheck::getParentId, vehicleCheckList.stream().map(TbVehicleCheck::getId).collect(Collectors.toList())));

        List<String> checkIds = vehicleCheckList.stream().map(TbVehicleCheck::getId).collect(Collectors.toList());
        if (!afterVehicleCheckList.isEmpty()) {
            checkIds.addAll(afterVehicleCheckList.stream().map(TbVehicleCheck::getId).collect(Collectors.toList()));
        }
        Map<String, List<TbVehicleCheck>> afterVehicleCheckParentGroup = afterVehicleCheckList.stream().collect(Collectors.groupingBy(TbVehicleCheck::getParentId));
        //根据交接车单查询对应车辆
        List<TbVehicleCheckDetail> checkDetailList = detailService.list(new LambdaQueryWrapper<TbVehicleCheckDetail>()
                .in(TbVehicleCheckDetail::getCheckId, checkIds)
                //车型
                .like(StrUtil.isNotBlank(query.getVehicleModel()), TbVehicleCheckDetail::getVehicleModel, query.getVehicleModel())
                .eq(StrUtil.isNotBlank(query.getVehicleType()), TbVehicleCheckDetail::getVehicleType, query.getVehicleType())
                //车架号
                .like(StrUtil.isNotBlank(query.getFrameNumber()), TbVehicleCheckDetail::getFrameNumber, query.getFrameNumber())
                .like(StrUtil.isNotBlank(query.getPlateNumber()), TbVehicleCheckDetail::getPlateNumber, query.getPlateNumber())
        );
        if (checkDetailList.isEmpty()) {
            return rentalVos;
        }
        Map<String, List<TbVehicleCheckDetail>> checkDetailCheckIdGroup = checkDetailList.stream().collect(Collectors.groupingBy(TbVehicleCheckDetail::getCheckId));
        for (TbContract tbContract : contractList) {
            //根据合同找交车单
            List<TbVehicleCheck> tbVehicleChecks = vehicleCheckContractIdGroup.get(tbContract.getId());
            if (ObjectUtil.isNotEmpty(tbVehicleChecks)) {
                for (TbVehicleCheck tbVehicleCheck : tbVehicleChecks) {
                    //根据交车单找收车单
                    List<TbVehicleCheck> afterVehicleChecks = afterVehicleCheckParentGroup.get(tbVehicleCheck.getId());
                    if (ObjectUtil.isEmpty(afterVehicleChecks)) {
                        //交车单没有对应的收车单时
                        List<TbVehicleCheckDetail> tbVehicleCheckDetails = checkDetailCheckIdGroup.get(tbVehicleCheck.getId());
                        if (ObjectUtil.isNotEmpty(tbVehicleCheckDetails)) {
                            for (TbVehicleCheckDetail tbVehicleCheckDetail : tbVehicleCheckDetails) {
                                VehicleRentalVo vehicleRentalVo = new VehicleRentalVo();
                                vehicleRentalVo.setVehicleType(tbVehicleCheckDetail.getVehicleType());
                                vehicleRentalVo.setPlateNumber(tbVehicleCheckDetail.getPlateNumber());
                                vehicleRentalVo.setFrameNumber(tbVehicleCheckDetail.getFrameNumber());
                                vehicleRentalVo.setVehicleModel(tbVehicleCheckDetail.getVehicleModel());
                                vehicleRentalVo.setContractName(tbContract.getName());
                                //格式化时间
                                vehicleRentalVo.setContractStartDate(DateUtil.beginOfDay(tbContract.getStartTime()));
                                vehicleRentalVo.setContractEndDate(DateUtil.beginOfDay(tbContract.getEndTime()));
                                //根据合同查找车型 明细
                                List<TbContractVehicle> inContractVehicle = contractVehicleContractIdGroup.get(tbContract.getId());
                                if (ObjectUtil.isEmpty(inContractVehicle)) {
                                    vehicleRentalVo.setRentalUnitPrice(BigDecimal.ZERO);
                                } else {
                                    TbContractVehicle tbContractVehicle = inContractVehicle.stream().filter(i -> i.getVehicleModel().equals(tbVehicleCheckDetail.getVehicleModel())).findFirst().orElse(null);
                                    if (tbContractVehicle == null) {
                                        vehicleRentalVo.setRentalUnitPrice(BigDecimal.ZERO);
                                    } else {
                                        vehicleRentalVo.setRentalUnitPrice(NumberUtil.mul(tbContractVehicle.getTotalPrice(), wan));
                                    }
                                }
                                //格式化时间
                                vehicleRentalVo.setRentalDeliveryDate(DateUtil.beginOfDay(tbVehicleCheck.getCheckTime()));
                                //没有收车时间
//                            vehicleRentalVo.setRentalDeliveryDate();

                                boolean target = false;
                                VehicleRentalVo cer = vehicleRentalVo;
                                boolean first = true;
                                DateTime timeTi = DateUtil.beginOfDay(tbContract.getStartTime());
                                while (!target) {
                                    //按月偏移
                                    timeTi.offset(DateField.MONTH,1);
                                    if (first) {
                                        cer.setPaymentDate(timeTi.toJdkDate());
                                        first = false;
                                        if (!DateUtil.beginOfDay(cer.getContractStartDate()).equals(DateUtil.beginOfDay(cer.getRentalDeliveryDate()))) {
                                            long day = DateUtil.betweenDay(cer.getRentalDeliveryDate(), timeTi, true);
                                            cer.setAmountCollected(NumberUtil.div(NumberUtil.mul(cer.getRentalUnitPrice(),day),30).setScale(2, RoundingMode.HALF_UP));
                                        } else {
                                            if (timeTi.after(cer.getContractEndDate())) {
                                                long day = DateUtil.betweenDay(DateUtil.offsetMonth(timeTi, -1), cer.getContractEndDate(), true) + 1;
                                                cer.setAmountCollected(NumberUtil.div(NumberUtil.mul(cer.getRentalUnitPrice(),day),30).setScale(2, RoundingMode.HALF_UP));
                                                target = true;
                                            } else {
                                                cer.setAmountCollected(cer.getRentalUnitPrice());
                                            }
                                        }
                                    } else {
                                        VehicleRentalVo the = new VehicleRentalVo();
                                        BeanUtil.copyProperties(cer,the);
                                        cer = the;
                                        cer.setPaymentDate(timeTi.toJdkDate());
                                        if (timeTi.after(cer.getContractEndDate())) {
                                            long day = DateUtil.betweenDay(DateUtil.offsetMonth(timeTi, -1), cer.getContractEndDate(), true) + 1;
                                            cer.setAmountCollected(NumberUtil.div(NumberUtil.mul(cer.getRentalUnitPrice(),day),30).setScale(2, RoundingMode.HALF_UP));
                                            target = true;
                                        } else {
                                            cer.setAmountCollected(cer.getRentalUnitPrice());
                                        }
                                    }
                                    rentalVos.add(cer);
                                }

                            }
                        }
                    } else {
                        //交车单有对应的收车单时
                        List<TbVehicleCheckDetail> tbVehicleCheckDetails = checkDetailCheckIdGroup.get(tbVehicleCheck.getId());
                        if (ObjectUtil.isNotEmpty(tbVehicleCheckDetails)) {
                            for (TbVehicleCheckDetail tbVehicleCheckDetail : tbVehicleCheckDetails) {
                                VehicleRentalVo vehicleRentalVo = new VehicleRentalVo();
                                vehicleRentalVo.setVehicleType(tbVehicleCheckDetail.getVehicleType());
                                vehicleRentalVo.setPlateNumber(tbVehicleCheckDetail.getPlateNumber());
                                vehicleRentalVo.setFrameNumber(tbVehicleCheckDetail.getFrameNumber());
                                vehicleRentalVo.setVehicleModel(tbVehicleCheckDetail.getVehicleModel());
                                vehicleRentalVo.setContractName(tbContract.getName());
                                //格式化时间
                                vehicleRentalVo.setContractStartDate(DateUtil.beginOfDay(tbContract.getStartTime()));
                                vehicleRentalVo.setContractEndDate(DateUtil.beginOfDay(tbContract.getEndTime()));
                                //根据合同查找车型 明细
                                List<TbContractVehicle> inContractVehicle = contractVehicleContractIdGroup.get(tbContract.getId());
                                if (ObjectUtil.isEmpty(inContractVehicle)) {
                                    vehicleRentalVo.setRentalUnitPrice(BigDecimal.ZERO);
                                } else {
                                    TbContractVehicle tbContractVehicle = inContractVehicle.stream().filter(i -> i.getVehicleModel().equals(tbVehicleCheckDetail.getVehicleModel())).findFirst().orElse(null);
                                    if (tbContractVehicle == null) {
                                        vehicleRentalVo.setRentalUnitPrice(BigDecimal.ZERO);
                                    } else {
                                        vehicleRentalVo.setRentalUnitPrice(NumberUtil.mul(tbContractVehicle.getTotalPrice(), wan));
                                    }
                                }
                                //格式化时间
                                vehicleRentalVo.setRentalDeliveryDate(DateUtil.beginOfDay(tbVehicleCheck.getCheckTime()));
                                //收车时间
                                vehicleRentalVo.setRentalPickupDate(DateUtil.beginOfDay(afterVehicleChecks.get(0).getCheckTime()));

                                boolean target = false;
                                VehicleRentalVo cer = vehicleRentalVo;
                                boolean first = true;
                                DateTime timeTi = DateUtil.beginOfDay(tbContract.getStartTime());
                                while (!target) {
                                    //按月偏移
                                    timeTi.offset(DateField.MONTH,1);
                                    if (first) {
                                        cer.setPaymentDate(timeTi.toJdkDate());
                                        first = false;
                                        if (!DateUtil.beginOfDay(cer.getContractStartDate()).equals(DateUtil.beginOfDay(cer.getRentalDeliveryDate()))) {
                                            long day = DateUtil.betweenDay(cer.getRentalDeliveryDate(), timeTi, true);
                                            cer.setAmountCollected(NumberUtil.div(NumberUtil.mul(cer.getRentalUnitPrice(),day),30).setScale(2, RoundingMode.HALF_UP));
                                        } else {
                                            if (timeTi.after(cer.getContractEndDate())) {
                                                long day = DateUtil.betweenDay(DateUtil.offsetMonth(timeTi, -1), cer.getContractEndDate(), true) + 1;
                                                cer.setAmountCollected(NumberUtil.div(NumberUtil.mul(cer.getRentalUnitPrice(),day),30).setScale(2, RoundingMode.HALF_UP));
                                                target = true;
                                            } else {
                                                cer.setAmountCollected(cer.getRentalUnitPrice());
                                            }
                                        }
                                    } else {
                                        VehicleRentalVo the = new VehicleRentalVo();
                                        BeanUtil.copyProperties(cer,the);
                                        cer = the;
                                        cer.setPaymentDate(timeTi.toJdkDate());
                                        if (timeTi.after(cer.getRentalPickupDate())) {
                                            long day = DateUtil.betweenDay(DateUtil.offsetMonth(timeTi, -1), cer.getRentalPickupDate(), true) + 1;
                                            cer.setAmountCollected(NumberUtil.div(NumberUtil.mul(cer.getRentalUnitPrice(),day),30).setScale(2, RoundingMode.HALF_UP));
                                            target = true;
                                        } else {
                                            cer.setAmountCollected(cer.getRentalUnitPrice());
                                        }
                                    }
                                    rentalVos.add(cer);
                                }

                            }
                        }
                    }
                }
            }
        }
        if (ObjectUtil.isAllNotEmpty(query.getPaymentDateStart(),query.getPaymentDateEnd())) {
            rentalVos = rentalVos.stream().filter(r->DateUtil.isOverlap(query.getPaymentDateStart(),query.getPaymentDateEnd(),r.getPaymentDate(),r.getPaymentDate())).collect(Collectors.toList());
        }
        rentalVos.sort(Comparator.comparing(VehicleRentalVo::getPlateNumber).thenComparing(VehicleRentalVo::getContractName).thenComparing(VehicleRentalVo::getPaymentDate));
        return rentalVos;
    }
}
