package com.pqs9200.controller.business;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.njcn.enums.LogTypeEnum;
import com.njcn.pojo.commons.DatePojo;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.device.DeviceGeneral;
import com.njcn.pojo.commons.device.DeviceValue;
import com.njcn.pojo.data.GridTop;
import com.njcn.pojo.data.LineMaps;
import com.njcn.pojo.excel.AreaRuntimeExcelBody;
import com.njcn.pojo.excel.CommonParamter;
import com.njcn.pojo.excel.CompanyRuntimeExcelBody;
import com.njcn.pojo.excel.ReasonExcelBody;
import com.njcn.service.configuration.DeviceService;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.PubUtils;
import com.pqs9200.service.data.IOverviewServer;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import scala.Int;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 概览业务的controller
 * */
@Controller
@RequestMapping("/overview")
public class OverviewController {

	// 日志记录
	private static final Logger logger = LoggerFactory.getLogger(AreaController.class);
	@Autowired
	private IOverviewServer iOverviewServer;
	@Autowired
	UserLogDetailService userLogservice;
	@Autowired
	private DeviceService deviceService;
    @Resource
    UserLogDetailService userLog;
	//操作类型
	private String strMessage ="";
	
	/********************************
	 * 查询监测点的经纬度及相应的信息
	 *******************************/
	@RequestMapping(value="getLineMaps",method=RequestMethod.POST)
	@ResponseBody
	public HttpResult getLineMaps(HttpServletRequest request){
		HttpResult result=new HttpResult();
		strMessage="查询监测点的经纬度及相应的信息";
		
		try{
			List<LineMaps> levelList=iOverviewServer.getLineMaps();
			if(levelList.isEmpty()){
				result.setCode(500);
				result.setBody(null);
				result.setMessage("没有数据");
			}else{
				result.setCode(200);
				result.setBody(levelList);
				result.setMessage("获取数据成功");
			}
			
//			userLogservice.getLog("业务查询",strMessage + "成功");
            userLog.getLog("查询地理信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(),0);
		}catch(Exception e){
//			userLogservice.getLog("业务查询", strMessage + "失败");
            userLog.getLog("查询地理信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(),0);
			logger.error(strMessage + "失败,失败原因：" + e.getMessage());
		}
		return result;
	}
	
	
	/*******************************
	 * 查询电网拓扑图信息
	 * *****************************/
	@RequestMapping(value="getGridTop",method=RequestMethod.POST)
	@ResponseBody
	public HttpResult getGridTop(HttpServletRequest request){
		HttpResult result=new HttpResult();
		strMessage="查询电网拓扑图信息";
		
		try{
			List<GridTop> levelList=iOverviewServer.getGridTop();
			if(levelList.isEmpty()){
				result.setCode(500);
				result.setBody(null);
				result.setMessage("没有数据");
			}else{
				result.setCode(200);
				result.setBody(levelList);
				result.setMessage("获取数据成功");
			}
			
//			userLogservice.getLog("业务查询",strMessage + "成功");
		}catch(Exception e){
//			userLogservice.getLog("业务查询", strMessage + "失败");
			logger.error(strMessage + "失败,失败原因：" + e.getMessage());
		}
		
		return result;
	}
	
	/*******************************
	 * 根据监测点ID查询对应的未处理暂降事件信息
	 * *****************************/
	@RequestMapping(value="queryLineMapByAssID",method=RequestMethod.POST)
	@ResponseBody
	public HttpResult queryLineMapByAssID(HttpServletRequest request,String eventass_index){
		HttpResult result=new HttpResult();
		strMessage="根据监测点ID查询对应的未处理暂降事件信息";
		try{
			//获取区域对应的暂降次数
			List<LineMaps> levelList = iOverviewServer.queryLineMapByAssID(eventass_index);
			if(levelList.isEmpty()){
				result.setCode(500);
				result.setBody(null);
				result.setMessage("没有数据");
			}else{
				result.setCode(200);
				result.setBody(levelList);
				result.setMessage("获取数据成功");
			}

            userLog.getLog("查询未处理暂降事件", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(),0);
		}catch(Exception e){
            userLog.getLog("查询未处理暂降事件", "失败", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(),0);
			logger.error(strMessage + "失败,失败原因：" + e.getMessage());
		}
		
		return result;
	}

	/**
	 *概览--》终端状态
	 */
	@PostMapping("deviceStatus")
	@ResponseBody
	public HttpResult getDeviceStatus(String overview,HttpServletRequest request,String startTime,String endTime) {
		HttpResult result=PubUtils.initResult(TokenManager.getToken().getLoginName(),request,LogTypeEnum.BUSSINESS.toString(),0);
		DeviceGeneral data ;
		DatePojo datePojo;
		datePojo = PubUtils.validateDate(startTime, endTime, "deviceStatus");
		if (!datePojo.getValidity()) {
			result = PubUtils.assignmentResult(null, 500, datePojo.getMsg());
			return result;
		}
		try {
			data=deviceService.getDeviceData(overview,datePojo.getStartTime(),datePojo.getEndTime());
			result = PubUtils.assignmentResultLog(data, 200, "获取终端运行数据成功","查询暂降概览终端状态", "成功",result);
		} catch (Exception e) {
			logger.error("获取终端运行数据异常，异常为："+e.toString());
			result = PubUtils.assignmentResultLog(null, 500, "获取终端运行数据异常","查询暂降概览终端状态", "失败",result);
		}
		return result;
	}


	/**
	 * 下载区域统计表格数据
	 */
	@RequestMapping(value = "downloadRuntimeStatusData", method = RequestMethod.POST)
	public void downloadRuntimeStatusData(@RequestBody CommonParamter commonParamter, HttpServletResponse response,String startTime,String endTime) {
		DeviceGeneral data;
		BufferedOutputStream out=null;
		DatePojo datePojo;
		datePojo = PubUtils.validateDate(commonParamter.getStartTime(), commonParamter.getEndTime(), "deviceStatus");
		if (!datePojo.getValidity()) {
			return;
		}
		try {
			out = new BufferedOutputStream(response.getOutputStream());
			ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
			data = deviceService.getDeviceData("", commonParamter.getArea(),datePojo.getStartTime(),datePojo.getEndTime());
			Sheet sheet1 = new Sheet(1, 0, AreaRuntimeExcelBody.class);
			sheet1.setSheetName("区域");
			writer.write(getAreaRuntimeExcel(data), sheet1);
			Sheet sheet2 = new Sheet(2, 0, CompanyRuntimeExcelBody.class);
			sheet2.setSheetName("厂家");
			writer.write(getCompanyRuntimeExcel(data), sheet2);
			writer .finish();
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			try {
				if(null!=out){
					out.close();
				}
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}

	}


	private List<AreaRuntimeExcelBody> getAreaRuntimeExcel(DeviceGeneral deviceGeneral) {
		List<AreaRuntimeExcelBody> areaRuntimeExcelBodies=new ArrayList<>();
		if(null!=deviceGeneral){
			List<DeviceValue> deviceValues = deviceGeneral.getArea();
			if(!CollectionUtils.isEmpty(deviceValues)){
				int totalTimes=0;
				int normal=0;
				int breaks=0;
				int shutdown=0;
				float totalOnline=-1f;
				boolean onlineFlag=false;
				for (DeviceValue deviceValue:deviceValues) {
					AreaRuntimeExcelBody areaRuntimeExcelBody=new AreaRuntimeExcelBody();
					areaRuntimeExcelBody.setName(deviceValue.getName());
					areaRuntimeExcelBody.setAmounts(deviceValue.getAmounts());
					areaRuntimeExcelBody.setNormal(deviceValue.getStatus().getNormalData()+"");
					areaRuntimeExcelBody.setBreaks(deviceValue.getStatus().getBreaksData()+"");
					areaRuntimeExcelBody.setShutdown(deviceValue.getStatus().getShutdownData()+"");
					areaRuntimeExcelBody.setOnline(getOnlie(deviceValue.getOnline()));
					totalTimes= Integer.parseInt(deviceValue.getAmounts())+totalTimes;
					normal= deviceValue.getStatus().getNormalData()+normal;
					breaks= deviceValue.getStatus().getBreaksData()+breaks;
					shutdown= deviceValue.getStatus().getShutdownData()+shutdown;
					areaRuntimeExcelBodies.add(areaRuntimeExcelBody);
					if(!getOnlie(deviceValue.getOnline()).equalsIgnoreCase("/")&&!getOnlie(deviceValue.getOnline()).equalsIgnoreCase("暂无数据")){
						onlineFlag=true;
						totalOnline=totalOnline+Float.valueOf(getOnlie(deviceValue.getOnline()))*deviceValue.getStatus().getNormalData();
					}
				}
				AreaRuntimeExcelBody areaRuntimeExcelBody=new AreaRuntimeExcelBody();
				areaRuntimeExcelBody.setName("总计");
				areaRuntimeExcelBody.setAmounts(totalTimes+"");
				areaRuntimeExcelBody.setNormal(normal+"");
				areaRuntimeExcelBody.setBreaks(breaks+"");
				areaRuntimeExcelBody.setShutdown(shutdown+"");
				if(onlineFlag){
					totalOnline=totalOnline+1;
				}
				if(totalOnline==-1){
					areaRuntimeExcelBody.setOnline("暂无数据");
				}else{
					if(normal==0){
						totalOnline=0f;
					}else{
						totalOnline=PubUtils.floatRound(2,(totalOnline/normal));
					}
				}
				areaRuntimeExcelBody.setOnline(totalOnline+"");
				areaRuntimeExcelBodies.add(areaRuntimeExcelBody);
			}
		}
		return  areaRuntimeExcelBodies;
	}

	private String getOnlie(String online){
		switch (online){
			case "3.1415":
				return "/";
			case "3.14159":
				return "暂无数据";
			default:
				return online;
		}

	}


	private List<CompanyRuntimeExcelBody> getCompanyRuntimeExcel(DeviceGeneral deviceGeneral) {
		List<CompanyRuntimeExcelBody> companyRuntimeExcelBodies=new ArrayList<>();
		if(null!=deviceGeneral){
			List<DeviceValue> deviceValues = deviceGeneral.getInterval();
			if(!CollectionUtils.isEmpty(deviceValues)){
				int totalTimes=0;
				int normal=0;
				int breaks=0;
				int shutdown=0;
				float totalOnline=-1f;
				boolean onlineFlag=false;
				for (DeviceValue deviceValue:deviceValues) {
					CompanyRuntimeExcelBody companyRuntimeExcelBody=new CompanyRuntimeExcelBody();
					companyRuntimeExcelBody.setName(deviceValue.getName());
					companyRuntimeExcelBody.setAmounts(deviceValue.getAmounts());
					companyRuntimeExcelBody.setNormal(deviceValue.getStatus().getNormalData()+"");
					companyRuntimeExcelBody.setBreaks(deviceValue.getStatus().getBreaksData()+"");
					companyRuntimeExcelBody.setShutdown(deviceValue.getStatus().getShutdownData()+"");
					companyRuntimeExcelBody.setOnline(getOnlie(deviceValue.getOnline()));
					totalTimes= Integer.parseInt(deviceValue.getAmounts())+totalTimes;
					normal= deviceValue.getStatus().getNormalData()+normal;
					breaks= deviceValue.getStatus().getBreaksData()+breaks;
					shutdown= deviceValue.getStatus().getShutdownData()+shutdown;
					companyRuntimeExcelBodies.add(companyRuntimeExcelBody);
					if(!getOnlie(deviceValue.getOnline()).equalsIgnoreCase("/")&&!getOnlie(deviceValue.getOnline()).equalsIgnoreCase("暂无数据")){
						onlineFlag=true;
						totalOnline=totalOnline+Float.valueOf(getOnlie(deviceValue.getOnline()))*deviceValue.getStatus().getNormalData();
					}
				}
				CompanyRuntimeExcelBody companyRuntimeExcelBody=new CompanyRuntimeExcelBody();
				companyRuntimeExcelBody.setName("总计");
				companyRuntimeExcelBody.setAmounts(totalTimes+"");
				companyRuntimeExcelBody.setNormal(normal+"");
				companyRuntimeExcelBody.setBreaks(breaks+"");
				companyRuntimeExcelBody.setShutdown(shutdown+"");
				if(onlineFlag){
					totalOnline=totalOnline+1;
				}
				if(totalOnline==-1){
					companyRuntimeExcelBody.setOnline("暂无数据");
				}else{
					if(normal==0){
						totalOnline=0f;
					}else{
						totalOnline=PubUtils.floatRound(2,(totalOnline/normal));
					}
				}
				companyRuntimeExcelBody.setOnline(totalOnline+"");
				companyRuntimeExcelBodies.add(companyRuntimeExcelBody);
			}
		}
		return  companyRuntimeExcelBodies;
	}

	@PostMapping("getRole")
	@ResponseBody
	public int getRole(String url) {
		return deviceService.getRole(url);
	}
}
