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

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gci.boot.modules.statis.service.RepairStatisService;
import com.gci.boot.modules.statis.service.UpkeepStatisService;
import com.gci.boot.modules.statis.vo.*;
import com.gci.boot.modules.system.service.ISysDictService;
import com.gci.boot.modules.system.vo.DictModel;
import com.gci.boot.modules.vehicles.entity.*;
import com.gci.boot.modules.vehicles.mapper.TbRepairInfoMapper;
import com.gci.boot.modules.vehicles.mapper.TbUpkeepBillMapper;
import com.gci.boot.modules.vehicles.service.*;
import com.gci.boot.modules.vehicles.vo.RepairDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UpkeepStatisServiceImpl implements UpkeepStatisService {

    @Autowired
    private TbUpkeepBillMapper upkeepBillMapper;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private ITbUpkeepBillService upkeepBillService;
    @Autowired
    private ITbUpkeepOfferService upkeepOfferService;
    @Autowired
    private ITbUpkeepPlanService upkeepPlanService;

    @Override
    public Page getUpkeepStatisPage(Page page, StatisParamVO vo) {
        if("1".equals(vo.getStatisType())){
            vo.setStatisTime("YYYY-MM-DD");
        }else if("2".equals(vo.getStatisType())){
            vo.setStatisTime("YYYY-MM");
        }else if("3".equals(vo.getStatisType())){
            vo.setStatisTime("YYYY");
        }else{
            vo.setStatisTime("YYYY-MM-DD");
        }

        List<UpkeepStatisVO> list = new ArrayList<>();
        list =  upkeepBillMapper.findStatisUpkeepByDayMonthYear(page,vo);

        //补充动态列---报修分类
        List<DictModel> modelList =  sysDictService.queryDictItemsByCode("repair_class");
        modelList.sort(Comparator.comparing(DictModel::getValue));
        for(UpkeepStatisVO upkeepStatisVO : list){
            //todo 维修报价的分类
            List<String> upkeepBillIds =  Arrays.asList(upkeepStatisVO.getUpkeepBillIds().split(","));
            LambdaQueryWrapper<TbUpkeepOffer> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(TbUpkeepOffer::getUpkeepBillId,upkeepBillIds);
            List<TbUpkeepOffer> offerList = upkeepOfferService.list(queryWrapper);
            //处理数据维修细项
            List<RepairDetailVO> repairDetailList = new ArrayList<>();
            for(TbUpkeepOffer offer : offerList){
                if(StrUtil.isNotBlank(offer.getUpkeepDetailJson())){
                    repairDetailList.addAll(JSONUtil.toList(offer.getUpkeepDetailJson(), RepairDetailVO.class));
                }
            }
            List<ColumnItemVO> colList = new ArrayList<>();
            for(DictModel dictModel : modelList){
                ColumnItemVO itemVO = new ColumnItemVO();
                itemVO.setColName(dictModel.getText());
                long count = repairDetailList.stream().filter(item->dictModel.getValue().equals(item.getRepairClass())).count();
                itemVO.setCount((int) count);
                colList.add(itemVO);
            }
            upkeepStatisVO.setColList(colList);
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public List<List<Object>> getAllUpkeepStatis(StatisParamVO vo) {
        if("1".equals(vo.getStatisType())){
            vo.setStatisTime("YYYY-MM-DD");
        }else if("2".equals(vo.getStatisType())){
            vo.setStatisTime("YYYY-MM");
        }else if("3".equals(vo.getStatisType())){
            vo.setStatisTime("YYYY");
        }else{
            vo.setStatisTime("YYYY-MM-DD");
        }
        List<UpkeepStatisVO> list = new ArrayList<>();
        list =  upkeepBillMapper.findStatisUpkeepAll(vo,new ArrayList<>());

        List<List<Object>> datas = new ArrayList<>();
        //车辆种类字典
        List<DictModel> vehicleTypeList =  sysDictService.queryDictItemsByCode("vehicle_type");
        Map<String, String> vehicleTypeMap = vehicleTypeList.stream().collect(Collectors.toMap(DictModel::getValue, DictModel::getText));
        //补充动态列---报修分类
        List<DictModel> modelList =  sysDictService.queryDictItemsByCode("repair_class");
        modelList.sort(Comparator.comparing(DictModel::getValue));
        for(UpkeepStatisVO upkeepStatisVO : list){
            List<Object> data = new ArrayList<>();
            data.add(upkeepStatisVO.getProjectName());
            data.add(upkeepStatisVO.getStatisTime());
            data.add(vehicleTypeMap.getOrDefault(upkeepStatisVO.getVehicleType(),upkeepStatisVO.getVehicleType() + " 无匹配字典"));
            data.add(upkeepStatisVO.getUpkeepTimes());
            data.add(upkeepStatisVO.getUpkeepAmount());
            data.add(upkeepStatisVO.getAvgAmount());
            //todo 维修报价的分类
            List<String> upkeepBillIds =  Arrays.asList(upkeepStatisVO.getUpkeepBillIds().split(","));
            LambdaQueryWrapper<TbUpkeepOffer> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(TbUpkeepOffer::getUpkeepBillId,upkeepBillIds);
            List<TbUpkeepOffer> offerList = upkeepOfferService.list(queryWrapper);
            //处理数据维修细项
            List<RepairDetailVO> repairDetailList = new ArrayList<>();
            for(TbUpkeepOffer offer : offerList){
                if(StrUtil.isNotBlank(offer.getUpkeepDetailJson())){
                    repairDetailList.addAll(JSONUtil.toList(offer.getUpkeepDetailJson(), RepairDetailVO.class));
                }
            }
            for(DictModel dictModel : modelList){
                long count = repairDetailList.stream().filter(item->dictModel.getValue().equals(item.getRepairClass())).count();
                data.add(count);
            }
            datas.add(data);
        }
        return datas;
    }

    @Override
    public UpkeepBoardVO getUpkeepInfo(Date startTime, Date endTime) {
        UpkeepBoardVO vo = new UpkeepBoardVO();
        //如果开始结束时间为空，默认取近半年的
        if (Objects.isNull(startTime) || Objects.isNull(endTime)) {
            Calendar calendar = Calendar.getInstance();
            endTime = calendar.getTime();
            calendar.add(Calendar.MONTH, -6);
            startTime = calendar.getTime();
        }
        LambdaQueryWrapper<TbUpkeepPlan> planQuery = new LambdaQueryWrapper<>();
        planQuery.ne(TbUpkeepPlan::getAuditStatus,"4")
                .le(TbUpkeepPlan::getPredictTime,endTime)
                .ge(TbUpkeepPlan::getPredictTime,startTime);
        int planCount = upkeepPlanService.count(planQuery);
        vo.setPlanCount(planCount);

        LambdaQueryWrapper<TbUpkeepBill> billQuery = new LambdaQueryWrapper<>();
        billQuery.ne(TbUpkeepBill::getFlowStatus,9)
                .le(TbUpkeepBill::getPredictTime,endTime)
                .ge(TbUpkeepBill::getPredictTime,startTime);
        List<TbUpkeepBill> billList = upkeepBillService.list(billQuery);
        if(Objects.nonNull(billList) && billList.size()>0){
            int done = (int)billList.stream().filter(item->item.getFlowStatus() == 8).count();
            int undone = billList.size() - done;

            DecimalFormat decimalFormat = new DecimalFormat("#.##");
            double percent = (double) done /  billList.size() * 100;
            String formattedPercent = decimalFormat.format(percent);

            vo.setOrderCount(billList.size());
            vo.setDoneOrderCount(done);
            vo.setUndoneOrderCount(undone);
            vo.setPercent(formattedPercent + "%");
        }
        return vo;
    }
}
