package com.xjrsoft.module.banding.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.banding.dto.AddBandingTaskClassDto;
import com.xjrsoft.module.banding.dto.BandingTaskClassListDto;
import com.xjrsoft.module.banding.dto.BandingTaskClassPageDto;
import com.xjrsoft.module.banding.dto.BandingTaskClassStudentPageDto;
import com.xjrsoft.module.banding.dto.ChangeClassDto;
import com.xjrsoft.module.banding.dto.ChangeClassStatusDto;
import com.xjrsoft.module.banding.dto.StudentDto;
import com.xjrsoft.module.banding.dto.SureBandingTaskDto;
import com.xjrsoft.module.banding.dto.UpdateBandingClassDto;
import com.xjrsoft.module.banding.entity.BandingTask;
import com.xjrsoft.module.banding.entity.BandingTaskClass;
import com.xjrsoft.module.banding.entity.BandingTaskClassStudent;
import com.xjrsoft.module.banding.service.IBandingTaskClassService;
import com.xjrsoft.module.banding.service.IBandingTaskClassStudentService;
import com.xjrsoft.module.banding.vo.BandingTaskClassExcelVo;
import com.xjrsoft.module.banding.vo.BandingTaskClassPageVo;
import com.xjrsoft.module.banding.vo.BandingTaskClassStudentListVo;
import com.xjrsoft.module.banding.vo.BandingTaskClassSureListVo;
import com.xjrsoft.module.banding.vo.BandingTaskClassVo;
import com.xjrsoft.module.student.dto.BaseNewStudentPageDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
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 org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* @title: 新生分班任务
* @Author dzx
* @Date: 2024-07-01
* @Version 1.0
*/
@RestController
@RequestMapping("/banding" + "/bandingTaskClass")
@Api(value = "/banding"  + "/bandingTaskClass",tags = "新生分班任务班级配置代码")
@AllArgsConstructor
public class BandingTaskClassController {


    private final IBandingTaskClassService bandingTaskClassService;
    private final IBandingTaskClassStudentService classStudentService;

    @GetMapping(value = "/list")
    @ApiOperation(value="新生分班任务班级配置列表")
    @SaCheckPermission("bandingtask:detail")
    public RT<List<BandingTaskClassPageVo>> list(@Valid BandingTaskClassPageDto dto){

        List<BandingTaskClassPageVo> list = bandingTaskClassService.getList(dto);
        return RT.ok(list);
    }

    @GetMapping(value = "/class-student")
    @ApiOperation(value="分班后的学生列表")
    @SaCheckPermission("bandingtask:detail")
    public RT<List<BandingTaskClassStudentListVo>> classStudent(@Valid BandingTaskClassStudentPageDto dto){
        List<BandingTaskClassStudentListVo> list = bandingTaskClassService.classStudent(dto);
        return RT.ok(list);
    }

    @GetMapping(value = "/class-sure")
    @ApiOperation(value="分班确认列表")
    @SaCheckPermission("bandingtask:detail")
    public RT<List<BandingTaskClassSureListVo>> classSure(@Valid BandingTaskClassStudentPageDto dto){
        List<BandingTaskClassSureListVo> list = bandingTaskClassService.getClassSure(dto);
        return RT.ok(list);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value="根据id查询新生分班任务信息")
    @SaCheckPermission("bandingTaskClass:detail")
    public RT<BandingTaskClassVo> info(@RequestParam Long id){
        BandingTaskClass bandingTaskClass = bandingTaskClassService.getById(id);
        if (bandingTaskClass == null) {
           return RT.error("找不到此数据！");
        }
        return RT.ok(BeanUtil.toBean(bandingTaskClass, BandingTaskClassVo.class));
    }


