package com.jxy.marketall.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jxy.common.core.text.Convert;
import com.jxy.common.core.utils.DateUtils;
import com.jxy.common.core.utils.StringUtils;
import com.jxy.common.core.web.Result.AjaxResult;
import com.jxy.common.redis.service.RedisService;
import com.jxy.marketall.dto.*;
import com.jxy.marketall.entity.BiAn;
import com.jxy.marketall.enums.ExchangeRateSumbolCNName;
import com.jxy.marketall.enums.GDPType;
import com.jxy.marketall.enums.MacroeconomicsRedisName;
import com.jxy.marketall.mapper.BiAnMapper;
import com.jxy.marketall.mapper.BiAnMapper2;
import com.jxy.marketall.mapper.MacroEconomyMapper;
import com.jxy.marketall.service.BiAnService;
import com.jxy.marketall.service.MacroEconomyService;
import com.jxy.marketall.utils.EnumUtils;
import com.jxy.marketall.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description BiAn查询业务处理
 * @Date 2022/6/2017:51
 * @Author 杜懿
 */
@Service
public class MacroEconomyServiceImpl implements MacroEconomyService {

    @Autowired
    private MacroEconomyMapper macroEconomyMapper;

    @Autowired
    private RedisService redisService;


    @Override
    public AjaxResult getTreasuriesYields(TreasuriesYieldsVo vo){
        //处理期限
        String[] intervals={"1m","3m","6m","1y","2y","5y","10y","20y","30y"};

        if(!Arrays.asList(intervals).contains(vo.getLimit())){
            return AjaxResult.error("期限传参有误，取值范围:{1m,3m,6m,1y,2y,5y,10y,20y,30y}");
        }

        if(StringUtils.isBlank(vo.getEnd()) && StringUtils.isBlank(vo.getStart())){
            return AjaxResult.error("时间不能为空");
        }

        //根据前端传参转换为数据库字段
        vo.setLimit(getFiledByVo(vo.getLimit()));
        List<DateBigDecimalDto> returnList = new ArrayList<>();
        if(StringUtils.isNotBlank(vo.getEnd())){
            List<DateStringDto> list = macroEconomyMapper.selectTreasuriesYieldsByEndTime(vo);
            list.stream().forEach(e -> {
                if(StringUtils.isNotBlank(e.getValue()) && !"NULL".equals(e.getValue())){
                    DateBigDecimalDto dto = new DateBigDecimalDto();
                    dto.setDate(e.getDate());
                    dto.setValue(Convert.toBigDecimal(StringUtils.clean(e.getValue())));
                    returnList.add(dto);
                }
            });
            Collections.reverse(returnList);
        }
        if(StringUtils.isNotBlank(vo.getStart())){
            List<DateStringDto> list = macroEconomyMapper.selectTreasuriesYieldsByStartTime(vo);
            list.stream().forEach(e -> {
                if(StringUtils.isNotBlank(e.getValue()) && !"NULL".equals(e.getValue())){
                    DateBigDecimalDto dto = new DateBigDecimalDto();
                    dto.setDate(e.getDate());
                    dto.setValue(Convert.toBigDecimal(StringUtils.clean(e.getValue())));
                    returnList.add(dto);
                }
            });
        }

        return AjaxResult.success(returnList);
    }

