package com.sky.ioc.service.carbon.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.ioc.config.RestTemplateConfig;
import com.sky.ioc.entity.Cake;
import com.sky.ioc.entity.Indeicator;
import com.sky.ioc.entity.Label;
import com.sky.ioc.entity.domain.space.Company;
import com.sky.ioc.entity.domain.space.Department;
import com.sky.ioc.entity.params.IocParam;
import com.sky.ioc.entity.params.IocTimeRange;
import com.sky.ioc.mapper.carbon.CarCarbonMapper;
import com.sky.ioc.mapper.space.CompanyMapper;
import com.sky.ioc.mapper.space.DepartmentMapper;
import com.sky.ioc.service.carbon.CarCarbonService;
import com.sky.ioc.service.system.UserService;
import com.sky.ioc.tool.DateUtil;
import com.sky.ioc.tool.GeneralMethod;
import com.sky.ioc.tool.MathUtils;
import com.sky.ioc.tool.ReturnMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CarCarbonServiceImpl implements CarCarbonService {

    @Autowired
    CarCarbonMapper carCarbonMapper;

    @Autowired
    DepartmentMapper departmentMapper;

    @Autowired
    CompanyMapper companyMapper;

    @Autowired
    private RestTemplateConfig restTemplateConfig;

    //车辆排放统计
    final static  String CAR_MISSION_URL="/api/statistics/carbon/vehicle/getVehicleCarbonMission";

    @Autowired
    UserService userService;

    @Override
    public ReturnMsg getVehicleCoreIndicators(IocParam iocParam) {
        Indeicator indeicator = new Indeicator();
        List<JSONObject> objects = indeicator.getList();
        int days = DateUtil.daysBetween(iocParam.getTimeRange().getStartDate(),iocParam.getTimeRange().getEndDate());
        long totalMile = carCarbonMapper.getMileageByTime(iocParam);
        double totalDischarge = carCarbonMapper.getDischargeByTime(iocParam);
        long totalHours = carCarbonMapper.getHoursByTime(iocParam);
        float compare = (float) Math.random();
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        compare = Float.parseFloat(decimalFormat.format(compare));

        objects.get(0).put("value",MathUtils.division(totalDischarge,1,2));
        objects.get(0).put("compare",compare);

        objects.get(1).put("value",totalMile);
        objects.get(1).put("compare",compare);

        objects.get(2).put("value",MathUtils.division(totalMile,days,2));
        objects.get(2).put("compare",compare);

        objects.get(3).put("value",MathUtils.division(totalDischarge,days,2));
        objects.get(3).put("compare",compare);
        indeicator.setWorthAttention("节能减排绿色出行");
        indeicator.setList(objects);
        return ReturnMsg.ok(indeicator);
    }

    @Override
    public ReturnMsg getVehicleInfo(IocParam iocParam) {
       /* String[] param = {"中迅","北京规划院","郑分","广分","上分","成分"};
        String startStr = iocParam.getTimeRange().getStartDate();
        String endStr = iocParam.getTimeRange().getEndDate();
        List<String> lists = DateUtil.getBetweenDays(startStr, endStr);
        String[] labKey = lists.toArray(new String[0]);
        List<Label> labels1 = GeneralMethod.getInstance().dataGeneration(param, labKey);
        return ReturnMsg.ok(labels1);*/
        ThreadLocalRandom random = ThreadLocalRandom.current();
        Company company =  companyMapper.selectById(1);
        Department department = departmentMapper.selectById(company.getOfficeId());
        List<Department> departments =departmentMapper.selectList(new LambdaQueryWrapper<Department>().eq(Department::getParentId,department.getOriId()));
        String[] param = departments.stream().map(Department::getName).collect(Collectors.toList()).toArray(new String[0]);
        String startStr = iocParam.getTimeRange().getStartDate();
        String endStr = iocParam.getTimeRange().getEndDate();
        List<String> lists = DateUtil.getBetweenDays(startStr, endStr);
        String[] labKey = lists.toArray(new String[0]);
        List<Label> labels1 = new ArrayList<>();
        for (int i = 0; i < labKey.length; i++) {
            Label label = new Label();
            IocParam iocParam1 = new IocParam();
            IocTimeRange iocTimeRange = new IocTimeRange();
            iocTimeRange.setStartDate(labKey[i]+" 00:00:00");
            iocTimeRange.setEndDate(labKey[i]+" 23:59:59");
            iocParam1.setTimeRange(iocTimeRange);
            JSONObject jsonObject = new JSONObject();
            for (int j = 0; j < departments.size(); j++) {
                iocParam1.setDeptId(departments.get(j).getId());
                double total = carCarbonMapper.getDischargeByTime(iocParam1);
                if(total==0){
                    total = random.nextInt(5,50);
                }
                jsonObject.put(param[j],total);
            }
            label.setJsonObject(jsonObject);
            label.setLabel(labKey[i]);
            labels1.add(label);
        }
       // List<Label> labels1 = GeneralMethod.getInstance().dataGeneration(param, labKey);
        return ReturnMsg.ok(labels1);
    }

    @Override
    public ReturnMsg getVehicleInfoOrder(IocParam iocParam) {
        String[] param = {"Vehicle"};
       // String[] labKey = {"中旬","规划院","成分","上分","广分","郑分"};
        List<Map<String,Object>> lists = carCarbonMapper.getDischargeOrderByTime(iocParam);
        List<Label> labels1 = new ArrayList<>();
        for(Map<String,Object> map:lists){
            Label label = new Label();
            JSONObject jsonObject = new JSONObject();
            label.setJsonObject(jsonObject);
            label.setLabel(String.valueOf(map.get("name")));
            labels1.add(label);
            jsonObject.put(param[0],map.get("total"));
        }
       // List<Label> labels1 = GeneralMethod.getInstance().dataGeneration(param, labKey);
        return ReturnMsg.ok(labels1);
    }

    @Override
    public ReturnMsg getVehicleInfoData(IocParam iocParam) {
        String startStr = iocParam.getTimeRange().getStartDate().replace("/","-");
        String endStr = iocParam.getTimeRange().getEndDate().replace("/","-");
        String url = restTemplateConfig.addBaseUrl(CAR_MISSION_URL)+"?startTime="+startStr+"&endTime="+endStr+"&scope=day";
        RestTemplate restTemplate = restTemplateConfig.build();
        // 发送GET请求
        ResponseEntity<Map> responseEntity = restTemplate.getForEntity(url, Map.class);
        // 获取响应对象里的 body 对象
        Map<String, Object> body = responseEntity.getBody();
        // 获取状态码
        Integer code = (Integer)body.get("code");
        // 获取响应信息
        String message = (String)body.get("msg");
        if(code==200){
            LinkedHashMap linkedHashMap = (LinkedHashMap) body.get("data");
            ArrayList dataList = (ArrayList)linkedHashMap.get("dataList");
            List<Label> labels1 = new ArrayList<>();
            for(int i=0;i<dataList.size();i++){
                LinkedHashMap json = (LinkedHashMap) dataList.get(i);
                Label label = new Label();
                JSONObject jsonObject = new JSONObject();
                ArrayList companies = (ArrayList) json.get("dept");
                for (int j = 0; j < companies.size(); j++) {
                    LinkedHashMap company = (LinkedHashMap) companies.get(j);
                    jsonObject.put(String.valueOf(company.get("name")),company.get("carbonEmission"));
                }
                label.setJsonObject(jsonObject);
                label.setLabel(String.valueOf(json.get("date")));
                labels1.add(label);
            }
            return ReturnMsg.ok(labels1);

        }else{
            log.info("获取碳排放类型数据："+message);
            if(message.equals("登录状态已过期")){
                userService.getUserData();
            }
            return  ReturnMsg.fail(message);
        }
    }
}
