package com.ruoyi.web.controller.api;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.mall.domain.Bo.CheckOutReportBo;
import com.ruoyi.mall.domain.Bo.CheckingOutParamBo;
import com.ruoyi.mall.domain.MallMemberUser;
import com.ruoyi.mall.domain.MemberReportIntelligence;
import com.ruoyi.mall.domain.ReportDraft;
import com.ruoyi.mall.domain.ReportIntelligence;
import com.ruoyi.mall.domain.Vo.*;
import com.ruoyi.mall.mapper.MallMemberUserMapper;
import com.ruoyi.mall.service.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**志愿填报 自主选择*/
@RestController
@RequestMapping("/api/CheckingOut")
public class ApiCheckingOutController {

    @Resource
    private MallMemberUserMapper mallMemberUserMapper;
    @Resource
    private CheckingOutService checkingOutService;
    @Resource
    private IMemberReportIntelligenceService memberReportIntelligenceService;
    @Resource
    private IMallMemberUserService mallMemberUserService;
    @Resource
    private IMallSchoolAcceptService mallSchoolAcceptService;
    @Resource
    private IReportIntelligenceService reportIntelligenceService;
    @Resource
    private IReportDraftService reportDraftService;
    @Resource
    private IMallAcceptPlanService mallAcceptPlanService;

    /**新增 草稿志愿
     *
     * @param reportDraft 已有报告必传报告id
     * @return
     */
    @PostMapping("/addDraft")
    public AjaxResult addDraft(@RequestBody ReportDraft reportDraft){
        try{

          int i  =  reportDraftService.insertReportDraft(reportDraft);
          return AjaxResult.success("ok");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("公告列表查询异常");
        }
    }

    /**删除 草稿志愿
     *
     * @param reportDraft 必传
     * @return
     */
    @PostMapping("/delDraft")
    public AjaxResult delDraft(@RequestBody ReportDraft reportDraft){
        try{
            //要删除的志愿在正式表里
            List<ReportDraft> drafts = reportDraftService.selectReportDraftList(reportDraft);
            if(drafts.size()>0){//要删除的在草稿表里
                int i  =  reportDraftService.batchDelete(reportDraft);
            }
            if(null != reportDraft.getReportId()){
                ReportIntelligence param = new ReportIntelligence();
                param.setUserId(reportDraft.getUserId());
                param.setReportId(reportDraft.getReportId());
                param.setBatchId(reportDraft.getBatchId());
                param.setSchoolId(reportDraft.getSchoolId());
                param.setMajorId(reportDraft.getMajorId());
                List<ReportIntelligence> list = reportIntelligenceService.selectReportIntelligenceList(param);
                // 删除正式表里的数据
                if(null != list && list.size()>0){
                    int i = reportIntelligenceService.deleteReportIntelligenceByItemId(list.get(0).getItemId());
                }
            }

            return AjaxResult.success("ok");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("公告列表查询异常");
        }
    }

    /**根据筛选 查询院校专业
     *
     * @param bo
     * @return
     */
    // 并计算专业录取率
    @PostMapping("/getDataList")
    public AjaxResult getDataList(@RequestBody CheckingOutParamBo bo) {
        try{
            // 查询用户成绩
            MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(bo.getMemberId());
            if (ObjectUtils.isEmpty(mallMemberUser.getMajorScore()) || ObjectUtils.isEmpty(mallMemberUser.getCultureScore())){
                return AjaxResult.error("请先录入成绩");
            }
            List<SchoolMajorVO> result = new ArrayList<>();

            Integer pageNum = bo.getPageNum();
            Integer pageSize = bo.getPageSize();
            //完全新增报告志愿 查询列表
//            PageHelper.startPage(pageNum,pageSize);

            if(null != mallMemberUser.getRateFlag() && mallMemberUser.getRateFlag() == 1){
                // 已更新录取率数据
                List<SchoolMajorVO> list = checkingOutService.schoolOriginal2(bo, mallMemberUser);
                return AjaxResult.success(new PageInfo<>(list));

            }else{
                if ( null != mallMemberUser.getCultureScore() && null != mallMemberUser.getMajorScore()){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            mallMemberUserService.updateRate(mallMemberUser.getId(), mallMemberUser.getCultureScore(), mallMemberUser.getMajorScore(), mallMemberUser.getSubjectType());
                        }
                    }).start();
                }

