package com.inspect.statistics.controller;

import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.inspect.base.core.constant.AlgConstants;
import com.inspect.base.core.exception.ServiceException;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.poi.ExcelUtil;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.base.core.web.page.TableDataInfo;
import com.inspect.common.log.annotation.Log;
import com.inspect.common.log.enums.BizType;
import com.inspect.message.MessageUtils;
import com.inspect.statistics.domain.StatisticsPatrolResult;
import com.inspect.statistics.service.PatrolStatisticsService;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLEncoder;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({"/statistics"})
public class PatrolStatisticsController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(PatrolStatisticsController.class);
    @Resource
    PatrolStatisticsService statisticsService;

    @Autowired
    MessageUtils messageUtils;

    @GetMapping({"/list"})
    public TableDataInfo queryPatrolResult(StatisticsPatrolResult result) {
        this.statisticsService.verifyParam(result);
        this.startPage();
        List<StatisticsPatrolResult> patrolResults = this.statisticsService.queryPatrolResult(result);
        return this.getDataTable(patrolResults);
    }

    @Log(
            title = "数据对比分析-巡视结果列表查询",
            businessType = BizType.OTHER
    )
    @GetMapping({"/listMulti"})
    public TableDataInfo queryPatrolResultMulti(StatisticsPatrolResult result) {
        try {
            this.statisticsService.verifyParam(result);
        } catch (ServiceException e) {
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(500);
            rspData.setMsg(e.getMessage());
            return rspData;
        }

        this.startPage();
        if (StringUtils.isNotEmpty(result.getRecognitionType())) {
            if ("4".equals(result.getRecognitionType())) {
                List<String> arrayList = new ArrayList<>();
                arrayList.add(AlgConstants.INFRA_1800);
                arrayList.add(AlgConstants.INFRA_YU3);
                arrayList.add(AlgConstants.INFRA_CAMERA);
                arrayList.add(AlgConstants.INFRA_CAMERA_REVERSE);
                // 红外测温
                result.setRecognitionTypes(arrayList);
            } else {
                List<String> arrayList = new ArrayList<>();
                arrayList.add("1".equals(result.getRecognitionType()) ? AlgConstants.METER : result.getRecognitionType());
                result.setRecognitionTypes(arrayList);
            }
        }

        List<StatisticsPatrolResult> patrolResults = this.statisticsService.queryPatrolResultMulti(result);
        return this.getDataTable(patrolResults);
    }

    @GetMapping({"/chartsMulti"})
    public AjaxResult chartsMulti(StatisticsPatrolResult result) {
        try {
            this.statisticsService.verifyParam(result);
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        }

        if (StringUtils.isNotEmpty(result.getRecognitionType())) {
            if ("4".equals(result.getRecognitionType())) {
                List<String> arrayList = new ArrayList();
                arrayList.add(AlgConstants.INFRA_1800);
                arrayList.add(AlgConstants.INFRA_YU3);
                arrayList.add(AlgConstants.INFRA_CAMERA);
                arrayList.add(AlgConstants.INFRA_CAMERA_REVERSE);
                // 红外测温
                result.setRecognitionTypes(arrayList);
            } else {
                List<String> arrayList = new ArrayList<>();
                arrayList.add("1".equals(result.getRecognitionType()) ? AlgConstants.METER : result.getRecognitionType());
                result.setRecognitionTypes(arrayList);
            }
        }
        JSONArray group = this.statisticsService.chartsMulti(result);
        return AjaxResult.success(group);
    }

    @Log(
            title = "数据对比分析-巡视结果数据对比",
            businessType = BizType.OTHER
    )
    @PostMapping({"/analyse"})
    public AjaxResult analyse(@RequestBody String json) {
        JSONObject jsonObject = JSONObject.parseObject(json);
        Integer type = jsonObject.getInteger("type");
        String lineIds = jsonObject.getString("lineIds");
        double threshold = jsonObject.getDoubleValue("threshold");
        if (type == null) {
            throw new ServiceException("对比类型不能为空");
        } else if (StringUtils.isBlank(lineIds) && lineIds.split(",").length < 2) {
            throw new ServiceException("对比项不能为空,且大于一项");
        } else {
            return this.statisticsService.analyse(type, lineIds, threshold);
        }
    }

    @Log(
            title = "数据对比分析-同设备表计对比",
            businessType = BizType.OTHER
    )
    @PostMapping({"/verifyNumber"})
    public AjaxResult verifyNumber(@RequestBody String json) {
        JSONObject jsonObject = JSONObject.parseObject(json);
        Integer num = jsonObject.getInteger("num");
        String deviceId = jsonObject.getString("deviceId");
        String patrolDeviceCode = jsonObject.getString("patrolDeviceCode");
        if (StringUtils.isBlank(deviceId)) {
            throw new ServiceException("设备ID不能为空");
        } else {
            if (num == null) {
                num = 5;
            }

            return this.statisticsService.queryNumTypeInfo(num, deviceId, patrolDeviceCode);
        }
    }

    @Log(
            title = "数据对比分析-巡视结果导出",
            businessType = BizType.EXPORT
    )
    @GetMapping({"/export"})
    public void exportExcel(StatisticsPatrolResult result, HttpServletResponse response) throws IOException {
        this.statisticsService.verifyParam(result);
        List<StatisticsPatrolResult> patrolResults = this.statisticsService.queryPatrolResultMulti(result);
//        ExcelUtil<StatisticsPatrolResult> util = new ExcelUtil<>(StatisticsPatrolResult.class);
//        util.exportExcelWithFileName(response, patrolResults, "巡视结果", "数据对比分析");
        ExcelWriter writer = new ExcelWriter();
        String[] configColArr = new String[]{"deviceName", "time", "value", "patrolStatus", "checkResult"};
        HashMap<String, String> colMap = this.statisticsService.colMap();
        for (String col : configColArr) {
            if (StringUtils.isNotBlank(colMap.get(col))) {
                writer.addHeaderAlias(col, colMap.get(col));
            }
        }

        long now = System.currentTimeMillis();
        String filename = messageUtils.get("巡视结果") + "_" + messageUtils.get("数据对比分析") + "_" + now;
        filename = URLEncoder.encode(filename, "utf8");
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
        response.setCharacterEncoding("utf-8");
        writer.setOnlyAlias(true);
        writer.write(patrolResults, true);
        writer.flush(response.getOutputStream());
        writer.close();
    }

    @Log(
            title = "数据对比分析-自定义字段导出",
            businessType = BizType.EXPORT
    )
    @GetMapping({"/configExport"})
    public void configExport(StatisticsPatrolResult result, HttpServletResponse response) throws IOException {
        logger.info("----------自定义字段导出,result:{}", result);
        this.statisticsService.verifyParam(result);
        List<StatisticsPatrolResult> patrolResults = this.statisticsService.queryPatrolResultMultiExport(result);
        for (StatisticsPatrolResult patrolResult : patrolResults) {
            String dataType = patrolResult.getDataType();
            if ("1".equals(dataType)) {
                patrolResult.setDataType(messageUtils.get("摄像机"));
            } else if ("2".equals(dataType)) {
                patrolResult.setDataType(messageUtils.get("机器人"));
            } else if ("3".equals(dataType)) {
                patrolResult.setDataType(messageUtils.get("无人机"));
            } else if ("4".equals(dataType)) {
                patrolResult.setDataType(messageUtils.get("声纹"));
            } else if ("5".equals(dataType)) {
                patrolResult.setDataType(messageUtils.get("在线监测"));
            }

            String recognitionType = patrolResult.getRecognitionType();
            if (StringUtils.isNotEmpty(recognitionType)) {
                if ("1".equals(recognitionType)) {
                    patrolResult.setRecognitionType(messageUtils.get("表计读取"));
                } else if ("2".equals(recognitionType)) {
                    patrolResult.setRecognitionType(messageUtils.get("位置状态识别"));
                } else if ("4".equals(recognitionType)) {
                    patrolResult.setRecognitionType(messageUtils.get("红外测温"));
                } else if ("52".equals(recognitionType)) {
                    patrolResult.setRecognitionType(messageUtils.get("仪表读数"));
                } else if ("118".equals(recognitionType)) {
                    patrolResult.setRecognitionType(messageUtils.get("形变"));
                } else if ("119".equals(recognitionType)) {
                    patrolResult.setRecognitionType(messageUtils.get("红外1800"));
                } else if ("120".equals(recognitionType)) {
                    patrolResult.setRecognitionType(messageUtils.get("无人机红外"));
                } else if ("121".equals(recognitionType)) {
                    patrolResult.setRecognitionType(messageUtils.get("摄像头红外"));
                } else if ("122".equals(recognitionType)) {
                    patrolResult.setRecognitionType(messageUtils.get("摄像头红外灰度反算"));
                }
            }

            Integer patrolStatus = patrolResult.getPatrolStatus();
            if (patrolStatus != null) {
                if (patrolStatus == 0) {
                    patrolResult.setPatrolStatusName(messageUtils.get("未审核"));
                } else if (patrolStatus == 1) {
                    patrolResult.setPatrolStatusName(messageUtils.get("已审核"));
                }
            }

            String fileType = patrolResult.getFileType();
            if (StringUtils.isNotEmpty(fileType)) {
                StringBuilder stringBuilder = new StringBuilder();
                String[] fileTypeArr = fileType.split(",");
                for (String s : fileTypeArr) {
                    if ("1".equals(s)) {
                        stringBuilder.append(messageUtils.get("红外图谱")).append(",");
                    } else if ("2".equals(s)) {
                        stringBuilder.append(messageUtils.get("可见光照片")).append(",");
                    } else if ("3".equals(s)) {
                        stringBuilder.append(messageUtils.get("音频")).append(",");
                    } else if ("4".equals(s)) {
                        stringBuilder.append(messageUtils.get("视频")).append(",");
                    }
                }
                String fileTypeStr = stringBuilder.toString();
                if (fileTypeStr.endsWith(",")) {
                    fileTypeStr = fileTypeStr.substring(0, fileTypeStr.length() - 1);
                }
                patrolResult.setFileType(fileTypeStr);
            }

            String valid = patrolResult.getValid();
            if (StringUtils.isNotEmpty(valid)) {
                if ("0".equals(valid)) {
                    patrolResult.setValid(messageUtils.get("失败"));
                } else if ("2".equals(valid)) {
                    patrolResult.setValid(messageUtils.get("成功"));
                } else {
                    patrolResult.setValid(messageUtils.get("判别异常"));
                }
            }
        }
        this.statisticsService.configExport(patrolResults, result, response);

    }

    @GetMapping({"/colMap"})
    public AjaxResult colMap() {
        HashMap<String, String> colMap = this.statisticsService.colMap();
        return AjaxResult.success(colMap);
    }
}
