package com.izouma.nineth.web;

import com.izouma.nineth.domain.ActivitySurpriseBox;
import com.izouma.nineth.domain.SurpriseBoxContent;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.ActivitySurpriseBoxRepo;
import com.izouma.nineth.utils.JpaUtils;
import com.izouma.nineth.utils.ObjUtils;
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.util.List;

/**
 * 配置活动惊喜盒子
 */
@RestController
@RequestMapping("/activitySurpriseBox")
@AllArgsConstructor
public class ActivitySurpriseBoxController extends BaseController {

    private ActivitySurpriseBoxRepo activitySurpriseBoxRepo;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public ActivitySurpriseBox save(@RequestBody ActivitySurpriseBox record) {
        if (record.getId() != null) {
            ActivitySurpriseBox orig = activitySurpriseBoxRepo.findById(record.getId()).orElseThrow(new BusinessException("盒子无记录"));
            int grantCount = orig.getGrantCount();
            ObjUtils.merge(orig, record);
            int stock = orig.getProperties().stream().mapToInt(SurpriseBoxContent::getStock).sum();
            orig.setBoxSum(stock);
            orig.setGrantCount(grantCount);//避免前端乱传
            return activitySurpriseBoxRepo.save(orig);
        }
        int stock = record.getProperties().stream().mapToInt(SurpriseBoxContent::getStock).sum();
        record.setBoxSum(stock);
        record.setGrantCount(0);
        return activitySurpriseBoxRepo.save(record);
    }

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

    @GetMapping("/get/{id}")
    public ActivitySurpriseBox get(@PathVariable Long id) {
        return activitySurpriseBoxRepo.findById(id).orElseThrow(new BusinessException("盒子无记录"));
    }
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        activitySurpriseBoxRepo.softDelete(id);
    }

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