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.Address;
import com.jxy.marketall.enums.AddressCoinType;
import com.jxy.marketall.service.ActiveAddressService;
import com.jxy.marketall.service.NodeJsMarketFeign;
import com.jxy.marketall.service.ReceivingAddressService;
import com.jxy.marketall.utils.EnumUtils;
import com.jxy.marketall.vo.CoinVo;
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 日收到交易地址查询业务处理
 * @Date 2022/5/19 17:51
 * @Author 杜懿
 */
@Service
public class ReceivingAddressServiceImpl implements ReceivingAddressService {

    @Autowired
    private NodeJsMarketFeign nodeJsMarketFeign;

    @Override
    public AjaxResult findReceivingAddressByCoin(CoinVo coinVo){

        HashMap<String,String> map = new HashMap<>();
        String coin = coinVo.getCoin();
        /** 条件范围 */
        if(!EnumUtils.isInclude(AddressCoinType.class,coin)){
            //todo 自定义异常
            throw new  RuntimeException();
        }
        AddressCoinType addressCoinType = (AddressCoinType) EnumUtils.get(AddressCoinType.class,coin);
        map.put("coin",addressCoinType.getInfo());

        /** 判断起止时间是否为空 */
        if(!StringUtils.isEmpty(coinVo.getStart()) && !StringUtils.isEmpty(coinVo.getEnd())){

            map.put("start",coinVo.getStart());
            map.put("end",coinVo.getEnd());

        }

        /** 调用查询接口 */
        JSONObject returnDto = nodeJsMarketFeign.receivingAddress(map);

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

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

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

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

            DataDto dataDto = new DataDto();
            Address 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);
    }

}