    @Override
    public AjaxResult getMoneyStockMeasures(MoneyStockMeasuresVo vo) {

        if(vo.getIfAdjusted() == 0){
            List<NotAdjustedMoneyStockMeasuresDto>  list = redisService.getCacheList(MacroeconomicsRedisName.MONEY_STOCK_MEASURES_NOT_ADJUSTED.getKey());
            if(list.size() < 1){
                return AjaxResult.error("未查询到数据,请稍后再试");
            }

            if(StringUtils.isNotBlank(vo.getStart())){
                Date start = DateUtils.parseDate(vo.getStart());
                list = list.stream().filter(dto -> (dto.getDate().after(start) || dto.getDate().equals(start))).collect(Collectors.toList());
            }

            if(StringUtils.isNotBlank(vo.getEnd())){
                Date end = DateUtils.parseDate(vo.getEnd());
                list = list.stream().filter(dto -> (dto.getDate().before(end) || dto.getDate().equals(end))).collect(Collectors.toList());
            }

            return AjaxResult.success(list);
        }else if(vo.getIfAdjusted() == 1){

            List<AdjustedMoneyStockMeasuresDto> list = redisService.getCacheList(MacroeconomicsRedisName.MONEY_STOCK_MEASURES_ADJUSTED.getKey());

            if(list.size() < 1){
                return AjaxResult.error("未查询到数据,请稍后再试");
            }

            if(StringUtils.isNotBlank(vo.getStart())){
                Date start = DateUtils.parseDate(vo.getStart());
                list = list.stream().filter(dto -> (dto.getDate().after(start) || dto.getDate().equals(start))).collect(Collectors.toList());
            }

            if(StringUtils.isNotBlank(vo.getEnd())){
                Date end = DateUtils.parseDate(vo.getEnd());
                list = list.stream().filter(dto -> (dto.getDate().before(end) || dto.getDate().equals(end))).collect(Collectors.toList());
            }

            return AjaxResult.success(list);
        }else {
            return AjaxResult.error("传参异常");
        }


    }

