package com.izouma.dingdong.web;

import com.izouma.dingdong.utils.SecurityUtils;
import com.izouma.dingdong.domain.Coupon;
import com.izouma.dingdong.service.CouponService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.CouponRepo;
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.data.domain.PageImpl;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/coupon")
@AllArgsConstructor
public class CouponController extends BaseController {
    private CouponService couponService;
    private CouponRepo couponRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<Coupon> all(PageQuery pageQuery) {
        //return couponRepo.findAll(toSpecification(pageQuery,Coupon.class),toPageRequest(pageQuery));
        List<Coupon> collect = couponRepo.findAll(toSpecification(pageQuery, Coupon.class)).stream().filter(Coupon::getEnabled).collect(Collectors.toList());
        return new PageImpl<>(collect, toPageRequest(pageQuery), pageQuery.getSize());
    }

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

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

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

    ///true所有 false未过期
    @ApiOperation("是否显示所有")
    @GetMapping("/my")
    public List<Coupon> my(Boolean isAll) {
        return couponService.my(SecurityUtils.getAuthenticatedUser().getId(), isAll);
    }

    @GetMapping("/platform")
    public List<Coupon> platform() {
        return couponRepo.findAllByMerchantIdNullAndEnabledTrue();
    }
}

