package com.xjrsoft.module.textbook.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.LambdaQueryWrapper;
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.enums.DeleteMark;
import com.xjrsoft.common.enums.TextbookTypeEnum;
import com.xjrsoft.common.model.result.R;
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.BaseClassCourse;
import com.xjrsoft.module.base.entity.BaseCourseSubject;
import com.xjrsoft.module.student.entity.BaseClassMajorSet;
import com.xjrsoft.module.student.service.IBaseClassMajorSetService;
import com.xjrsoft.module.textbook.dto.*;
import com.xjrsoft.module.textbook.entity.Textbook;
import com.xjrsoft.module.textbook.entity.TextbookClassRelation;
import com.xjrsoft.module.textbook.entity.TextbookStudentClaim;
import com.xjrsoft.module.textbook.service.ITextbookService;
import com.xjrsoft.module.textbook.service.ITextbookStudentClaimService;
import com.xjrsoft.module.textbook.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @title: 教材管理
* @Author dzx
* @Date: 2023-12-25
* @Version 1.0
*/
@RestController
@RequestMapping("/textbook" + "/textbook")
@Api(value = "/textbook"  + "/textbook",tags = "教材管理代码")
@AllArgsConstructor
public class TextbookController {

    private final ITextbookService textbookService;

    private final ITextbookStudentClaimService textbookStudentClaimService;


    private final IBaseClassMajorSetService baseClassMajorSetService;

