package com.izouma.nineth.web;

import com.izouma.nineth.config.SysConstants;
import com.izouma.nineth.domain.ActivityCollection;
import com.izouma.nineth.domain.ActivityInvite;
import com.izouma.nineth.domain.AwardActivityCollectionInfo;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.dto.UserRankDTO;
import com.izouma.nineth.enums.ActivityCollectionType;
import com.izouma.nineth.repo.ActivityInviteRepo;
import com.izouma.nineth.service.ActivityCollectionService;
import com.izouma.nineth.service.SysConfigService;
import com.izouma.nineth.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/activityCollection")
@AllArgsConstructor
public class ActivityCollectionController extends BaseController {
    private final ActivityCollectionService activityCollectionService;
    private final SysConfigService sysConfigService;
    private ActivityInviteRepo activityInviteRepo;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public ActivityCollection save(@RequestBody ActivityCollection input) {
        return activityCollectionService.save(input);
    }

    @PostMapping("/getInvitationTime")
    public boolean getInvitationTime(@RequestParam int projectId) {
        ActivityInvite activityInvite = activityInviteRepo.asdasdasfaf(LocalDateTime.now());
        User user = currentUser();
        if (user!=null && Integer.valueOf(sysConfigService.getInt(SysConstants.TESTER_USER_ID)).longValue() == user.getId()) {
           return true;
        }
        if (activityInvite==null){
            return false;
        }
        LocalDateTime currentTime = LocalDateTime.now();
        return currentTime.isAfter(activityInvite.getInviteStartdatetime()) && currentTime.isBefore( activityInvite.getInviteEnddatetime());
    }

    @PostMapping("/getInvitationDate")
    public ActivityInvite getInvitationDate(@RequestParam int projectId) {
        ActivityInvite activityInvite = activityInviteRepo.asdasdasfaf( LocalDateTime.now());
        User user = currentUser();
        if (user!=null && Integer.valueOf(sysConfigService.getInt(SysConstants.TESTER_USER_ID)).longValue() == user.getId() && activityInvite == null) {
            activityInvite = activityInviteRepo.findRecent();
        }
        if (activityInvite!=null){
            activityInvite.setByInvitePrize(null);
            activityInvite.setInvitePrizeList(null);
            activityInvite.setAwardDistributionType(null);
        }
        return activityInvite;
    }

    @PostMapping("/getRanking")
    public List<UserRankDTO> getRanking(@RequestParam int type, @RequestParam int start, @RequestParam int count ,@RequestParam(required = false) int projectId) {
        List<UserRankDTO> dataList = activityCollectionService.getRanking(type,start,count,projectId);
        return dataList;
    }

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<ActivityCollection> all(@RequestBody PageQuery pageQuery) {
        final User user = currentUser();
        Long testerUserId = Integer.valueOf(sysConfigService.getInt(SysConstants.TESTER_USER_ID)).longValue();
        if (!testerUserId.equals(user.getId())) {
            List<String> list = new ArrayList<>(0);
            pageQuery.getQuery().put("startTime", list);
        }
        Page<ActivityCollection> pageData =  activityCollectionService.all(pageQuery);
        //获取用户持有数量

        pageData.forEach(activityCollection -> {
            //如果是旧版数据 则补充Type为default
            if(activityCollection.getType() == null){
                activityCollection.setType(ActivityCollectionType.DEFAULT);
            }
            activityCollection.setStock(activityCollection.getAwardList().stream().mapToInt(AwardActivityCollectionInfo::getStock).sum());
            boolean collected = activityCollectionService.userCollected(activityCollection, user);
            activityCollection.setCollected(collected);
            activityCollection.setAwardCollectionName(activityCollection.getAwardList().get(0).getCollectionName());
            activityCollection.setAwardCollectionId(activityCollection.getAwardList().get(0).getCollectionId());
        });
        return pageData;
    }


    @PostMapping("/allActivity")
    public Page<ActivityCollection> allActivity(@RequestBody PageQuery pageQuery) {
        Page<ActivityCollection> pageData =  activityCollectionService.all(pageQuery);
        //获取用户持有数量
        pageData.forEach(activityCollection -> {
            //如果是旧版数据 则补充Type为default
            if(activityCollection.getType() == null){
                activityCollection.setType(ActivityCollectionType.DEFAULT);
            }
            //计算总库存量
            activityCollection.setStock(activityCollection.getAwardList().stream().mapToInt(AwardActivityCollectionInfo::getStock).sum());
            activityCollection.setAwardCollectionName(activityCollection.getAwardList().get(0).getCollectionName());
            activityCollection.setAwardCollectionId(activityCollection.getAwardList().get(0).getCollectionId());
        });
        return pageData;
    }

    @GetMapping("/get/{id}")
    public ActivityCollection get(@PathVariable Long id) {
        return activityCollectionService.getById(id);
    }

    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        activityCollectionService.softDelete(id);
    }

    @PostMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, @RequestBody PageQuery pageQuery) throws IOException {
        List<ActivityCollection> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }
}

