package cn.im.trafficplan.action;

import cn.base.util.*;
import cn.im.trafficplan.model.TrafficplanexecmodeBean;
import cn.im.trafficplan.model.TrafficplanlinkagedeviceBean;
import cn.im.trafficplan.service.TrafficplanalarmdeviceService;
import cn.im.trafficplan.service.TrafficplanexecmodeService;
import cn.im.trafficplan.service.TrafficplanlinkagedeviceService;
import cn.im.trafficplan.service.TrafficplanmanageService;
import net.sf.json.JSONArray;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import cn.base.aspect.OperateType;
import cn.base.bean.BaseAction;
import cn.base.excel.ExcelCol;
import cn.base.excel.ExportEngine;
import cn.bsystem.ptuserrole.model.PtyhBean;

@SuppressWarnings({"all"})
@Component("trafficplanmanageAction")
public class TrafficplanmanageAction extends BaseAction{
	private static final long serialVersionUID = 1L;
	private static Logger iLog = Logger.getLogger(TrafficplanmanageAction.class);
	
	@Autowired
	private TrafficplanmanageService service;
	
	@Autowired
	private TrafficplanalarmdeviceService serviceD;
	
	@Autowired
	private TrafficplanlinkagedeviceService serviceL;
	
	@Autowired
	private TrafficplanexecmodeService serviceE;
	
