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.service.CacheService;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
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.HashMap;
import java.util.List;
import java.util.Map;

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

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

    private int convertVersion(String version) {
        String[] arr = version.split("\\.");
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            str.insert(0, String.format("%03d", Integer.parseInt(arr[arr.length - 1 - i])));
        }
        return Integer.parseInt(str.toString());
    }

    @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("无记录"));
    }

    @PreAuthorize("hasRole('ADMIN')")
    @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.findByPlatformAndVersionAndDelFalse("iOS", version).orElseThrow(new BusinessException("版本不存在"));
    }

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

    @GetMapping("/getVersion")
    public AppVersion checkReview(@RequestParam String platform, @RequestParam String version) {
        return appVersionRepo.findByPlatformAndVersionAndDelFalse(platform, version).orElseThrow(new BusinessException("版本不存在"));
    }

    @GetMapping("/checkUpdate")
    @Cacheable(value = "checkUpdate", key = "#platform+'@'+#version")
    public Map<String, Object> checkUpdate(@RequestParam String platform, @RequestParam String version) {
        Map<String, Object> map = new HashMap<>();
        AppVersion appVersion = appVersionRepo.findFirstByPlatformAndReviewFalseAndDelFalseOrderByVersionNumDesc(platform)
                .orElseThrow(new BusinessException("版本不存在"));
        map.put("version", appVersion);

        if (convertVersion(version) < appVersion.getVersionNum()) {
            map.put("needUpdate", true);
        } else {
            map.put("needUpdate", false);
        }
        return map;
    }
}

