package com.xjrsoft.module.student.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xjrsoft.common.enums.DeleteMark;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.base.entity.BaseGrade;
import com.xjrsoft.module.base.entity.BaseMajorSet;
import com.xjrsoft.module.organization.entity.Department;
import com.xjrsoft.module.student.dto.AddEnrollmentPlanDto;
import com.xjrsoft.module.student.dto.EnrollmentPlanPageDto;
import com.xjrsoft.module.student.dto.PreviewEnrollmentPlanDto;
import com.xjrsoft.module.student.dto.UpdateEnrollmentPlanDto;
import com.xjrsoft.module.student.entity.EnrollmentPlan;
import com.xjrsoft.module.student.entity.EnrollmentPlanMajorSet;
import com.xjrsoft.module.student.service.IEnrollmentPlanMajorSetService;
import com.xjrsoft.module.student.service.IEnrollmentPlanService;
import com.xjrsoft.module.student.vo.EnrollmentPlanPageVo;
import com.xjrsoft.module.student.vo.EnrollmentPlanVo;
import com.xjrsoft.module.student.vo.PreviewEnrollmentPlanListVo;
import com.xjrsoft.module.student.vo.PreviewEnrollmentPlanVo;
import com.xjrsoft.module.system.entity.DictionaryDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
* @title: 招生计划维护
* @Author phoenix
* @Date: 2024-06-13
* @Version 1.0
*/
@RestController
@RequestMapping("/student" + "/enrollmentPlan")
@Api(value = "/student"  + "/enrollmentPlan",tags = "招生计划维护代码")
@AllArgsConstructor
public class EnrollmentPlanController {


    private final IEnrollmentPlanService enrollmentPlanService;

    private final IEnrollmentPlanMajorSetService enrollmentPlanMajorSetService;

