package com.sky.ioc.service.parking.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.parking.IllegalParking;
import com.sky.ioc.entity.domain.parking.Park;
import com.sky.ioc.entity.domain.parking.Parking;
import com.sky.ioc.entity.domain.space.BuildingRoom;
import com.sky.ioc.entity.params.IocParam;
import com.sky.ioc.entity.params.IocTimeRange;
import com.sky.ioc.mapper.IllegalParkingMapper;
import com.sky.ioc.mapper.ParkMapper;
import com.sky.ioc.mapper.ParkingMapper;
import com.sky.ioc.service.parking.ParkingService;
import com.sky.ioc.tool.DateUtil;
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.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * TODO 智慧停车
 * @Description
 * @Author LunCe
 * @Date 2023/2/10 13:45
 **/
@Service
@Slf4j
public class ParkingServiceImpl implements ParkingService {

    @Autowired
    ParkingMapper parkingMapper;

    @Autowired
    ParkMapper parkMapper;


    @Autowired
    RestTemplateConfig restTemplateConfig;

    @Autowired
    IllegalParkingMapper illegalParkingMapper;

    final static  String PARKING_URL="/api/parking/PARKING/parkingInfo/list";


    @Override
    public ReturnMsg getCoreIndicators(IocParam iocParam) {
        Indeicator indeicator = new Indeicator();
        List<JSONObject> objects = indeicator.getList();
        //车位数量
        Integer totalParking = parkingMapper.getTotalParkingByCompanyIdAndDeptId(iocParam);
        //停车记录数
        Integer totalPark = parkMapper.getTotalParkByCompanyIdAndDeptIdAndEntryTime(iocParam);
        Double avgPark = 0d;
        //违停数量
        Long total = illegalParkingMapper.selectCount(new LambdaQueryWrapper<IllegalParking>()
                .gt(IllegalParking::getIllegalTime,iocParam.getTimeRange().getStartDate())
                .le(IllegalParking::getIllegalTime,iocParam.getTimeRange().getEndDate()));
        Integer days = DateUtil.daysBetween(iocParam.getTimeRange().getStartDate(),iocParam.getTimeRange().getEndDate());
        if(totalPark>0&&days>0){
            BigDecimal bigDecimal = new BigDecimal(totalPark);
            BigDecimal avgPersonPriceDec = bigDecimal.divide(new BigDecimal(days), 2, RoundingMode.HALF_UP);
            avgPark = avgPersonPriceDec.doubleValue();
        }
        long usedPark = parkMapper.pageUsedCount(iocParam);
        ThreadLocalRandom random = ThreadLocalRandom.current();
        float compare = (float) Math.random();
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        compare = Float.parseFloat(decimalFormat.format(compare));
        objects.get(0).put("value",totalParking);
        objects.get(0).put("compare",compare);

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

        objects.get(2).put("value",total);
        objects.get(2).put("compare",-compare);

        objects.get(3).put("value",totalParking-usedPark);
        objects.get(3).put("compare",1);
        indeicator.setWorthAttention("⼀⻋⼀位不乱停");
        indeicator.setList(objects);
        return ReturnMsg.ok(indeicator);
    }

    @Override
    public ReturnMsg getTrafficflowSituation(IocParam iocParam) {
        String[] param = {"getInto","leave"};
        String startStr = iocParam.getTimeRange().getStartDate();
        String endStr = iocParam.getTimeRange().getEndDate();
        List<String> list = DateUtil.getBetweenDays(startStr, endStr);
        String[] labKey = list.toArray(new String[0]);
      //  String[] labKey = {"1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"};
     //   List<Label> labels1 = GeneralMethod.getInstance().dataGeneration(param, labKey);
        List<Label> lists = new ArrayList<>();
        for (int i = 0; i < labKey.length; i++) {
            Label label = new Label();
            JSONObject jsonObject = new JSONObject();
            IocParam iocParam1 = new IocParam();
            IocTimeRange timeRange = new IocTimeRange();
            timeRange.setStartDate(labKey[i]+" 00:00:00");
            timeRange.setEndDate(labKey[i]+" 23:59:00");
            iocParam1.setTimeRange(timeRange);
            Integer entry = parkMapper.getTotalParkByCompanyIdAndDeptIdAndEntryTime(iocParam1);
            Integer leave = parkMapper.getTotalParkByCompanyIdAndDeptIdAndDepartureTime(iocParam1);
            jsonObject.put(param[0],entry);
            jsonObject.put(param[1],leave);
            label.setJsonObject(jsonObject);
            label.setLabel(labKey[i]);
            lists.add(label);
        }
        return ReturnMsg.ok(lists);
    }

