package com.tuoheng.admin.service;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.dto.InspectionFileExportExcelDto;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.entity.InspectionFile;
import com.tuoheng.admin.enums.*;
import com.tuoheng.admin.mapper.InspectionFileMapper;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.request.inspectionfile.QueryInspectionFilePageListRequest;
import com.tuoheng.admin.service.inspectionfile.IInspectionFileService;
import com.tuoheng.admin.utils.excel.*;
import com.tuoheng.common.core.config.UploadFileConfig;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.utils.CommonUtils;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class InspectionFileServiceTest {

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private IInspectionFileService iInspectionFileService;

    @Test
    public void testPageList() {
        QueryInspectionFilePageListRequest request = new QueryInspectionFilePageListRequest();
        request.setKey("");
        request.setQuestionCode("1");
        request.setStatus(15);
        request.setDeptId("");
        request.setBeginTime(DateUtils.now());
        request.setEndTime(DateUtils.now());
        request.setPage(1);
        request.setLimit(2);

        JSONObject json = (JSONObject) JSONObject.toJSON(request);
        log.info("-----> 获取分页列表请求参数：json={}", json);

        JsonResult result = iInspectionFileService.getPageList(request);
        System.out.println(">>>>>>>>>>>>>" + result);
    }

    @Test
    public void testAddList() {
        List<InspectionFile> thirstyQuestionFiles = new ArrayList<>();
        InspectionFile inspectionFile;
        for (int i = 1; i < 2; i++) {
            inspectionFile = new InspectionFile();
            inspectionFile.setQuestionCode(i + "");
            inspectionFile.setTenantId("1");
            inspectionFile.setInspectionId("1");
            // 文件类型
            inspectionFile.setFileType(FileTypeEnum.IMAGE.getCode());
            // 文件编码
            inspectionFile.setFileCode(inspectionFile.getFileCode());
            // 文件名称
            inspectionFile.setFileName(inspectionFile.getFileName());
            //图片大小，单位MB，保留两位小数，目前没有获取图片大小的字段
            inspectionFile.setFileSize(0.00);

            // 问题图片审核状态
            inspectionFile.setStatus(QuestionEnum.NOTREVIEWED.getCode());
            // 问题图片来源
            inspectionFile.setSource(SourceEnum.AI.getCode());
            inspectionFile.setCreateUser("1"); // 设置默认用户
            inspectionFile.setCreateTime(DateUtils.now());

            if (0 == 1) {
                inspectionFile.setMark(MarkEnum.NOTVALID.getCode());
                log.info("修改问题mark值mark={}", inspectionFile.getMark());
            }

            thirstyQuestionFiles.add(inspectionFile);
        }

        String id = RandomUtil.randomString(36);
        System.out.println(id);
        System.out.println(id.length());

        CommonUtils.batchOperate((x) -> inspectionFileMapper.addBatch(x), thirstyQuestionFiles, 1000);
    }

    @Test
    public void testUpdate() {
        //查询当前问题
        InspectionFile entity = inspectionFileMapper.selectOne(new LambdaQueryWrapper<InspectionFile>()
                .eq(InspectionFile::getId, "5l7pr9kuhfiuf8opi0h79qy2ghv6kb5093yq")
                .eq(InspectionFile::getMark, 1));

        LambdaUpdateWrapper<InspectionFile> qw = new LambdaUpdateWrapper<>();
        qw.eq(InspectionFile::getId, entity.getId());
        qw.eq(InspectionFile::getMark, 1);
        qw.set(InspectionFile::getStatus, 15);
        qw.set(InspectionFile::getCheckUser, "aa");
        qw.set(InspectionFile::getCheckTime, DateUtils.now());
        int count = inspectionFileMapper.update(entity, qw);
    }

    @Test
    public void tesExport() {
        Inspection inspection = inspectionMapper.selectOne(Wrappers.<Inspection>lambdaQuery()
                .eq(Inspection::getId, 1)
                .eq(Inspection::getMark, MarkEnum.VALID.getCode())
                .last("limit 1"));
        List<InspectionFile> inspectionFileList = inspectionFileMapper.selectList(Wrappers.<InspectionFile>lambdaQuery()
                .eq(InspectionFile::getInspectionId, 1)
                .eq(InspectionFile::getMark, MarkEnum.VALID.getCode())
                .last("limit 1, 10"));


        File fd = new File(UploadFileConfig.uploadFolder + "/inspectionFile");
        //目录是否存在
        if(!fd.exists()){
            fd.mkdirs();
        }
        String fileName = inspection.getName()+"+"+inspection.getCode()+".xlsx";
//        String filePath = "/data/java/tuoheng_waterway/inspectionFile/";
        String filePath = UploadFileConfig.uploadFolder + "/inspectionFile/" + fileName;

        try {
            easyExcel(inspection, inspectionFileList, filePath);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }

    }

    public JsonResult easyExcel(Inspection inspection, List<InspectionFile> inspectionFileList, String filePath) throws MalformedURLException {
        log.info("文件输出目录及格式：filePathName={}", filePath);

        List<InspectionFileExportExcelDto> inspectionFileExportExcelDtoList = new ArrayList<>();
        InspectionFile inspectionFile;
        InspectionFileExportExcelDto inspectionFileExportExcelDto;
        for (int i = 0; i < inspectionFileList.size(); i++) {
            inspectionFile = inspectionFileList.get(i);
            inspectionFileExportExcelDto = new InspectionFileExportExcelDto();
            inspectionFileExportExcelDto.setSequence(i + 1);
            inspectionFileExportExcelDto.setFileOriginal(new URL(CommonConfig.imageURL + inspectionFile.getFileOriginal()));
            inspectionFileExportExcelDto.setFileImage(new URL(CommonConfig.imageURL + inspectionFile.getFileImage()));
            inspectionFileExportExcelDto.setLocation(inspectionFile.getLongitude() + "," + inspectionFile.getLatitude());
//            inspectionFileExportExcelDto.setSectionName(inspection.getSectionName());
//            inspectionFileExportExcelDto.setRoadName(inspection.getRoadName());
            if (InspectionFileStatusEnum.WAIT_CONFIRMED.getCode() == inspectionFile.getStatus()) {
                inspectionFileExportExcelDto.setStatus("待确认");
            } else if (InspectionFileStatusEnum.IGNORED.getCode() == inspectionFile.getStatus()) {
                inspectionFileExportExcelDto.setStatus("已忽略");
            } else if (InspectionFileStatusEnum.CONFIRMED.getCode() == inspectionFile.getStatus()) {
                inspectionFileExportExcelDto.setStatus("已确认");
            } else if (InspectionFileStatusEnum.GENERATE_ORDER.getCode() == inspectionFile.getStatus()) {
                inspectionFileExportExcelDto.setStatus("已生成工单");
            } else if (InspectionFileStatusEnum.PROCESSED.getCode() == inspectionFile.getStatus()) {
                inspectionFileExportExcelDto.setStatus("已处理");
            }
            inspectionFileExportExcelDtoList.add(inspectionFileExportExcelDto);
        }

        List<List<String>> heads = new ArrayList<>();
        String totalName = "疑似问题清单";

        String totalName2 = "巡检任务：" + inspection.getName() + " 巡检时间：" + inspection.getInspectionTime();

        String[] nameString = {"序号", "问题类型", "问题图片", "标注图片", "位置", "所属路段", "所属高速", "状态"};
        for (String excelName : nameString) {
            heads.add(Arrays.asList(totalName, totalName2, excelName));
        }
        //需要写出的表格（对应实体类）
        try {

            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(StyleUtils.getHeadStyle(), StyleUtils.getContentStyle());

            EasyExcel.write(filePath, InspectionFileExportExcelDto.class).sheet("问题清单数据")
                    .head(heads)
//                    .registerWriteHandler(new SimpleColumnWidthStyleStrategy(20)) // 简单的列宽策略，列宽20
                    .registerWriteHandler(new CustomCellWriteWidthHandler())
//                    .registerWriteHandler(new CustomCellWriteHeightConfig())
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .registerWriteHandler(new ImageModifyHandler())
                    .doWrite(inspectionFileExportExcelDtoList); // 数据源


//            // 内容样式
//            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//            contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);      // 水平居中
//            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);  // 垂直居中
//            contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);//细实线
//            contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
//            contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
//            contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
//
//
//            //设计内容居中
//            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER); //设置内容自动换行
//            contentWriteCellStyle.setWrapped(true);
//
//            //设置头部样式
//            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
//            //设置头部标题居中
//            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//            // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
//            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
//
//            // 将数据写进流，如果是响应流则写进header对应的文件里
//            ExcelWriter excelWriter = EasyExcel.write(filePath, InspectionFileExportExcelDto.class).build();
//
//            //指定sheet的名字和头信息
//            WriteSheet writeSheet = EasyExcel.writerSheet(0, "日历导出")
//                    .head(heads)
//                    .registerWriteHandler(new SimpleColumnWidthStyleStrategy(20))
//                    .registerWriteHandler(horizontalCellStyleStrategy)
//                    .registerWriteHandler(new CustomCellWriteHandler())
////                    .registerWriteHandler(new CustomCellWriteHeightConfig())
//                    .registerWriteHandler(new ImageModifyHandler())
//                    .build();
//            //将数据真正写入excel中
//            excelWriter.write(inspectionFileExportExcelDtoList, writeSheet);
//            //千万别忘记finish 会帮忙关闭流
//            excelWriter.finish();

        } catch (Exception e) {
            log.info("生成数据导出excel异常");
            throw new RuntimeException(e);
        }
        log.info("开始写入表格中");

        return JsonResult.success();
    }
}
