package cn.iocoder.yudao.module.llm.controller.admin.dataset;

import cn.iocoder.yudao.module.llm.controller.admin.dataset.vo.DatasetAnswerRespVO;
import cn.iocoder.yudao.module.llm.controller.admin.dataset.vo.DatasetQuestionPageReqVO;
import cn.iocoder.yudao.module.llm.controller.admin.dataset.vo.DatasetQuestionRespVO;
import cn.iocoder.yudao.module.llm.controller.admin.dataset.vo.DatasetQuestionSaveReqVO;
import cn.iocoder.yudao.module.llm.dal.dataobject.dataset.DatasetQuestionDO;
import cn.iocoder.yudao.module.llm.service.dataset.DatasetQuestionService;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;


@Tag(name = "管理后台 - 数据集数据问题+标注")
@RestController
@RequestMapping("/llm/dataset-question")
@Validated
public class DatasetQuestionController {

    @Resource
    private DatasetQuestionService datasetQuestionService;


    @PutMapping("data-anno")
    @Operation(summary = "保存标注接口")
    @PreAuthorize("@ss.hasPermission('llm:dataset-question:anno')")
    public CommonResult<Boolean> updateDatasetQuestionDataAnno(@Valid @RequestBody List<DatasetQuestionSaveReqVO> updateReqVOS) {
        datasetQuestionService.updateDatasetQuestionDataAnno(updateReqVOS);
        return success(true);
    }
    @GetMapping("/page")
    @Operation(summary = "获得数据集数据问题分页")
    @PreAuthorize("@ss.hasPermission('llm:dataset-question:query')")
    public CommonResult<PageResult<DatasetQuestionRespVO>> getDatasetQuestionPage(@Valid DatasetQuestionPageReqVO pageReqVO) {
        PageResult<DatasetQuestionRespVO> pageResult = datasetQuestionService.getDatasetQuestionPage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出数据集数据文件 Excel")
    @PreAuthorize("@ss.hasPermission('llm:dataset-files:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDatasetFilesExcel(@Valid DatasetQuestionPageReqVO pageReqVO,
                                        HttpServletResponse response) throws IOException {
        HSSFWorkbook template = new HSSFWorkbook();
        HSSFSheet sheet = template.createSheet();
        // 创建样式并设置垂直居中
        HSSFCellStyle cellStyle = template.createCellStyle();
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        int count = 0;
        HSSFRow row = sheet.createRow(count);
        row.createCell(0).setCellValue("问题内容");
        row.createCell(1).setCellValue("标注内容");
        count++;
        List<Integer> id = new ArrayList<>();
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DatasetQuestionRespVO> list = datasetQuestionService.getDatasetQuestionPage(pageReqVO).getList();
        for (DatasetQuestionRespVO item : list){
            String question = item.getQuestion();
            List<DatasetAnswerRespVO> datasetAnswerRespVO = item.getDatasetAnswerRespVO();
            List<String> collect = datasetAnswerRespVO.stream().map(DatasetAnswerRespVO::getAnswer).collect(Collectors.toList());
            if (collect.size() == 0){
                row = sheet.createRow(count);
                row.createCell(0).setCellValue(question);
                row.createCell(1).setCellValue("");
                id.add(count);
                count++;
            }else {
                for (String s : collect) {
                    row = sheet.createRow(count);
                    row.createCell(0).setCellValue(question);
                    row.createCell(1).setCellValue(s);
                    count++;
                }
                id.add(count-1);
            }
        }
        //合并相同内容的单元格
        for (int i = 0; i < id.size() - 1; i++){
            if (id.get(i+1)-id.get(i)>1) {
                sheet.addMergedRegion(new CellRangeAddress(id.get(i)+1, id.get(i + 1), 0, 0));
            }
        }
        // 导出 Excel
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            template.write(response.getOutputStream());
            response.getOutputStream().close();
            template.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

/*    @PutMapping("/update")
    @Operation(summary = "更新数据集数据问题")
    @PreAuthorize("@ss.hasPermission('llm:dataset-question:update')")
    public CommonResult<Boolean> updateDatasetQuestion(@Valid @RequestBody DatasetQuestionSaveReqVO updateReqVO) {
        datasetQuestionService.updateDatasetQuestion(updateReqVO);
        return success(true);
    }*/

/*    @DeleteMapping("/delete")
    @Operation(summary = "删除数据集数据问题")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('llm:dataset-question:delete')")
    public CommonResult<Boolean> deleteDatasetQuestion(@RequestParam("id") Long id) {
        datasetQuestionService.deleteDatasetQuestion(id);
        return success(true);
    }*/

/*    @GetMapping("/get")
    @Operation(summary = "获得数据集数据问题")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('llm:dataset-question:query')")
    public CommonResult<DatasetQuestionRespVO> getDatasetQuestion(@RequestParam("id") Long id) {
        DatasetQuestionDO datasetQuestion = datasetQuestionService.getDatasetQuestion(id);
        return success(BeanUtils.toBean(datasetQuestion, DatasetQuestionRespVO.class));
    }*/



/*    @GetMapping("/export-excel")
    @Operation(summary = "导出数据集数据问题 Excel")
    @PreAuthorize("@ss.hasPermission('llm:dataset-question:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDatasetQuestionExcel(@Valid DatasetQuestionPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DatasetQuestionDO> list = datasetQuestionService.getDatasetQuestionPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "数据集数据问题.xls", "数据", DatasetQuestionRespVO.class,
                        BeanUtils.toBean(list, DatasetQuestionRespVO.class));
    }*/

    /*    @PostMapping("/create")
    @Operation(summary = "创建数据集数据问题")
    @PreAuthorize("@ss.hasPermission('llm:dataset-question:create')")
    public CommonResult<Long> createDatasetQuestion(@Valid @RequestBody DatasetQuestionSaveReqVO createReqVO) {
        return success(datasetQuestionService.createDatasetQuestion(createReqVO));
    }*/

}
