package com.ruoyi.web.controller.back;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
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.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.syzy.domain.BBusiWishUniversitySubmitMarjors;
import com.ruoyi.syzy.domain.BBusiWishUniversitySubmitRecruitPlan;
import com.ruoyi.syzy.domain.BindPlanEnrollMajor;
import com.ruoyi.syzy.service.IBBusiWishUniversitySubmitMarjorsService;
import com.ruoyi.syzy.service.IBBusiWishUniversitySubmitRecruitPlanService;
import com.ruoyi.web.domain.ManualBindingQueryDto;
import com.ruoyi.web.service.MatchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 院校招生计划Controller
 *
 * @author voluntary
 * @date 2023-03-24
 */
@RestController
@RequestMapping("/back/busiWishUniversitySubmitRecruitPlan")
@Api(tags = "后台 招生计划")
public class BackBusiWishUniversitySubmitRecruitPlanController extends BaseController
{
    @Autowired
    private IBBusiWishUniversitySubmitRecruitPlanService planService;
    @Autowired
    private IBBusiWishUniversitySubmitMarjorsService submitMarjorsService;
    @Autowired
    private MatchService matchService;

    /**
     * 查询院校招生计划列表
     */
    @PreAuthorize("@ss.hasPermi('back:busiWishUniversitySubmitRecruitPlan:list')")
    @GetMapping("/list")
    public TableDataInfo list(BBusiWishUniversitySubmitRecruitPlan plan)
    {
        if(StringUtils.isEmpty(plan.getLocation())){
//            throw new RuntimeException("地区【location】不能为空");
        }
        Integer year = planService.selectSubmitRecruitsMaxYearByLocation(plan.getLocation());
        if(null== year){
//            year = Calendar.getInstance().get(Calendar.YEAR);
        }else {
            plan.setYear(String.valueOf(year));
        }

        startPage();
        List<BBusiWishUniversitySubmitRecruitPlan> list = planService.selectBBusiWishUniversitySubmitRecruitPlanList(plan);
        for (BBusiWishUniversitySubmitRecruitPlan pp : list) {
            if(StringUtils.isEmpty(pp.getMarjorNameText())){
                continue;
            }
            BBusiWishUniversitySubmitMarjors marjorsQuery= new BBusiWishUniversitySubmitMarjors();
            marjorsQuery.setMarjorNameText(pp.getMarjorNameText());
            marjorsQuery.setUniversityId(pp.getUniversityId());
            marjorsQuery.setLocation(pp.getLocation());
            marjorsQuery.setLiberalScience(pp.getLiberalScience().intValue());
            pp.setBindEnrollList(submitMarjorsService.selectBBusiWishUniversitySubmitMarjorsList(marjorsQuery));
        }

        return getDataTable(list);
    }

