package com.xjrsoft.module.room.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.excel.CustomCellRangeAddress;
import com.xjrsoft.common.utils.excel.HandleUtil;
import com.xjrsoft.module.room.dto.AddRoomValueWeekDto;
import com.xjrsoft.module.room.dto.RoomValueWeekPageDto;
import com.xjrsoft.module.room.dto.UpdateRoomValueWeekDto;
import com.xjrsoft.module.room.service.IRoomValueWeekService;
import com.xjrsoft.module.room.vo.RoomValueWeekExcelVo;
import com.xjrsoft.module.room.vo.RoomValueWeekItemExcelVo;
import com.xjrsoft.module.room.vo.RoomValueWeekItemVo;
import com.xjrsoft.module.room.vo.RoomValueWeekPageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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 javax.validation.Valid;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
* @title: 宿管值班管理
* @Author dzx
* @Date: 2024-01-03
* @Version 1.0
*/
@RestController
@RequestMapping("/room" + "/roomValueWeek")
@Api(value = "/room"  + "/roomValueWeek",tags = "宿管值班管理代码")
@AllArgsConstructor
public class RoomValueWeekController {


    private final IRoomValueWeekService roomValueWeekService;

    @GetMapping(value = "/page")
    @ApiOperation(value="宿管值班管理列表(分页)")
    @SaCheckPermission("roomvalueweek:detail")
    public RT<PageOutput<RoomValueWeekPageVo>> page(@Valid RoomValueWeekPageDto dto){
        roomValueWeekService.updateNumberPeople();
        Page<RoomValueWeekPageVo> page = roomValueWeekService.getPage(new Page<>(dto.getLimit(), dto.getSize()), dto);
        PageOutput<RoomValueWeekPageVo> pageOutput = ConventPage.getPageOutput(page, RoomValueWeekPageVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value="根据id查询宿管值班管理信息")
    @SaCheckPermission("roomvalueweek:detail")
    public RT<RoomValueWeekItemVo> info(@RequestParam Long id){
        RoomValueWeekItemVo roomValueWeek = roomValueWeekService.getItemInfo(id);
        if (roomValueWeek == null) {
           return RT.error("找不到此数据！");
        }
        return RT.ok(roomValueWeek);
    }


    @PostMapping
    @ApiOperation(value = "新增宿管值班管理")
    @SaCheckPermission("roomvalueweek:add")
    public RT<Boolean> add(@Valid @RequestBody AddRoomValueWeekDto dto){
        boolean isSuccess = roomValueWeekService.add(dto);
        return RT.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "修改宿管值班管理")
    @SaCheckPermission("roomvalueweek:edit")
    public RT<Boolean> update(@Valid @RequestBody UpdateRoomValueWeekDto dto){

        return RT.ok(roomValueWeekService.updateItem(dto));

    }

    @DeleteMapping
    @ApiOperation(value = "删除宿管值班管理")
    @SaCheckPermission("roomvalueweek:delete")
    public RT<Boolean> delete(@Valid @RequestBody List<Long> ids){
        return RT.ok(roomValueWeekService.delete(ids));

    }

    @GetMapping("/export")
    @ApiOperation(value = "导出")
    public ResponseEntity<byte[]> exportData(@Valid RoomValueWeekPageDto dto, @RequestParam(defaultValue = "false") Boolean isTemplate) throws IOException {
        List<RoomValueWeekExcelVo> dataList = roomValueWeekService.getList(dto);
        String sheetName = "数据";
        String fileName = "RoomValueWeek" + ExcelTypeEnum.XLSX.getValue();
        ByteArrayOutputStream bot = new ByteArrayOutputStream();

        ExcelWriter excelWriter = EasyExcel.write(bot).excelType(ExcelTypeEnum.XLSX).build();
        WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).needHead(Boolean.FALSE).build();

        List<RoomValueWeekItemExcelVo> demoDataList2 = new ArrayList<>();
        demoDataList2.add(new RoomValueWeekItemExcelVo(){{
            setColumn1("");
            setColumn2("");
            setColumn3("");
            setColumn4("");
        }});

        //写入数据，并计算需要合并的单元格
        int tableRows = 6;
        int j = 0;
        List<CellRangeAddress> cellRangeAddressList = new ArrayList<>();
        List<CustomCellRangeAddress> styleList = new ArrayList<>();
        for (int i = 0; i < dataList.size() * 2; ){

            WriteTable writeTable = EasyExcel.writerTable(i + 1).head(RoomValueWeekItemExcelVo.class).needHead(Boolean.FALSE).build();
            excelWriter.write(dataList.get(j).getItemList(), writeSheet, writeTable);
            //存下需要合并的单元格
            cellRangeAddressList.add(new CellRangeAddress((tableRows * j) + 0, (tableRows * j) + 0, 0, 3));
            cellRangeAddressList.add(new CellRangeAddress((tableRows * j) + 1, (tableRows * j) + 1, 0, 1));
            cellRangeAddressList.add(new CellRangeAddress((tableRows * j) + 1, (tableRows * j) + 1, 2, 3));
            cellRangeAddressList.add(new CellRangeAddress((tableRows * j) + 3, (tableRows * j) + 4, 0, 0));
            cellRangeAddressList.add(new CellRangeAddress((tableRows * j) + 3, (tableRows * j) + 4, 1, 1));

            //存下需要设置样式的单元
            styleList.add(new CustomCellRangeAddress((tableRows * j) + 0, (tableRows * j) + 0, 0, 3, Boolean.TRUE));
            styleList.add(new CustomCellRangeAddress((tableRows * j) + 1, (tableRows * j) + 1, 0, 3, Boolean.TRUE));
            styleList.add(new CustomCellRangeAddress((tableRows * j) + 2, (tableRows * j) + 2, 0, 3));
            styleList.add(new CustomCellRangeAddress((tableRows * j) + 3, (tableRows * j) + 3, 0, 3));
            styleList.add(new CustomCellRangeAddress((tableRows * j) + 4, (tableRows * j) + 4, 0, 3));

            WriteTable writeTable3 = EasyExcel.writerTable(i + 2).build();
            excelWriter.write(demoDataList2, writeSheet, writeTable3);
            cellRangeAddressList.add(new CellRangeAddress((tableRows * j) + 5, (tableRows * j) + 5, 0, 3));

            j ++;
            i = i + 2;
        }
        excelWriter.finish();

        // 将ByteArrayOutputStream转换为InputStream
        InputStream in = new ByteArrayInputStream(bot.toByteArray());

        //使用poi合并单元格，使用registerWriteHandler合并单元格会与fill方法中创建单元格后校验合并单元格冲突而引发报错
        XSSFWorkbook workbook = new XSSFWorkbook(in);
        XSSFSheet sheetAt = workbook.getSheet(sheetName);
        //合并单元格
        for (CellRangeAddress cellRangeAddress : cellRangeAddressList) {
            sheetAt.addMergedRegion(cellRangeAddress);
        }
        //设置样式
        for (CustomCellRangeAddress cellRangeAddress : styleList) {
            HandleUtil.setRegionStyle(sheetAt, cellRangeAddress, HandleUtil.setDefaultStyle(workbook, cellRangeAddress.getIsBlod()));
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        workbook.write(os);
        os.flush();
        os.close();

        return RT.fileStream(os.toByteArray(), fileName);
    }


}