package com.izouma.nineth.repo;

import com.alibaba.excel.EasyExcel;
import com.izouma.nineth.ApplicationTests;
import com.izouma.nineth.domain.Asset;
import com.izouma.nineth.domain.Order;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.domain.UserProperty;
import com.izouma.nineth.dto.AirDropExcelDTO;
import com.izouma.nineth.dto.TestDTO;
import com.izouma.nineth.enums.AssetStatus;
import com.izouma.nineth.enums.OrderStatus;
import com.izouma.nineth.service.CacheService;
import com.izouma.nineth.utils.excel.UploadDataListener;
import org.apache.commons.lang3.ObjectUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


public class UserPropertyRepoTest extends ApplicationTests {

    @Autowired
    private UserPropertyRepo userPropertyRepo;
    @Autowired
    private AssetRepo        assetRepo;
    @Autowired
    private UserRepo         userRepo;
    @Autowired
    private CacheService     cacheService;
    @Autowired
    private OrderRepo        orderRepo;

    @Test
    public void save() {
        UserProperty property = new UserProperty();
        property.setId(9972L);
        property.setMaxCount(5);
        //24h
//        property.setTime(86400L);
        userPropertyRepo.save(property);
    }

    @Test
    public void get() {

        AtomicInteger userMax = new AtomicInteger();
        userPropertyRepo.findById(9972L).ifPresent(userProperty -> userMax.set(userProperty.getMaxCount()));
        System.out.println(userMax.addAndGet(1));
    }

    @Test
    public void clear() {
    }

    @Test
    public void setProperty() {
        //封神星主
        List<Long> userIds = userRepo.findIdByLevel();
        userIds.forEach(id -> {
            UserProperty userProperty = userPropertyRepo.findById(id).orElse(new UserProperty(id, 0));
            userProperty.setMaxCount(userProperty.getMaxCount() + 1);
            if (userProperty.getMaxCount() > 6) {
                userProperty.setMaxCount(6);
            }
            userPropertyRepo.save(userProperty);
        });


        //OASIS004：绿洲朋克战神3D持斧模型 2516069L 或  OASIS002: 绿洲朋克猴王3D旋转眺望模型 2514968L
        //OASISPUNK007：OASISPUNK绿洲朋克族人共治会荣誉勋章 5050947L
        //冠军赛 · 李小龙80周年纪念勋章 7275L
        List<Asset> assets = assetRepo.findByCollectionIdInAndStatus(Arrays.asList(2516069L, 2514968L, 5050947L, 7275L), AssetStatus.NORMAL);
        Map<Long, List<Asset>> collect = assets.stream().collect(Collectors.groupingBy(Asset::getOwnerId));
        collect.forEach((key, value) -> {
            List<Long> ids = value.stream().map(Asset::getCollectionId).distinct().collect(Collectors.toList());
            int size = ids.size();
            if (ids.contains(2516069L) && ids.contains(2514968L)) {
                size -= 1;
            }
            UserProperty userProperty = userPropertyRepo.findById(key).orElse(new UserProperty(key, 0));
            userProperty.setMaxCount(userProperty.getMaxCount() + size);
            if (userProperty.getMaxCount() > 6) {
                userProperty.setMaxCount(6);
            }
            userPropertyRepo.save(userProperty);
        });

        //凤鸣寺
        File file = new File("/Users/qiufangchao/Desktop/mingdan.xlsx");
        UploadDataListener<AirDropExcelDTO> listener = new UploadDataListener<>();
        List<AirDropExcelDTO> dtos = EasyExcel.read(file, AirDropExcelDTO.class, listener)
                .sheet()
                .doReadSync();
        List<Long> userIds2 = userRepo.findIdByPhones(dtos.stream()
                .map(AirDropExcelDTO::getPhone)
                .collect(Collectors.toSet()));
        System.out.println(userIds2);
        userIds2.forEach(id -> {
            UserProperty userProperty = userPropertyRepo.findById(id).orElse(new UserProperty(id, 0));
            userProperty.setMaxCount(userProperty.getMaxCount() + 1);
            if (userProperty.getMaxCount() > 6) {
                userProperty.setMaxCount(6);
            }
            userPropertyRepo.save(userProperty);
        });

        //vip
        File file1 = new File("/Users/qiufangchao/Desktop/VIP.xlsx");
        UploadDataListener<AirDropExcelDTO> listener1 = new UploadDataListener<>();
        List<AirDropExcelDTO> dtos1 = EasyExcel.read(file1, AirDropExcelDTO.class, listener1)
                .sheet()
                .doReadSync();
        Set<String> userIds3 = dtos1.stream()
                .map(AirDropExcelDTO::getPhone)
                .collect(Collectors.toSet());
        System.out.println(userIds3);
        userIds3.forEach(id -> {
            UserProperty userProperty = userPropertyRepo.findById(Long.parseLong(id))
                    .orElse(new UserProperty(Long.parseLong(id), 0));
            userProperty.setMaxCount(userProperty.getMaxCount() + 1);
            if (userProperty.getMaxCount() > 6) {
                userProperty.setMaxCount(6);
            }
            userPropertyRepo.save(userProperty);
        });


        //-1
        Iterable<UserProperty> all = userPropertyRepo.findAll();
        all.forEach(p -> {
            if (p.getMaxCount() > 1) {
                p.setMaxCount(p.getMaxCount() - 1);
                userPropertyRepo.save(p);
            }
        });

    }