    @Override
    public ReturnMsg getVacantParkingSpace(IocParam iocParam) {
        List<Park> lists = parkMapper.getVacantList(iocParam);
       // List<String> numbers = lists.stream().map(Park::getParkingNumbers).collect(Collectors.toList());
        List<Parking> list = new ArrayList<>();
        for(int i=0;i< lists.size();i++){
            Park park = lists.get(i);
            Parking parking = parkingMapper.selectOne(new LambdaQueryWrapper<Parking>().eq(Parking::getParkingNumbers,park.getParkingNumbers()));
            parking.setCompany("北京电信规划设计院");
            String startTime = iocParam.getTimeRange().getStartDate().replace("/","-")+" 00:00:00";
            String endTime = iocParam.getTimeRange().getEndDate().replace("/","-")+" 23:59:00";
            long hours = DateUtil.hoursBetween(startTime,endTime);
            parking.setPrkingDurationLong(hours-park.getHours()+"h");
            list.add(parking);

        }
        return ReturnMsg.ok(list);
    }
    @Override
    public ReturnMsg getParkingSpaceDetails(IocParam iocParam) {
        List<Parking> list = parkingMapper.getListByCompanyIdAndDeptId(iocParam);
        String[] persons = {"李劲","李良","宋明宇","陈涵亮","李超","章峰","梁松","方运诚","徐涵衍","万浩波",
                "周浩广","许鸿博","荣浩博","许鸿畴","徐瀚文","陈浩初","程涵煦","许鸿与","徐廖文","吴初"};
        for(int i=0;i< list.size();i++){
            Parking parking = list.get(i);
            int flag = i;
            if(i>=20){
                flag = i%20;
            }
            parking.setPeople(persons[flag]);
            parking.setCompany("北京电信规划设计院");
            parking.setPosition(parking.getPosition());
            List<Park> lists = parkMapper.selectList(new LambdaQueryWrapper<Park>().eq(Park::getParkingNumbers,parking.getParkingNumbers()));
            int totalHours = 0;
            for(int j =0;j<lists.size();j++){
                if(lists.get(j).getDepartureTime()!=null&&!lists.get(j).getDepartureTime().equals("null")){
                    long hours =  DateUtil.hoursBetween(lists.get(j).getEntryTime(),lists.get(j).getDepartureTime());
                    totalHours+=hours;
                }
            }
            parking.setPrkingDurationLong(totalHours+"h");

        }
        return ReturnMsg.ok(list);
    }

    @Override
    public ReturnMsg getParkingData() {
        String url = restTemplateConfig.addBaseUrl(PARKING_URL)+"?pageNum=1&pageSize=1000";

        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){
            ArrayList list = (ArrayList) body.get("rows");
            if(list!=null&&list.size()>0){
                parkingMapper.delete(null);
                for (int i=0;i<list.size();i++){
                    LinkedHashMap json = (LinkedHashMap) list.get(i);
                    Parking parking = new Parking();
                    parking.setId((Integer) json.get("id"));
                    parking.setParkingNumbers(String.valueOf(json.get("parkingNumbers")));
                    parking.setParkingType(String.valueOf(json.get("parkingType")));
                    parking.setPosition(String.valueOf(json.get("parkingArea")));

                   parkingMapper.insert(parking);
                }
            }
            return ReturnMsg.ok();

        }else{
            log.info("获取车位数据："+message);
            return  ReturnMsg.fail(message);
        }
    }


    @Override
    public ReturnMsg getStopViolation(IocParam iocParam) {

      //  List<Map<String,String>> lists = parkMapper.getListByCompanyIdAndDeptIdAndType(iocParam,1);
    //    List<Map<String,Object>> lists = illegalParkingMapper.listByTimeAndDeptId(iocParam);
        List<Cake> list = new ArrayList<>();
       /* for(Map<String,Object> map:lists){
            Cake cake = new Cake();

        }*/

        list.add(new Cake("郑分"));
        list.add(new Cake("北京规划院"));
        list.add(new Cake("中讯院"));
        list.add(new Cake("广分"));
        return ReturnMsg.ok(list);
    }

    @Override
    public ReturnMsg getOccupationOfParkingSpace(IocParam iocParam) {
        //List<Map<String,String>> lists = parkMapper.getListByCompanyIdAndDeptIdAndType(iocParam,null);
        List<Cake> list = new ArrayList<>();
        list.add(new Cake("郑分"));
        list.add(new Cake("北京规划院"));
        list.add(new Cake("中讯院"));
        list.add(new Cake("广分"));
        return ReturnMsg.ok(list);
    }


}
