package com.izouma.nineth.web;

import com.izouma.nineth.domain.ActivityInvite;
import com.izouma.nineth.domain.ActivitySurpriseBox;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.enums.AwardDistributionType;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.ActivityInviteRepo;
import com.izouma.nineth.service.ActivityInviteService;
import com.izouma.nineth.utils.JpaUtils;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.List;

@RestController
@RequestMapping("/activityInvite")
@AllArgsConstructor
@Slf4j
public class ActivityInviteController extends BaseController {
    private ActivityInviteRepo activityInviteRepo;
    private static Thread airDropThread;
    private ActivityInviteService activityInviteService;



    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public ActivityInvite save(@RequestBody ActivityInvite record) {
        if (record.getId() != null) {
            ActivityInvite orig = activityInviteRepo.findById(record.getId()).orElseThrow(new BusinessException("活动无记录"));
            ObjUtils.merge(orig, record);
            return activityInviteRepo.save(orig);
        }
        return activityInviteRepo.save(record);
    }

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<ActivityInvite> all(@RequestBody PageQuery pageQuery) {
//        activityInviteService.reissue();
        return activityInviteRepo.findAll(JpaUtils.toSpecification(pageQuery, ActivitySurpriseBox.class), JpaUtils.toPageRequest(pageQuery));
    }

    /**
     * 发放活动奖励
     *
     * @param activityId
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/activityAward")
    public int activityAward(@RequestParam Long activityId) {
        if (airDropThread != null && airDropThread.isAlive()) {
            throw new BusinessException("奖励正在发放，稍后在试");
        }
        ActivityInvite activityInvite = activityInviteRepo.findById(activityId).orElseThrow(new BusinessException("活动不存在"));
        //ZERO("每达到一个条件实时发放一次奖励"),ONE("活动结束后发放所有已达成条件的奖励"), TWO("活动结束后按最高奖励发放");
        if (AwardDistributionType.ZERO == activityInvite.getAwardDistributionType()) {
            throw new BusinessException("邀请奖励是实时发放的");
        }
        if (activityInvite.getInviteEnddatetime().isAfter(LocalDateTime.now())) {
            throw new BusinessException("活动还未结束,请等活动结束后在操作");
        }
        airDropThread = new Thread(() -> activityInviteService.activityTerminationReward( activityInvite));
        airDropThread.start();
        return -1;
    }


    @GetMapping("/get/{id}")
    public ActivityInvite get(@PathVariable Long id) {
        return activityInviteRepo.findById(id).orElseThrow(new BusinessException("活动邀请无记录"));
    }
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        activityInviteRepo.softDelete(id);
    }

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

