package com.jxy.marketall.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.core.web.Result.PageResult;
import com.jxy.common.redis.service.RedisService;
import com.jxy.marketall.dto.CountDto;
import com.jxy.marketall.entity.BTCBigAmountVout;
import com.jxy.marketall.entity.BTCTags;
import com.jxy.marketall.mapper.BTCBigAmountVoutMapper;
import com.jxy.marketall.mapper.BTCNewV2Mapper;
import com.jxy.marketall.service.BTCBigAmountVoutService;
import com.jxy.marketall.vo.BTCBigTxCountVo;
import com.jxy.marketall.vo.BTCVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description btc大额交易查询业务处理
 * @Date 2022/6/21  11:51
 * @Author 杜懿
 */
@Service("BTCBigAmountVoutService")
public class BTCBigAmountVoutServiceImpl extends ServiceImpl<BTCBigAmountVoutMapper, BTCBigAmountVout> implements BTCBigAmountVoutService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private BTCNewV2Mapper btcNewV2Mapper;

    @Override
    public AjaxResult findBTCBigAmountVoutByBTCVo(BTCVo btcVo) {

        if (!StringUtils.isEmpty(btcVo.getTotal())){

            //校验字符合法性
            //校验是否为字母或数字
            if(!btcVo.getTotal().matches("^[A-Za-z0-9]+$")){
                btcVo.setTotal(btcVo.getTotal().replaceAll(",",""));
                //total不是数字或者字母  1、输入了浮点数  2、输入非法字符 直接返回空数据
                if(!btcVo.getTotal().matches("^(-?\\d+)(\\.\\d+)?$")){

                    PageResult result = new PageResult();
                    result.setCount(0L);
                    result.setTotalPage(0L);
                    result.setData(new ArrayList<>());
                    return AjaxResult.success("模糊搜索传参格式有误，仅支持数字字母",result);
                }
            }
            Double amount = Convert.toDouble(btcVo.getTotal());
            if (amount != null){
                btcVo.setAmount(amount);
            }else {
                if (btcVo.getTotal().length()>=62){
                    btcVo.setTxId(btcVo.getTotal());
                }else{
                    btcVo.setVout(btcVo.getTotal());
                }
            }
        }

        Page<BTCBigAmountVout> page = new Page<>(btcVo.getPage(),btcVo.getLimit(),9000L);

        page.setCurrent(btcVo.getPage());

        page.setSize(btcVo.getLimit());

        page.setOptimizeCountSql(false);

        if(StringUtils.isNull(btcVo.getStart()) && StringUtils.isNull(btcVo.getEnd())){
            Calendar calendar = Calendar.getInstance();
            Date date = calendar.getTime();
            calendar.add(Calendar.DATE, -7);
            btcVo.setStart(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,calendar.getTime()));
        }

        IPage<BTCBigAmountVout> iPage = baseMapper.getBTCBigAmountVoutDtoList(page,btcVo);


        PageResult result = new PageResult();

        if(iPage.getTotal() > 10000){
            iPage.setTotal(10000L);
        }

        List<BTCBigAmountVout> list = iPage.getRecords();

        long t1 = System.currentTimeMillis();
        List<BTCTags> btcTags = btcNewV2Mapper.getBTCTags();
        long t2 = System.currentTimeMillis();
        Map<String,String> map = btcTags.stream().collect(Collectors.toMap(
                BTCTags::getAddress,BTCTags::getTag,(key1,key2) ->key1
        ));
        long t3 = System.currentTimeMillis();
        list.stream().forEach(e ->{
            if(StringUtils.isNotNull(map.get(e.getVout()))){
                e.setTag(map.get(e.getVout()));
            }
        });
        long t4 = System.currentTimeMillis();

        result.setCount(iPage.getTotal());
        result.setTotalPage(iPage.getPages());
        result.setData(list);

        String msg ="查询耗时："+(t2-t1)+"ms,list转map耗时："+(t3-t2)+"ms,处理list耗时："+(t4-t3)+"s";

        return AjaxResult.success(msg,result);
    }

    @Override
    public AjaxResult findBTCBigAmountVoutByTime(BTCBigTxCountVo vo) {

        if(StringUtils.isEmpty(vo.getStart()) && StringUtils.isEmpty(vo.getEnd())){

            //起止时间都没传 则默认查最新一条数据的当前时间前一个月
            BTCBigAmountVout lastBTCBigAmountVout = redisService.getCacheObject("btcBigAmountVoutLastData");

            Date date = lastBTCBigAmountVout.getDate();
            vo.setEnd(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,date));
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            calendar.add(calendar.MONTH,-1);
            vo.setStart(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,calendar.getTime()));
            vo.setType("day");
        }

        List<CountDto> list = redisService.getCacheList("btcBigAmountVoutDayCount");

        if(list.size() == 0){
            return AjaxResult.error("数据丢失");
        }

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

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

        return AjaxResult.success(list);
    }


}
