package com.qmth.teachcloud.report.api;

import com.qmth.boot.api.annotation.Aac;
import com.qmth.boot.api.annotation.BOOL;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.teachcloud.common.bean.params.BasicSemesterParams;
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.BasicCourseService;
import com.qmth.teachcloud.common.service.BasicSemesterService;
import com.qmth.teachcloud.common.util.AuthThirdUtil;
import com.qmth.teachcloud.common.util.JacksonUtil;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import com.qmth.teachcloud.report.business.bean.params.CalculateParams;
import com.qmth.teachcloud.report.business.bean.params.CourseParam;
import com.qmth.teachcloud.report.business.bean.params.PublishParams;
import com.qmth.teachcloud.report.business.bean.params.TBExamParam;
import com.qmth.teachcloud.report.business.enums.PublishStatusEnum;
import com.qmth.teachcloud.report.business.service.AnalyzeForReportService;
import com.qmth.teachcloud.report.business.service.TBExamCourseService;
import com.qmth.teachcloud.report.business.service.TBExamService;
import com.qmth.teachcloud.report.business.templete.strategy.CourseCodeSyncTaskService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 教研分析开放接口前端控制器
 * </p>
 *
 * @author wangliang
 * @since 2022-04-26
 */
@Api(tags = "教研分析开放接口Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + "/${prefix.url.open}")
@Validated
public class OpenApiController {
    private final static Logger log = LoggerFactory.getLogger(OpenApiController.class);

    @Resource
    BasicSemesterService basicSemesterService;

    @Resource
    TBExamService tbExamService;

    @Resource
    BasicCourseService basicCourseService;

    @Resource
    TBExamCourseService tbExamCourseService;

    @Resource
    DictionaryConfig dictionaryConfig;

    @Resource
    CourseCodeSyncTaskService courseCodeSyncTaskService;

    @Resource
    AnalyzeForReportService analyzeForReportService;

    @ApiOperation(value = "学期创建/更新接口")
    @ApiResponses({@ApiResponse(code = 200, message = "学期创建/更新接口", response = Object.class)})
    @RequestMapping(value = "/semester_edit", method = RequestMethod.POST)
    @Aac(auth = BOOL.FALSE)
    public Result semesterEdit(@ApiParam(value = "接收学期数据信息", required = true) @RequestBody String result) throws IOException, InterruptedException, IllegalAccessException {
        Optional.ofNullable(result).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("数据为空"));
        String decodeJson = URLDecoder.decode(result, SystemConstant.CHARSET_NAME);
        log.info("semesterEdit进来了,result:{}", decodeJson);
        BasicSemesterParams basicSemesterParams = JacksonUtil.readJson(decodeJson, BasicSemesterParams.class);
        Optional.ofNullable(basicSemesterParams).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("转换后的数据为空"));
        basicSemesterParams.validParams();
        BasicSchool basicSchool = AuthThirdUtil.hasPermission();
        return ResultUtil.ok(basicSemesterService.saveBasicSemesterCommon(basicSemesterParams, basicSchool.getId(), null,true));
    }

    @ApiOperation(value = "考试创建/更新接口")
    @ApiResponses({@ApiResponse(code = 200, message = "考试创建/更新接口", response = Object.class)})
    @RequestMapping(value = "/exam_edit", method = RequestMethod.POST)
    @Aac(auth = BOOL.FALSE)
    public Result examEdit(@ApiParam(value = "接收考试数据信息", required = true) @RequestBody String result) throws IOException, InterruptedException {
        Optional.ofNullable(result).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("数据为空"));
        String decodeJson = URLDecoder.decode(result, SystemConstant.CHARSET_NAME);
        log.info("examEdit进来了,result:{}", decodeJson);
        TBExamParam tbExamParam = JacksonUtil.readJson(decodeJson, TBExamParam.class);
        Optional.ofNullable(tbExamParam).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("转换后的数据为空"));
        tbExamParam.validParams();
        BasicSchool basicSchool = AuthThirdUtil.hasPermission();
        tbExamParam.setSchoolId(basicSchool.getId());
        return ResultUtil.ok(tbExamService.editTBExam(tbExamParam));
    }

    @ApiOperation(value = "分析课程（试卷）创建/更新接口")
    @ApiResponses({@ApiResponse(code = 200, message = "分析课程（试卷）创建/更新接口", response = Object.class)})
    @RequestMapping(value = "/course_edit", method = RequestMethod.POST)
    @Aac(auth = BOOL.FALSE)
    @Transactional
    public Result courseEdit(@ApiParam(value = "接收分析课程（试卷）数据信息", required = true) @RequestBody String result) throws IOException, InterruptedException {
        Optional.ofNullable(result).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("数据为空"));
        String decodeJson = URLDecoder.decode(result, SystemConstant.CHARSET_NAME);
        log.info("courseEdit进来了进来了,result:{}", decodeJson);
        CourseParam courseParam = JacksonUtil.readJson(decodeJson, CourseParam.class);
        courseParam.validParams();
        BasicSchool basicSchool = AuthThirdUtil.hasPermission();
        basicCourseService.createCourse(basicSchool.getId(), courseParam.getCourseCode(), courseParam.getCourseName());
        tbExamCourseService.createCourse(basicSchool.getId(), courseParam.getExamId(), courseParam.getCourseCode(), courseParam.getCourseName(), courseParam.getPaperType(), courseParam.getTeachCollegeName());
        return ResultUtil.ok(true);
    }

    @ApiOperation(value = "生成课程（试卷）分析报告接口")
    @ApiResponses({@ApiResponse(code = 200, message = "生成课程（试卷）分析报告接口", response = Object.class)})
    @RequestMapping(value = "/calculate", method = RequestMethod.POST)
    @Aac(auth = BOOL.FALSE)
    public Result calculate(@ApiParam(value = "接收分析课程（试卷）数据信息", required = true) @RequestBody String result) throws IOException, InterruptedException {
        Optional.ofNullable(result).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("数据为空"));
        String decodeJson = URLDecoder.decode(result, SystemConstant.CHARSET_NAME);
        log.info("calculate进来了,result:{}", decodeJson);
        CalculateParams calculateParams = JacksonUtil.readJson(decodeJson, CalculateParams.class);
        calculateParams.validParams();
        BasicSchool basicSchool = AuthThirdUtil.hasPermission();
        calculateParams.setSchoolId(basicSchool.getId());

        String callbackPwd = dictionaryConfig.printOpenDomain().getCallbackPwd();
        Optional.ofNullable(callbackPwd).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("配置文件回调密码为空"));

        courseCodeSyncTaskService.start(calculateParams);
        return ResultUtil.ok(true);
    }

    @ApiOperation(value = "发布报告接口")
    @ApiResponses({@ApiResponse(code = 200, message = "发布报告接口", response = Object.class)})
    @RequestMapping(value = "/publish", method = RequestMethod.POST)
    @Aac(auth = BOOL.FALSE)
    public Result publish(@ApiParam(value = "发布报告接口", required = true) @RequestBody String result) throws IOException {
        Optional.ofNullable(result).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("数据为空"));
        String decodeJson = URLDecoder.decode(result, SystemConstant.CHARSET_NAME);
        log.info("calculate进来了,result:{}", decodeJson);
        PublishParams publishParams = JacksonUtil.readJson(decodeJson, PublishParams.class);
        publishParams.validParams();
        BasicSchool basicSchool = AuthThirdUtil.hasPermission();

        Boolean publishStatus = publishParams.getPublishStatus();
        PublishStatusEnum publishStatusEnum;
        if (publishStatus){
            publishStatusEnum = PublishStatusEnum.PUBLISH;
        }else {
            publishStatusEnum = PublishStatusEnum.UN_PUBLISH;
        }
        analyzeForReportService.publishReport(publishParams.getExamId(),publishParams.getCourseCode(),publishStatusEnum);
        return ResultUtil.ok(true);
    }


    @ApiOperation(value = "生成课程（试卷）分析报告接口测试")
    @ApiResponses({@ApiResponse(code = 200, message = "生成课程（试卷）分析报告接口", response = Object.class)})
    @RequestMapping(value = "/calculate_test", method = RequestMethod.POST)
    @Aac(auth = BOOL.FALSE)
    public Result calculateTest(@ApiParam(value = "考试id", required = true) @RequestParam Long examId,
                            @ApiParam(value = "科目编号", required = true) @RequestParam List<String> courseCode,
                            @ApiParam(value = "学校id", required = true) @RequestParam Long schoolId) throws IOException {
        CalculateParams calculateParams = new CalculateParams();
        calculateParams.setSchoolId(schoolId);
        calculateParams.setCourseCode(courseCode);
        calculateParams.setExamId(examId);
        courseCodeSyncTaskService.start(calculateParams);
        return ResultUtil.ok(true);
    }
}
