package com.ruoyi.web.controller.front;

import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.NewgaokaoType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.syzy.criteria.XkxcCriteria;
import com.ruoyi.syzy.domain.BBusiWishXkcx;
import com.ruoyi.syzy.domain.BCustomerXkcx;
import com.ruoyi.syzy.domain.BCustomerXkcxCourse;
import com.ruoyi.syzy.dto.XkxcSchemeDTO;
import com.ruoyi.syzy.service.IBBusiWishXkcxService;
import com.ruoyi.syzy.service.IBCustomerXkcxCourseService;
import com.ruoyi.syzy.service.IBCustomerXkcxService;
import com.ruoyi.web.service.AdminSelectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Api(tags = "生涯志愿-选科查询")
@RequestMapping("front/syzy/xkcx")
public class FrontSyzyXkcxController extends BaseController {
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IBBusiWishXkcxService xkcxService;
    @Autowired
    private IBCustomerXkcxCourseService xkcxCourseService;
    @Autowired
    private AdminSelectService adminSelectService;
    @Autowired
    private IBCustomerXkcxService customerXkcxService;

    @GetMapping("getSelectCourse")
    @ApiOperation("00 选科首选次选科目，如果是3+3则只填充course1")
    public AjaxResult getSelectCourse() {
        return AjaxResult.success(xkcxService.selectBBusiWishXkcxCourse());
    }

    @GetMapping("years")
    @ApiOperation("00 年份")
    public AjaxResult years() {
        List<Integer> years =xkcxService.selectBBusiWishXkcxYears(SecurityUtils.getLoginUser().getUser().getProvinceName());
        if(CollectionUtils.isEmpty(years)){
            years = JSONArray.parseArray(configService.selectConfigByKey("xkcx_years"), Integer.class);
        }
        return AjaxResult.success(years);
    }

    @GetMapping("list")
    @ApiOperation("01 查询列表")
    public TableDataInfo list(XkxcCriteria criteria, @ApiParam(value = "页数", example = "1") @RequestParam Integer pageNum,
        @ApiParam(value = "页大小", example = "15") @RequestParam Integer pageSize) {
        criteria.setUniversityIds(xkcxService.selectUniversityIds(criteria));
        startPage();
        List<BBusiWishXkcx> arr = null;
        logger.debug("xxxxxxxxxxxx:"+criteria.getCourse0());
        Boolean isDynamicHeader=true;
        if (Boolean.TRUE.equals(criteria.getCollect())||Boolean.TRUE.equals(criteria.getIsSelectCourse())) {
            if(null!=criteria.getQuerySource()&&criteria.getQuerySource()==2){
                //从学生选科的页面进入，只显示当前选科的roundId
                Integer roundId = adminSelectService.getSelectCourseRound();
                if(roundId==0){
                    throw new BaseException("未开启选科，无自选选科数据");
                }
                criteria.setRoundId(roundId);
            }
            arr = xkcxService.listCoursesByUser(criteria);
            isDynamicHeader = false ;
        } else if (StringUtils.isEmpty(criteria.getCourse1())){
            arr = xkcxService.listByMarjors(criteria);
        } else {
            arr = xkcxService.listByCourses(criteria);
        }

        if(isDynamicHeader){
            //动态表头
            Map<String,String> headerMap = new LinkedHashMap<String,String>(){
                {
                    put("universityName","院校名称");
                    put("marjorName","专业(类)名称");
                    put("marjorBelongs","专业备注");
                    put("level","专业层次");
                }
            };
            if(NewgaokaoType.isNotNewgaokao33(SecurityUtils.getLoginUser().getUser().getProvinceName())){
                headerMap.put("courseRemark0","首选科目范围");
                headerMap.put("courseRemark1","再选科目范围");

            }else {
                headerMap.put("courseRemark0","选考科目范围");
            }
            headerMap.put("year","年份");
            headerMap.put("collect","收藏");
            headerMap.put("isSelectCourse","选科收藏");

            return getDataTable(arr,headerMap);
        }

        return getDataTable(arr);
    }

    @GetMapping("collect/add")
    @ApiOperation("02 添加收藏")
    public AjaxResult addCollect(@ApiParam("收藏数据Id") @RequestParam Long refId) {
        xkcxService.addCollect(refId);
        return AjaxResult.success();
    }

    @GetMapping("collect/remove")
    @ApiOperation("03 取消收藏")
    public AjaxResult removeCollect(@ApiParam("收藏数据Id") @RequestParam Long refId) {
        xkcxService.removeCollect(refId);
        return AjaxResult.success();
    }


