package com.pqs9900.controller.linedata;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.pointInfo.LineLedger;
import com.njcn.utils.PubUtils;
import com.pqs9900.listener.LineMarkWeightExcelListener;
import com.pqs9900.listener.LineMarkWeightExcelListener;
import com.pqs9900.pojo.linedata.LineMarkWeight;
import com.pqs9900.pojo.linedata.LineMarkWeightVo;
import com.pqs9900.pojo.linedata.MarkWeightExcel;
import com.pqs9900.service.linedata.LineMarkWeightService;
import com.pqs9900.util.csv.GetByteEncode;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * system
 * 监测点评分权重
 * @author cdf
 * @date 2023/8/16
 */
@RestController
@RequestMapping("lineWeightMark")
public class LineMarkWeightController {

    @Resource
    private LineMarkWeightService lineMarkWeightService;

    /**
     * 获取监测点台账列表
     *
     * @author cdf
     * @date 2021/10/27
     */
    @GetMapping("getLineMarkWeight")
    public HttpResult getLineMarkWeight(Integer devFlag, Integer lineGrade) {
        List<LineMarkWeightVo> list = lineMarkWeightService.getLineMarkWeight(devFlag, 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(@RequestBody LineMarkWeight lineMarkWeight) {
        Integer res = lineMarkWeightService.singleOperate(lineMarkWeight);
        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 = lineMarkWeightService.getLineGrade(lineIndex);
        if (Objects.isNull(lineLedger)) {
            return PubUtils.assignmentResult(null, 500, "获取失败");
        }
        return PubUtils.assignmentResult(lineLedger, 200, "获取成功");
    }


    /**
     * 批量导入监测点评分excel
     *
     * @author cdf
     * @date 2021/10/27
     */
    @PostMapping("batchImportLineWeight")
    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<MarkWeightExcel> csvList = new ArrayList<>();


            BufferedReader bufferedReader = null;
            ByteArrayInputStream fis = null;
            InputStreamReader isr = null;
            byte[] bate;
            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() != 14) {
                        return PubUtils.assignmentResult(null, 500, msg + "数据缺失!");
                    }
                    if (flag == 1) {
                        if (!"省份".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 {


                            MarkWeightExcel MarkWeightExcel = new MarkWeightExcel();
                            MarkWeightExcel.setIndex(strList.get(0).trim());
                            MarkWeightExcel.setProvince(strList.get(1).trim());
                            MarkWeightExcel.setGdName(strList.get(2).trim());
                            MarkWeightExcel.setSubName(strList.get(3).trim());
                            MarkWeightExcel.setDevName(strList.get(4).trim());
                            MarkWeightExcel.setLineName(strList.get(5).trim());


                            try {
                                MarkWeightExcel.setCommunFeeMark(Integer.valueOf(strList.get(6)));
                                MarkWeightExcel.setAssetBelong(Integer.valueOf(strList.get(7)));
                                MarkWeightExcel.setServiceMark(Integer.valueOf(strList.get(8)));
                                MarkWeightExcel.setAgentMark(Integer.valueOf(strList.get(9)));
                                MarkWeightExcel.setCompanyMark(Integer.valueOf(strList.get(10)));
                                MarkWeightExcel.setUserMark(Integer.valueOf(strList.get(11)));
                                MarkWeightExcel.setLineTypeMark(Integer.valueOf(strList.get(12)));
                                MarkWeightExcel.setBusinessMark(Integer.valueOf(strList.get(13)));
                            } catch (NumberFormatException numberFormatException) {
                                return PubUtils.assignmentResult(null, 500, msg + "填写的分值格式错误!");
                            }
                            csvList.add(MarkWeightExcel);

                    }
                    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 = lineMarkWeightService.dealData(csvList);
            if ("操作成功".equals(deal)) {
                return PubUtils.assignmentResult(null, 200, deal);
            } else {
                return PubUtils.assignmentResult(null, 500, deal);
            }

        } else {
            LineMarkWeightExcelListener lineMarkWeightExcelListener = new LineMarkWeightExcelListener(lineMarkWeightService);
            try {
                EasyExcel.read(inputStream, MarkWeightExcel.class, lineMarkWeightExcelListener).sheet().headRowNumber(1).doRead();
            } catch (ExcelAnalysisException e) {
                return PubUtils.assignmentResult(null, 500, e.getMessage());
            }
        }

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


}
