package com.izouma.nineth.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.izouma.nineth.ApplicationTests;
import com.izouma.nineth.TokenHistory;
import com.izouma.nineth.domain.*;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.*;
import com.izouma.nineth.utils.TokenUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
class AssetServiceTest extends ApplicationTests {
    @Autowired
    private OrderRepo         orderRepo;
    @Autowired
    private BlindBoxItemRepo  blindBoxItemRepo;
    @Autowired
    private AssetService      assetService;
    @Autowired
    private CollectionRepo    collectionRepo;
    @Autowired
    private UserRepo          userRepo;
    @Autowired
    private CollectionService collectionService;
    @Autowired
    private AssetMintService  assetMintService;
    @Autowired
    private AssetRepo         assetRepo;
    @Autowired
    private NFTService        nftService;
    @Autowired
    private TokenHistoryRepo  tokenHistoryRepo;
    @Autowired
    private RocketMQTemplate  rocketMQTemplate;

    @Test
    void createAsset() {
        BlindBoxItem item = blindBoxItemRepo.findById(1860L).get();
        Order order = orderRepo.findById(1922L).get();
    }

    @Test
    void cancelConsignment() {
        assetService.cancelConsignment(1209L);
    }

    @Test
    void testCancelConsignment() {
        List<Long> ids = Arrays.asList(7920L, 26684L, 45655L,
                25308L, 157533L, 268927L, 7944L, 78740L,
                222146L, 268937L, 268949L, 765671L,
                220921L, 220949L, 766743L, 729011L,
                769787L, 702426L, 54865L, 304757L);
        ids.forEach(id -> assetService.cancelConsignment(id));

    }

    @Test
    public void testCreateAsset() {
        Order order = orderRepo.findById(4618L).get();
        Collection collection = collectionRepo.findById(order.getCollectionId()).get();
        BlindBoxItem blindBoxItem = blindBoxItemRepo.findById(4250L).get();
        User user = userRepo.findById(order.getUserId()).get();
        assetService.createAsset(blindBoxItem, user, order.getId(), order.getPrice(), "出售", 1);
    }

    @Test
    public void mint() {
        Asset asset = assetRepo.findById(4622L).get();
        assetMintService.mint(asset.getId());
    }

    @Test
    public void setHistory() {
        assetService.setHistory();
    }

    @Test
    public void cancelCon() {
        for (Asset asset : assetRepo.findNoAccount()) {
            try {
                assetService.cancelConsignment(asset.getId());
            } catch (Exception e) {

            }
        }
    }

    @Test
    public void fixNoHistory() {
        List<Asset> assets = assetRepo.findByNoHistory();

        for (Asset asset : assets) {
            if (StringUtils.isNotBlank(asset.getTokenId())) {
                User user = userRepo.findById(asset.getUserId()).get();
                TokenHistory tokenHistory = tokenHistoryRepo.save(TokenHistory.builder()
                        .tokenId(asset.getTokenId())
                        .fromUser(asset.getMinter())
                        .fromUserId(asset.getMinterId())
                        .fromAvatar(asset.getMinterAvatar())
                        .toUser(user.getNickname())
                        .toUserId(user.getId())
                        .toAvatar(user.getAvatar())
                        .operation("出售")
                        .price(asset.getPrice())
                        .tokenId(asset.getTokenId())
                        .build());
                tokenHistory.setCreatedAt(asset.getCreatedAt());
                tokenHistoryRepo.save(tokenHistory);
            }

        }
        System.out.println(assets);
    }


    @Test
    public void fixHistoryPrice() {
        List<TokenHistory> list = tokenHistoryRepo.findByOperationAndPriceNull("转让");
        System.out.println(list.size());
        StringBuilder builder = new StringBuilder();
        list.parallelStream().forEach(tokenHistory -> {
            List<Asset> assets = assetRepo.findByTokenIdAndCreatedAtBetween(tokenHistory.getTokenId(), tokenHistory.getCreatedAt()
                    .minusSeconds(10), tokenHistory.getCreatedAt().plusSeconds(1));
            if (assets.size() != 1) {
                throw new BusinessException("");
            }
            Order order = orderRepo.findById(assets.get(0).getOrderId())
                    .orElseThrow(new BusinessException(assets.get(0).getId() + "订单没找到"));
            builder.append(order.getId()).append(",").append(order.getPrice()).append("\n");
        });
        System.out.println(builder);
    }

    @Test
    public void all() {
        PageQuery pageQuery = new PageQuery();
        Map<String, Object> query = pageQuery.getQuery();
        query.put("userId", 7372);
        assetService.all(pageQuery)
                .getContent()
                .forEach(asset -> System.out.println(asset.getId() + "->" + asset.isOpened()));
    }

    @Test
    public void get() {
        Asset asset = assetRepo.findById(2366705L).orElseThrow(new BusinessException("无记录"));
        orderRepo.findByIdAndDelFalse(asset.getOrderId()).ifPresent(order -> asset.setOpened(order.isOpened()));
        System.out.println(asset);
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class kebi {
        @ExcelProperty(index = 2)
        private String phone;

        @ExcelProperty(index = 3)
        private int heibaman;

        @ExcelProperty(index = 4)
        private String numhei;

        @ExcelProperty(index = 5)
        private int huang;

        @ExcelProperty(index = 6)
        private String numhuang;
    }

    @Test
    public void asdfasdfasdfasdf() {
        List<kebi> list = EasyExcel.read("/Users/drew/Downloads/科比移民明细表(1).xlsx")
                .head(kebi.class).sheet()
                .headRowNumber(2)
                .doReadSync();
        Collection hei = collectionRepo.findById(2516276L).get();
        Collection huang = collectionRepo.findById(2516314L).get();
        List<Asset> assets = new ArrayList<>();
        for (kebi kebi : list) {
            User user = userRepo.findByPhoneAndDelFalse(kebi.getPhone()).orElse(null);
            if (user == null) {
                log.error("手机号{}没有找到", kebi.getPhone());
            } else {
                if (kebi.getHeibaman() > 0) {
                    for (Integer n : Arrays.stream(kebi.getNumhei()
                                    .replaceAll("\\.$", "")
                                    .replaceAll("^\\.", "")
                                    .split("\\."))
                            .map(String::trim)
                            .map(Integer::parseInt)
                            .collect(Collectors.toList())) {
                        Asset asset = Asset.create(hei, user);
                        asset.setTokenId(TokenUtils.genTokenId());
                        asset.setNumber(n);
                        assets.add(asset);
                    }
                }
                if (kebi.getHuang() > 0) {
                    for (Integer n : Arrays.stream(kebi.getNumhuang()
                                    .replaceAll("\\.$", "")
                                    .replaceAll("^\\.", "")
                                    .split("\\."))
                            .map(String::trim)
                            .map(Integer::parseInt)
                            .collect(Collectors.toList())) {
                        Asset asset = Asset.create(huang, user);
                        asset.setTokenId(TokenUtils.genTokenId());
                        asset.setNumber(n);
                        assets.add(asset);
                    }
                }
            }
        }
        System.out.println(assets.size());
        assetRepo.saveAll(assets);
        for (Asset asset : assets) {
            rocketMQTemplate.syncSend("mint-topic", asset.getId());
        }
    }
}