    @GetMapping(value = "/page")
    @ApiOperation(value="教材管理列表(分页)")
    @SaCheckPermission("textbook:detail")
    public RT<PageOutput<TextbookPageVo>> page(@Valid TextbookPageDto dto){
        Page<TextbookPageVo> page = textbookService.getPage(new Page<>(dto.getLimit(), dto.getSize()), dto);
        PageOutput<TextbookPageVo> pageOutput = ConventPage.getPageOutput(page, TextbookPageVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/page-subscription")
    @ApiOperation(value="教材管理列表(分页，教材征订用)")
    @SaCheckPermission("textbook:detail")
    public RT<PageOutput<TextbookSubscriptionListVo>> pageSubscription(@Valid TextbookSubscriptionListDto dto){
        List<String> classIdList = new ArrayList<>();
        if(dto.getClassIds() != null && !dto.getClassIds().equals("")){
            String[] classIdArr =  dto.getClassIds().split(",");
            classIdList = Arrays.asList(classIdArr);
        }

        MPJLambdaWrapper<Textbook> textbookMPJLambdaWrapper = new MPJLambdaWrapper<>();
        textbookMPJLambdaWrapper
                .select(Textbook::getId)
                .selectAs(Textbook::getId,TextbookSubscriptionListVo::getTextbookId)
                .selectAs(BaseCourseSubject::getName, TextbookSubscriptionListVo::getCourseName)
                .select(Textbook.class, x -> VoToColumnUtil.fieldsToColumns(TextbookSubscriptionListVo.class).contains(x.getProperty()))
                .leftJoin(BaseClassCourse.class, BaseClassCourse::getCourseId, Textbook::getCourseSubjectId)
                .leftJoin(BaseCourseSubject.class, BaseCourseSubject::getId, Textbook::getCourseSubjectId)
                .eq(dto.getBaseSemesterId() != null && dto.getBaseSemesterId() > 0, BaseClassCourse::getBaseSemesterId, dto.getBaseSemesterId())
                .in(!classIdList.isEmpty(),BaseClassCourse::getClassId, classIdList)
                .groupBy(Textbook::getId)
        ;
        IPage<TextbookSubscriptionListVo> page = textbookService.selectJoinListPage(ConventPage.getPage(dto),TextbookSubscriptionListVo.class,textbookMPJLambdaWrapper);

        //获取所有班级的总人数
        LambdaQueryWrapper<BaseClassMajorSet> baseClassMajorSetLambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseClassMajorSetLambdaQueryWrapper
                .in(!classIdList.isEmpty(), BaseClassMajorSet::getClassId, classIdList)
                .eq(BaseClassMajorSet::getDeleteMark, DeleteMark.NODELETE.getCode())
                ;
        List<BaseClassMajorSet> baseClassMajorSetList = baseClassMajorSetService.list(baseClassMajorSetLambdaQueryWrapper);

        int studentSubscriptionNumber = 0;
        for (BaseClassMajorSet baseClassMajorSet : baseClassMajorSetList){
            studentSubscriptionNumber += baseClassMajorSet.getTotalStudent();
        }

        for(TextbookSubscriptionListVo t : page.getRecords()){
            t.setClassIds(dto.getClassIds());
            if(t.getTextbookType() != null && !("").equals(t.getTextbookType())){
                t.setTextbookTypeCn(TextbookTypeEnum.getValue(t.getTextbookType()));
            }
            t.setStudentSubscriptionNumber(studentSubscriptionNumber);
        }
        PageOutput<TextbookSubscriptionListVo> pageOutput = ConventPage.getPageOutput(page, TextbookSubscriptionListVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/page-consumption")
    @ApiOperation(value="学生确认领取教材列表(分页，学生收费用)")
    @SaCheckPermission("textbook:detail")
    public RT<PageOutput<TextbookConsumptionPageVo>> pageConsumption(@Valid TextbookConsumptionPageDto dto){
        MPJLambdaWrapper<TextbookStudentClaim> textbookMPJLambdaWrapper = new MPJLambdaWrapper<>();
        textbookMPJLambdaWrapper
                .select(TextbookStudentClaim::getId)
                .selectAs(Textbook::getId,TextbookConsumptionPageVo::getTextbookId)
                .selectAs(BaseCourseSubject::getName, TextbookConsumptionPageVo::getCourseSubjectIdCn)
                .select(Textbook.class, x -> VoToColumnUtil.fieldsToColumns(TextbookConsumptionPageVo.class).contains(x.getProperty()))
                .leftJoin(Textbook.class, Textbook::getId, TextbookStudentClaim::getTextbookId)
                .leftJoin(BaseCourseSubject.class, BaseCourseSubject::getId, Textbook::getCourseSubjectId)
                .eq(dto.getBaseSemesterId() != null && dto.getBaseSemesterId() > 0, TextbookStudentClaim::getBaseSemesterId, dto.getBaseSemesterId())
                .eq(dto.getStudentUserId() != null && dto.getStudentUserId() > 0,TextbookStudentClaim::getStudentUserId, dto.getStudentUserId())
        ;
        IPage<TextbookConsumptionPageVo> page = textbookStudentClaimService.selectJoinListPage(ConventPage.getPage(dto),TextbookConsumptionPageVo.class,textbookMPJLambdaWrapper);
        for(TextbookConsumptionPageVo t : page.getRecords()){
            if(t.getTextbookType() != null && !t.getTextbookType().equals("")){
                t.setTextbookTypeCn(TextbookTypeEnum.getValue(t.getTextbookType()));
            }
        }
        PageOutput<TextbookConsumptionPageVo> pageOutput = ConventPage.getPageOutput(page, TextbookConsumptionPageVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/List-subscription")
    @ApiOperation(value="教材管理列表(不分页，教材征订用)")
    @SaCheckPermission("textbook:detail")
    public RT<List<TextbookSubscriptionListVo>> listSubscription(@Valid TextbookSubscriptionListDto dto){
        List<String> classIdList = new ArrayList<>();
        if(dto.getClassIds() != null && !dto.getClassIds().equals("")){
            String[] classIdArr =  dto.getClassIds().split(",");
            classIdList = Arrays.asList(classIdArr);
        }

        MPJLambdaWrapper<Textbook> textbookMPJLambdaWrapper = new MPJLambdaWrapper<>();
        textbookMPJLambdaWrapper
                .select(Textbook::getId)
                .selectAs(Textbook::getId,TextbookSubscriptionListVo::getTextbookId)
                .selectAs(BaseCourseSubject::getName, TextbookSubscriptionListVo::getCourseName)
                .selectSum(BaseClassMajorSet::getTotalStudent, TextbookSubscriptionListVo::getStudentSubscriptionNumber)
                .select(Textbook.class, x -> VoToColumnUtil.fieldsToColumns(TextbookSubscriptionListVo.class).contains(x.getProperty()))
                .leftJoin(TextbookClassRelation.class, TextbookClassRelation::getTextbookId, Textbook::getId)
                .leftJoin(BaseClassMajorSet.class, BaseClassMajorSet::getClassId, TextbookClassRelation::getClassId)
                .leftJoin(BaseCourseSubject.class, BaseCourseSubject::getId, Textbook::getCourseSubjectId)
                .in(!classIdList.isEmpty(),TextbookClassRelation::getClassId, classIdList)
                .groupBy(Textbook::getId)
                ;
        List<TextbookSubscriptionListVo> list = textbookService.selectJoinList(TextbookSubscriptionListVo.class,textbookMPJLambdaWrapper);
        return RT.ok(list);
    }

    @GetMapping(value = "/info-detail")
    @ApiOperation(value="根据id查询教材管理信息")
    @SaCheckPermission("textbook:detail")
    public RT info(@RequestParam Long id){
        Textbook textbook = textbookService.getById(id);
        if (textbook == null) {
           return RT.ok();
        }
        textbook.setTextbookClassRelationList(textbookService.getClassRelation(textbook.getId()));
        return RT.ok(BeanUtil.toBean(textbook, TextbookVo.class));
    }

    @GetMapping(value = "/info-byissn")
    @ApiOperation(value="根据isnn查询教材管理信息")
    @SaCheckPermission("textbook:detail")
    public RT<TextbookVo> infoByissn(@RequestParam String issn){
        TextbookVo textbook = textbookService.getInfoByissn(issn);
        if (textbook == null) {
            return RT.ok();
        }
        return RT.ok(textbook);
    }

    @GetMapping(value = "/info-subscription-list")
    @ApiOperation(value="教材管理-详情-征订记录")
    @SaCheckPermission("textbook:detail")
    public RT<List<TextbookSubscriptionRecordVo>> subscriptionList(@RequestParam Long id){
        List<TextbookSubscriptionRecordVo> result = textbookService.subscriptionList(id);
        if (result == null) {
            return RT.ok(new ArrayList<>());
        }
        return RT.ok(result);
    }

    @GetMapping(value = "/info-warehouse-list")
    @ApiOperation(value="教材管理-详情-入库记录")
    @SaCheckPermission("textbook:detail")
    public RT<List<TextbookWarehouseRecordListVo>> warehouseList(@RequestParam Long id){
        List<TextbookWarehouseRecordListVo> result = textbookService.warehouseList(id);
        if (result == null) {
            return RT.ok(new ArrayList<>());
        }
        return RT.ok(result);
    }

    @GetMapping(value = "/info-issue-list")
    @ApiOperation(value="教材管理-详情-出库记录")
    @SaCheckPermission("textbook:detail")
    public RT<List<TextbookIssueRecordListVo>> issueList(@RequestParam Long id){
        List<TextbookIssueRecordListVo> result = textbookService.issueList(id);
        if (result == null) {
            return RT.ok(new ArrayList<>());
        }
        return RT.ok(result);
    }

    @GetMapping(value = "/info-claim-list")
    @ApiOperation(value="教材管理-详情-领取记录")
    @SaCheckPermission("textbook:detail")
    public RT<List<WfTextbookClaimListVo>> claimList(@RequestParam Long id){
        List<WfTextbookClaimListVo> result = textbookService.claimList(id);
        if (result == null) {
            return RT.ok(new ArrayList<>());
        }
        return RT.ok(result);
    }

    @PostMapping
    @ApiOperation(value = "新增教材管理")
    @SaCheckPermission("textbook:add")
    public RT<Boolean> add(@Valid @RequestBody AddTextbookDto dto){
        Textbook textbook = BeanUtil.toBean(dto, Textbook.class);
        boolean isSuccess = textbookService.add(textbook);
        return RT.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "修改教材管理")
    @SaCheckPermission("textbook:edit")
    public RT<Boolean> update(@Valid @RequestBody UpdateTextbookDto dto){

        Textbook textbook = BeanUtil.toBean(dto, Textbook.class);
        return RT.ok(textbookService.update(textbook));

    }

    @DeleteMapping
    @ApiOperation(value = "删除教材管理")
    @SaCheckPermission("textbook:delete")
    public RT<Boolean> delete(@Valid @RequestBody List<Long> ids){
        return RT.ok(textbookService.delete(ids));
    }

    @GetMapping("/export")
    @ApiOperation(value = "导出")
    public ResponseEntity<byte[]> exportData(@Valid TextbookPageDto dto, @RequestParam(defaultValue = "false") Boolean isTemplate) {
        List<TextbookPageVo> customerList = isTemplate != null && isTemplate ? new ArrayList<>() : ((PageOutput<TextbookPageVo>) page(dto).getData()).getList();
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, TextbookPageVo.class).automaticMergeHead(false).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(customerList);

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

    @PostMapping("deliver-warehouse")
    @ApiOperation(value = "教材管理入库")
    @SaCheckPermission("textbook:add")
    public RT<Boolean> deliverWarehouse(@Valid @RequestBody AddTextbookWarehouseRecordDto dto){
        Boolean isSuccess = textbookService.deliverWarehouse(dto);
        return RT.ok(isSuccess);
    }

    @PostMapping("/textbook-standing-export-query")
    @ApiOperation(value = "台账条件导出")
    public ResponseEntity<byte[]> textbookStandingExportQuery(@Valid @RequestBody TextbookStandingExportQuerytDto dto) {
//    @GetMapping("/textbook-standing-export-query")
//    @ApiOperation(value = "台账条件导出")
//    public ResponseEntity<byte[]> textbookStandingExportQuery(@Valid TextbookStandingExportQuerytDto dto) {
        List<TextbookStandingExportQueryVo> customerList = textbookService.listTextbookStandingExportQuery(dto);
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, TextbookStandingExportQueryVo.class).automaticMergeHead(false).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(customerList);

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

    @PostMapping("/textbook-subscription-export-query")
    @ApiOperation(value = "教材征订记录条件导出")
    public ResponseEntity<byte[]> textbookSubscriptionExportQuery(@Valid @RequestBody TextbookSubscriptionExportQueryDto dto) {
//    @GetMapping("/textbook-subscription-export-query")
//    @ApiOperation(value = "教材征订记录条件导出")
//    public ResponseEntity<byte[]> textbookSubscriptionExportQuery(@Valid TextbookSubscriptionExportQueryDto dto) {

        ByteArrayOutputStream bot = textbookService.listTextbookSubscriptionExportQuery(dto);
        return RT.fileStream(bot.toByteArray(), "TextbookSubscription" + ExcelTypeEnum.XLSX.getValue());
    }

    @PostMapping("/textbook-claim-export-query")
    @ApiOperation(value = "教材发放记录条件导出")
    public ResponseEntity<byte[]> textbookClaimExportQuery(@Valid @RequestBody TextbookClaimExportQueryDto dto) {
//    @GetMapping("/textbook-claim-export-query")
//    @ApiOperation(value = "教材发放记录条件导出")
//    public ResponseEntity<byte[]> textbookClaimExportQuery(@Valid TextbookClaimExportQueryDto dto) {
        ByteArrayOutputStream bot = textbookService.listTextbookClaimExportQuery(dto);
        return RT.fileStream(bot.toByteArray(), "TextbookClaim" + ExcelTypeEnum.XLSX.getValue());
    }

    @PostMapping("/excel-import")
    @ApiOperation(value = "excel教材导入")
    @SaCheckPermission("coursetable:excelimport")
    public R excelImport( @RequestParam("file") MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        return R.ok(textbookService.excelImport(inputStream));
    }
}