package com.qmth.distributed.print.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qmth.boot.api.annotation.Aac;
import com.qmth.boot.api.annotation.BOOL;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.distributed.print.business.bean.params.open.GradeOpenPageParams;
import com.qmth.distributed.print.business.bean.params.open.GradeOpenParams;
import com.qmth.distributed.print.business.service.OpenApiService;
import com.qmth.teachcloud.common.bean.params.OpenParams;
import com.qmth.teachcloud.common.bean.result.LoginResult;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicSchool;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.AppSourceEnum;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.service.BasicSchoolService;
import com.qmth.teachcloud.common.service.SysUserService;
import com.qmth.teachcloud.common.service.TeachcloudCommonService;
import com.qmth.teachcloud.common.util.*;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 知学知考开放接口前端控制器
 * </p>
 *
 * @author wangliang
 * @since 2022-04-26
 */
@Api(tags = "知学知考开放接口Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_OPEN)
@Validated
public class OpenApiController {
    private static final Logger log = LoggerFactory.getLogger(OpenApiController.class);

    @Resource
    private OpenApiService openApiService;

    @Resource
    SysUserService sysUserService;

    @Resource
    TeachcloudCommonService teachcloudCommonService;

    @Resource
    BasicSchoolService basicSchoolService;

    @ApiOperation(value = "试卷基础配置查询")
    @ApiResponses({@ApiResponse(code = 200, message = "试卷基础配置查询", response = Object.class)})
    @PostMapping("/paper_config")
    @Aac(auth = BOOL.FALSE)
    public Result paperConfig(@ApiParam(value = "接收试卷配置数据信息", required = true) @RequestBody String result) throws UnsupportedEncodingException {
        Optional.ofNullable(result).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("数据为空"));
        String decodeJson = URLDecoder.decode(result, SystemConstant.CHARSET_NAME);
        log.info("paperConfigSelect进来了,result:{}", decodeJson);
        GradeOpenParams gradeOpenParams = JacksonUtil.readJson(decodeJson, GradeOpenParams.class);
        Optional.ofNullable(gradeOpenParams).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("转换后的数据为空"));
        gradeOpenParams.validParams();
        BasicSchool basicSchool = AuthThirdUtil.hasPermission();
        return ResultUtil.ok(openApiService.getPaperConfig(basicSchool, gradeOpenParams.getThirdExamId(), gradeOpenParams.getGradeCourseCode()));
    }

    @ApiOperation(value = "试卷考察点查询")
    @ApiResponses({@ApiResponse(code = 200, message = "试卷考察点查询", response = Object.class)})
    @PostMapping("/paper_dimension")
    @Aac(auth = BOOL.FALSE)
    public Result paperDimension(@ApiParam(value = "试卷考察点查询", required = true) @RequestBody String result) throws UnsupportedEncodingException {

        Optional.ofNullable(result).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("数据为空"));
        String decodeJson = URLDecoder.decode(result, SystemConstant.CHARSET_NAME);
        log.info("paperDimensionSelect进来了,result:{}", decodeJson);
        GradeOpenParams gradeOpenParams = JacksonUtil.readJson(decodeJson, GradeOpenParams.class);
        Optional.ofNullable(gradeOpenParams).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("转换后的数据为空"));
        gradeOpenParams.validParams();
        BasicSchool basicSchool = AuthThirdUtil.hasPermission();
        return ResultUtil.ok(openApiService.getPaperDimension(basicSchool, gradeOpenParams.getThirdExamId(), gradeOpenParams.getGradeCourseCode()));
    }

    @ApiOperation(value = "试卷蓝图查询")
    @ApiResponses({@ApiResponse(code = 200, message = "试卷蓝图查询", response = Object.class)})
    @PostMapping("/paper_structure")
    @Aac(auth = BOOL.FALSE)
    public Result paperStructure(@ApiParam(value = "试卷考察点查询", required = true) @RequestBody String result) throws UnsupportedEncodingException {
        Optional.ofNullable(result).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("数据为空"));
        String decodeJson = URLDecoder.decode(result, SystemConstant.CHARSET_NAME);
        log.info("paperStructureSelect进来了,result:{}", decodeJson);
        GradeOpenParams gradeOpenParams = JacksonUtil.readJson(decodeJson, GradeOpenParams.class);
        Optional.ofNullable(gradeOpenParams).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("转换后的数据为空"));
        gradeOpenParams.validParams();
        BasicSchool basicSchool = AuthThirdUtil.hasPermission();
        return ResultUtil.ok(openApiService.getPaperStructure(basicSchool, gradeOpenParams.getThirdExamId(), gradeOpenParams.getGradeCourseCode()));
    }

    @ApiOperation(value = "试卷评价模型查询")
    @ApiResponses({@ApiResponse(code = 200, message = "试卷评价模型查询", response = Object.class)})
    @PostMapping("/paper_evaluation")
    @Aac(auth = BOOL.FALSE)
    public Result paperEvaluation(@ApiParam(value = "试卷评价模型查询", required = true) @RequestBody String result) throws UnsupportedEncodingException {
        Optional.ofNullable(result).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("数据为空"));
        String decodeJson = URLDecoder.decode(result, SystemConstant.CHARSET_NAME);
        log.info("paperEvaluation进来了,result:{}", decodeJson);
        GradeOpenParams gradeOpenParams = JacksonUtil.readJson(decodeJson, GradeOpenParams.class);
        Optional.ofNullable(gradeOpenParams).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("转换后的数据为空"));
        gradeOpenParams.validParams();
        BasicSchool basicSchool = AuthThirdUtil.hasPermission();
        return ResultUtil.ok(openApiService.getPaperEvaluation(basicSchool, gradeOpenParams.getThirdExamId(), gradeOpenParams.getGradeCourseCode()));
    }

    @ApiOperation(value = "考生成绩查询")
    @ApiResponses({@ApiResponse(code = 200, message = "考生成绩查询", response = Object.class)})
    @PostMapping("/exam_student_score")
    @Aac(auth = BOOL.FALSE)
    public Result examStudentScore(@ApiParam(value = "考生成绩查询", required = true) @RequestBody String result) throws UnsupportedEncodingException {
        Optional.ofNullable(result).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("数据为空"));
        String decodeJson = URLDecoder.decode(result, SystemConstant.CHARSET_NAME);
        log.info("examStudentScore进来了,result:{}", decodeJson);
        GradeOpenPageParams gradeOpenPageParams = JacksonUtil.readJson(decodeJson, GradeOpenPageParams.class);
        Optional.ofNullable(gradeOpenPageParams).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("转换后的数据为空"));
        gradeOpenPageParams.validParams();
        BasicSchool basicSchool = AuthThirdUtil.hasPermission();
        return ResultUtil.ok(openApiService.listExamStudentScore(basicSchool, gradeOpenPageParams.getThirdExamId(), gradeOpenPageParams.getGradeCourseCode(), gradeOpenPageParams.getPageNumber(), gradeOpenPageParams.getPageSize()));
    }

    @ApiOperation(value = "单点登录")
    @ApiResponses({@ApiResponse(code = 200, message = "返回消息", response = Result.class)})
    @RequestMapping(value = "/account/login", method = RequestMethod.POST)
    @Aac(auth = BOOL.FALSE)
    public Result accountLogin(@ApiParam(value = "时间", required = true) @RequestParam String time,
                               @ApiParam(value = "地址", required = true) @RequestParam String path,
                               @ApiParam(value = "鉴权信息", required = true) @RequestParam String signature,
                               @ApiParam(value = "工号", required = true) @RequestParam String account,
                               @ApiParam(value = "返回url") @RequestParam(required = false) String returnUrl,
                               @ApiParam(value = "其它参数") @RequestParam(required = false) String params) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        if (Objects.isNull(time) || Objects.equals(time, "")) {
            throw ExceptionResultEnum.PARAMS_ERROR.exception("时间不能为空");
        }
        if (Objects.isNull(path) || Objects.equals(path, "")) {
            throw ExceptionResultEnum.PARAMS_ERROR.exception("路径不能为空");
        }
        if (Objects.isNull(signature) || Objects.equals(signature, "")) {
            throw ExceptionResultEnum.PARAMS_ERROR.exception("鉴权信息不能为空");
        }
        signature = new String(Base64Util.decode(signature), SystemConstant.CHARSET_NAME);
        if (Objects.isNull(account) || Objects.equals(account, "")) {
            throw ExceptionResultEnum.PARAMS_ERROR.exception("工号不能为空");
        }
        account = URLDecoder.decode(account, SystemConstant.CHARSET_NAME);

        BasicSchool basicSchool = AuthThirdUtil.hasPermissionCas(time, path, signature);
        OpenParams openParams = null;
        if (Objects.nonNull(params) && !Objects.equals(params, "")) {
            String decodeJson = URLDecoder.decode(params, SystemConstant.CHARSET_NAME);
            openParams = JacksonUtil.readJson(decodeJson, OpenParams.class);
        }

        //查询用户是否存在
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.lambda().eq(SysUser::getSchoolId, basicSchool.getId())
                .eq(SysUser::getLoginName, account)
                .eq(SysUser::getEnable, true);
        SysUser sysUser = sysUserService.getOne(sysUserQueryWrapper);
        Optional.ofNullable(sysUser).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("用户不存在"));

        LoginResult loginResult = teachcloudCommonService.login(sysUser.getPassword(), sysUser, AppSourceEnum.CAS_THIRD);
        if (Objects.nonNull(returnUrl) && !Objects.equals(returnUrl, "")) {
            returnUrl = URLDecoder.decode(returnUrl, SystemConstant.CHARSET_NAME);
        }
        loginResult.setReturnUrl(returnUrl);
        return ResultUtil.ok(loginResult);
    }

    @ApiOperation(value = "西交大登录之前逻辑")
    @ApiResponses({@ApiResponse(code = 200, message = "用户信息", response = SysUser.class)})
    @RequestMapping(value = "/login_before_xju_logic", method = RequestMethod.POST)
    @Aac(auth = BOOL.FALSE)
    public Result loginBeforeXjuLogic(@ApiParam(value = "登录账号", required = true) @RequestBody String account) throws UnsupportedEncodingException {
        Optional.ofNullable(account).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("账号为空"));
        String decodeJson = URLDecoder.decode(account, SystemConstant.CHARSET_NAME);
        log.info("loginBeforeXjuLogic进来了,result:{}", decodeJson);
        account = JacksonUtil.readJson(decodeJson, String.class);

        BasicSchool basicSchool = AuthThirdUtil.hasPermission();
        Set<String> schoolCodes = new HashSet<>(Arrays.asList("xjtu", "xjtuyjs"));
        schoolCodes.add(basicSchool.getCode());

        QueryWrapper<BasicSchool> basicSchoolQueryWrapper = new QueryWrapper<>();
        basicSchoolQueryWrapper.lambda().in(BasicSchool::getCode, schoolCodes);
        List<BasicSchool> basicSchoolList = basicSchoolService.list(basicSchoolQueryWrapper);
        if (CollectionUtils.isEmpty(basicSchoolList)) {
            throw ExceptionResultEnum.ERROR.exception("未找到西交大学校信息");
        }
        List<Long> schoolIds = basicSchoolList.stream().map(s -> s.getId()).collect(Collectors.toList());

        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.lambda().eq(SysUser::getLoginName, account)
                .eq(SysUser::getEnable, true)
                .in(SysUser::getSchoolId, schoolIds);
        return ResultUtil.ok(sysUserService.list(sysUserQueryWrapper));
    }
}