    @Override
    public AjaxResult getPSI(QueryVo vo) {

        List<DateBigDecimalDto> tempList = redisService.getCacheList(MacroeconomicsRedisName.LOAN_PSI.getKey());

        if(tempList.size() < 1){
            return AjaxResult.error("未查询到数据,请稍后再试");
        }

        if(StringUtils.isNotBlank(vo.getStart())){
            Date start = DateUtils.parseDate(vo.getStart());
            tempList = tempList.stream().filter(dto -> (dto.getDate().after(start) || dto.getDate().equals(start))).collect(Collectors.toList());
        }

        if(StringUtils.isNotBlank(vo.getEnd())){
            Date end = DateUtils.parseDate(vo.getEnd());
            tempList = tempList.stream().filter(dto -> (dto.getDate().before(end) || dto.getDate().equals(end))).collect(Collectors.toList());
        }

        List<DateStrBigDecimalDto> list = tempList.stream().map(e ->{
            DateStrBigDecimalDto dto = new DateStrBigDecimalDto();
            dto.setDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM,e.getDate()));
            dto.setValue(e.getValue());
            return dto;
        }).collect(Collectors.toList());

        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getGDPPrivateInvestor(QueryVo vo) {

        List<DateBigDecimalDto> tempList = redisService.getCacheList(MacroeconomicsRedisName.LOAN_FDHBPI_GDP.getKey());

        if(tempList.size() < 1){
            return AjaxResult.error("未查询到数据,请稍后再试");
        }

        if(StringUtils.isNotBlank(vo.getStart())){
            Date start = DateUtils.parseDate(vo.getStart());
            tempList = tempList.stream().filter(dto -> (dto.getDate().after(start) || dto.getDate().equals(start))).collect(Collectors.toList());
        }

        if(StringUtils.isNotBlank(vo.getEnd())){
            Date end = DateUtils.parseDate(vo.getEnd());
            tempList = tempList.stream().filter(dto -> (dto.getDate().before(end) || dto.getDate().equals(end))).collect(Collectors.toList());
        }

        List<DateStrBigDecimalDto> list = tempList.stream().map(e ->{

            DateStrBigDecimalDto dto = new DateStrBigDecimalDto();
            //getYear是计算当前年份与1900的差值 所以需要+1900
            int year = e.getDate().getYear() +1900;
            //getMoth的值是0-11 eg:0,1,2对应第一季度
            int m = ((e.getDate().getMonth())/3) + 1;
            String dateStr = "";
            switch (m){
                case 1: dateStr= dateStr+year+" Q1";break;
                case 2: dateStr= dateStr+year+" Q2";break;
                case 3: dateStr= dateStr+year+" Q3";break;
                case 4: dateStr= dateStr+year+" Q4";break;
            }
            dto.setDate(dateStr);
            dto.setValue(e.getValue());
            return dto;
        }).collect(Collectors.toList());

        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getWEI(QueryVo vo) {
        List<DateBigDecimalDto> list = redisService.getCacheList(MacroeconomicsRedisName.WEI.getKey());

        if(list.size() < 1){
            return AjaxResult.success("未查询到数据,请稍后再试",list);
        }

        if(StringUtils.isNotBlank(vo.getStart())){
            Date start = DateUtils.parseDate(vo.getStart());
            list = list.stream().filter(dto -> (dto.getDate().after(start) || dto.getDate().equals(start))).collect(Collectors.toList());
        }

        if(StringUtils.isNotBlank(vo.getEnd())){
            Date end = DateUtils.parseDate(vo.getEnd());
            list = list.stream().filter(dto -> (dto.getDate().before(end) || dto.getDate().equals(end))).collect(Collectors.toList());
        }

        return AjaxResult.success( list);
    }

    @Override
    public AjaxResult getNewExchangeRate() {

        List<ExchangeRateDto> list = macroEconomyMapper.getNewExchangeRate();

        list.stream().forEach(e -> e.setCn(ExchangeRateSumbolCNName.getCNBySymbol(e.getSymbol())));

        if(list.size() < 1){
            return AjaxResult.success("未获取到数据",list);
        }
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getExchangeRateList(BiAnVo vo) {
        String[] s = {"USDEUR", "USDGBP", "USDJPY", "USDCAD", "USDSEK", "USDCHF", "USDCNY", "USDRUB", "DXY"};

        if(StringUtils.isNull(vo)){
            return AjaxResult.success("参数缺失",new ArrayList<>());
        }

        if (StringUtils.isBlank(vo.getSymbol())){
            return AjaxResult.success("参数缺失",new ArrayList<>());
        }

        String symbol = vo.getSymbol().toUpperCase();

        if(!Arrays.asList(s).contains(symbol))
        {
            return AjaxResult.success("参数有误",new ArrayList<>());
        }

        List<DateStringDto> list = macroEconomyMapper.getExchangeRateList(symbol);

        Collections.reverse(list);

        return AjaxResult.success(symbol,list);
    }

    @Override
    public AjaxResult getNewGDP() {

         GDPTableDto dto =redisService.getCacheObject(MacroeconomicsRedisName.GDP_NEW.getKey());

        //if(list.size() < 1){
        //    return AjaxResult.error("未获取到数据");
        //}

        return AjaxResult.success(dto);
    }

    @Override
    public AjaxResult getGDPList(BiAnVo vo) {

        if(StringUtils.isBlank(vo.getSymbol())){
            return AjaxResult.success("参数缺失",new ArrayList<>());
        }

        if(EnumUtils.isInclude(GDPType.class,vo.getSymbol())){
            List<DateStrBigDecimalDto> list = redisService.getCacheList(GDPType.valueOf(vo.getSymbol().toUpperCase()).getKey());

            if (list.size() <1 ){
                return AjaxResult.success("未从后台获取到数据",list);
            }
            return AjaxResult.success(list);
        }else {
            return AjaxResult.success("参数错误",new ArrayList<>());
        }

    }

    public String getFiledByVo(String s){
        //1m,3m,6m,1y,2y,5y,10y,20y,30y
        String result = null;
        switch (s){
            case "1m": result ="1_Mo";break;
            case "3m": result ="3_Mo";break;
            case "6m": result ="6_Mo";break;
            case "1y": result ="1_Yr";break;
            case "2y": result ="2_Yr";break;
            case "5y": result ="5_Yr";break;
            case "10y": result ="10_Yr";break;
            case "20y": result ="20_Yr";break;
            case "30y": result ="30_Yr";break;
        }
        return result;
    }


    //public List<DateBigDecimalDto> getList(String key,int sma){
    //
    //    List<DateBigDecimalDto> list = new ArrayList<>();
    //
    //    if(redisService.hasKey(key)){
    //        list = redisService.getCacheList(key);
    //    }
    //
    //    if(sma > 0){
    //        //todo sma处理
    //        list = getSMA(list,sma);
    //        //返回处理过的数据
    //        //return AjaxResult.success(list);
    //    }
    //
    //    return list;
    //}
}