    @PostMapping
    @ApiOperation(value = "新增新生分班")
    @SaCheckPermission("bandingTaskClass:add")
    public RT<Boolean> add(@Valid @RequestBody List<AddBandingTaskClassDto> dtoList){
        List<BandingTaskClass> dataList = new ArrayList<>();
        List<String> errorList = new ArrayList<>();
        for (AddBandingTaskClassDto dto : dtoList) {
            if(dto.getSortCode() != null){
                List<BandingTaskClass> list = bandingTaskClassService.list(
                        new QueryWrapper<BandingTaskClass>().lambda()
                                .eq(BandingTaskClass::getSortCode, dto.getSortCode())
                                .eq(BandingTaskClass::getBandingTaskId, dto.getBandingTaskId())
                );
                if(!list.isEmpty()){
                    errorList.add(dto.getName());
                }
            }

            BandingTaskClass bandingTask = BeanUtil.toBean(dto, BandingTaskClass.class);
            bandingTask.setCreateDate(new Date());
        }
        if(!errorList.isEmpty()){
            return RT.error(errorList.toString().replace("[", "").replace("]", "") + "，分班排序重复");
        }

        boolean isSuccess = bandingTaskClassService.saveBatch(dataList);
        return RT.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "批量新增或者修改新生分班")
    @SaCheckPermission("bandingTaskClass:edit")
    public RT<Boolean> update(@Valid @RequestBody List<UpdateBandingClassDto> dtoList){
        List<BandingTaskClass> insList = new ArrayList<>();
        List<BandingTaskClass> updList = new ArrayList<>();

        List<BandingTaskClass> updNullList = new ArrayList<>();
        List<String> errorList = new ArrayList<>();
        for (UpdateBandingClassDto dto : dtoList) {
            if(dto.getSortCode() != null){
                List<BandingTaskClass> list = bandingTaskClassService.list(
                        new QueryWrapper<BandingTaskClass>().lambda()
                                .eq(BandingTaskClass::getSortCode, dto.getSortCode())
                                .eq(BandingTaskClass::getBandingTaskId, dto.getBandingTaskId())
                                .ne(dto.getId() != null,BandingTaskClass::getId, dto.getId())
                );
                if(!list.isEmpty()){
                    errorList.add(dto.getName());
                }
            }

            BandingTaskClass bandingTask = BeanUtil.toBean(dto, BandingTaskClass.class);
            if(bandingTask.getId() != null){
                bandingTask.setModifyDate(new Date());
                if(bandingTask.getSortCode() == null){
                    updNullList.add(bandingTask);
                }else{
                    updList.add(bandingTask);
                }
            }else{
                bandingTask.setCreateDate(new Date());
                insList.add(bandingTask);
            }
        }
        if(!errorList.isEmpty()){
            return RT.error(errorList.toString().replace("[", "").replace("]", "") + "，分班排序重复");
        }

        if(!updNullList.isEmpty()){
            bandingTaskClassService.updateNull(updNullList);
        }

        boolean saveBatch = bandingTaskClassService.saveBatch(insList);
        boolean isSuccess = bandingTaskClassService.updateBatchById(updList);
        return RT.ok(isSuccess);
    }

    @DeleteMapping
    @ApiOperation(value = "删除新生分班")
    @SaCheckPermission("bandingTaskClass:delete")
    public RT<Boolean> delete(@Valid @RequestBody List<Long> ids){
        if(!ids.isEmpty()){
            classStudentService.remove(
                    new QueryWrapper<BandingTaskClassStudent>().lambda()
                            .in(BandingTaskClassStudent::getBandingTaskClassId, ids)
            );
        }

        return RT.ok(bandingTaskClassService.delete(ids));

    }
    @PostMapping("/import")
    @ApiOperation(value = "导入")
    public RT<Boolean> importData(@RequestParam Long bandingTaskId, @RequestParam MultipartFile file) throws IOException {
        List<Map<Integer, Object>> excelDataList = EasyExcel.read(file.getInputStream()).sheet().headRowNumber(3).doReadSync();
        Boolean result = bandingTaskClassService.importData(bandingTaskId, excelDataList);
        return RT.ok(result);
    }

