package com.izouma.jiashanxia.web;

import com.izouma.jiashanxia.domain.Package;
import com.izouma.jiashanxia.enums.PackageType;
import com.izouma.jiashanxia.service.PackageService;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.PackageRepo;
import com.izouma.jiashanxia.utils.ObjUtils;
import com.izouma.jiashanxia.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.util.List;

@RestController
@RequestMapping("/package")
@AllArgsConstructor
public class PackageController extends BaseController {
    private PackageService packageService;
    private PackageRepo    packageRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<Package> all(@RequestBody PageQuery pageQuery) {
        pageQuery.setSort("type,asc");
        return packageService.all(pageQuery);
    }

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

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

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

    @GetMapping("/team")
    @ApiOperation("团队套餐")
    public List<Package> team() {
        return packageRepo.findAllByType(PackageType.TEAM);
    }

    @PostMapping("/openTeamSet")
    @ApiOperation("开通团队套餐")
    public void openTeamSet(Long userId, Long packageId) {
        packageService.openTeamSet(userId, packageId);
    }

    @PostMapping("/recharge")
    @ApiOperation("充值团队套餐")
    public void recharge(Long userId, Long packageId, Integer num) {
        packageService.recharge(userId, packageId, num);
    }

    @GetMapping("/allList")
    public List<Package> allList() {
        return packageRepo.findAll();
    }
}

