package com.qmth.distributed.print.api;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.boot.core.solar.crypto.AppLicenseUtil;
import com.qmth.boot.tools.signature.SignatureEntity;
import com.qmth.boot.tools.signature.SignatureType;
import com.qmth.distributed.print.business.service.AuthInfoService;
import com.qmth.teachcloud.common.config.DictionaryConfig;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicSchool;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.service.CommonCacheService;
import com.qmth.teachcloud.common.util.*;
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.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

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

    @Resource
    AuthInfoService authInfoService;

    @Resource
    CommonCacheService commonCacheService;

    @Resource
    DictionaryConfig dictionaryConfig;

    @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 {
        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());
    }

    @ApiOperation(value = "测试推送信息给教研分析")
    @ApiResponses({@ApiResponse(code = 200, message = "测试推送信息给教研分析", response = Objects.class)})
    @RequestMapping(value = "/test/push", method = RequestMethod.POST)
    public void testPush() throws IOException {
        Long schoolId = SystemConstant.getHeadOrUserSchoolId();
        BasicSchool basicSchool = commonCacheService.schoolCache(schoolId);
        Long timestamp = System.currentTimeMillis();
//        /**
//         * 测试推送学期
//         */
//        BasicSemesterParams basicSemesterParams = new BasicSemesterParams("测试学期1", System.currentTimeMillis(), System.currentTimeMillis() + 1L);
//        String accessToken = SignatureEntity.build(SignatureType.SECRET, SystemConstant.METHOD, dictionaryConfig.reportOpenDomain().getSemesterApi(), timestamp, basicSchool.getAccessKey(), basicSchool.getAccessSecret());
//        String result = HttpUtil.postJson(dictionaryConfig.reportOpenDomain().getHostUrl() + dictionaryConfig.reportOpenDomain().getSemesterApi(), JacksonUtil.parseJson(basicSemesterParams), accessToken, timestamp);
//        if (Objects.nonNull(result)) {
//            log.info("result:{}", JacksonUtil.parseJson(result));
//        }

//        /**
//         * 测试推送考试
//         */
//        Map<String, Object> map = new HashMap<>();
//        map.computeIfAbsent("examName", v -> "测试考试1");
//        map.computeIfAbsent("examTime", v -> timestamp);
//        map.computeIfAbsent("semesterId", v -> 262908000564412416L);
//        String accessToken = SignatureEntity.build(SignatureType.SECRET, SystemConstant.METHOD, dictionaryConfig.reportOpenDomain().getExamApi(), timestamp, basicSchool.getAccessKey(), basicSchool.getAccessSecret());
//        String result = HttpUtil.postJson(dictionaryConfig.reportOpenDomain().getHostUrl() + dictionaryConfig.reportOpenDomain().getExamApi(), JacksonUtil.parseJson(map), accessToken, timestamp);
//        if (Objects.nonNull(result)) {
//            log.info("result:{}", JacksonUtil.parseJson(result));
//        }

//        /**
//         * 测试推送分析课程（试卷）
//         */
//        Map<String, Object> map = new HashMap<>();
//        map.computeIfAbsent("examId", v -> 262946761763454976L);
//        map.computeIfAbsent("courseCode", v -> 2022052700001L + "A");//试卷编号+卷型
//        map.computeIfAbsent("courseName", v -> "测试课程1");
//        map.computeIfAbsent("paperType", v -> "A");
//        map.computeIfAbsent("teachCollegeName", v -> "测试机构1");//机构名称
//        String accessToken = SignatureEntity.build(SignatureType.SECRET, SystemConstant.METHOD, dictionaryConfig.reportOpenDomain().getCourseEditApi(), timestamp, basicSchool.getAccessKey(), basicSchool.getAccessSecret());
//        String result = HttpUtil.postJson(dictionaryConfig.reportOpenDomain().getHostUrl() + dictionaryConfig.reportOpenDomain().getCourseEditApi(), JacksonUtil.parseJson(map), accessToken, timestamp);
//        if (Objects.nonNull(result)) {
//            log.info("result:{}", JacksonUtil.parseJson(result));
//        }

//        /**
//         * 测试单点登录
//         */
//        Map<String, Object> map = new HashMap<>();
//        map.computeIfAbsent("loginName", v -> "admin");
//        map.computeIfAbsent("role", v -> RoleTypeEnum.OFFICE_TEACHER);
//        map.computeIfAbsent("orgName", v -> "本科生院");
//        map.computeIfAbsent("realName", v -> "admin");
//        map.computeIfAbsent("mobileNumber", v -> "18008659001");
//        map.computeIfAbsent("returnUrl", v -> "https://www.baidu.com");
//        String accessToken = SignatureEntity.build(SignatureType.SECRET, SystemConstant.METHOD, dictionaryConfig.reportOpenDomain().getSsoLoginApi(), timestamp, basicSchool.getAccessKey(), basicSchool.getAccessSecret());
//        String result = HttpUtil.postJson(dictionaryConfig.reportOpenDomain().getHostUrl() + dictionaryConfig.reportOpenDomain().getSsoLoginApi(), JacksonUtil.parseJson(map), accessToken, timestamp);
//        if (Objects.nonNull(result)) {
//            log.info("result:{}", JacksonUtil.parseJson(result));
//        }

        /**
         * 测试生成课程（试卷）分析报告接口
         */
        try {
            Map<String, Object> map = new HashMap<>();
            map.computeIfAbsent("examId", v -> 262946761763454976L);
            map.computeIfAbsent("courseCode", v -> Arrays.asList(2022052700001L + "A",
                    2022052700001L + "B",
                    2022052700001L + "C",
                    2022052700001L + "D",
                    2022052700001L + "E",
                    2022052700001L + "F",
                    2022052700001L + "G"));//试卷编号+卷型
            String source = Base64Util.encode(ShaUtils.sha1(map.get("examId") + map.get("courseCode").toString()));
            log.info("source:{}", source);
            String accessToken = SignatureEntity.build(SignatureType.SECRET, SystemConstant.METHOD, dictionaryConfig.reportOpenDomain().getCalculateApi(), timestamp, basicSchool.getAccessKey(), basicSchool.getAccessSecret());
            String result = HttpUtil.postJson(dictionaryConfig.reportOpenDomain().getHostUrl() + dictionaryConfig.reportOpenDomain().getCalculateApi(), JacksonUtil.parseJson(map), accessToken, timestamp);
            if (Objects.nonNull(result)) {
                log.info("result:{}", JacksonUtil.parseJson(result));
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (Objects.nonNull(jsonObject.get("code")) && jsonObject.getIntValue("code") != HttpStatus.HTTP_OK) {
                    throw ExceptionResultEnum.ERROR.exception(jsonObject.getString("error"));
                }
            }
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            //TODO 生成txt文件
            if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        }
    }
}
