package com.ruoyi.web.controller.front;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BoolValues;
import com.ruoyi.common.enums.UserRegStatus;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.syzy.criteria.ZytbMarjorCriteriaNew;
import com.ruoyi.syzy.domain.BBusiWishRecords;
import com.ruoyi.syzy.dto.SubmitWishRecordDTO;
import com.ruoyi.syzy.dto.SubmitWishRecordDTO.SubmitWishRecordDetail;
import com.ruoyi.syzy.dto.ZytbBatch;
import com.ruoyi.syzy.service.IBBusiWishLocationSubmitsService;
import com.ruoyi.syzy.service.IBBusiWishRecordsService;
import com.ruoyi.web.domain.Constant;
import com.ruoyi.web.domain.ZytbDto;
import com.ruoyi.web.service.ZyService;
import com.ruoyi.web.util.VolunteerExporter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "生涯志愿-志愿填报")
@RequestMapping("front/syzy/zytb")
public class FrontSyzyZytbController extends BaseController {
    @Autowired
    private IBBusiWishLocationSubmitsService wishLocationSubmitsService;
    @Autowired
    private IBBusiWishRecordsService wishRecordsService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ZyService zyService;
    @Autowired
    ISysUserService sysUserService;
    @Autowired
    TokenService tokenService;

    @GetMapping("batches")
    @ApiOperation("01.填报批次")
    public TableDataInfo batches(@ApiParam("总分") @RequestParam Float score) {
        // 获取当前登录用户省份
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        String location = sysUser.getLocation();
        List<ZytbBatch> batchs = wishLocationSubmitsService.batches(location, score, zyService.getExamMajor());
        return getDataTable(batchs);
    }

    @PostMapping("save")
    @ApiOperation("04.志愿保存")
    public AjaxResult save(@RequestBody SubmitWishRecordDTO data) {
        if (null == data.getDetail().getYear()) {
            data.getDetail().setYear(DateUtils.getCurrentYear());
        }
        //体验卡在0615~0831之间不能使用
        String msg = zyService.limitExperienceCard(SecurityUtils.getLoginUser().getUser());
        if(StringUtils.isNotEmpty(msg)){
            throw new BaseException(msg);
        }
        SysUser u = SecurityUtils.getLoginUser().getUser();
        SubmitWishRecordDTO.User us = new SubmitWishRecordDTO.User();
        us.setName(u.getNickName());
        us.setSex(u.getSex());
        us.setProvinceName(u.getLocation());
        us.setExamType(u.getExamType().name());
        us.setExamMajor(String.valueOf(u.getExamMajor()));
        us.setExamMajorName(u.getExamMajorName());
        data.setUserSnapshot(us);
        if(StringUtils.isBlank(data.getDetail().getMode())) {
            data.getDetail().setMode(us.getExamMajorName());
        }
        wishRecordsService.save(data);
        return AjaxResult.success("保存成功", data.getId());
    }

    @GetMapping("recordDetail")
    @ApiOperation("02.查询明细")
    public AjaxResult recordDetail(@ApiParam(value = "志愿id", example = "1") @RequestParam Long wishResId) {
        BBusiWishRecords wishRecords = wishRecordsService.selectBBusiWishRecordsById(wishResId);
        if (null != wishRecords) {
            SubmitWishRecordDetail detail = JSON.parseObject(wishRecords.getDetail(), SubmitWishRecordDetail.class);
            List<String> summary = new ArrayList<String>();
            detail.getBatch().getWishes().forEach(wish -> {
                summary.add(String.format("[%s]%s", wish.getCode(), wish.getName()));
            });
            SubmitWishRecordDTO.User us = JSON.parseObject(wishRecords.getUserSnapshot(), SubmitWishRecordDTO.User.class);
            wishRecords.setMode(us.getExamMajorName());
            wishRecords.setScore(detail.getScore());
            wishRecords.setSummary(summary);
        }
        return AjaxResult.success("查询成功", wishRecords);
    }

