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.vo.ColumnItemVO;
import com.gci.boot.modules.statis.vo.RepairBoardVO;
import com.gci.boot.modules.statis.vo.StatisParamVO;
import com.gci.boot.modules.statis.vo.RepairStatisVO;
import com.gci.boot.modules.system.service.ISysDictService;
import com.gci.boot.modules.system.vo.DictModel;
import com.gci.boot.modules.vehicles.entity.TbRepairInfo;
import com.gci.boot.modules.vehicles.entity.TbRepairOffer;
import com.gci.boot.modules.vehicles.mapper.TbRepairInfoMapper;
import com.gci.boot.modules.vehicles.service.ITbRepairInfoService;
import com.gci.boot.modules.vehicles.service.ITbRepairOfferService;
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 javax.security.auth.callback.LanguageCallback;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RepairStatisServiceImpl implements RepairStatisService {

    @Autowired
    private TbRepairInfoMapper repairInfoMapper;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private ITbRepairInfoService repairInfoService;
    @Autowired
    private ITbRepairOfferService repairOfferService;

    @Override
    public Page getRepairStatisPage(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<RepairStatisVO> list = new ArrayList<>();
        list =  repairInfoMapper.findStatisRepairByDayMonthYear(page,vo);

        //补充动态列---报修分类
        List<DictModel> modelList =  sysDictService.queryDictItemsByCode("repair_class");
        modelList.sort(Comparator.comparing(DictModel::getValue));
        for(RepairStatisVO repairStatisVO : list){
            //todo 维修报价的分类
            List<String> repairIds =  Arrays.asList(repairStatisVO.getRepairIds().split(","));
            LambdaQueryWrapper<TbRepairOffer> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(TbRepairOffer::getRepairId,repairIds);
            List<TbRepairOffer> offerList = repairOfferService.list(queryWrapper);
            //处理数据维修细项
            List<RepairDetailVO> repairDetailList = new ArrayList<>();
            for(TbRepairOffer offer : offerList){
                if(StrUtil.isNotBlank(offer.getRepairDetailJson())){
                    repairDetailList.addAll(JSONUtil.toList(offer.getRepairDetailJson(), 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);
            }
            repairStatisVO.setColList(colList);
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public List<List<Object>> getAllRepairStatis(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<RepairStatisVO> list = new ArrayList<>();
        list =  repairInfoMapper.findStatisRepairAll(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(RepairStatisVO repairStatisVO : list){
            List<Object> data = new ArrayList<>();
            data.add(repairStatisVO.getProjectName());
            data.add(repairStatisVO.getStatisTime());
            data.add(vehicleTypeMap.getOrDefault(repairStatisVO.getVehicleType(),repairStatisVO.getVehicleType() + " 无匹配字典"));
            data.add(repairStatisVO.getRepairTimes());
            data.add(repairStatisVO.getRepairAmount());
            data.add(repairStatisVO.getAvgAmount());
            //todo 维修报价的分类
            List<String> repairIds =  Arrays.asList(repairStatisVO.getRepairIds().split(","));
            LambdaQueryWrapper<TbRepairOffer> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(TbRepairOffer::getRepairId,repairIds);
            List<TbRepairOffer> offerList = repairOfferService.list(queryWrapper);
            //处理数据维修细项
            List<RepairDetailVO> repairDetailList = new ArrayList<>();
            for(TbRepairOffer offer : offerList){
                if(StrUtil.isNotBlank(offer.getRepairDetailJson())){
                    repairDetailList.addAll(JSONUtil.toList(offer.getRepairDetailJson(), 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 List<RepairBoardVO> getRepairInfo(Date startTime, Date endTime) {
        List<RepairBoardVO> result = new ArrayList<>();
        //如果开始结束时间为空，默认取近半年的
        if (Objects.isNull(startTime) || Objects.isNull(endTime)) {
            Calendar calendar = Calendar.getInstance();
            endTime = calendar.getTime();
            calendar.add(Calendar.MONTH, -6);
            startTime = calendar.getTime();
        }
        //查时间区间内完成维修的工单，已开始时间为查询
        LambdaQueryWrapper<TbRepairInfo> repairQuery = new LambdaQueryWrapper<>();
        repairQuery.eq(TbRepairInfo::getFlowStatus,8)
                .le(TbRepairInfo::getRepairTime,endTime)
                .ge(TbRepairInfo::getRepairTime,startTime);
        List<TbRepairInfo> repairInfoList = repairInfoService.list(repairQuery);
        if(Objects.nonNull(repairInfoList) && repairInfoList.size()>0){
            List<String> repairIds = repairInfoList.stream().map(TbRepairInfo::getId).collect(Collectors.toList());
            LambdaQueryWrapper<TbRepairOffer> offerQuery = new LambdaQueryWrapper<>();
            offerQuery.in(TbRepairOffer::getRepairId,repairIds);
            List<TbRepairOffer> offerList = repairOfferService.list(offerQuery);
            //查维修细项
            if(Objects.nonNull(offerList) && offerList.size()>0){
                //报修分类字典
                List<DictModel> modelList =  sysDictService.queryDictItemsByCode("repair_class");
                List<RepairDetailVO> repairDetailList = new ArrayList<>();
                for(TbRepairOffer offer : offerList){
                    if(StrUtil.isNotBlank(offer.getRepairDetailJson())){
                        repairDetailList.addAll(JSONUtil.toList(offer.getRepairDetailJson(), RepairDetailVO.class));
                    }
                }
                for(DictModel dictModel : modelList){
                    long count = repairDetailList.stream().filter(item->dictModel.getValue().equals(item.getRepairClass())).count();
                    RepairBoardVO vo = new RepairBoardVO();
                    vo.setRepairClass(dictModel.getText());
                    vo.setCount((int)count);
                    result.add(vo);
                }
            }
        }
        if(result.size() > 0){
            int sum = result.stream() .mapToInt(RepairBoardVO::getCount).sum();
            if(sum > 0){
                // 保留两位小数的格式
                DecimalFormat decimalFormat = new DecimalFormat("#.##");

                result.forEach(item->{
                    double percent = (double) item.getCount() / sum * 100;
                    String formattedPercent = decimalFormat.format(percent);
                    item.setPercent(formattedPercent + "%");
                });
            }
        }
        return result;
    }
}
