package com.ruoyi.web.controller.front;


import com.ruoyi.common.annotation.Anonymous;
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.core.text.Convert;
import com.ruoyi.common.enums.ExamType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.content.VistorContextHolder;
import com.ruoyi.sy.domain.*;
import com.ruoyi.sy.service.ISyMajorCareerProspectsService;
import com.ruoyi.sy.service.ISyMajorOverviewService;
import com.ruoyi.sy.service.ISyMajorService;
import com.ruoyi.sy.service.ISyVocationalService;
import com.ruoyi.syzy.domain.BCustomerMarjors;
import com.ruoyi.syzy.domain.TreeSelectVocational;
import com.ruoyi.syzy.dto.UniversitiesCondDTO;
import com.ruoyi.syzy.service.IBBusiWishUniversitiesService;
import com.ruoyi.syzy.service.IBCustomerMarjorsService;
import com.ruoyi.util.ConstantUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Api(tags = "前端-三库-专业")
@RestController
@RequestMapping("front/major/")
public class FrontSyMajorRelationController extends BaseController {
    @Autowired
    private ISyMajorCareerProspectsService majorCareerProspectsService;
    @Autowired
    private ISyMajorOverviewService syMajorOverviewService;
    @Autowired
    private ISyMajorService syMajorService;
    @Autowired
    private ISyVocationalService vocationalService;
    @Autowired
    private FrontUniversitiesController universitiesController;
    @Autowired
    private IBCustomerMarjorsService customerMarjorsService;
    @Autowired
    private IBBusiWishUniversitiesService universitiesService;

    /**
     * code在此处表示专业编码 name表示学校名称
     * @param code
     * @return
     */
    @GetMapping("getUniversityByCode")
    @ApiOperation("03 根据专业查找所开设院校--废弃")
    @Anonymous
    public TableDataInfo getUniversityByCode(@RequestParam(required = true) String code,
                                             @ApiParam(value = "页数", example = "1") @RequestParam Integer pageNum,
                                             @ApiParam(value = "页大小", example = "15") @RequestParam Integer pageSize) {
//        List<BBusiWishUniversitiesProfession> syMajorUniversityList = universitiesService.selectBBusiWishUniversitiesProfessionByCode(code);
        UniversitiesCondDTO cond = new UniversitiesCondDTO();
        cond.setMajorCodes(code);
        //是否收藏
        return getDataTable(universitiesController.getUniversitiesList(cond,VistorContextHolder.getLocation(),pageNum,pageSize));
    }

    @GetMapping("getMajorOverviewByCode")
    @ApiOperation("02 根据三级专业编码获取专业概况")
    @Anonymous
    public AjaxResult getMajorOverviewByCode(@RequestParam(required = true) String code) {
        code = StringUtils.getNumeric(code);//过滤字母
        String examTypeData = ConstantUtil.getExamTypeData(VistorContextHolder.getExamType().title());
        SyMajorOverview syMajorOverview = syMajorOverviewService.selectSyMajorOverviewByCode(examTypeData, code);
        if(StringUtils.isNull(syMajorOverview)){
            return AjaxResult.success(new SyMajorCareerProspects());
        }
        //是否收藏
        SyMajor syMajor = syMajorService.selectSyMajorByCode(code);
        Boolean isCollect = false;
        if (null!=syMajor&&SecurityUtils.hasLoginUser()){
            syMajorOverview.setMarjorId(syMajor.getId());
            BCustomerMarjors query = new BCustomerMarjors().setStatus(1).setMarjorId(syMajor.getId()).setCustomerCode(SecurityUtils.getLoginUser().getUser().getCode());
            if(CollectionUtils.isNotEmpty(customerMarjorsService.selectBCustomerMarjorsList(query))){
                isCollect = true;
            }
        }
        syMajorOverview.setIsCollect(isCollect);

        return AjaxResult.success(syMajorOverview);
    }

    @GetMapping("getMajorOverviewByCodes")
    @ApiOperation("02-1 根据三级专业编码获取专业概况")
    public AjaxResult getMajorOverviewByCodes(@RequestParam(required = true) String codes) {
        if(StringUtils.isBlank(codes)){
            return AjaxResult.success(new ArrayList<>());
        }
        List<String> codeList= Arrays.asList(Convert.toStrArray(codes));
        List<String> codeQueryList = new ArrayList<>();
        //过滤字母
        for (String cc : codeList) {
            if(cc.length()<6){
                continue;
            }
            codeQueryList.add(StringUtils.getNumeric(cc));
        }
        String examTypeData = ConstantUtil.getExamTypeData(VistorContextHolder.getExamType().title());
        List<SyMajorOverview> resultList = syMajorOverviewService.selectSyMajorOverviewByCodes(examTypeData, codeQueryList);
        if(CollectionUtils.isEmpty(resultList)){
            return AjaxResult.success(new ArrayList<>());
        }

        return AjaxResult.success(resultList);
    }