    @GetMapping("record")
    @ApiOperation("05.我的志愿表")
    public TableDataInfo record(@ApiParam(value = "页数", example = "1") @RequestParam Integer pageNum,
        @ApiParam(value = "页大小", example = "15") @RequestParam Integer pageSize) {
        startPage();
        String customerCode = SecurityUtils.getLoginUser().getUser().getCode(); // TODO 标识
        BBusiWishRecords exam = new BBusiWishRecords();
        exam.setCustomerCode(customerCode);
        exam.setStatus(1);
        List<BBusiWishRecords> list = wishRecordsService.selectBBusiWishRecordsList(exam);
        list.forEach(row -> {
//            row.setBatchName(BatchUtil.getLabel(Integer.valueOf(row.getBatch())));
            SubmitWishRecordDetail detail = JSON.parseObject(row.getDetail(), SubmitWishRecordDetail.class);
            List<String> summary = new ArrayList<String>();
            detail.getBatch().getWishes().forEach(wish -> {
                summary.add(String.format("[%s]%s", wish.getCode(), wish.getName()));
            });
            SubmitWishRecordDTO.User us = JSON.parseObject(row.getUserSnapshot(), SubmitWishRecordDTO.User.class);
            row.setMode(us.getExamMajorName());
            row.setScore(detail.getScore());
            row.setSummary(summary);
        });
        return getDataTable(list);
    }

    @GetMapping("record/del")
    @ApiOperation("06.删除我的志愿表")
    public AjaxResult removeRecord(@ApiParam(value = "页数", example = "1") @RequestParam Long id) {
        wishRecordsService.deleteBBusiWishRecordsById(id);
        return success("删除成功");
    }


