package com.ruoyi.web.controller.api;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.domain.Vo.QueryArtilceCommentListResponse;
import com.ruoyi.mall.domain.Vo.ReportIntelligenceVo;
import com.ruoyi.mall.domain.Vo.SchoolMajorVO;
import com.ruoyi.mall.mapper.MallAcceptRateSettingMapper;
import com.ruoyi.mall.service.*;
import com.ruoyi.mall.service.impl.MallCountMethodServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**一键生成志愿
 *
 */
@RestController
@RequestMapping("/api/IntelligenceReport")
public class ApiIntelligenceReportController extends BaseController {

    @Resource
    private IMallSchoolService mallSchoolService;
    @Resource
    private IMallMemberUserService mallMemberUserService;
    @Resource
    private IMallSchoolAcceptService mallSchoolAcceptService;
    @Resource
    private MallAcceptRateSettingMapper mallAcceptRateSettingMapper;
    @Resource
    private IMallCountMethodService mallCountMethodService;
    @Resource
    private IMemberReportIntelligenceService memberReportIntelligenceService;
    @Resource
    private IReportIntelligenceService reportIntelligenceService;

    /**验证成绩完善度 */
    @GetMapping("/checkScore")
    public AjaxResult checkScore(@RequestParam @NotNull(message = "IntelligenceReport.checkScore.memberId.isnull") Long memberId){
        try{//文化成绩 联考成绩
            MallMemberUser mallMemberUser = mallMemberUserService.selectMallMemberUserById(memberId);
            if(null == mallMemberUser || null == mallMemberUser.getMajorScore() || null == mallMemberUser.getCultureScore() ){
                return AjaxResult.error("请先完善 我的-成绩管理 !");
            }
            return AjaxResult.success("验证成功");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("服务器异常");
        }
    }
    /**根据批次、个人成绩 生成志愿报告*/
        //结果 生成一个报告和 一些志愿条目 分别在两张表里
    @GetMapping("/generateIntelligenceReport")
    public AjaxResult generateIntelligenceReport(@RequestParam @NotNull(message = "IntelligenceReport.generateIntelligenceReport.memberId.isnull") Long memberId,
                                                 @RequestParam @NotNull(message = "IntelligenceReport.generateIntelligenceReport.batchId.isnull") Long batchId){
        try{//返回报告{志愿条目}列表
            MallMemberUser mallMemberUser = mallMemberUserService.selectMallMemberUserById(memberId);
            if(null == mallMemberUser || null == mallMemberUser.getMajorScore() || null == mallMemberUser.getCultureScore() ){
                return AjaxResult.error("请先完善 我的-成绩管理 !");
            }
            //基础数据
            List<ReportIntelligenceVo> listForIntelligence = mallSchoolAcceptService.getListForIntelligence(mallMemberUser.getSubjectType(),batchId);
            if(null != listForIntelligence && listForIntelligence.size()>0){
               int result =memberReportIntelligenceService.generateInsertReportAndItem(listForIntelligence, mallMemberUser, batchId, memberId,"0");
               return AjaxResult.success("志愿报告已经生成");
            }else {
                if(batchId.equals(4L)){
                    return AjaxResult.error(500, "专科批次暂无数据");
                }
                return AjaxResult.error(500, "数据获取异常");
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("服务器异常");
        }

    }



    /** 报告列表*/
    @GetMapping("/getReportList")
    public AjaxResult getReportList(@RequestParam(defaultValue = "1") Integer pageNum,
                                    @RequestParam(defaultValue = "10") Integer pageSize,
                                    @RequestParam @NotNull(message = "IntelligenceReport.getReportList.memberId.isnull") Long memberId){
        try{//
            PageHelper.startPage(pageNum, pageSize);
            MemberReportIntelligence memberReportIntelligence = new MemberReportIntelligence();
            memberReportIntelligence.setUserId(memberId);
            //智能报告类型
            memberReportIntelligence.setReportType("0");
            List<MemberReportIntelligence> memberReportIntelligences = memberReportIntelligenceService.selectMemberReportIntelligenceList(memberReportIntelligence);
            PageInfo<MemberReportIntelligence> pageInfo = new PageInfo<>(memberReportIntelligences);
            return AjaxResult.success().put("data", pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("服务器异常");
        }
    }
    /**报告详情*/
    @GetMapping("/getReportDetail")
    public AjaxResult getReportDetail(@RequestParam(defaultValue = "1") Integer pageNum,
                                      @RequestParam(defaultValue = "50") Integer pageSize,
                                      @RequestParam @NotNull(message = "IntelligenceReport.getReportDetail.reportId.isnull") Long reportId){
        try{//
            //报告
            MemberReportIntelligence report = memberReportIntelligenceService.selectMemberReportIntelligenceByReportId(reportId);
            if(null == report){
                return AjaxResult.error("找不到报告信息");
            }
            //用户成绩
            MallMemberUser user = mallMemberUserService.selectMallMemberUserById(report.getUserId());
            if(null == user || null == user.getMajorScore() || null == user.getCultureScore() ){
                return AjaxResult.error("请先完善 我的-成绩管理 !");
            }

            // 查报告志愿条目
            ReportIntelligence reportItem = new ReportIntelligence();
            reportItem.setReportId(reportId);


            List<ReportIntelligenceVo> vos = reportIntelligenceService.selectReportItemVoList(reportItem,user);
            if(null != vos && vos.size()>0){
                Page page = new Page<>(pageNum,pageSize);
                //为Page类中的total属性赋值
                int total = vos.size();
                page.setTotal(total);
                //计算当前需要显示的数据下标起始值
                int startIndex = (pageNum - 1) * pageSize;
                int endIndex = Math.min(startIndex + pageSize,total);
                //从链表中截取需要显示的子链表，并加入到Page
                page.addAll(vos.subList(startIndex,endIndex));
                //以Page创建PageInfo
                PageInfo pageInfo = new PageInfo<>(page);
                return AjaxResult.success().put("data",pageInfo);
            }else{
                PageInfo<ReportIntelligenceVo> pageInfo = new PageInfo<>(new ArrayList<>());
                return AjaxResult.success().put("data", pageInfo);
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("服务器异常");
        }
    }

    /**删除志愿
     *
     * @param itemId 志愿id
     * @return
     */
    @GetMapping("/delReportItem")
    public AjaxResult delReportItem(@RequestParam@NotNull(message = "IntelligenceReport.delItem.itemId.isnull")Long itemId){
        try {
            int i = reportIntelligenceService.deleteReportIntelligenceByItemId(itemId);
            if(i>0) {
                return AjaxResult.success("志愿删除成功");
            }else{
                return AjaxResult.error(500,"志愿删除失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("服务器异常");
        }
    }

    /**修改志愿顺序
     *
     */
    @PostMapping("/sortItem")
    public AjaxResult sortItem(@RequestBody  Long[] ids){
        try{
            List<ReportIntelligence> update = new ArrayList<>();
            int sort = 1;
            for (Long id : ids) {
                ReportIntelligence u = new ReportIntelligence();
                u.setItemId(id);
                u.setSort(sort++);
                update.add(u);
            }
            // 批量修改志愿条目顺序 by itemId
            int i = reportIntelligenceService.updateItemsSortByItemIds(update);
            return AjaxResult.success("顺序更新成功");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("服务器异常");
        }
    }
    /**删除报告*/
    @GetMapping("/delReport")
    public AjaxResult delReport(@RequestParam@NotNull(message = "IntelligenceReport.delReport.reportId.isnull")Long reportId){
        try {
            int i = memberReportIntelligenceService.deleteMemberReportIntelligenceByReportId(reportId);
            if(i>0) {
                return AjaxResult.success("报告删除成功");
            }else{
                return AjaxResult.error(500,"报告删除失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("服务器异常");
        }
    }

    /**重新生成*/
    // 删除原报告 新增报告
    //结果 生成一个报告和 一些志愿条目 分别在两张表里
    @GetMapping("/reGenerateReport")
    public AjaxResult reGenerateReport(@RequestParam(defaultValue = "1") Integer pageNum,
                                       @RequestParam(defaultValue = "10") Integer pageSize,
                                       @RequestParam @NotNull(message = "IntelligenceReport.reGenerateReport.memberId.isnull") Long memberId,
                                       @RequestParam @NotNull(message = "IntelligenceReport.reGenerateReport.batchId.isnull") Long batchId,
                                       @RequestParam @NotNull(message = "IntelligenceReport.reGenerateReport.reportId.isnull") Long reportId){
        try{//返回报告{志愿条目}列表
            MallMemberUser mallMemberUser = mallMemberUserService.selectMallMemberUserById(memberId);
            if(null == mallMemberUser || null == mallMemberUser.getMajorScore() || null == mallMemberUser.getCultureScore() ){
                return AjaxResult.error("请先完善 我的-成绩管理 !");
            }

            //基础数据
            List<ReportIntelligenceVo> listForIntelligence = mallSchoolAcceptService.getListForIntelligence(mallMemberUser.getSubjectType(),batchId);
            if(null != listForIntelligence && listForIntelligence.size()>0){
                Long newReportId =memberReportIntelligenceService.reGenerateInsertReportAndItem(listForIntelligence, mallMemberUser, batchId, memberId,reportId,"0");
                //返回

                // 查报告志愿条目
                ReportIntelligence reportItem = new ReportIntelligence();
                reportItem.setReportId(newReportId);

                PageHelper.startPage(pageNum, pageSize);
                List<ReportIntelligenceVo> vos = reportIntelligenceService.selectReportItemVoList(reportItem,mallMemberUser);
                PageInfo<ReportIntelligenceVo> pageInfo = new PageInfo<>(vos);
                return AjaxResult.success().put("data", pageInfo);
            }else {
                return AjaxResult.error(500, "数据获取异常");
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("服务器异常");
        }

    }
}