    @PostMapping("/export-query")
    @ApiOperation(value = "导出学生列表")
    public ResponseEntity<byte[]> exportData(@Valid @RequestBody BandingTaskClassStudentPageDto dto) {
        List<BandingTaskClassStudentListVo> listVos = bandingTaskClassService.classStudent(dto);
        List<BandingTaskClassExcelVo> list = BeanUtil.copyToList(listVos, BandingTaskClassExcelVo.class);
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, BandingTaskClassExcelVo.class).automaticMergeHead(false).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(list);

        return RT.fileStream(bot.toByteArray(), "banding" + ExcelTypeEnum.XLSX.getValue());
    }

    @PostMapping("/reset")
    @ApiOperation(value = "重置功能")
    @SaCheckPermission("bandingTaskClass:add")
    public RT<Boolean> reset(@Valid @RequestBody SureBandingTaskDto dto){
        boolean isSuccess = bandingTaskClassService.reset(dto.getBandingTaskId());
        return RT.ok(isSuccess);
    }


    @PostMapping("/change-class")
    @ApiOperation(value = "调整班级")
    @SaCheckPermission("bandingTaskClass:change-class")
    public RT<Boolean> changeClass(@Valid @RequestBody ChangeClassDto dto){
        boolean isSuccess = classStudentService.changeClass(dto);
        return RT.ok(isSuccess);
    }

    @PostMapping("/remove-student")
    @ApiOperation(value = "移出学生")
    @SaCheckPermission("bandingTaskClass:remove-student")
    public RT<Boolean> removeStudent(@Valid @RequestBody ChangeClassDto dto){
        boolean isSuccess = classStudentService.removeStudent(dto);
        return RT.ok(isSuccess);
    }

    @PostMapping("/insert-student")
    @ApiOperation(value = "移入学生")
    @SaCheckPermission("bandingTaskClass:insert-student")
    public RT<Boolean> insertStudent(@Valid @RequestBody ChangeClassDto dto){
        boolean isSuccess = classStudentService.insertStudent(dto);
        return RT.ok(isSuccess);
    }

    @GetMapping("/satisfy-student")
    @ApiOperation(value = "满足学生")
    @SaCheckPermission("bandingTaskClass:satisfy-student")
    public RT<List<BaseNewStudentPageDto>> satisfyStudent(@Valid StudentDto dto){
        List<BaseNewStudentPageDto> list = classStudentService.satisfyStudent(dto);
        return RT.ok(list);
    }

    @GetMapping("/surplus-student")
    @ApiOperation(value = "剩余学生")
    @SaCheckPermission("bandingTaskClass:surplus-student")
    public RT<List<BaseNewStudentPageDto>> surplusStudent(@Valid StudentDto dto){
        List<BaseNewStudentPageDto> list = classStudentService.surplusStudent(dto);
        return RT.ok(list);
    }


    @GetMapping("/classListParam")
    @ApiOperation(value = "根据专业和年级查询班级")
    @SaCheckPermission("bandingTaskClass:surplus-student")
    public RT<List<BandingTaskClassVo>> classListParam(@Valid BandingTaskClassListDto dto){
        List<BandingTaskClassVo> list = bandingTaskClassService.selectJoinList(BandingTaskClassVo.class,
                new MPJLambdaWrapper<BandingTaskClass>()
                        .select(BandingTaskClass::getId)
                        .select(BandingTaskClass.class, x -> VoToColumnUtil.fieldsToColumns(BandingTaskClass.class).contains(x.getProperty()))
                        .leftJoin(BandingTask.class, BandingTask::getId, BandingTaskClass::getBandingTaskId)
                        .eq(BandingTask::getGradeId, dto.getGradeId())
                        .eq(BandingTaskClass::getMajorSetId, dto.getMajorSetId())
        );
        return RT.ok(list);
    }

    @PostMapping(value = "/change-status")
    @ApiOperation(value="修改状态")
    @SaCheckPermission("officebuild:detail")
    public RT<Boolean> changeStatus(@Valid @RequestBody ChangeClassStatusDto dto) throws Exception {
        BandingTaskClass taskClass = bandingTaskClassService.getById(dto.getId());
        taskClass.setStatus(dto.getStatus());
        bandingTaskClassService.updateById(taskClass);
        return RT.ok(true);
    }
}