package com.qmth.paper.library.api;

import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.boot.core.solar.crypto.AppLicenseUtil;
import com.qmth.paper.library.common.contant.ApiPrefixConstant;
import com.qmth.paper.library.common.contant.SystemConstant;
import com.qmth.paper.library.common.service.AuthInfoService;
import com.qmth.paper.library.common.util.Result;
import com.qmth.paper.library.common.util.ResultUtil;
import com.qmth.paper.library.common.util.ServletUtil;
import io.swagger.annotations.*;
import org.apache.commons.io.IOUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * <p>
 * 激活授权配置表 前端控制器
 * </p>
 */
@Api(tags = "授权配置Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + ApiPrefixConstant.PREFIX_AUTH)
@Validated
public class TSAuthController {

    @Resource
    AuthInfoService authInfoService;

    @ApiOperation(value = "导出硬件信息")
    @ApiResponses({@ApiResponse(code = 200, message = "导出硬件信息", response = Object.class)})
    @RequestMapping(value = "/export/device/info", method = RequestMethod.POST)
    public void info() {
        try {
            HttpServletResponse response = ServletUtil.getResponse();
            response.setHeader("Content-Disposition", "attachment; filename=" + SystemConstant.urlEncode("device.info"));
            IOUtils.copy(new ByteArrayInputStream(AppLicenseUtil.buildDeviceInfo().value()), response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "离线激活")
    @ApiResponses({@ApiResponse(code = 200, message = "授权配置信息", response = Boolean.class)})
    @RequestMapping(value = "/offline/activation", method = RequestMethod.POST)
    public Result offlineActivation(@ApiParam(value = "上传文件", required = true) @RequestParam() MultipartFile file) throws Exception {
        try {
            authInfoService.updateLicense(file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultUtil.ok(true);
    }

    @ApiOperation(value = "查询激活信息")
    @ApiResponses({@ApiResponse(code = 200, message = "授权配置信息", response = Long.class)})
    @RequestMapping(value = "/select", method = RequestMethod.POST)
    public Result select() {
        return ResultUtil.ok(authInfoService.selectAuthInfo());
    }
}