    @GetMapping("saveSelectCourse")
    @ApiOperation("025 添加/取消选科收藏")
    public AjaxResult addSelectCourse(@ApiParam("收藏数据Id") @RequestParam Long refId,
                                      @ApiParam("收藏或取消收藏") @RequestParam Boolean isSelectCourse) {
        this.saveSelectCourse(refId,isSelectCourse);
        return AjaxResult.success();
    }

    @GetMapping("scheme")
    @ApiOperation("04 根据选择的项目生成方案")
    public TableDataInfo schemeList(@ApiParam("专业Id") @RequestParam String ids) {
        List<String> idList = Arrays.asList(StringUtils.splitPreserveAllTokens(ids, ","));
        List<XkxcSchemeDTO> arr = xkcxService.listSchemeBySubmitId(idList);
        return getDataTable(arr);
    }

    @GetMapping("my")
    @ApiOperation("05 我的选科")
    public TableDataInfo schemeList() {
        List<XkxcSchemeDTO> arr = xkcxService.listMyScheme();
        return getDataTable(arr);
    }

    @PostMapping("scheme/add")
    @ApiOperation("06 添加方案")
    public AjaxResult addScheme(@RequestBody BCustomerXkcxCourse data) {
        try {
            if (StringUtils.isBlank(data.getCustomerCode())) {
                data.setCustomerCode(SecurityUtils.getLoginUser().getUser().getCode());
            }
        } catch (Exception ige) {
        }
        data.setCreateTime(new Date());
        xkcxCourseService.insertBCustomerXkcxCourse(data);
        return AjaxResult.success();
    }

    @GetMapping("scheme/df")
    @ApiOperation("07 设置默认")
    public AjaxResult setDf(@ApiParam("收藏数据Id") @RequestParam Long id, @ApiParam("是否默认") @RequestParam Boolean df) {
        BCustomerXkcxCourse entity = xkcxCourseService.selectBCustomerXkcxCourseById(id);
        entity.setDf(Boolean.TRUE.equals(df) ? 1 : 0);
        xkcxCourseService.updateBCustomerXkcxCourse(entity);
        return AjaxResult.success();
    }

    @GetMapping("scheme/remove")
    @ApiOperation("08 取消方案")
    public AjaxResult removeScheme(@ApiParam("数据Id") @RequestParam Long id) {
        xkcxCourseService.deleteBCustomerXkcxCourseById(id);
        return AjaxResult.success();
    }

    /**
     *  保存（添加或取消）选科收藏
     * @param refId
     * @param isSelectCourse
     */
    public void saveSelectCourse(Long refId,Boolean isSelectCourse) {
        String ucode = SecurityUtils.getLoginUser().getUser().getCode();
        BCustomerXkcx exam = new BCustomerXkcx();
        exam.setCustomerCode(ucode);
        exam.setIsSelectCourse(1);
        Integer roundId = adminSelectService.getSelectCourseRound();
        if(roundId==0){
            throw new BaseException("未开启选科，不能收藏");
        }
        exam.setRoundId(roundId);
        List<BCustomerXkcx> coll = new ArrayList<>();
        if(isSelectCourse){//为收藏时才限制
            coll = customerXkcxService.selectBCustomerXkcxList(exam);
            if(!CollectionUtils.isEmpty(coll)&&coll.size()>=6){
                //最多只能保存6条记录
                throw new BaseException("最多只能收藏6条选科记录");
            }
        }

        exam = new BCustomerXkcx();
        exam.setCustomerCode(ucode);
        exam.setSubmitId(refId);
        coll = customerXkcxService.selectBCustomerXkcxList(exam);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(coll)) {
            BCustomerXkcx entity = coll.get(0);
            entity.setIsSelectCourse(isSelectCourse?1:0);
            //收藏选科就一定收藏该记录
            if(null!=isSelectCourse&&isSelectCourse){
                entity.setStatus(1);
                entity.setRoundId(roundId);
            }else if(null!=isSelectCourse&&!isSelectCourse){
                entity.setRoundId(0);
            }
            customerXkcxService.updateBCustomerXkcx(entity);
        } else {
            BCustomerXkcx entity = new BCustomerXkcx();
            entity.setCustomerCode(ucode);
            entity.setSubmitId(refId);
            if(null!=isSelectCourse&&isSelectCourse){
                entity.setStatus(1);
            }else if(null!=isSelectCourse&&!isSelectCourse){
                entity.setRoundId(0);
            }
            entity.setIsSelectCourse(isSelectCourse?1:0);
            entity.setRoundId(roundId);
            entity.setCreateTime(new Date());
            customerXkcxService.insertBCustomerXkcx(entity);
        }
    }



}
