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.extension.plugins.pagination.Page;
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.module.base.entity.BaseSemester;
import com.xjrsoft.module.base.service.IBaseSemesterService;
import com.xjrsoft.module.textbook.dto.*;
import com.xjrsoft.module.textbook.entity.Textbook;
import com.xjrsoft.module.textbook.service.ITextbookService;
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.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 IBaseSemesterService baseSemesterService;

    @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 = "/info-detail")
    @ApiOperation(value="根据id查询教材管理信息")
    @SaCheckPermission("textbook:detail")
    public RT<TextbookVo> 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) {
        List<TextbookSubscriptionExportQueryVo> customerList = textbookService.listTextbookSubscriptionExportQuery(dto);
        ByteArrayOutputStream bot = new ByteArrayOutputStream();

        // 设置动态头
        String baseSemesterCn = "";
        if(dto.getBaseSemesterId() != null){
            LambdaQueryWrapper<BaseSemester> baseSemesterLambdaQueryWrapper = new LambdaQueryWrapper<>();
            baseSemesterLambdaQueryWrapper
                    .eq(BaseSemester::getId, dto.getBaseSemesterId());
            BaseSemester baseSemester = baseSemesterService.getOne(baseSemesterLambdaQueryWrapper);
            if(baseSemester != null){
                baseSemesterCn = baseSemester.getName();
            }
        }
        String headTitle = "重庆市铜梁职业教育中心" + baseSemesterCn + "教材征订表";
        List<List<String>> headList = new ArrayList<>();
//        List<String> head0 = new ArrayList<>();
//        head0.add("个人信息");
//        head0.add("用户名");
//        List<String> head1 = new ArrayList<>();
//        head1.add("个人信息");
//        head1.add("年龄");
//        List<String> head2 = new ArrayList<>();
//        head2.add("个人信息");
//        head2.add("地址");
        headList.add(new ArrayList<String>(){{
            add(headTitle);
            add("国际标准刊号");
        }});
        headList.add(new ArrayList<String>(){{
            add(headTitle);
            add("书名");
        }});
        headList.add(new ArrayList<String>(){{
            add(headTitle);
            add("出版社");
        }});
        headList.add(new ArrayList<String>(){{
            add(headTitle);
            add("主编");
        }});
        headList.add(new ArrayList<String>(){{
            add(headTitle);
            add("估价(元)");
        }});
        headList.add(new ArrayList<String>(){{
            add(headTitle);
            add("是否为规划教材");
        }});
        headList.add(new ArrayList<String>(){{
            add(headTitle);
            add("对应课程");
        }});
        headList.add(new ArrayList<String>(){{
            add(headTitle);
            add("使用年级");
        }});
        headList.add(new ArrayList<String>(){{
            add(headTitle);
            add("使用班级");
        }});
        headList.add(new ArrayList<String>(){{
            add(headTitle);
            add("学生用书征订数量");
        }});
        headList.add(new ArrayList<String>(){{
            add(headTitle);
            add("教师教材用书征订数量");
        }});
        headList.add(new ArrayList<String>(){{
            add(headTitle);
            add("教师教参用书征订数量");
        }});
        headList.add(new ArrayList<String>(){{
            add(headTitle);
            add("学科组名称");
        }});
        headList.add(new ArrayList<String>(){{
            add(headTitle);
            add("有无配套教学资源");
        }});
        headList.add(new ArrayList<String>(){{
            add(headTitle);
            add("备注");
        }});
        EasyExcel.write(bot, TextbookSubscriptionExportQueryVo.class).automaticMergeHead(true).excelType(ExcelTypeEnum.XLSX).head(headList).sheet().doWrite(customerList);

        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));
    }
}