package com.xjrsoft.module.student.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
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.student.dto.AddBaseStudentScholarshipReleaseDto;
import com.xjrsoft.module.student.dto.AddStudentScholarshipDto;
import com.xjrsoft.module.student.dto.BaseStudentScholarshipReleasePageDto;
import com.xjrsoft.module.student.dto.UpdateBaseStudentScholarshipReleaseDto;
import com.xjrsoft.module.student.entity.BaseStudentScholarshipApplicant;
import com.xjrsoft.module.student.entity.BaseStudentScholarshipRelease;
import com.xjrsoft.module.student.service.IBaseStudentScholarshipApplicantService;
import com.xjrsoft.module.student.service.IBaseStudentScholarshipReleaseService;
import com.xjrsoft.module.student.vo.BaseStudentScholarshipReleasePageVo;
import com.xjrsoft.module.student.vo.BaseStudentScholarshipReleaseRecordVo;
import com.xjrsoft.module.student.vo.BaseStudentScholarshipReleaseVo;
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 org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
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-25
* @Version 1.0
*/
@RestController
@RequestMapping("/student" + "/baseStudentScholarshipRelease")
@Api(value = "/student"  + "/baseStudentScholarshipRelease",tags = "奖学金发放记录表代码")
@AllArgsConstructor
public class BaseStudentScholarshipReleaseController {

    private final IBaseStudentScholarshipApplicantService applicantService;
    private final IBaseStudentScholarshipReleaseService releaseService;