    @GetMapping(value = "/page")
    @ApiOperation(value="招生计划维护列表(分页)")
    @SaCheckPermission("enrollmentplan:detail")
    public RT<PageOutput<EnrollmentPlanPageVo>> page(@Valid EnrollmentPlanPageDto dto){

        MPJLambdaWrapper<EnrollmentPlan> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper
                .disableSubLogicDel()
                .select(EnrollmentPlan::getId)
                .selectAs(DictionaryDetail::getName, EnrollmentPlanPageVo::getEnrollTypeCn)
                .selectAs(BaseGrade::getName, EnrollmentPlanPageVo::getGradeIdCn)
                .select("(select count(*) from enrollment_plan_major_set a where a.enrollment_plan_id = t.id and a.delete_mark = 0) as baseMajorSetSum")
                .select("(select sum(a.base_major_set_enrollment_num) from enrollment_plan_major_set a where a.enrollment_plan_id = t.id and a.delete_mark = 0) as enrollmentStuNum")
                .select(EnrollmentPlan.class,x -> VoToColumnUtil.fieldsToColumns(EnrollmentPlanPageVo.class).contains(x.getProperty()))
                .leftJoin(DictionaryDetail.class, DictionaryDetail::getCode, EnrollmentPlan::getEnrollType)
                .leftJoin(BaseGrade.class, BaseGrade::getId, EnrollmentPlan::getGradeId)
                .like(dto.getName() != null && !dto.getName().isEmpty(), EnrollmentPlan::getName, dto.getName())
                .eq(dto.getEnrollType() != null && !dto.getEnrollType().isEmpty(), EnrollmentPlan::getEnrollType, dto.getEnrollType())
                .eq(EnrollmentPlan::getDeleteMark, DeleteMark.NODELETE)
                .eq(dto.getGradeId() != null, EnrollmentPlan::getGradeId, dto.getGradeId())
                .orderByDesc(EnrollmentPlan::getStartDate)
                ;
        IPage<EnrollmentPlanPageVo> page = enrollmentPlanService.selectJoinListPage(ConventPage.getPage(dto), EnrollmentPlanPageVo.class, queryWrapper);
        PageOutput<EnrollmentPlanPageVo> pageOutput = ConventPage.getPageOutput(page, EnrollmentPlanPageVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/preview-page")
    @ApiOperation(value="预览招生计划")
    @SaCheckPermission("enrollmentplan:detail")
    public RT<PreviewEnrollmentPlanVo> previewPage(@Valid PreviewEnrollmentPlanDto dto){

        MPJLambdaWrapper<EnrollmentPlan> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper
                .disableSubLogicDel()
                .select(EnrollmentPlan::getId)
                .selectAs(DictionaryDetail::getName, PreviewEnrollmentPlanVo::getEnrollTypeCn)
                .selectAs(BaseGrade::getName, PreviewEnrollmentPlanVo::getGradeIdCn)
                .select("(select sum(a.base_major_set_enrollment_num) from enrollment_plan_major_set a where a.enrollment_plan_id = t.id and a.delete_mark = 0) as enrollmentStuNum")
                .select(EnrollmentPlan.class,x -> VoToColumnUtil.fieldsToColumns(PreviewEnrollmentPlanVo.class).contains(x.getProperty()))
                .leftJoin(DictionaryDetail.class, DictionaryDetail::getCode, EnrollmentPlan::getEnrollType)
                .leftJoin(BaseGrade.class, BaseGrade::getId, EnrollmentPlan::getGradeId)
                .eq(EnrollmentPlan::getId, dto.getEnrollmentPlanId())
                .eq(EnrollmentPlan::getDeleteMark, DeleteMark.NODELETE)
                .orderByDesc(EnrollmentPlan::getStartDate)
        ;
        PreviewEnrollmentPlanVo result = enrollmentPlanService.selectJoinOne(PreviewEnrollmentPlanVo.class, queryWrapper);

        if(result == null){
            return RT.ok(result);
        }

        MPJLambdaWrapper<EnrollmentPlanMajorSet> queryWrapperPreviewEnrollmentPlanList = new MPJLambdaWrapper<>();
        queryWrapperPreviewEnrollmentPlanList
                .selectAs(BaseMajorSet::getStudyYear, PreviewEnrollmentPlanListVo::getStudyYear)
                .selectAs(BaseMajorSet::getName, PreviewEnrollmentPlanListVo::getBaseMajorSetIdCn)
                .selectAs(EnrollmentPlanMajorSet::getBaseMajorSetEnrollmentNum, PreviewEnrollmentPlanListVo::getBaseMajorSetEnrollmentNum)
                .select("t3.name as baseMajorGradationIdCn")
                .select("(select group_concat(b.name) from enrollment_plan_graduate_school a left join base_graduate_school b on a.base_graduate_school_id = b.id where a.enrollment_plan_major_set_id = t.id) as graduateSchool")
                .leftJoin(BaseMajorSet.class, BaseMajorSet::getId, EnrollmentPlanMajorSet::getBaseMajorSetId)
                .leftJoin(Department.class, Department::getId, BaseMajorSet::getDepartmentId)
                .leftJoin("base_major_gradation t3 on t3.id = t1.major_gradation_id")
                .eq(EnrollmentPlanMajorSet::getEnrollmentPlanId, dto.getEnrollmentPlanId())
                .orderByDesc(BaseMajorSet::getMajorGradationId);
        List<PreviewEnrollmentPlanListVo> previewEnrollmentPlanList = enrollmentPlanMajorSetService.selectJoinList(PreviewEnrollmentPlanListVo.class, queryWrapperPreviewEnrollmentPlanList);

        result.setPreviewEnrollmentPlanListVoList(previewEnrollmentPlanList);
        return RT.ok(result);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value="根据id查询招生计划维护信息")
    @SaCheckPermission("enrollmentplan:detail")
    public RT<EnrollmentPlanVo> info(@RequestParam Long id){
        EnrollmentPlan enrollmentPlan = enrollmentPlanService.getById(id);
        if (enrollmentPlan == null) {
           return RT.error("找不到此数据！");
        }
        return RT.ok(BeanUtil.toBean(enrollmentPlan, EnrollmentPlanVo.class));
    }



    @PostMapping
    @ApiOperation(value = "新增招生计划维护")
    @SaCheckPermission("enrollmentplan:add")
    public RT<Boolean> add(@Valid @RequestBody AddEnrollmentPlanDto dto){
        EnrollmentPlan enrollmentPlan = BeanUtil.toBean(dto, EnrollmentPlan.class);
        enrollmentPlan.setCreateDate(new Date());
        enrollmentPlan.setCreateUserId(StpUtil.getLoginIdAsLong());
        enrollmentPlan.setStatus(0);
        //获取sortCode的最大数量
        QueryWrapper<EnrollmentPlan> queryWrapperSortcode = new QueryWrapper<>();
        queryWrapperSortcode.select("IFNULL(MAX(sort_code),0) as sortCode");
        EnrollmentPlan e = enrollmentPlanService.getOne(queryWrapperSortcode);
        int sortCode = e.getSortCode() + 1;
        enrollmentPlan.setSortCode(sortCode);
        boolean isSuccess = enrollmentPlanService.save(enrollmentPlan);
        return RT.ok(isSuccess);
    }

    @PutMapping("/change-status")
    @ApiOperation(value = "修改招生计划状态")
    @SaCheckPermission("enrollmentplan:edit")
    public RT<Boolean> changeStatus(@Valid @RequestBody UpdateEnrollmentPlanDto dto){
        EnrollmentPlan oldEnrollmentPlan = enrollmentPlanService.getById(dto.getId());
        if(oldEnrollmentPlan == null){
            throw new MyException("该招生计划已经失效！！！");
        }

        EnrollmentPlan enrollmentPlan = BeanUtil.toBean(dto, EnrollmentPlan.class);
        return RT.ok(enrollmentPlanService.updateById(enrollmentPlan));
    }

    @PutMapping
    @ApiOperation(value = "修改招生计划维护")
    @SaCheckPermission("enrollmentplan:edit")
    public RT<Boolean> update(@Valid @RequestBody UpdateEnrollmentPlanDto dto){

        EnrollmentPlan enrollmentPlan = BeanUtil.toBean(dto, EnrollmentPlan.class);
        return RT.ok(enrollmentPlanService.updateById(enrollmentPlan));

    }

    @DeleteMapping
    @ApiOperation(value = "删除招生计划维护")
    @SaCheckPermission("enrollmentplan:delete")
    public RT<Boolean> delete(@Valid @RequestBody List<Long> ids){
        return RT.ok(enrollmentPlanService.removeBatchByIds(ids));

    }

}