	/**
	 * 根据planID删除预案管理
	 * @return
	 */
	@OperateType(value=LogConstants.LOG_DELETE,info="deleteTrafficPlanByPlanID")
	public void deleteTrafficPlanByPlanID(){
		Map map = Struts2Utils.getRequestParameterMap();
		try{
			String planID = String.valueOf( map.get("planID"));
			if(RHUtil.isNotEmpty(map.get("planID"))){
				service.delete_TrafficplanmanageByplanID(String.valueOf(map.get("planID")));
				serviceD.delete_TrafficplanalarmdeviceByPlanID(String.valueOf(map.get("planID")));
				serviceL.delete_TrafficplanlinkagedeviceByPlanID(String.valueOf(map.get("planID")));
				serviceE.delete_TrafficplanexecmodeByPlanID(String.valueOf(map.get("planID")));
			}
			Struts2Utils.renderJson(Constants.SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			iLog.error("TrafficplanmanageAction-deleteTrafficPlanByPlanID-error:" +e);
			Struts2Utils.renderJson("error");
		}
		
	}
	/**
	 * 分页
	 */
//	@OperateType(value = LogConstants.LOG_QUERY ,info ="listTrafficplanmanageByPage")
//	public void listTrafficplanmanageByPage(){
//		Map map = Struts2Utils.getRequestParameterMap();
//		try {
//			int start = Integer.parseInt(Struts2Utils.getParameter("start"));
//			int limit = Integer.parseInt(Struts2Utils.getParameter("limit"));
//			map.put("start",start );
//			map.put("limit",limit );
//			Struts2Utils.renderJson(this.service.listTrafficplanmanageByPage(map));
//		} catch (Exception e) {
//			e.printStackTrace();
//			iLog.error("TrafficplanmanageAction-listTrafficplanmanageByPage-error:" +e);
//			Struts2Utils.renderJson(null);
//		}
//	}
	/**
	 * 查询已选设备
	 *//*
	@OperateType(value = LogConstants.LOG_QUERY ,info ="query_alarmDevice_Origin")
	public void query_alarmDevice_Origin(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			String condition = Struts2Utils.getParameter("condition");
			String planID = Struts2Utils.getParameter("planID");
			String state = Struts2Utils.getParameter("state");
			System.out.println(condition+","+planID+","+state);
			map.put("condition",condition );
			map.put("planID",planID );
			if("2".equals(state)){
				map.put("state"," a.xh not in (SELECT distinct deviceId from trafficplanalarmdevice c where c.planID='"+planID+"' )  ");
			}else if("1".equals(state)){
				map.put("state","a.xh=c.deviceId and c.planID='"+planID +"'");
			}else {
				map.put("state","" );
			}
//			map.put("state1",state );
			Struts2Utils.renderJson(this.service.query_alarmDevice_Origin(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("TrafficplanmanageAction-query_alarmDevice_Origin-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}*/
	/**
	 * 查询已选设备
	 */
	@OperateType(value = LogConstants.LOG_QUERY ,info ="query_alarmDevice_Origin")
	public void query_alarmDevice_Origin(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			String condition = Struts2Utils.getParameter("condition");
			String planID = Struts2Utils.getParameter("planID");
			System.out.println(condition+","+planID);
			map.put("condition",condition );
			map.put("planID",planID );
			Struts2Utils.renderJson(this.service.query_alarmDevice_Origin(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("TrafficplanmanageAction-query_alarmDevice_Origin-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	/**
	 * 删除
	 */
	@OperateType(value = LogConstants.LOG_DELETE ,info ="delete_Trafficplanmanage")
	public void delete_Trafficplanmanage(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			if(!CommUtils.isEmpty(map)){
				int result = service.delete_Trafficplanmanage(map);
				Struts2Utils.renderJson(Constants.SUCCESS);
			}else{
				 throw new Exception("请正确的选择删除记录!!!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("TrafficplanmanageAction-delete_Trafficplanmanage-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}

	/**
	 * 插入
	 */
	@OperateType(value = LogConstants.LOG_ADD ,info ="insert_Trafficplanmanage")
	public void insert_Trafficplanmanage(){
		Map map = Struts2Utils.getRequestParameterMap();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			String planID = StringUtil.getUUID();
			if(RHUtil.isNotEmpty(map.get("planID"))){
				service.delete_TrafficplanmanageByplanID(String.valueOf(map.get("planID")));
				serviceD.delete_TrafficplanalarmdeviceByPlanID(String.valueOf(map.get("planID")));
				serviceL.delete_TrafficplanlinkagedeviceByPlanID(String.valueOf(map.get("planID")));
				serviceE.delete_TrafficplanexecmodeByPlanID(String.valueOf(map.get("planID")));
				
			}
			map.put("planID", planID);
			String userName = ((PtyhBean)Struts2Utils.getSession().getAttribute("userInfo")).getYhmc();
			String now = DateUtil.currentDateTime();
			map.put("createAccount",userName );
			map.put("createTime",now );
			map.put("modifyAccount", userName);
			map.put("modifyTime",now);
			//插入trafficplanmanage
			service.insert_Trafficplanmanage(map);
			//插入trafficplanalarmdevice
			String[] deviceNames = (String.valueOf(map.get("deviceName"))).split(",");
			String[] channelIds = (String.valueOf(map.get("channelId"))).split(",");
			String[] alarmDeviceIds = (String.valueOf(map.get("alarmDeviceId"))).split(",");
			for(int i=0;i<deviceNames.length;i++){
				Map<String,String> mapD = new HashMap<String,String>();
				String alarmID = StringUtil.getUUID();
				mapD.put("alarmID", alarmID);
				mapD.put("planID", planID);
				mapD.put("deviceId",alarmDeviceIds[i] );
				mapD.put("deviceName", deviceNames[i]);
				mapD.put("channelId", channelIds[i]);
				mapD.put("createAccount", userName);
				mapD.put("createTime", now);
				mapD.put("modifyAccount", userName);
				mapD.put("modifyTime", now);
				serviceD.insert_Trafficplanalarmdevice(mapD);
			}
			//交通预案联动设备信息表
			List<TrafficplanexecmodeBean> list = JSONArray.toList(JSONArray.fromObject(map.get("tpem")),TrafficplanexecmodeBean.class);
			System.out.println(map.get("tpem"));
			//设备执行顺序
//			int index = 1;
			for(int i=0;i<list.size();i++){
				String jsya = String.valueOf(map.get("jsya"));
				if(StringUtils.isEmpty(jsya)){
					jsya = "99";
				}
				if(list.get(i).getExecOrder()<=Integer.parseInt(String.valueOf(map.get("jsya")))){
					Map<String,Object> mapL = new HashMap<String,Object>();
					String linkageID = StringUtil.getUUID();
					String type = list.get(i).getPlanType();
					if("99".equals(type)) {  //结束预案手动执行
						mapL.put("execModel", "1"); 
					}else {  //其他自动执行
						mapL.put("execModel", "0");
					}
					mapL.put("linkageID", linkageID);
					mapL.put("planID", planID);
					mapL.put("linkageDeviceType", type);
					mapL.put("linkageDeviceName", list.get(i).getTypeName());
					mapL.put("linkageOrder", list.get(i).getExecOrder());
					mapL.put("createAccount", userName);
					mapL.put("createTime", now);
					mapL.put("modifyAccount", userName);
					mapL.put("modifyTime", now);
//					String execID = StringUtil.getUUID();
//					mapL.put("execID", execID);
					mapL.put("planType", list.get(i).getPlanType());
					mapL.put("typeName", list.get(i).getTypeName());
					mapL.put("execOrder", list.get(i).getExecOrder());
//					mapL.put("messageTitle", list.get(i).get("noticePeople"));
//					mapL.put("messageContent", list.get(i).get("noticeContent"));
					serviceL.insert_Trafficplanlinkagedevice(mapL);
					if("交通信号灯".equals(list.get(i).getTypeName())||"情报板".equals(list.get(i).getTypeName())
							|| "声光报警".equals(list.get(i).getTypeName())||"语音播报".equals(list.get(i).getTypeName())
							|| "通风控制".equals(list.get(i).getTypeName())||"照明控制".equals(list.get(i).getTypeName())
							|| "车道指示器".equals(list.get(i).getTypeName())){
						System.out.println(list.get(i).getNoticeContent());
						List<TrafficplanexecmodeBean> list1 = JSONArray.toList(JSONArray.fromObject(list.get(i).getNoticeContent().subSequence(1, list.get(i).getNoticeContent().length()-1)),TrafficplanexecmodeBean.class);
						//设备执行顺序
						int index = 1;
						for(int j=0;j<list1.size();j++){
							
							TrafficplanexecmodeBean tb = list1.get(j);
							mapL.put("execModel", tb.getExecModel());
							mapL.put("delayTime", tb.getDelayTime());
							mapL.put("messageContent", tb.getMessageContent());
							System.out.println(tb.getLinkageDeviceId());
							if(tb.getLinkageDeviceId().indexOf(",")!=-1){
								String[] LinkageDeviceIds = tb.getLinkageDeviceId().split(",");
								for(String str :LinkageDeviceIds){
									String[] LinkageDeviceIdss = str.split("-");
									mapL.put("execID", StringUtil.getUUID());
									mapL.put("linkageID", linkageID);
									mapL.put("execOrder", index++);
//									serviceL.insert_Trafficplanlinkagedevice(mapL);
									mapL.put("linkageDeviceId", LinkageDeviceIdss[0]);
									mapL.put("linkageDeviceName", LinkageDeviceIdss[1]);
									serviceE.insert_Trafficplanexecmode(mapL);
								}
							}else{
								String[] LinkageDeviceIdss = tb.getLinkageDeviceId().split("-");
								mapL.put("execID", StringUtil.getUUID());
								mapL.put("linkageID", linkageID);
								mapL.put("execOrder", index++);
//								serviceL.insert_Trafficplanlinkagedevice(mapL);
								mapL.put("linkageDeviceId", LinkageDeviceIdss[0]);
								mapL.put("linkageDeviceName", LinkageDeviceIdss[1]);
								serviceE.insert_Trafficplanexecmode(mapL);
							}
							
						}
						
					}else if("大屏上墙".equals(list.get(i).getTypeName())){
						mapL.put("messageContent", list.get(i).getNoticeContent());
						mapL.put("execID", StringUtil.getUUID());
						mapL.put("execOrder", 1);
						serviceE.insert_Trafficplanexecmode(mapL);
					}else if("结束预案".equals(list.get(i).getTypeName())){
						String[] contents = list.get(i).getNoticeContent().split("-");
						mapL.put("messageContent",contents[1] );
						mapL.put("messageTitle", contents[0]);
						mapL.put("linkageDeviceId", "0");
						mapL.put("execID", StringUtil.getUUID());
						mapL.put("execOrder", 1);
						serviceE.insert_Trafficplanexecmode(mapL);
					}
				}
			}
			Struts2Utils.renderJson(Constants.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("TrafficplanmanageAction-insert_Trafficplanmanage()-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	/**
	 * 修改
	 */
	@OperateType(value = LogConstants.LOG_UPDATE ,info ="update_Trafficplanmanage")
	public void update_Trafficplanmanage(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			int result = service.update_Trafficplanmanage(map);
			Struts2Utils.renderJson(Constants.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("TrafficplanmanageAction-update_Trafficplanmanage-error: " +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	/**
	 * 
	 */
	@OperateType(value = LogConstants.LOG_QUERY ,info ="query_Trafficplanmanage_sjgl")
	public void query_Trafficplanmanage_sjgl(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			int page = Integer.parseInt(Struts2Utils.getParameter("page"));
			int rows = Integer.parseInt(Struts2Utils.getParameter("rows"));
			int start = ( (page == 0 ?  1 : page ) - 1) * rows ;
			map.put("start",start );
			map.put("limit",rows );
			Struts2Utils.renderJson(this.service.query_Trafficplanmanage_sjgl(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("TrafficplanmanageAction-query_Trafficplanmanage_sjgl-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	/**
	 * 选择预案
	 */
	@OperateType(value = LogConstants.LOG_QUERY ,info ="query_Trafficplanmanage_choose")
	public void query_Trafficplanmanage_choose(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			int page = Integer.parseInt(Struts2Utils.getParameter("page"));
			int rows = Integer.parseInt(Struts2Utils.getParameter("rows"));
			int start = ( (page == 0 ?  1 : page ) - 1) * rows ;
			map.put("start",start );
			map.put("limit",rows );
			Struts2Utils.renderJson(this.service.query_Trafficplanmanage_choose(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("TrafficplanmanageAction-query_Trafficplanmanage_choose-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	/**
	 * 查询预案管理list
	 */
	@OperateType(value = LogConstants.LOG_QUERY ,info ="listTrafficplanmanageByPage")
	public void listTrafficplanmanageByPage(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			int start = Integer.parseInt(Struts2Utils.getParameter("start"));
			int limit = Integer.parseInt(Struts2Utils.getParameter("limit"));
			String planStartTime = Struts2Utils.getParameter("planStartTime");
			String planStopTime = Struts2Utils.getParameter("planStopTime");
			if(StringUtils.isNotEmpty(planStartTime)){
				planStartTime  = planStartTime+" 00:00:00";
			}else{
				planStartTime = "";
			}
			map.put("planStartTime", planStartTime);
			if(StringUtils.isNotEmpty(planStopTime)){
				planStopTime  = planStopTime+" 23:59:59";
			}else{
				planStopTime = "";
			}
			map.put("planStopTime", planStopTime);
//			System.out.println(Struts2Utils.getParameter("planStopTime"));
//			String planStartTime = Struts2Utils.getParameter("planStartTime");
//			String sqlTime = "";
//			if(StringUtils.isNotEmpty(planStartTime)){
//				sqlTime += "planStartTime>='"+planStartTime+"'"; 
//			}
			map.put("start",start );
			map.put("limit",limit );
			map.put("order", "createTime");
			Struts2Utils.renderJson(this.service.listTrafficplanmanageByPage(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("TrafficplanmanageAction-listTrafficplanmanageByPage-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	/**
	 * 报警源设备查询
	 */
	/*@OperateType(value = LogConstants.LOG_QUERY ,info ="query_alarmDevice")
	public void query_alarmDevice(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			String condition = Struts2Utils.getParameter("condition");
			System.out.println(condition);
			map.put("condition", condition);
			Struts2Utils.renderJson(this.service.query_alarmDevice(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("TrafficplanmanageAction-query_alarmDevice-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}*/
	
	/**
	 * 报警源设备查询
	 */
	@OperateType(value = LogConstants.LOG_QUERY ,info ="query_alarmDevice")
	public void query_alarmDevice(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			String roadId = Struts2Utils.getParameter("roadId");
			System.out.println(roadId);
			map.put("roadId", roadId);
			Struts2Utils.renderJson(this.service.query_alarmDevice(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("TrafficplanmanageAction-query_alarmDevice-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	/**
	 * 诱导灯查询
	 */
	@OperateType(value = LogConstants.LOG_QUERY ,info ="query_TrafficLightDevice")
	public void query_TrafficLightDevice(){
//		Map map = Struts2Utils.getRequestParameterMap();
		try {
//			String condition = Struts2Utils.getParameter("condition");
//			map.put("condition", condition);
			Struts2Utils.renderJson(this.service.query_TrafficLightDevice());
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("TrafficplanmanageAction-query_TrafficLightDevice-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	/**
	 * led查询
	 */
	@OperateType(value = LogConstants.LOG_QUERY ,info ="query_TrafficLedDevice")
	public void query_TrafficLedDevice(){
//		Map map = Struts2Utils.getRequestParameterMap();
		try {
//			String condition = Struts2Utils.getParameter("condition");
//			map.put("condition", condition);
			Struts2Utils.renderJson(this.service.query_TrafficLedDevice());
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("TrafficplanmanageAction-query_TrafficLedDevice-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	
	@OperateType(value = LogConstants.LOG_QUERY ,info ="getLinkageDeviceCommandfromHis")
	public void getLinkageDeviceCommandfromHis(){
		Map map = Struts2Utils.getRequestParameterMap();
		List<Map> result = new ArrayList<Map>();
		try {
//			String condition = Struts2Utils.getParameter("condition");
//			map.put("condition", condition);
			List<Map> list = this.service.getLinkageDeviceCommandfromHis(map);
			for(int i=0;i<list.size();i++){
				Map hisMap = this.service.gethisStateLast(list.get(i));
				hisMap.put("planID", list.get(i).get("planId"));
//				hisMap.put("planID", list.get(i).get("planId"));//todo
				result.add(hisMap);
			}
			Struts2Utils.renderJson(result);
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("TrafficplanmanageAction-getLinkageDeviceCommandfromHis-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
}