                result = checkingOutService.schoolOriginal(bo, mallMemberUser);
//
                if(null != result && result.size()>0){
                    result = result.stream().filter(s -> s.getRateType()!= -2).collect(Collectors.toList());

                    Page page = new Page<>(pageNum,pageSize);
                    //为Page类中的total属性赋值
                    int total = result.size();
                    page.setTotal(total);
                    //计算当前需要显示的数据下标起始值
                    int startIndex = (pageNum - 1) * pageSize;
                    int endIndex = Math.min(startIndex + pageSize,total);
                    //从链表中截取需要显示的子链表，并加入到Page
                    if(result.size()>pageSize) {
                        page.addAll(result.subList(startIndex, endIndex));
                    }else{
                        page.addAll(result);
                    }
                    //以Page创建PageInfo
                    PageInfo pageInfo = new PageInfo<>(page);
                    return AjaxResult.success().put("data",pageInfo);
                }else{
                    PageInfo<SchoolMajorVO> pageInfo = new PageInfo<>(new ArrayList<>());
                    return AjaxResult.success().put("data", pageInfo);
                }

            }


        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("院校专业列表查询异常");
        }
    }
    /**获取 添加志愿 小分类数字*/
    // 并计算专业录取率
    @PostMapping("/getTypeData")
    public AjaxResult getTypeData(@RequestBody CheckingOutParamBo bo) {
        try{
            // 查询用户成绩
            MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(bo.getMemberId());
            if (ObjectUtils.isEmpty(mallMemberUser.getMajorScore()) || ObjectUtils.isEmpty(mallMemberUser.getCultureScore())){
                return AjaxResult.error("请先录入成绩");
            }
            if (null != mallMemberUser.getRateFlag() && mallMemberUser.getRateFlag() == 1){
                // 录取率数据已更新完毕
                return  AjaxResult.success(checkingOutService.tagNum2(bo, mallMemberUser));

            }else{
                return  AjaxResult.success(checkingOutService.tagNum(bo, mallMemberUser));
            }


        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("菜单标签列表查询异常");
        }
    }

    /**生成自主选择志愿报告*/ // [{schoolId:,majorId:}]
    @PostMapping("/generateReport")
    public AjaxResult generateReport(@RequestBody CheckOutReportBo bo){
        try{
            //ReportIntelligenceVo[] listForIntelligence, MallMemberUser mallMemberUser, Long batchId, Long memberId,String reportType
            MallMemberUser mallMemberUser = mallMemberUserService.selectMallMemberUserById(bo.getUserId());
            if(null == mallMemberUser || null == mallMemberUser.getMajorScore() || null == mallMemberUser.getCultureScore() ){
                return AjaxResult.error("请先完善 我的-成绩管理 !");
            }
            //新增数据
            //取 草稿里的数据
            ReportDraft param = new ReportDraft();
            param.setUserId(bo.getUserId());
            param.setBatchId(bo.getBatchId());
            if(null != bo.getReportId()){
                param.setReportId(bo.getReportId());
            }
            List<ReportDraft> drafts = reportDraftService.selectReportDraftList(param);
            for (ReportDraft draft : drafts) {
                draft.setLinkId(draft.getMajorId());  // 关联新的专业id
            }
            List< ReportIntelligenceVo>  items = drafts.stream().map(d -> BeanUtil.toBean(d,ReportIntelligenceVo.class)).collect(Collectors.toList());
            //存
            //完全新增 新增报告+志愿条目
            if(null == bo.getReportId()){
                //新增报告 和 条目
                memberReportIntelligenceService.insertChoiceReportAndItem(items,mallMemberUser,bo.getBatchId(),mallMemberUser.getId(),"1"); //报告类型 0智能生成 1自主选择
            }else{//在原有基础上新增 只新增志愿条目
                if(null != items && items.size()>0 ){
                    int  sort = 1;
                    for (ReportIntelligenceVo vo : items) {
                        vo.setSort(sort++);
                        vo.setBatchId(bo.getBatchId());
                        vo.setCreateTime(DateUtils.getNowDate());
                        vo.setReportId(bo.getReportId());
                        vo.setUserId(mallMemberUser.getId());
                    }
                    //新增志愿条目
                    //返回展示数据 方便后期 删条目 新增条目 调排序
                    int itemI = reportIntelligenceService.insertBatch(items);
                }
            }
            //删草稿数据
            int i = reportDraftService.batchDelete(param);
            return AjaxResult.success("ok");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("生成列表异常");
        }
    }
    /** 手动志愿报告列表*/
    @GetMapping("/getReportList")
    public AjaxResult getReportList(@RequestParam(defaultValue = "1") Integer pageNum,
                                    @RequestParam(defaultValue = "10") Integer pageSize,
                                    @NotNull(message = "getReportList.userId.isnull")Long memberId){
        try{//
            PageHelper.startPage(pageNum, pageSize);
            MemberReportIntelligence memberReportIntelligence = new MemberReportIntelligence();
            memberReportIntelligence.setUserId(memberId);
            //智能报告类型
            memberReportIntelligence.setReportType("1");
            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 = "10") 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);

            PageHelper.startPage(pageNum, pageSize);
            List<ReportIntelligenceVo> vos = reportIntelligenceService.selectReportItemVoList(reportItem,user);
            PageInfo<ReportIntelligenceVo> pageInfo = new PageInfo<>(vos);
            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("服务器异常");
        }
    }
    /**删除报告（重新生成）*/
    @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("服务器异常");
        }
    }
    /**修改志愿顺序
     *
     */
    @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("/getChangeBatch")
    public AjaxResult sortItem(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               @RequestParam @NotNull(message = "CheckingOut.getChangeBatch.batchId.isnull") Long batchId,
                               @RequestParam @NotNull(message = "CheckingOut.getChangeBatch.userId.isnull") Long userId){
        try{
            //用户成绩
            MallMemberUser user = mallMemberUserService.selectMallMemberUserById(userId);
            if(null == user || null == user.getSubjectType() ){
                return AjaxResult.error("请先完善 我的-成绩信息!");
            }
            AcceptChangeVo result = mallAcceptPlanService.getChangeBatch(pageNum,pageSize,batchId,user);
            return AjaxResult.success().put("data",result);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("服务器异常");
        }
    }

    /** 已加入志愿数 */
    @GetMapping("/num")
    public AjaxResult num(@NotNull(message = "api.CheckingOut.num.batchId.isnull") Long batchId, @NotNull(message = "api.CheckingOut.num.userId.isnull") Long userId,Long reportId){
        try{
            //用户成绩
            MallMemberUser user = mallMemberUserService.selectMallMemberUserById(userId);
            if(null == user || null == user.getMajorScore() || null == user.getCultureScore() ){
                return AjaxResult.error("请先完善 我的-成绩管理 !");
            }
            // 已添加志愿列表  有reportId 查reportId+草稿总和  没有reportid 只查草稿总和
            //报告全部志愿 正式+草稿
                //取 草稿里的数据
                ReportDraft param = new ReportDraft();
                param.setUserId(userId);
                param.setBatchId(batchId);
                if(null != reportId){
                    param.setReportId(reportId);
                }
                List<ReportDraft> drafts = reportDraftService.selectReportDraftList(param);
                List< ReportIntelligenceVo>  items = drafts.stream().map(d -> BeanUtil.toBean(d,ReportIntelligenceVo.class)).collect(Collectors.toList());
                //有reportId 取报告里的数据
                if(null != reportId){
                    ReportIntelligence reportIntelligence = new ReportIntelligence();
                    reportIntelligence.setReportId(reportId);
                    List<ReportIntelligence> reportIntelligences = reportIntelligenceService.selectReportIntelligenceList(reportIntelligence);
                    if(null != reportIntelligences && reportIntelligences.size()>0){
                        List<ReportIntelligenceVo> collect = reportIntelligences.stream().map(s -> BeanUtil.toBean(s, ReportIntelligenceVo.class)).collect(Collectors.toList());
                        items.addAll(collect);
                    }
                }
                CheckOutTagVo result = checkingOutService.num(items,user,batchId);


            return AjaxResult.success().put("data",result);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("服务器异常");
        }
    }

    /**填报志愿 卡片组
     *
     * @param userId 当前用户id
     * @return
     */
    @GetMapping("/getCardData")
    public AjaxResult getCardData(@NotNull(message = "cardData.userId.isNull")Long userId) {
        try{
            // 查询用户成绩
            MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(userId);
            if (ObjectUtils.isEmpty(mallMemberUser.getMajorScore()) || ObjectUtils.isEmpty(mallMemberUser.getCultureScore())){
                return AjaxResult.error("请先录入成绩");
            }
            //ReportCardVo
            List<ReportCardVo> reportCardVos = checkingOutService.cardData(mallMemberUser);
            return AjaxResult.success().put("data",reportCardVos);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("菜单标签列表查询异常");
        }
    }

    /** 报告审核状态 和 评语
     *
     * @param reportId 报告编号
     * @return
     */
    @GetMapping("/getReportCheckData")
    public AjaxResult getReportCheckData(@NotNull(message = "getReportCheckData.reportId.isNull")Long reportId) {
        try{
            //Report
            MemberReportIntelligence memberReportIntelligence = memberReportIntelligenceService.selectMemberReportIntelligenceByReportId(reportId);
            return AjaxResult.success().put("data",memberReportIntelligence);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("菜单标签列表查询异常");
        }
    }

}