    @GetMapping("getMajorCareerProspectsByCode")
    @ApiOperation("01 根据三级专业编码获取职业前景")
    public AjaxResult getMajorCareerProspectsByCode(@RequestParam(required = true) String code) {
        code = StringUtils.getNumeric(code);//过滤字母
        SyMajorCareerProspects majorCareerProspects = majorCareerProspectsService.selectSyMajorCareerProspectsByCode(code);
        if(StringUtils.isNull(majorCareerProspects)){
            return AjaxResult.success(new SyMajorCareerProspects());
        }
        return AjaxResult.success(majorCareerProspects);
    }

    @GetMapping("getMajorCareerProspectsByCodes")
    @ApiOperation("01-2 根据三级专业编码获取职业前景")
    public AjaxResult getMajorCareerProspectsByCodes(@RequestParam(required = true) String codes) {
        if(StringUtils.isBlank(codes)){
            return AjaxResult.success(new ArrayList<>());
        }
        List<String> codeList= Arrays.asList(Convert.toStrArray(codes));
        List<String> codeQueryList = new ArrayList<>();
        //过滤字母
        for (String cc : codeList) {
            if(cc.length()<6){
                continue;
            }
            codeQueryList.add(StringUtils.getNumeric(cc));
        }
        List<SyMajorCareerProspects> resultList = majorCareerProspectsService.selectSyMajorCareerProspectsByCodes(codeQueryList);
        if(CollectionUtils.isEmpty(resultList)){
            return AjaxResult.success(new ArrayList<>());
        }

        return AjaxResult.success(resultList);
    }

    @GetMapping("getMajorDetailByCodes")
    @ApiOperation("02-1 根据三级专业编码获取专业概况及职业前景")
    public AjaxResult getMajorDetailByCodes(@RequestParam(required = true) String codes) {
        if(StringUtils.isBlank(codes)){
            return AjaxResult.success(new ArrayList<>());
        }
        List<String> codeList= Arrays.asList(Convert.toStrArray(codes));
        List<String> codeQueryList = new ArrayList<>();
        //过滤字母
        for (String cc : codeList) {
            if(cc.length()<6){
                continue;
            }
            codeQueryList.add(StringUtils.getNumeric(cc));
        }

        if(CollectionUtils.isEmpty(codeQueryList)){
            return AjaxResult.success(new ArrayList<>());
        }
        String examTypeData = ConstantUtil.getExamTypeData(VistorContextHolder.getExamType().title());
        Map<String, SyMajorOverview> overviewMap = syMajorOverviewService.selectSyMajorOverviewByCodes(examTypeData, codeQueryList)
                .stream().collect(Collectors.toMap(SyMajorOverview::getCode, Function.identity()));

        Map<String,SyMajorCareerProspects> prospectsMap = majorCareerProspectsService.selectSyMajorCareerProspectsByCodes(codeQueryList)
                .stream().collect(Collectors.toMap(SyMajorCareerProspects::getCode, Function.identity()));

        List<SyMajorDetail> resultList = new ArrayList<>();
        for (String code : codeQueryList) {
            SyMajorDetail detail = new SyMajorDetail();
            detail.setCode(code);
            detail.setOverview(overviewMap.containsKey(code)?overviewMap.get(code):new SyMajorOverview());
            detail.setProspects(prospectsMap.containsKey(code)?prospectsMap.get(code):new SyMajorCareerProspects());
            resultList.add(detail);
        }

        return AjaxResult.success(resultList);
    }

