package com.pqs9900.controller.linedata;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.njcn.enums.LogTypeEnum;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.pointInfo.LineLedger;
import com.njcn.utils.PubUtils;
import com.pqs9900.listener.LineMarkExcelListener;
import com.pqs9900.pojo.linedata.MarkExcel;
import com.pqs9900.service.linedata.LineMarkService;
import com.pqs9900.util.csv.GetByteEncode;
import com.pqs9900.util.csv.ReadCsvUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * system
 *
 * @author cdf
 * @date 2021/10/27
 */
@RestController
@RequestMapping("lineMark")
public class LineMarkController {

    @Resource
    private LineMarkService lineMarkService;

    /**
     * 获取监测点台账列表
     *
     * @author cdf
     * @date 2021/10/27
     */
    @GetMapping("getLineMark")
    public HttpResult getLineMark(Integer status, Integer lineGrade) {
        List<LineLedger> list = lineMarkService.getLineMark(status, lineGrade);
        if (CollectionUtil.isNotEmpty(list)) {
            return PubUtils.assignmentResult(list, 200, "获取成功");
        } else {
            return PubUtils.assignmentResult(null, 500, "获取失败");
        }
    }

    /**
     * 单个新增或修改监测点等级
     *
     * @author cdf
     * @date 2021/11/2
     */
    @PostMapping("singleOperate")
    public HttpResult singleOperate(Integer lineIndex, String lineGrade) {
        if (Objects.isNull(lineIndex)) {
            return PubUtils.assignmentResult(null, 500, "参数出错");
        }
        Integer res = lineMarkService.singleOperate(lineIndex, lineGrade);
        if (res == 1) {
            return PubUtils.assignmentResult(null, 200, "操作成功");
        } else {
            return PubUtils.assignmentResult(null, 500, "操作失败");
        }
    }

    /**
     * 获取监测点评级
     *
     * @author cdf
     * @date 2021/11/2
     */
    @GetMapping("getLineGrade")
    public HttpResult getLineGrade(Integer lineIndex) {
        LineLedger lineLedger = lineMarkService.getLineGrade(lineIndex);
        if (Objects.isNull(lineLedger)) {
            return PubUtils.assignmentResult(null, 500, "获取失败");
        }
        return PubUtils.assignmentResult(lineLedger, 200, "获取成功");
    }


    /**
     * 批量导入监测点评分excel
     *
     * @author cdf
     * @date 2021/10/27
     */
    @PostMapping("batchImport")
    public HttpResult batchExport(@RequestParam(value = "file") MultipartFile file) {
        HttpResult result;
        //获取文件名
        String fileName = file.getOriginalFilename();

        //文件大小(此大小为kb)
        Long fileSize = file.getSize() / 1024;
        //判断文件大小
        if (fileSize > 30720) {
            result = PubUtils.assignmentResult(null, 500, "上传失败,上传文件超过30M，文件过大!");
            return result;
        }

        if (!fileName.matches("^.+\\.(?i)(xlsx)$") && !fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(csv)$")) {
            result = PubUtils.assignmentResult(null, 500, "上传文件类型错误!");
            return result;
        }
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            return PubUtils.assignmentResult(null, 500, "文件读取异常!");
        }


