package com.qmth.teachcloud.common.api.api;

import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.boot.core.solar.config.SolarProperties;
import com.qmth.boot.core.solar.crypto.AppLicenseUtil;
import com.qmth.boot.core.solar.model.AppInfo;
import com.qmth.boot.core.solar.service.SolarService;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.service.AuthInfoService;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import com.qmth.teachcloud.common.util.ServletUtil;
import io.swagger.annotations.*;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.util.Objects;

/**
 * <p>
 * 激活授权配置表 前端控制器
 * </p>
 *
 * @author wangliang
 * @since 2022-04-26
 */
@Api(tags = "授权配置Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_AUTH)
@Validated
public class TSAuthController {
    private final static Logger log = LoggerFactory.getLogger(TSAuthController.class);

    @Resource
    AuthInfoService authInfoService;

    @Resource
    SolarService solarService;

    @Resource
    SolarProperties solarProperties;

    @ApiOperation(value = "同步机构接口")
    @RequestMapping(value = "/sync/org", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "菜单信息", response = Result.class)})
    public Result syncOrg() throws Exception {
        if (Objects.isNull(solarProperties.getAccessKey()) && Objects.isNull(solarProperties.getAccessSecret())) {
            throw ExceptionResultEnum.ERROR.exception("key和secret为空");
        }
        AppInfo appInfo = solarService.update(solarProperties.getAccessKey(), solarProperties.getAccessSecret());
        if (Objects.isNull(appInfo)) {
            throw ExceptionResultEnum.ERROR.exception("同步机构失败");
        } else {
            authInfoService.appInfoInit(appInfo, solarProperties.getAccessKey(), solarProperties.getAccessSecret());
        }
        return ResultUtil.ok(true);
    }

    @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) {
            log.error(SystemConstant.LOG_ERROR, e);
        }
    }

    @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(required = true) MultipartFile file) throws Exception {
        authInfoService.updateLicense(file.getBytes());
        return ResultUtil.ok(true);
    }

    @ApiOperation(value = "在线激活")
    @ApiResponses({@ApiResponse(code = 200, message = "授权配置信息", response = Boolean.class)})
    @RequestMapping(value = "/online/activation", method = RequestMethod.POST)
    public Result onlineActivation(@ApiParam(value = "accessKey", required = true) @RequestParam(required = true) String accessKey,
                                   @ApiParam(value = "accessSecret", required = true) @RequestParam(required = true) String accessSecret) throws Exception {
        AppInfo appInfo = solarService.update(accessKey, accessSecret);
        if (Objects.isNull(appInfo)) {
            throw ExceptionResultEnum.ERROR.exception("激活失败，请检查key和secret输入是否正确");
        } else {
            authInfoService.appInfoInit(appInfo, accessKey, accessSecret);
        }
        return ResultUtil.ok(true);
    }

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