package cn.im.trafficdevice.action;

 import cn.im.trafficdevice.service.SbtdspyzdService;

import java.io.DataOutputStream;
import java.io.File;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.amq.peas.XdPtzDefinedPeas;
import cn.amq.peas.XdPtzMovedNotifyPeas;
import cn.base.aspect.OperateType;
import cn.base.bean.BaseAction;
import cn.base.bean.BeanHelper;
import cn.base.conf.TraffAccident;
import cn.base.excel.ExcelCol;
import cn.base.excel.ExportEngine;
import cn.base.util.CommUtils;
import cn.base.util.Constants;
import cn.base.util.LogConstants;
import cn.base.util.StringUtil;
import cn.base.util.Struts2Utils;

@SuppressWarnings({"all"})
@Component("sbtdspyzdAction")
public class SbtdspyzdAction extends BaseAction{
	private static final long serialVersionUID = 1L;
	private static Logger iLog = Logger.getLogger(SbtdspyzdAction.class);
	
	@Autowired
	private SbtdspyzdService service;
	
	/**
	 * 分页
	 */
	//@OperateType(value = LogConstants.LOG_QUERY ,info ="listSbtdspyzdByPage")
	public void listSbtdspyzdByPage(){
		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.listSbtdspyzdByPage(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("SbtdspyzdAction-listSbtdspyzdByPage-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	/**
	 * 查询总数
	 */
	//@OperateType(value = LogConstants.LOG_QUERY ,info ="count_Sbtdspyzd")
	public void count_Sbtdspyzd(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			Struts2Utils.renderJson(this.service.count_Sbtdspyzd(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("SbtdspyzdAction-count_Sbtdspyzd-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	/**
	 * 查询 Sbtdspyzd
	 */
	//@OperateType(value = LogConstants.LOG_GET ,info ="query_Sbtdspyzd")
	public void query_Sbtdspyzd(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			Struts2Utils.renderJson(this.service.query_Sbtdspyzd(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("SbtdspyzdAction-query_Sbtdspyzd-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	//@OperateType(value = LogConstants.LOG_GET ,info ="getAll")
	public void getAll(){
		try {
			Struts2Utils.renderJson(this.service.getAll());
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("SbtdspyzdAction-getAll-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	/**
	 * 查询 一条Sbtdspyzd
	 */
	//@OperateType(value = LogConstants.LOG_GET ,info ="get_SbtdspyzdOne")
	public void get_SbtdspyzdOne(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			Struts2Utils.renderJson(this.service.get_SbtdspyzdOne(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("SbtdspyzdActionquery_Sbtdspyzd-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	/**
	 * 删除
	 */
	//@OperateType(value = LogConstants.LOG_DELETE ,info ="deleteSbtdspyzd")
	public void delete_Sbtdspyzd(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			if(!CommUtils.isEmpty(map)){
				Map record = service.get_Sbtdspyzd(map);
				int result = service.delete_Sbtdspyzd(map);
				if(result>0){
					Struts2Utils.renderJson(Constants.SUCCESS);
					List<XdPtzDefinedPeas> list = new LinkedList<XdPtzDefinedPeas>();	
					XdPtzDefinedPeas peas = new XdPtzDefinedPeas();
					peas.setGjxh((String)record.get("xh"));
					peas.setSbbh((String) record.get("sbbh"));
					peas.setGjsj((String) record.get("xgrq"));
					peas.setZt(12);
					try{
						peas.setTdbh(new BigDecimal(record.get("tdbh")+"").intValue()-1);
						peas.setYzdbh(new BigDecimal(record.get("kz1")+"").intValue());
					}catch(Exception e){
						iLog.error("发送预置点位定义amq，通道编号或预置点位编号转换数据类型出错： "+e);
					}
					list.add(peas);
					BeanHelper.getAmqXdPtzDefinedService().publishPresetPointAction(list);
				}else{
					Struts2Utils.renderJson(Constants.FAIL);
				}
			}else{
				 throw new Exception("请正确的选择删除记录!!!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("SbtdspyzdAction-delete_Sbtdspyzd-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}

	/**
	 * 插入
	 */
	//@OperateType(value = LogConstants.LOG_ADD ,info ="insert_Sbtdspyzd")
	public void insert_Sbtdspyzd(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			if(StringUtil.checkEmpty(map.get("xh"))){
				map.put("xh",StringUtil.getUUID());
			}
			CommUtils.addYhParams(map, false);
			List<XdPtzDefinedPeas> list = new LinkedList<XdPtzDefinedPeas>();	
			XdPtzDefinedPeas peas = new XdPtzDefinedPeas();
			peas.setGjxh((String) map.get("xh"));
			peas.setSbbh((String) map.get("sbbh"));
			peas.setGjsj((String) map.get("xgrq"));
			peas.setZt(10);
			try{
				peas.setTdbh(Integer.valueOf( (String)map.get("tdbh"))-1);
				peas.setYzdbh(Integer.valueOf( (String)map.get("kz1")));
			}catch(Exception e){
				iLog.error("发送预置点位定义amq，通道编号或预置点位编号转换数据类型出错： "+e);
			}
			list.add(peas);
			
			if(!StringUtil.checkEmpty(map.get("checkparam"))){
				Map sMap = new HashMap();
				sMap.put("tableparam", map.get("checkparam"));
				List ls = service.query_Sbtdspyzd(sMap);
				if(!StringUtil.checkEmpty(ls)||ls.size()>0){
					Struts2Utils.renderJson(Constants.SAME);
				}else{
					service.insert_Sbtdspyzd(map);
					Struts2Utils.renderJson(Constants.SUCCESS);
					BeanHelper.getAmqXdPtzDefinedService().publishPresetPointAction(list);
				}
			}else{
				service.insert_Sbtdspyzd(map);
				Struts2Utils.renderJson(Constants.SUCCESS);
				BeanHelper.getAmqXdPtzDefinedService().publishPresetPointAction(list);
			}			
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("SbtdspyzdAction-insert_Sbtdspyzd()-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	/**
	 * 修改
	 */
	//@OperateType(value = LogConstants.LOG_UPDATE ,info ="update_Sbtdspyzd")
	public void update_Sbtdspyzd(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			
			CommUtils.addYhParams(map, true);
			List<XdPtzDefinedPeas> list = new LinkedList<XdPtzDefinedPeas>();
			List<XdPtzMovedNotifyPeas> list1 = new LinkedList<XdPtzMovedNotifyPeas>();
			XdPtzMovedNotifyPeas peas1 = new XdPtzMovedNotifyPeas();
			peas1.setGjxh((String) map.get("XGTJxh"));
			peas1.setGjsj((String) map.get("xgrq"));
			peas1.setSbbh((String) map.get("sbbh"));
			peas1.setTdbh(Integer.valueOf( (String)map.get("tdbh"))-1);
			peas1.setZt(1);
			list1.add(peas1);
			BeanHelper.getAmqXdPtzMovedNotifyService().publishXdPtzMovedNotifyAction(list1);
			
			XdPtzDefinedPeas peas = new XdPtzDefinedPeas();
			peas.setGjxh((String) map.get("XGTJxh"));
			peas.setSbbh((String) map.get("sbbh"));
			peas.setGjsj((String) map.get("xgrq"));
			peas.setZt(11);
			try{
				peas.setTdbh(Integer.valueOf( (String)map.get("tdbh"))-1);
				peas.setYzdbh(Integer.valueOf( (String)map.get("kz1")));
			}catch(Exception e){
				iLog.error("发送预置点位定义amq，通道编号或预置点位编号转换数据类型出错： "+e);
			}
			list.add(peas);
			
			if(!StringUtil.checkEmpty(map.get("checkparam"))){
				Map sMap = new HashMap();
				sMap.put("tableparam", map.get("checkparam"));
				List ls = service.query_Sbtdspyzd(sMap);
				if(!StringUtil.checkEmpty(ls)||ls.size()>0){
					Struts2Utils.renderJson(Constants.SAME);
				}else{
					int result = service.update_Sbtdspyzd(map);
					Struts2Utils.renderJson(Constants.SUCCESS);
					BeanHelper.getAmqXdPtzDefinedService().publishPresetPointAction(list);
				}
			}else{
				int result = service.update_Sbtdspyzd(map);
				Struts2Utils.renderJson(Constants.SUCCESS);
				BeanHelper.getAmqXdPtzDefinedService().publishPresetPointAction(list);
			}
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("SbtdspyzdAction-update_Sbtdspyzd-error: " +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	/**
	 * 批量删除
	 */
	//@OperateType(value = LogConstants.LOG_DELETE ,info ="batch_delete_Sbtdspyzd")
	public void batch_delete_Sbtdspyzd(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			Map m = new HashMap();
			m.put("keyword", map.get("keyword").toString());
			int result = service.batch_delete_Sbtdspyzd(m);
			Struts2Utils.renderJson(Constants.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("SbtdspyzdAction-batch_delete_Sbtdspyzd-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	//@OperateType(value = LogConstants.LOG_DELETE ,info ="getMonitorChooseObj")
	public void getMonitorChooseObj(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			Struts2Utils.renderJson(BeanHelper.getModuleConfFactory().getTraffAccident());
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("SbtdspyzdAction-getMonitorChooseObj-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	/**
	 * 复位更新相机移位缓存
	 */
	//@OperateType(value = LogConstants.LOG_DELETE ,info ="updateMonitorMovedCache")
	public void updateMonitorMovedCache(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			String key = map.get("sbbh")+"-"+map.get("tdbh");
			BeanHelper.getCacheMonitorMovedDataService().setCacheMonitorMovedDataMap(key, "0");
			Struts2Utils.renderJson(Constants.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("SbtdspyzdAction-getMonitorChooseObj-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	/**
	 * 获取相机移位缓存
	 */
	//@OperateType(value = LogConstants.LOG_DELETE ,info ="getMonitorMovedCache")
	public void getMonitorMovedCache(){
		try {
			Struts2Utils.renderJson(BeanHelper.getCacheMonitorMovedDataService().getCacheMonitorMovedDataMap());
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("SbtdspyzdAction-getMonitorChooseObj-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	//@OperateType(value = LogConstants.LOG_DELETE ,info ="movedNotify")
	public void movedNotify(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			
			TraffAccident ta = BeanHelper.getModuleConfFactory().getTraffAccident();
			String url = ta.getUrlAndPort()+"/scene?video_id="+map.get("sbbh")+"_"+(Integer.valueOf((String)map.get("tdbh"))-1);
			URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();// 设置通用请求的属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("PUT");
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            String params = "{ \"preset_index\": "+(Integer.valueOf(""+map.get("preset_index")))+",\"scene_is_valid\": "+Boolean.valueOf(""+map.get("scene_is_valid"))+"}";
            dos.writeBytes(params);				
            dos.flush();				
            dos.close();
			int statusCode = conn.getResponseCode();
			if(statusCode==200){
				Struts2Utils.renderJson("success");
			}else{
				Struts2Utils.renderJson(null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("SbtdspyzdAction-movedNotify-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}
	
	/**
	 * 导出Excel
	 */
	/*
	//@OperateType(value = LogConstants.LOG_EXPORT ,info ="exp_Sbtdspyzd")
	public void exp_Sbtdspyzd(){
		try {
			Map map = Struts2Utils.getRequestParameterMap();
			map.put("start",0 );
			map.put("limit",5000);
			List<Map> sList = service.query_Sbtdspyzd(map);		
			List<HashMap> expList = new ArrayList<HashMap>();
			for(Map m : sList){
				Map exportMap = new HashMap();
				exportMap.put("yhzh", m.get("yhzh"));
				expList.add((HashMap) exportMap);
			}
			int excelNum = 2;
			ExcelCol[] cells = new ExcelCol[excelNum];
			String[] zdbm = {"yhzh", "yhmc",};
			String[] zdmc = {"用户账号", "用户名称"};
			for(int i=0;i<excelNum;i++){
				cells[i] = new ExcelCol();
				cells[i].setColKey(zdbm[i]);
				cells[i].setColName(zdmc[i]);
			}		
			SimpleDateFormat formart = new SimpleDateFormat("yyyy-MM-dd");   
        	String dateTime=formart.format(new Date()); 
			Map params = new HashMap();
			params.put("fileName", "设备通道视频预置点-"+dateTime);
			params.put("sheetName", "设备通道视频预置点");
			params.put("header", "设备通道视频预置点");	
			new ExportEngine().exportCommData(params, cells, (ArrayList)map.get("rows"), Struts2Utils.getResponse());
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("SbtdspyzdAction-exoprtExcel-error:" +e);
			
		}
	}
	*/
	
	/**
	 * 导入Excel
	 */
	/*
	//@OperateType(value = LogConstants.LOG_IMPORT ,info ="imp_Sbtdspyzd")
	public String imp_Sbtdspyzd(String excelFile,Object user) {
		String rs = "导入格式有误!";
		int rowNum = 0;
		int dataCount = 0;
		int successNum = 0;
		int repeatNum = 0;
		int failNum = 0;
		try {
		
			ExcelReader readExcel = new ExcelReader();
			readExcel.openFile(excelFile);
			readExcel.setSheetNum(0);
			int count = readExcel.getRowCount();
			iLog.info("总行数count--->" + count);
			rs = " 导入数据成功！总共"+ dataCount +"条数据,重复"+repeatNum+"条数据！失败"+failNum+"条数据!";
			File file = new File(excelFile);
			if(file.exists()){
				file.delete();
			}
		} catch (Exception e) {
			if (rowNum > 3) {
				rs = "资源部分导入(更新)失败！Excel第" + rowNum + "行起未导入(更新)成功！";
			} else {
				rs = "资源导入(更新)失败！";
			}
			iLog.error("SbtdspyzdAction-imp_Sbtdspyzd-error:" +e);
			e.printStackTrace();
		}		
		return rs;
	}
	*/
}