    @GetMapping(value = "/page")
    @ApiOperation(value = "奖学金发放记录表列表(分页)")
    @SaCheckPermission("basestudentscholarshiprelease:detail")
    public RT<PageOutput<BaseStudentScholarshipReleasePageVo>> page(@Valid BaseStudentScholarshipReleasePageDto dto) {

        Page<BaseStudentScholarshipReleasePageVo> page = releaseService.getPage(new Page<>(dto.getLimit(), dto.getSize()), dto);
        PageOutput<BaseStudentScholarshipReleasePageVo> pageOutput = ConventPage.getPageOutput(page, BaseStudentScholarshipReleasePageVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/record")
    @ApiOperation(value = "奖学金发放记录表列表(分页)")
    @SaCheckPermission("basestudentscholarshiprelease:detail")
    public RT<PageOutput<BaseStudentScholarshipReleaseRecordVo>> record(@Valid BaseStudentScholarshipReleasePageDto dto) {

        IPage<BaseStudentScholarshipReleaseRecordVo> page = releaseService.selectJoinListPage(ConventPage.getPage(dto), BaseStudentScholarshipReleaseRecordVo.class,
                new MPJLambdaWrapper<BaseStudentScholarshipRelease>()
                        .select(BaseStudentScholarshipRelease::getId)
                        .select(BaseStudentScholarshipRelease.class,x -> VoToColumnUtil.fieldsToColumns(BaseStudentScholarshipRelease.class).contains(x.getProperty()))
                        .eq(BaseStudentScholarshipRelease::getBaseStudentScholarshipApplicantId, dto.getApplicantId())
        );
        PageOutput<BaseStudentScholarshipReleaseRecordVo> pageOutput = ConventPage.getPageOutput(page, BaseStudentScholarshipReleaseRecordVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value = "根据申请id查询奖学金发放记录表信息")
    @SaCheckPermission("basestudentscholarshiprelease:detail")
    public RT<BaseStudentScholarshipReleaseVo> info(@RequestParam Long id) {
        BaseStudentScholarshipApplicant applicant = applicantService.getById(id);
        if (applicant == null) {
            return RT.error("找不到此数据！");
        }
        List<BaseStudentScholarshipRelease> list = releaseService.list(
                new QueryWrapper<BaseStudentScholarshipRelease>().lambda()
                        .eq(BaseStudentScholarshipRelease::getBaseStudentScholarshipApplicantId, id)
        );
        double sum = list.stream().filter(value -> value.getAmount() != null).mapToDouble(value -> value.getAmount()).sum();
        BaseStudentScholarshipReleaseVo releaseVo = new BaseStudentScholarshipReleaseVo();
        releaseVo.setScholarshipApplicantId(applicant.getBaseStudentScholarshipCategoryId());
        releaseVo.setTotalAmount(applicant.getAmount());
        releaseVo.setReleaseAmount(sum);
        return RT.ok(releaseVo);
    }


    @PostMapping
    @ApiOperation(value = "新增奖学金发放记录表")
    @SaCheckPermission("basestudentscholarshiprelease:add")
    public RT<Boolean> add(@Valid @RequestBody AddBaseStudentScholarshipReleaseDto dto) {
        BaseStudentScholarshipApplicant applicant = applicantService.getById(dto.getBaseStudentScholarshipApplicantId());
        if(dto.getAmount() > applicant.getAmount()){
            return RT.error("发放金额不能大于获奖金额");
        }
        BaseStudentScholarshipRelease baseStudentScholarshipRelease = BeanUtil.toBean(dto, BaseStudentScholarshipRelease.class);
        boolean isSuccess = releaseService.save(baseStudentScholarshipRelease);
        return RT.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "修改奖学金发放记录表")
    @SaCheckPermission("basestudentscholarshiprelease:edit")
    public RT<Boolean> update(@Valid @RequestBody UpdateBaseStudentScholarshipReleaseDto dto) {

        BaseStudentScholarshipRelease baseStudentScholarshipRelease = BeanUtil.toBean(dto, BaseStudentScholarshipRelease.class);
        return RT.ok(releaseService.updateById(baseStudentScholarshipRelease));

    }

    @DeleteMapping
    @ApiOperation(value = "删除奖学金发放记录表")
    @SaCheckPermission("basestudentscholarshiprelease:delete")
    public RT<Boolean> delete(@Valid @RequestBody List<Long> ids) {
        return RT.ok(releaseService.remove(ids));
    }

    @PostMapping("add-student")
    @ApiOperation(value = "添加学生")
    @SaCheckPermission("basestudentscholarshiprelease:add")
    public RT<Boolean> addStudent(@Valid @RequestBody AddStudentScholarshipDto dto) {
        if(dto.getApplicantIds() != null && !dto.getApplicantIds().isEmpty()){
            List<BaseStudentScholarshipApplicant> applicantList = applicantService.list(
                    new QueryWrapper<BaseStudentScholarshipApplicant>().lambda()
                            .in(BaseStudentScholarshipApplicant::getId, dto.getApplicantIds())
            );
            List<BaseStudentScholarshipApplicant> dataList = new ArrayList<>();
            List<BaseStudentScholarshipRelease> insertList = new ArrayList<>();
            for (BaseStudentScholarshipApplicant applicantVo : applicantList) {
                applicantVo.setScholarshipLevel(dto.getScholarshipLevel());
                applicantVo.setBaseStudentScholarshipCategoryId(dto.getBaseStudentScholarshipCategoryId());
                applicantVo.setReviewStatus(1);
                applicantVo.setAmount(dto.getTotalAmount().doubleValue());
                dataList.add(applicantVo);

                insertList.add(
                        new BaseStudentScholarshipRelease(){{
                            setCreateDate(new Date());
                            setAmount(0D);
                            setBaseStudentScholarshipApplicantId(applicantVo.getId());
                        }}
                );
            }
            if(!dataList.isEmpty()){
                applicantService.updateBatchById(dataList);
            }
            if(!insertList.isEmpty()){
                releaseService.saveBatch(insertList);
            }
        }
        return RT.ok(true);
    }

    @PostMapping("/import")
    @ApiOperation(value = "奖助学金发放导入")
    public RT<List<Map<String, String>>> scoreImport(@RequestParam MultipartFile file) throws IOException {
        List<Map<String, String>> maps = applicantService.importData(file);
        return RT.ok(maps);
    }
}