package com.izouma.nineth.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.izouma.nineth.domain.UserProperty;
import com.izouma.nineth.repo.UserPropertyRepo;
import com.izouma.nineth.repo.UserRepo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
@AllArgsConstructor
public class EventMgmtService {

    private final UserPropertyRepo userPropertyRepo;
    private final UserService      userService;
    private final UserRepo         userRepo;
    private final CacheService     cacheService;

    public void clearUserProperty() {
        userPropertyRepo.deleteAll();
    }

    public void importUserProperty(MultipartFile file) throws IOException {
        List<UserProperty> list = EasyExcel.read(file.getInputStream()).head(UserProperty.class).doReadAllSync();
        list.parallelStream().forEach(up -> {
            UserProperty userProperty = userPropertyRepo.findById(up.getId()).orElse(new UserProperty(up.getId(), 0));
            userProperty.setMaxCount(userProperty.getMaxCount() + up.getMaxCount());
            userPropertyRepo.save(userProperty);
        });
    }

    public void clearVipPoint() {
        userRepo.clearVipPoint();
        cacheService.clearUser();
        cacheService.clearUserMy();
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class VipPointDTO {
        @ExcelProperty("用户ID")
        private Long userId;

        @ExcelProperty("num")
        private int num;
    }

    public void importVipPoint(MultipartFile file) throws IOException {
        List<VipPointDTO> list = EasyExcel.read(file.getInputStream()).head(VipPointDTO.class).doReadAllSync();
        list.parallelStream().forEach(v -> {
            userRepo.updateVipPoint(v.getUserId(), v.getNum());
        });
        cacheService.clearUser();
        cacheService.clearUserMy();
    }
}