    /**
     * @param type
     * @param level 传3时表示需要1 2 3级的专业树 传2表示需要1 2 级专业树
     * @param batch:批次，4表示专科，小于4为本科
     * @return
     */
    @GetMapping("getAllMajor")
    @ApiOperation("00 获取所有专业（三级树形结构）")
    @Anonymous
    public AjaxResult getAllMajor(String type,Integer level,String parentCode,Integer batch) {
        SyMajor query = new SyMajor().setLevel(level).setParentCode(parentCode);
        SysUser user = VistorContextHolder.getContext();
        if(StringUtils.isNotBlank(type)) {
            if("高职本科".equals(type)) {
                query.setType("职教本科");
            } else {
                query.setType(type);
            }
        } else if(null != batch) {
            query.setType(batch >= 4 ? "专科" : "本科");
        }
        String examType = null==user?(null==VistorContextHolder.getExamType()?"单招（应届普高）":VistorContextHolder.getExamType().name()):(null==user.getExamType()?"单招（应届普高）":user.getExamType().title());
//        query.setExamType(ConstantUtil.getExamTypeData(user.getExamType().title()));
        query.setExamType(ConstantUtil.getExamTypeData(examType));
        List<SyMajor> majorList = syMajorService.selectSyMajorList(query);
        List<SyVocational> toList = new ArrayList<>();

        List<String>  majorListByPlan = new ArrayList<>();
        //湖南：计划中有的专业加入
        String location = VistorContextHolder.getLocation();
        if ("湖南".equals(location)){
            majorListByPlan = syMajorService.selectMajorsByPlan(location).stream().map(major->major.getName()).collect(Collectors.toList());
        }
        Boolean isFilter = false;
        for (SyMajor major : majorList) {
            if (CollectionUtils.isNotEmpty(majorListByPlan) ) {
                if (major.getLevel()==3&&!majorListByPlan.contains(major.getName())) {
                    isFilter = true;
                }else {
                    SyVocational syVocational = new SyVocational();
                    BeanUtils.copyProperties(major, syVocational);
                    toList.add(syVocational);
                }
            }else {
                SyVocational syVocational = new SyVocational();
                BeanUtils.copyProperties(major, syVocational);
                toList.add(syVocational);
            }
        }
        List<TreeSelectVocational> list = vocationalService.buildVocationalTreeSelect(toList);
        if (isFilter){
            //清除非第三级中children为空
            list = filterEmptyChildren(list);
        }

        return AjaxResult.success(list);
    }

    /**
     * level为0时 level>0 即返回1、2、3级数据；level为1时 level>1 即返回2、3级数据
     * @param name
     * @param level
     * @return
     */
    @GetMapping("getMajorByName")
    @ApiOperation("00 获取专业及子结构 适用于二级与三级")
    @Anonymous
    public AjaxResult getMajorByName(@ApiParam("专业名称") @RequestParam String name, @ApiParam("type") @RequestParam(required = false) String type, @ApiParam("层级") @RequestParam Integer level,
                                     Integer batch) {
        SyMajor query = new SyMajor().setName(name);
        if(StringUtils.isNotBlank(type)) {
            if("高职本科".equals(type)) {
                query.setType("职教本科");
            } else {
                query.setType(type);
            }
        } else if(null != batch) {
            query.setType(batch >= 4 ? "专科" : "本科");
        }
        String examTypeData = ConstantUtil.getExamTypeData(VistorContextHolder.getExamType().title());
        query.setExamType(examTypeData);
        List<SyMajor> majorList = syMajorService.selectSyMajorList(query).stream().filter(major->major.getLevel()>level).collect(Collectors.toList());
        List<TreeSelectVocational> resultList = new ArrayList<>();

        majorList.forEach(ll->{
            //获取
            List<SyMajor> syMajors =syMajorService.selectSyMajorAndChildrenByCode(new SyMajor().setCode(ll.getCode()).setLevel(level).setExamType(examTypeData));
            if(CollectionUtils.isNotEmpty(syMajors)){
                List<SyVocational> toList = new ArrayList<>();
                syMajors.forEach(major->{
                    SyVocational syVocational=new SyVocational();
                    BeanUtils.copyProperties(major,syVocational);
                    toList.add(syVocational);
                });
                List<TreeSelectVocational> llist = vocationalService.buildVocationalTreeSelect(toList);
                resultList.addAll(llist);
            }

        });

        return AjaxResult.success(resultList);
    }

    /**
     * 清除列表中 level != 3 且 children 为空的节点
     */
    public List<TreeSelectVocational> filterEmptyChildren(List<TreeSelectVocational> list) {
        if (list == null) {
            return new ArrayList<>();
        }
        return list.stream()
                .filter(node -> {
                    // 如果 level == 3，保留该节点
                    if (Integer.valueOf(3).equals(node.getLevel())) {
                        return true;
                    }

                    // 如果 level != 3，但有子节点，先递归处理子节点
                    if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                        List<TreeSelectVocational> filteredChildren = filterEmptyChildren(node.getChildren());
                        node.setChildren(filteredChildren);

                        // 处理子节点后，如果还有子节点，则保留该节点
                        return !filteredChildren.isEmpty();
                    }
                    // level != 3 且没有子节点，过滤掉
                    return false;
                })
                .collect(Collectors.toList());
    }
}