        if (fileName.matches("^.+\\.(?i)(csv)$")) {
            //解析csv文件
            List<MarkExcel> csvList = new ArrayList<>();


            BufferedReader bufferedReader = null;
            ByteArrayInputStream fis = null;
            InputStreamReader isr = null;
            byte[] bate = new byte[0];
            try {
                bate = file.getBytes();
                fis = new ByteArrayInputStream(bate);
                //指定以当前文件编码读取
                isr = new InputStreamReader(fis, GetByteEncode.getEncoding(bate));
                bufferedReader = new BufferedReader(isr);

                String csvStr;
                int flag = 1;
                //读取到的内容给line变量
                while ((csvStr = bufferedReader.readLine()) != null) {
                    String msg = "";
                    if (flag == 1) {
                        msg = "表头行";
                    } else {
                        msg = "第" + flag + "行";
                    }

                    System.out.println(csvStr);

                    String[] strArr = csvStr.trim().replace("\uFEFF","").split(",");
                    List<String> strList = Arrays.asList(strArr);
                    if (CollectionUtil.isEmpty(strList)) {
                        return PubUtils.assignmentResult(null, 500, msg + "数据缺失!");
                    }
                    if (strList.size() != 6) {
                        return PubUtils.assignmentResult(null, 500, msg + "数据缺失!");
                    }
                    if (flag == 1) {
                        if (!"省份".equals(strList.get(0)) || !"供电公司".equals(strList.get(1)) || !"所属变电站".equals(strList.get(2))
                                || !"装置名称".equals(strList.get(3)) || !"监测点名称".equals(strList.get(4)) || !"监测点评级".equals(strList.get(5))) {
                            return PubUtils.assignmentResult(null, 500, "csv表头出错!");
                        }
                    } else {
                        MarkExcel markExcel = new MarkExcel();
                        markExcel.setProvince(strList.get(0).trim());
                        markExcel.setGdName(strList.get(1).trim());
                        markExcel.setSubName(strList.get(2).trim());
                        markExcel.setDevName(strList.get(3).trim());
                        markExcel.setLineName(strList.get(4).trim());
                        markExcel.setMark(strList.get(5).trim());
                        csvList.add(markExcel);
                    }
                    flag++;
                }
                if (CollectionUtil.isEmpty(csvList)) {
                    return PubUtils.assignmentResult(null, 500, "导入数据为空!");
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    if (isr != null) {
                        isr.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


            String deal = lineMarkService.dealData(csvList);
            if ("操作成功".equals(deal)) {
                return PubUtils.assignmentResult(null, 200, deal);
            } else {
                return PubUtils.assignmentResult(null, 500, deal);
            }


        } else {
            LineMarkExcelListener lineMarkExcelListener = new LineMarkExcelListener(lineMarkService);
            try {
                EasyExcel.read(inputStream, MarkExcel.class, lineMarkExcelListener).sheet().headRowNumber(1).doRead();
            } catch (ExcelAnalysisException e) {
                return PubUtils.assignmentResult(null, 500, e.getMessage());
            }
        }


        return PubUtils.assignmentResult(null, 200, "操作成功");
    }

    /**
     * 导出模板
     *
     * @author cdf
     * @date 2021/11/1
     */
 /*   @GetMapping("exportTemplate")
    public void exportTemplate(HttpServletResponse response) {
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());


        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        try {
            response.setContentType("application/force-download");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "No-cache");
            response.setDateHeader("Expires", 0);
            String encodeFileName = URLEncoder.encode("监测点评级批量模板", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName + ".xls");

            OutputStream outputStream = null;
            outputStream = response.getOutputStream();
            ExcelWriterBuilder builder = EasyExcel.write(outputStream, MarkExcel.class).registerWriteHandler(new SheetWriteHandler() {
                @Override
                public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
                }

                @Override
                public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

                    String[] yesOrNo = new String[]{"极重要", "重要", "普通", "不重要"};

                    Sheet sheet = writeSheetHolder.getSheet();
                    DataValidationHelper helper = sheet.getDataValidationHelper();//设置下拉框
                    *//***起始行、终止行、起始列、终止列**//*
                    CellRangeAddressList addressList = new CellRangeAddressList(1, 1000, 5, 5);
                    *//***设置下拉框数据**//*
                    DataValidationConstraint constraint = helper.createExplicitListConstraint(yesOrNo);
                    DataValidation dataValidation = helper.createValidation(constraint, addressList);
                    *//***处理Excel兼容性问题**//*
                    if (dataValidation instanceof XSSFDataValidation) {
                        dataValidation.setSuppressDropDownArrow(true);
                        dataValidation.setShowErrorBox(true);
                    } else {
                        dataValidation.setSuppressDropDownArrow(false);
                    }
                    sheet.addValidationData(dataValidation);

                }


            }).registerWriteHandler(horizontalCellStyleStrategy);
            ExcelWriter excelWriter = builder.build();
            WriteSheet sheet1 = EasyExcel.writerSheet(0).head(MarkExcel.class).build();
            excelWriter.write(new ArrayList(0), sheet1);


            excelWriter.finish();


        } catch (IOException e) {
            e.printStackTrace();
        }
       *//* wb.write(outputStream);
        wb.close();
        outputStream.close();*//*

    }*/

    /*********************************************************终端在线率*************begin*/

    /**
     * 获取终端在线率
     *
     * @author cdf
     * @date 2021/11/2
     */
    public HttpResult getOnlineData(String area, String begin, String end, String lineGrade) {

        return null;
    }


    public static String getFileCharsetName(InputStream inputStream) throws IOException {
        byte[] head = new byte[3];
        inputStream.read(head);

        String charsetName = "GBK";//或GB2312，即ANSI
        if (head[0] == -1 && head[1] == -2) //0xFFFE
        {
            charsetName = "UTF-16";
        } else if (head[0] == -2 && head[1] == -1) //0xFEFF
        {
            charsetName = "Unicode";//包含两种编码格式：UCS2-Big-Endian和UCS2-Little-Endian
        } else if (head[0] == -27 && head[1] == -101 && head[2] == -98) {
            charsetName = "UTF-8"; //UTF-8(不含BOM)
        } else if (head[0] == -17 && head[1] == -69 && head[2] == -65) {
            charsetName = "UTF-8"; //UTF-8-BOM
        }

        inputStream.close();

        System.out.println("");
        return charsetName;
    }


    /**
     * 批量修改退运监测点评级为空
     * @author cdf
     * @date 2023/7/6
     */
    @GetMapping("batchUpdateLineMarkStop")
    public HttpResult batchUpdateLineMarkStop(){
        boolean flag = lineMarkService.batchUpdateLineMarkStop();
        if(flag){
            return PubUtils.assignmentResult(null, 200, "操作成功");
        }
        return PubUtils.assignmentResult(null, 500, "不存在退运评级的监测点");
    }

}
