package com.izouma.dingdong.web.user;

import com.izouma.dingdong.converter.StringArrayConverter;
import com.izouma.dingdong.utils.SecurityUtils;
import com.izouma.dingdong.web.BaseController;
import com.izouma.dingdong.domain.user.UserCoupon;
import com.izouma.dingdong.service.user.UserCouponService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.user.UserCouponRepo;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.utils.excel.ExcelUtils;

import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/userCoupon")
@AllArgsConstructor
public class UserCouponController extends BaseController {
    private UserCouponService userCouponService;
    private UserCouponRepo userCouponRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<UserCoupon> all(PageQuery pageQuery) {
        return userCouponRepo.findAll(toSpecification(pageQuery, UserCoupon.class), toPageRequest(pageQuery));
    }

    @GetMapping("/get/{id}")
    public UserCoupon get(@PathVariable Long id) {
        return userCouponRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

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

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

    @ApiOperation("后台发放优惠券")
    @PostMapping("/issue")
    public void issue(@RequestParam Long userId, String couponId) {
        userCouponService.issue(userId, couponId);
    }

    @ApiOperation("未过期的")
    @GetMapping("/my")
    public List<UserCoupon> my() {
        List<UserCoupon> coupons = userCouponRepo.findAllByUserIdAndIsUsedFalse(SecurityUtils.getAuthenticatedUser().getId());
        return coupons.stream().filter(c -> !LocalDate.now().isAfter(c.getCoupon().getEndDate())).collect(Collectors.toList());
    }

    @ApiOperation("已过期的")
    @GetMapping("/myHis")
    public List<UserCoupon> myHis() {
        List<UserCoupon> coupons = userCouponRepo.findAllByUserIdAndIsUsedFalse(SecurityUtils.getAuthenticatedUser().getId());
        return coupons.stream().filter(c -> LocalDate.now().isAfter(c.getCoupon().getEndDate())).collect(Collectors.toList());
    }
}

