package com.izouma.nineth.web;

import com.izouma.nineth.domain.AppVersion;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.AppVersionRepo;
import com.izouma.nineth.service.AppVersionService;
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.web.bind.annotation.*;

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

@RestController
@RequestMapping("/appVersion")
@AllArgsConstructor
public class AppVersionController extends BaseController {
    private AppVersionService appVersionService;
    private AppVersionRepo    appVersionRepo;

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


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

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

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

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

    @GetMapping("/checkIosReview")
    public AppVersion checkIosReview(@RequestParam String version) {
        return appVersionRepo.findByPlatformAndVersion("iOS", version).orElseThrow(new BusinessException("版本不存在"));
    }

    @GetMapping("/checkAndroidReview")
    public AppVersion checkAndroidReview(@RequestParam String version) {
        return appVersionRepo.findByPlatformAndVersion("Android", version).orElseThrow(new BusinessException("版本不存在"));
    }
}

