package org.springblade.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.utils.BaiduApiUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.business.entity.WeatherInfo;
import org.springblade.business.mapper.WeatherInfoMapper;
import org.springblade.business.service.WeatherInfoService;
//import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springblade.core.mp.support.Condition;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service
public class WeatherInfoServiceImpl extends ServiceImpl<WeatherInfoMapper, WeatherInfo> implements WeatherInfoService {

    /**
     * 根据所选年份获取当年所有天气台账
     */
    public List<Map<String,List<Map<String,Object>>>> queryWeatherAllByYear(String yearMonthDay){
        //todo 先写死区域编码ID，之后根据当前登录账户的信息获取
        String contractAreaId = "12332112345678";
        //todo ======================================

        //获取当前区域yearMonthDay的所有数据
        Map<String,Object> queryMap = new HashMap<>();
        List<WeatherInfo> yearWeatherList;
        if(yearMonthDay.contains("~")){
            String[] yearMonthDays = yearMonthDay.split("~");
            //区间
            queryMap.put("contractAreaId", contractAreaId);
            yearWeatherList = this.list(Condition.getQueryWrapper(queryMap, WeatherInfo.class).lambda().between(WeatherInfo::getRecordTime, yearMonthDays[0].trim(), yearMonthDays[1].trim()).orderByAsc(WeatherInfo::getRecordTime));
        } else {
            queryMap.put("recordTime", yearMonthDay);
            queryMap.put("contractAreaId", contractAreaId);
            yearWeatherList = this.list(Condition.getQueryWrapper(queryMap, WeatherInfo.class).lambda().orderByAsc(WeatherInfo::getRecordTime));
        }

        if(yearWeatherList != null && yearWeatherList.size() != 0){
            //结果数据
            List<Map<String,List<Map<String,Object>>>> result = new ArrayList<>();
            //将得到的所有数据按1~12月分组
            for(int i = 1; i < 13; i ++){
                //月份
                String month = i < 10 ? "0" + i : "" + i;
                //记录月份
                Map<String,List<Map<String,Object>>> monthMap = new HashMap<>();

                //处理每月数据
                Iterator<WeatherInfo> iterator = yearWeatherList.iterator();
                List<Map<String,Object>> dayMapList = new ArrayList<>();
                while (iterator.hasNext()){
                    WeatherInfo weatherInfo = iterator.next();
                    String recordTime = DateUtil.format(weatherInfo.getRecordTime(), "yyyy-MM-dd");
                    //检查记录时间是否含有当前月份
                    if(recordTime.contains("-" + month + "-")){
                        Map<String,Object> dayMap = new HashMap<>();
                        dayMap.put("recordTime", recordTime);
                        dayMap.put("temp", weatherInfo.getTempLow() + "~" + weatherInfo.getTempHigh());
                        dayMap.put("weather", weatherInfo.getWeather());

                        dayMapList.add(dayMap);
                        iterator.remove();
                    }
                }
                //写入每月集合中
                monthMap.put("month", dayMapList);

                //写入最终集合中
                result.add(monthMap);
            }

            return result;
        }

        return null;
    }

    /**
     * 获取当前系统所有项目下所有合同段的当天天气
     */
//    @Scheduled(cron = "0 0 7 * * ?")
    public void syncWeatherInfo(){
        //todo 目前缺少合同段所在区域的地图编号及ID，所以暂时写死区域数据ID，之后修改为接口获取
        String cityCode = "450721";
        String areaId = "12332112345678";

        //todo 这里之后会换成批量
        for(int i = 0; i < 1; i ++){
            try{
                //校验当前区域是否已经获取当天日期（手动补填或自动获取）
                Map<String,Object> queryMap = new HashMap<>();
                queryMap.put("contractAreaId", areaId);
                queryMap.put("recordTime", DateUtil.format(new Date(), "yyyy-MM-dd"));
                //查询
                long count = this.count(Condition.getQueryWrapper(queryMap, WeatherInfo.class));
                if(count > 0){
                    //存在，取消自动同步
                    log.info("今日的天气已经同步完成！contractAreaId：" + areaId + "，syncTime：" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    continue;
                }

                //获取天气信息（百度天气）
                Map<String,String> weatherMap = BaiduApiUtil.getTodayWeather(cityCode);
                if(weatherMap != null){
                    //计算平均气温
                    BigDecimal aver = (new BigDecimal(weatherMap.get("high")).add(new BigDecimal(weatherMap.get("low")))).divide(new BigDecimal("2"), 1, BigDecimal.ROUND_HALF_UP);
                    WeatherInfo newWeather = new WeatherInfo(areaId, weatherMap.get("weather"), aver.toString(), weatherMap.get("high"), weatherMap.get("low"), weatherMap.get("windLevel"));
                    this.save(newWeather);
                    log.info("今日的天气已经同步完成！contractAreaId：" + areaId + "，syncTime：" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                } else {
                    log.info("获取今日的天气失败！contractAreaId：" + areaId + "，syncTime：" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}