    @Test
    public void setByphone() {
        File file = new File("/Users/qiufangchao/Desktop/mingdan.xlsx");
        UploadDataListener<AirDropExcelDTO> listener = new UploadDataListener<>();
        List<AirDropExcelDTO> dtos = EasyExcel.read(file, AirDropExcelDTO.class, listener)
                .sheet()
                .doReadSync();
//        List<Long> userIds = userRepo.findIdByPhones(dtos.stream()
//                .map(AirDropExcelDTO::getPhone)
//                .collect(Collectors.toSet()));
//        System.out.println(userIds);

        List<User> users = userRepo.findByPhoneInAndDelFalse(dtos.stream()
                .map(AirDropExcelDTO::getPhone)
                .collect(Collectors.toSet()));

        Map<String, Long> userMap = users.stream().collect(Collectors.toMap(User::getPhone, User::getId));
        dtos.forEach(dto -> {
            Long aLong = userMap.get(dto.getPhone());
            if (aLong == null) {
                System.out.println(dto.getPhone());
            }
        });


//        userIds.forEach(id -> {
//            UserProperty userProperty = userPropertyRepo.findById(id).orElse(new UserProperty(id, 0));
//            userProperty.setMaxCount(userProperty.getMaxCount() + 1);
//            if (userProperty.getMaxCount() > 6) {
//                userProperty.setMaxCount(6);
//            }
//            userPropertyRepo.save(userProperty);
//        });
    }

    @Test
    public void setById() {
//        userPropertyRepo.deleteAll();
        File file = new File("/Users/sunnianwen/Desktop/all1.xlsx");
        File file2 = new File("/Users/sunnianwen/Desktop/123.xlsx");

        UploadDataListener<AirDropExcelDTO> listener = new UploadDataListener<>();
        List<AirDropExcelDTO> dtos = EasyExcel.read(file, AirDropExcelDTO.class, listener)
                .sheet()
                .doReadSync();
        List<AirDropExcelDTO> dtos2 = EasyExcel.read(file2, AirDropExcelDTO.class, listener)
                .sheet()
                .doReadSync();
//        Set<String> userIds = dtos.stream()
//                .map(AirDropExcelDTO::getPhone)
//                .collect(Collectors.toSet());
//        System.out.println(userIds);
        dtos.forEach(id -> {
            UserProperty userProperty = userPropertyRepo.findById(Long.parseLong(id.getPhone()))
                    .orElse(new UserProperty(Long.parseLong(id.getPhone()), 0));
            userProperty.setMaxCount(Integer.parseInt(id.getName()));
//            if (userProperty.getMaxCount() > 6) {
//                userProperty.setMaxCount(6);
//            }
            userPropertyRepo.save(userProperty);
        });
        dtos2.forEach(id -> {

            UserProperty userProperty = userPropertyRepo.findById(Long.parseLong(id.getPhone()))
                    .orElse(null);
            if (ObjectUtils.isEmpty(userProperty)) {
                userProperty = new UserProperty(Long.parseLong(id.getPhone()), Integer.parseInt(id.getName()));
            } else {
                userProperty.setMaxCount(userProperty.getMaxCount() + 1);
            }

            userPropertyRepo.save(userProperty);
        });
    }

