package com.qmth.jkserver.controller.system;

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.jkserver.common.Constants;
import com.qmth.jkserver.constant.SystemConstant;
import com.qmth.jkserver.core.cache.JkCacheService;
import com.qmth.jkserver.core.exception.JkServerException;
import com.qmth.jkserver.enums.UserRole;
import com.qmth.jkserver.model.User;
import com.qmth.jkserver.service.AuthInfoService;
import com.qmth.jkserver.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(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 = Object.class)})
    public Object syncOrg() throws Exception {
        SystemConstant.superOper();
        if (Objects.isNull(solarProperties.getAccessKey()) && Objects.isNull(solarProperties.getAccessSecret())) {
            throw new JkServerException("key和secret为空");
        }
        AppInfo appInfo = solarService.update(solarProperties.getAccessKey(), solarProperties.getAccessSecret());
        if (Objects.isNull(appInfo)) {
            throw new JkServerException("同步机构失败");
        } else {
            authInfoService.appInfoInit(appInfo, solarProperties.getAccessKey(), solarProperties.getAccessSecret());
        }
        return true;
    }

    @ApiOperation(value = "导出硬件信息")
    @ApiResponses({@ApiResponse(code = 200, message = "导出硬件信息", response = Object.class)})
    @RequestMapping(value = "/export/device/info", method = RequestMethod.POST)
    public void info() {
        try {
            SystemConstant.superOper();
            HttpServletResponse response = ServletUtil.getResponse();
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            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 = Object.class)})
    @RequestMapping(value = "/offline/activation", method = RequestMethod.POST)
    public Object offlineActivation(@ApiParam(value = "上传文件", required = true) @RequestParam(required = true) MultipartFile file) throws Exception {
        SystemConstant.superOper();
        authInfoService.updateLicense(file.getBytes());
        return true;
    }

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

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