    @ApiOperation("20.获取地区科目年度")
    @RequestMapping(value = "/getVoluntaryHeaders", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult getVoluntaryHeaders(@ApiParam(value = "年度") @RequestParam(required = false) Integer year, @ApiParam(value = "组合") @RequestParam String mode, Boolean isMock) {
        if(null==isMock){
            isMock = false;
        }
        AjaxResult ajaxResult = AjaxResult.success(zyService.getVoluntaryHeaders(isMock,year, mode.split(",")[0]));
        ajaxResult.put("isMock", isMock);
        return ajaxResult;
    }

    @ApiOperation("21.获取推荐志愿")
    @RequestMapping(value = "/getRecommendVoluntary", method = {RequestMethod.POST})
    public TableDataInfo getRecommendVoluntary(@RequestBody ZytbMarjorCriteriaNew query, HttpServletResponse response,
                                               @ApiParam(value = "页数", example = "1") @RequestParam Integer pageNum,
                                               @ApiParam(value = "页大小", example = "5") @RequestParam Integer pageSize) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (UserRegStatus.isNotVip()) {
            pageNum = 1;
            pageSize = 1;
        }
        if (!BoolValues.isFalse(user.getScoreLock())) {
            //在锁分阶段，强行将分数及mode重置为用户所填写锁定的值
            query.setScore(user.getScore());
        }
        query.setMode(String.valueOf(user.getExamMajor()));
        if (null != query.getWishResId() && query.getWishResId() > 0) {
            return getDataTable(zyService.filterResEmptyHistory(zyService.getRecommendVoluntaryRes(query.getWishResId(), pageNum, pageSize)));
        }

        //体验卡在0615~0831之间不能使用、非高三卡不能使用
        String msg = zyService.limitExperienceCard(SecurityUtils.getLoginUser().getUser());
        if(StringUtils.isNotEmpty(msg)){
            throw new BaseException(msg);
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = new SysUser();
        if (null != query.getSeatInput() && !query.getSeatInput().equals(user.getSeatInput())) { // 更新最后的 SeatInput
            sysUser.setUserId(user.getUserId());
            sysUser.setSeatInput(query.getSeatInput());
            loginUser.getUser().setSeatInput(query.getSeatInput());
        }
        if (!BoolValues.isTrue(user.getScoreLock()) && query.getScore() != null && !query.getScore().equals(user.getScore())) {
            //-1（中间状态），0（非锁分状态）时可以修改
            sysUser.setUserId(user.getUserId());
            sysUser.setScore(query.getScore());
            user.setScore(query.getScore());
        }
        if (null != sysUser.getUserId()) {
            sysUserService.updateUserProfile(sysUser);
            tokenService.setLoginUser(loginUser);
        }
        return getDataTable(zyService.filterResEmptyHistory(zyService.getRecommendVoluntary(query, pageNum, pageSize)));
    }


    @ApiOperation("22.获取推荐志愿明细")
    @RequestMapping(value = "/getVoluntaryMarjors", method = {RequestMethod.POST})
    public AjaxResult getVoluntaryMarjors(@RequestBody ZytbDto.ZytbVoluntaryMarjorCond query) {
        if (null != query.getWishResId() && query.getWishResId() > 0) {
            return AjaxResult.success(zyService.filterEmptyHistory(zyService.getVoluntaryMarjorsRes(query.getWishResId(), query.getCollegeCode(), query.getJCode())));
        }
        return AjaxResult.success(zyService.filterEmptyHistory(zyService.getVoluntaryMarjors(query)));
    }


    @ApiOperation("23.获取模拟志愿初始参数-分数区间、科类（物理历史、理科文科）")
    @RequestMapping(value = "/getVoluntaryData", method = {RequestMethod.GET,RequestMethod.POST})
    public AjaxResult getVoluntaryData(String provinceName,Integer year) {
        Map<String,Object> resultMap = new HashMap<>();
        try {
//            JSONObject jsonObject= SecurityUtils.getLoginUser().getUser().getVoluntaryParam();
            String voluntaryCount= configService.selectConfigByKey("voluntary.num");
            if(StringUtils.isNotEmpty(voluntaryCount)){
                JSONArray array = JSONArray.parseArray(voluntaryCount);
                array.stream().forEach(item->{
                    JSONObject jsonObject=(JSONObject) item;
                    if(jsonObject.getString("location").trim().contains(SecurityUtils.getLoginUser().getUser().getLocation().trim())){
                        jsonObject.entrySet().forEach(e->{
                            resultMap.put(e.getKey(),e.getValue());
                        });
                        return;
                    }
                });
            }
        }catch (Exception e){
            logger.debug("获取志愿参数失败",e);
        }

        String examMajor = zyService.getExamMajor();
        Integer maxScore = getMaxScore(examMajor);
        resultMap.put("maxScore",maxScore);
        resultMap.put("minScore",0);
        return AjaxResult.success(resultMap);
    }

    private Integer getMaxScore(String examMajor) {
        String scores = configService.selectConfigByKey(Constant.CFG_MAJOR_SCORES);
        if(StringUtils.isBlank(scores)) {
            scores = "{'20': 300, '0': 750}";
        }
        JSONObject scoreObj = JSONObject.parseObject(scores);
        Integer maxScore;
        if(null == (maxScore = scoreObj.getInteger(examMajor)) && null == (maxScore = scoreObj.getInteger("0"))) {
            maxScore = 750;
        }
        return maxScore;
    }

    @GetMapping("/export")
    public void export(@RequestParam Long wishResId, HttpServletResponse response)
    {
        Map dataMap = Maps.newHashMap();
        List<ZytbDto.ZytbVolunteerRes> volunteerResList = zyService.getRecommendVoluntaryRes(wishResId, 1, 100, dataMap);
        SubmitWishRecordDetail detail = (SubmitWishRecordDetail) dataMap.get("detail");
        BBusiWishRecords record = (BBusiWishRecords) dataMap.get("record");
        String location = (String) dataMap.get("location");
        Integer currYear = (Integer) dataMap.get("currYear");
        Integer currSubmitYear = (Integer) dataMap.get("currSubmitYear");
        Integer seat = (Integer) dataMap.get("seat");
        VolunteerExporter.export(location, record, detail, currYear, currSubmitYear, seat, volunteerResList, response);
    }
}