    @Test
    public void statistic() {
        Map<Long, Integer> map = new HashMap<>();
        //凤鸣寺
        File file = new File("/Users/qiufangchao/Desktop/mingdan.xlsx");
        UploadDataListener<AirDropExcelDTO> listener = new UploadDataListener<>();
        List<AirDropExcelDTO> dtos = EasyExcel.read(file, AirDropExcelDTO.class, listener)
                .sheet()
                .doReadSync();
        List<Long> userIds = userRepo.findIdByPhones(dtos.stream()
                .map(AirDropExcelDTO::getPhone)
                .collect(Collectors.toSet()));
        userIds.forEach(id -> map.merge(id, 1, Integer::sum));
        //封神星主
        List<Long> userIds1 = userRepo.findIdByLevel();
        userIds1.forEach(id -> map.merge(id, 1, Integer::sum));


        //OASIS004：绿洲朋克战神3D持斧模型 2516069L 或  OASIS002: 绿洲朋克猴王3D旋转眺望模型 2514968L
        //OASISPUNK007：OASISPUNK绿洲朋克族人共治会荣誉勋章 5050947L
        //冠军赛 · 李小龙80周年纪念勋章 7275L
        List<Asset> assets = assetRepo.findByCollectionIdInAndStatus(Arrays.asList(2516069L, 2514968L, 5050947L, 7275L), AssetStatus.NORMAL);
        Map<Long, List<Asset>> collect = assets.stream().collect(Collectors.groupingBy(Asset::getOwnerId));
        collect.forEach((key, value) -> {
            List<Long> ids = value.stream().map(Asset::getCollectionId).distinct().collect(Collectors.toList());
            int size = ids.size();
            if (ids.contains(2516069L) && ids.contains(2514968L)) {
                size -= 1;
            }
            map.merge(key, size, Integer::sum);
        });
        map.forEach((key, value) -> System.out.println(key + "," + value));
    }

    @Test
    public void test() {
        Iterable<UserProperty> all = userPropertyRepo.findAll();
        List<String> result = new ArrayList<>();
        all.forEach(p -> {
            if (p != null && p.getId() != null) {
                if (p.getMaxCount() > 0) {
                    int num = userRepo.countAllByCollectionIdAndCollectionInvitorAndSettleAccountIdIsNotNull(8573130L, p.getId());
                    User user = userRepo.findById(p.getId()).orElse(null);
                    if (user.getVipPurchase() > 0 || user.getCreatedAt().isAfter(LocalDateTime.of(2022, 7, 5, 0, 0))) {
                        if ((num / 3) + 1 != p.getMaxCount()) {
                            result.add(p.getId() + "," + p.getMaxCount() + "," + num);
                        }
                    } else {
                        if (num / 3 != p.getMaxCount()) {
                            result.add(p.getId() + "," + p.getMaxCount() + "," + num);
                        }
                    }
//                    if (num == 0) {
//                        userPropertyRepo.delete(p);
//                        user.setVipPoint(0);
//                        userRepo.save(user);
//                        cacheService.clearUser(user.getId());
//                        cacheService.clearUser(user.getId());
//                    }

//                    int size = num / 3;
//                    if (user.getVipPurchase() > 0 || user.getCreatedAt().isAfter(LocalDateTime.of(2022, 7, 5, 0, 0))) {
//                        if (size + 1 != p.getMaxCount()) {
//                            if (size + 1 >= 10 && p.getMaxCount() != 10) {
//                                p.setMaxCount(10);
//                                userPropertyRepo.save(p);
//                            } else {
//                                p.setMaxCount(size + 1);
//                                userPropertyRepo.save(p);
//                            }
//                        }
//
//                    } else {
//                        if (size != p.getMaxCount()) {
//                            if (size >= 10 && p.getMaxCount() != 10) {
//                                p.setMaxCount(10);
//                                userPropertyRepo.save(p);
//                            } else {
//                                p.setMaxCount(size);
//                                userPropertyRepo.save(p);
//                            }
//                        }
//                    }
                }
            }
        });
        result.forEach(System.out::println);
    }

    @Test
    public void test3() {
        List<String> result = new ArrayList<>();
        File file = new File("/Users/qiufangchao/Desktop/error.xlsx");
        UploadDataListener<TestDTO> listener = new UploadDataListener<>();
        List<TestDTO> dtos = EasyExcel.read(file, TestDTO.class, listener)
                .sheet()
                .doReadSync();
        dtos.forEach(dto -> {
            int size = dto.getReal() / 3;

            int orders = orderRepo.countAllByUserIdAndCollectionIdAndStatusIn(dto.getId(), 8573130L, Arrays.asList(OrderStatus.FINISH, OrderStatus.PROCESSING));
            User user = userRepo.findById(dto.getId()).orElse(null);
            if (user.getVipPurchase() > 0 || user.getCreatedAt().isAfter(LocalDateTime.of(2022, 7, 5, 0, 0))) {
                if (size + 1 < orders) {
                    int num = size + 1;
                    result.add(dto.getId() + "," + num + "," + orders);
                }
            } else {
                if (size < orders) {
                    result.add(dto.getId() + "," + size + "," + orders);
                }
            }

        });
        result.forEach(System.out::println);
    }

}
