package com.izouma.jiashanxia.web;

import com.izouma.jiashanxia.domain.GoodsInfo;
import com.izouma.jiashanxia.domain.UserPackage;
import com.izouma.jiashanxia.dto.UserPackageDTO;
import com.izouma.jiashanxia.repo.GoodsInfoRepo;
import com.izouma.jiashanxia.service.UserPackageService;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.UserPackageRepo;
import com.izouma.jiashanxia.utils.ObjUtils;
import com.izouma.jiashanxia.utils.SecurityUtils;
import com.izouma.jiashanxia.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("/userPackage")
@AllArgsConstructor
public class UserPackageController extends BaseController {
    private UserPackageService userPackageService;
    private UserPackageRepo    userPackageRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<UserPackage> all(@RequestBody PageQuery pageQuery) {
        return userPackageService.all(pageQuery);
    }

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

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

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

    @GetMapping("/my")
    public List<UserPackageDTO> my() {
        return userPackageRepo.userPackage(SecurityUtils.getAuthenticatedUser().getId());
    }

    @PreAuthorize("hasAnyRole('ADMIN','WRITER')")
    @GetMapping("/byUser")
    public List<UserPackageDTO> byUser(@RequestParam Long userId) {
        return userPackageRepo.userPackage(userId);
    }
}