    /**
     * 导出院校招生计划列表
     */
    @PreAuthorize("@ss.hasPermi('back:busiWishUniversitySubmitRecruitPlan:export')")
    @Log(title = "院校招生计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BBusiWishUniversitySubmitRecruitPlan busiWishUniversitySubmitRecruitPlan)
    {
        List<BBusiWishUniversitySubmitRecruitPlan> list = planService.selectBBusiWishUniversitySubmitRecruitPlanList(busiWishUniversitySubmitRecruitPlan);
        ExcelUtil<BBusiWishUniversitySubmitRecruitPlan> util = new ExcelUtil<BBusiWishUniversitySubmitRecruitPlan>(BBusiWishUniversitySubmitRecruitPlan.class);
        util.exportExcel(response, list, "院校招生计划数据");
    }

    /**
     * 获取院校招生计划详细信息
     */
    @PreAuthorize("@ss.hasPermi('back:busiWishUniversitySubmitRecruitPlan:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(planService.selectBBusiWishUniversitySubmitRecruitPlanById(id));
    }

    /**
     * 新增院校招生计划
     */
    @PreAuthorize("@ss.hasPermi('back:busiWishUniversitySubmitRecruitPlan:add')")
    @Log(title = "院校招生计划", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BBusiWishUniversitySubmitRecruitPlan busiWishUniversitySubmitRecruitPlan)
    {
        return toAjax(planService.insertBBusiWishUniversitySubmitRecruitPlan(busiWishUniversitySubmitRecruitPlan));
    }

    /**
     * 修改院校招生计划
     */
    @PreAuthorize("@ss.hasPermi('back:busiWishUniversitySubmitRecruitPlan:edit')")
    @Log(title = "院校招生计划", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BBusiWishUniversitySubmitRecruitPlan busiWishUniversitySubmitRecruitPlan)
    {
        return toAjax(planService.updateBBusiWishUniversitySubmitRecruitPlan(busiWishUniversitySubmitRecruitPlan));
    }

    /**
     * 删除院校招生计划
     */
    @PreAuthorize("@ss.hasPermi('back:busiWishUniversitySubmitRecruitPlan:remove')")
    @Log(title = "院校招生计划", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(planService.deleteBBusiWishUniversitySubmitRecruitPlanByIds(ids));
    }

    @Log(title = "绑定招生计划与院校线", businessType = BusinessType.UPDATE)
    @PostMapping("/bindPlanEnrollMajor")
    public AjaxResult bindPlanEnrollMajor(@RequestBody BindPlanEnrollMajor bindPlanEnrollMajor)
    {
        List<Long> enrollIds = Arrays.asList(bindPlanEnrollMajor.getEnrollIds());
        BBusiWishUniversitySubmitRecruitPlan plan = planService.selectBBusiWishUniversitySubmitRecruitPlanById(bindPlanEnrollMajor.getPlanId());
        List<BBusiWishUniversitySubmitMarjors> marjors = submitMarjorsService.selectBBusiWishUniversitySubmitMarjorsByIds(enrollIds);
        //1、计划的marjorNameText非空时，以计划来更新
        if (null!=plan.getMarjorNameText()) {
            marjors.stream().forEach(major->{
                if(StringUtils.isEmpty(major.getMarjorNameText())){
                    major.setMarjorNameText(plan.getMarjorNameText());
                    submitMarjorsService.updateBBusiWishUniversitySubmitMarjors(major);
                    logger.info("更新专业线id为{}的marjorNameText为:{}",major.getId(),plan.getMarjorNameText());
                }
            });

            return AjaxResult.success("更新成功1");
        }
        //2、计划的marjorNameText为空时，专业线的marjorNameText为空，以计划的marjorNameText来更新
        List<String> marjorNameList = new ArrayList<>();
        String tmpMarjorNameText = StringUtils.EMPTY;
        for (BBusiWishUniversitySubmitMarjors marjor : marjors) {
            if (StringUtils.isNotEmpty(marjor.getMarjorNameText())) {
                marjorNameList.add(marjor.getMarjorName());
                tmpMarjorNameText = marjor.getMarjorNameText();
            }
        }
        marjorNameList = marjorNameList.stream().distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(marjorNameList)) {
            //专业线的marjorName为空、plan的marjorName为空，此时以plan的为基准
            String marjorNameText = plan.getMarjorName()+"_"+plan.getMarjorBelongs();
            plan.setMarjorNameText(marjorNameText);
            planService.updateBBusiWishUniversitySubmitRecruitPlan(plan);
            marjors.stream().forEach(major->{
                if(plan.getMarjorName().trim().equalsIgnoreCase(major.getMarjorName().trim())){
                    //计划与录取的专业名称相同才更新
                    major.setMarjorNameText(marjorNameText);
                    submitMarjorsService.updateBBusiWishUniversitySubmitMarjors(major);
                    logger.info("更新专业线id为{}的marjorNameText为:{}",major.getId(),plan.getMarjorNameText());
                }
            });

            return AjaxResult.success("更新成功2");
        }
        //3、计划的marjorNameText为空时，专业线的marjorNameText非空，以专业线的为基准更新
        //校验marjorName是否相同
//        if(marjorNameList.size()==enrollIds.size()){
        if(marjorNameList.size()>1){
            return AjaxResult.error("选择"+enrollIds.size()+"个专业线对应的专业名称不全相同"+JSONObject.toJSONString(marjorNameList)+"，更新失败");
        }
//        String marjorNameText = marjorNameList.get(marjorNameList.size()-1);
        plan.setMarjorNameText(tmpMarjorNameText);
        planService.updateBBusiWishUniversitySubmitRecruitPlan(plan);
        for (BBusiWishUniversitySubmitMarjors major : marjors) {
            if (StringUtils.isEmpty(major.getMarjorNameText())) {
                //更新专业线的marjorNameText
                major.setMarjorNameText(tmpMarjorNameText);
                submitMarjorsService.updateBBusiWishUniversitySubmitMarjors(major);
                logger.info("更新专业线id为{}的marjorNameText为:{}", major.getId(), plan.getMarjorNameText());
            }
        }

        return AjaxResult.success("更新成功3");
    }

    /// <summary>
    /// 获取近3年的年份标签，手工绑定按此年份分割
    /// </summary>
    @GetMapping("/getManualBindingYears")
    @ApiOperation("查询招生计划与专业线的年份")
    public AjaxResult getManualBindingYears() {
        int[] planYears = new int[] {2023, 2022, 2021};
        int[] majorYears = new int[] {2022, 2021, 2020};
        AjaxResult result = AjaxResult.success();
        result.put("planYears", planYears);
        result.put("majorYears", majorYears);
        return result;
    }

    @PostMapping("/getManualBindingList")
    @ApiOperation("查询招生计划与专业线的匹配关系")
    /// <returns>table data of `ManualBindingRecruitPlanDto`</returns>
    public TableDataInfo getManualBindingList(@RequestBody ManualBindingQueryDto queryDto, Integer pageNum, Integer pageSize) {
        if (StringUtils.isBlank(queryDto.getLocation())) {
            throw new RuntimeException("参数错误，location不能为空");
        }
        return getDataTable(matchService.findManualBindingRecruitPlanList(queryDto, pageNum, pageSize));
    }

    @PostMapping("/exportManualBindingList")
    @ApiOperation("导出匹配关系，以供修改")
    public void exportManualBindingList(ManualBindingQueryDto queryDto, HttpServletResponse response) {
        try {
            if (StringUtils.isBlank(queryDto.getLocation())) {
                throw new RuntimeException("参数错误，location不能为空");
            }
            if (StringUtils.isBlank(queryDto.getYear())) {
                throw new RuntimeException("参数错误，year不能为空");
            }
            if (StringUtils.isBlank(queryDto.getMatchType())) {
                throw new RuntimeException("参数错误，matchType不能为空");
            }
            matchService.exportManualBindingList(queryDto, response);
        } catch (Exception e) {
            logger.error("exportManualBindingList", e);
            response.setStatus(404);
        }
    }

    @PostMapping("/importManualBindingList")
    @ApiOperation("导入匹配关系, 校验后入库")
    public AjaxResult importManualBindingList(@RequestParam("file") MultipartFile file, @RequestParam("location") String location, @RequestParam("planYear") Integer planYear) {
        try {
            matchService.importManualBindingList(location, planYear, file.getInputStream());
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
