package com.jxy.marketall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jxy.common.core.text.Convert;
import com.jxy.common.core.utils.StringUtils;
import com.jxy.common.core.web.Result.AjaxResult;
import com.jxy.marketall.dto.DataDto;
import com.jxy.marketall.entity.Coinmetrics;
import com.jxy.marketall.entity.ETF;
import com.jxy.marketall.enums.CoinmetricsType;
import com.jxy.marketall.enums.ETFType;
import com.jxy.marketall.service.CoinmetricsService;
import com.jxy.marketall.service.ETFService;
import com.jxy.marketall.service.NodeJsMarketFeign;
import com.jxy.marketall.utils.EnumUtils;
import com.jxy.marketall.vo.TypeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * @Description ETF查询业务处理
 * @Date 2022/5/19 17:51
 * @Author 杜懿
 */
@Service
public class ETFServiceImpl implements ETFService {
    @Autowired
    private NodeJsMarketFeign nodeJsMarketFeign;
    @Override
    public AjaxResult findETFByType(TypeVo typeVo) {

        HashMap<String,String> map = new HashMap<>();
        String type = typeVo.getType();

        /** 条件范围 */
        if(!EnumUtils.isInclude(ETFType.class,type)){
            //todo 自定义异常
            throw new  RuntimeException();
        }

        ETFType etfType = (ETFType) EnumUtils.get(ETFType.class,type);
        map.put("type",etfType.getInfo());


        /** 判断起止时间是否为空 */
        if(!StringUtils.isEmpty(typeVo.getStart()) && !StringUtils.isEmpty(typeVo.getEnd())){
            map.put("start",typeVo.getStart());
            map.put("end",typeVo.getEnd());
        }

        /** 调用查询接口 */

        JSONObject returnDto = nodeJsMarketFeign.ETF(map);

        JSONArray data = JSON.parseArray(JSONObject.toJSONString(returnDto.get("data")));

        List<ETF> list = JSONObject.parseArray(data.toJSONString(),ETF.class);

        List<DataDto> dataList = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {

            DataDto dataDto = new DataDto();
            ETF entry = list.get(i);
            dataDto.setId(entry.getId());
            dataDto.setTime(entry.getDate());
            dataDto.setValue(Convert.toDouble(entry.getValue()));
            dataList.add(i,dataDto);
        }

        return AjaxResult.success(dataList);
    }


}
