<?php
session_start();
if( !defined('IN') ) die('bad request!');
include_once( AROOT . 'controller' . DS . 'app.class.php');
header("Content-Type: text/html; charset=utf-8");

class overviewController extends appController
{
	public function __construct(){
		parent::__construct();
	}

	//发送错误结果集
	public function send_error($number,$msg)
	{
		$obj = array();
		$obj['code'] = intval($number);
		$obj['result'] = $msg;

		if( g('API_EMBED_MODE') == 1 ){
			return json_encode($obj);
		}else{
			header("Content-Type: application/json");
			die(json_encode($obj));
		}
	}

	//发送结果集
	public function send_result($data)
	{
		$obj = array();
		$obj['code'] = 0;
		$obj['result'] = 'success';
		$obj['data'] = $data;

		if( g('API_EMBED_MODE') == 1 ){
			return json_encode($obj);
		}else{
			header("Content-Type: application/json");
			die(json_encode($obj));
		}
	}

	// 获取项目场站总数、闸门调控次数以及水泵调控次数
	public function getProjectBasicInfo()
	{
		$token = $_GET['token'];

		// 获取登录人员基本信息
		$user_basic = $this -> getLoginUserInfoByToken($token);

		// 获取当前项目中所有控制柜
		$sql = prepare("select id from device where project_id = ?i and status = 1",array($user_basic['project_id']));

		$data_device_array = get_data($sql);

		// for ($i=0; $i < count($data_device_array); $i++) { 
		// 	$device_id = $data_device_array[$i]['id'];

		// 	$sql_1 = prepare("select (main_sewage_pump_count+standby_sewage_pump_count+main_rain_pump_count) as pump_count,(gate_up_count+gate_down_count) as gate_count from data where device_id = ?i order by id desc limit 1",array($device_id));

		// 	$total_pump_count += get_line($sql_1)['pump_count'];
		// 	$total_gate_count += get_line($sql_1)['gate_count'];
		// }

		$sql_pump_count = prepare("select count(*) from event where event like ?s and device_id in (select id from device where project_id = ?i and status = 1)",array('%泵%',$user_basic['project_id']));
		
		$total_pump_count = get_var($sql_pump_count) == null ? 0 :  get_var($sql_pump_count);

		$sql_gate_count = prepare("select count(*) from event where event like ?s and device_id in (select id from device where project_id = ?i and status = 1)",array('%闸门%',$user_basic['project_id']));
		$total_gate_count = get_var($sql_gate_count) == null ? 0 :  get_var($sql_gate_count);

		// 获取场站数量
		$sql_1 = prepare("select count(*) from device where project_id = ?i and status = 1",array($user_basic['project_id']));
		$terminal_count = get_var($sql_1);

		$result = array('total_pump_count'=>$total_pump_count,'total_gate_count'=>$total_gate_count,'terminal_count'=>$terminal_count);

		return self::send_result($result);
	}

	// 获取总览内容中闸门总次数以及本月闸门次数
	public function getOverviewGateActionInfo()
	{
		$token = $_GET['token'];

		// 获取登录人员基本信息
		$user_basic = $this -> getLoginUserInfoByToken($token);

		// 获取当前项目中所有控制柜
		$sql = prepare("select id from device where project_id = ?i",array($user_basic['project_id']));

		$data_device_array = get_data($sql);

		// $month_start_table = "data_".date("Ym",time())."01";

		// for ($i=0; $i < count($data_device_array); $i++) { 
		// 	$device_id = $data_device_array[$i]['id'];

		// 	// 获取总的闸门次数
		// 	$sql_1 = prepare("select (gate_up_count+gate_down_count) as gate_count from data where device_id = ?i order by id desc limit 1",array($device_id));
		// 	$total_gate_count += get_var($sql_1);

		// 	// 获取本月之前的闸门次数
		// 	$sql_2 = prepare("select (gate_up_count+gate_down_count) as gate_count from ".$month_start_table." where device_id = ?i order by id desc limit 1",array($device_id));
		// 	$last_gate_count += get_var($sql_2);
		// }

		$start_time = date("Y-m",time())."-01 00:00:00";
		$end_time   = date("Y-m-d H:i:s",time());

		// 获取总的闸门次数
		$sql_gate_count = prepare("select count(*) from event where event like ?s and device_id in (select id from device where project_id = ?i and status = 1)",array('%闸门%',$user_basic['project_id']));
		$total_gate_count = get_var($sql_gate_count) == null ? 0 :  get_var($sql_gate_count);

		// 获取本月之前的闸门次数
		$sql_current_gate_count = prepare("select count(*) from event where event like ?s and device_id in (select id from device where project_id = ?i and status = 1) and event_time >= ?s and event_time <= ?s",array('%闸门%',$user_basic['project_id'],$start_time,$end_time));
		$current_gate_count = get_var($sql_current_gate_count) == null ? 0 :  get_var($sql_current_gate_count);
		
		$result = array("total_gate_count"=>$total_gate_count,'current_gate_count'=>$current_gate_count);

		return self::send_result($result);
	}

	// 获取总览内容中水泵总次数以及本月水泵次数
	public function getOverviewPumpActionInfo()
	{
		$token = $_GET['token'];

		// 获取登录人员基本信息
		$user_basic = $this -> getLoginUserInfoByToken($token);

		// 获取当前项目中所有控制柜
		$sql = prepare("select id from device where project_id = ?i",array($user_basic['project_id']));

		$data_device_array = get_data($sql);

		// $month_start_table = "data_".date("Ym",time())."01";

		// for ($i=0; $i < count($data_device_array); $i++) { 
		// 	$device_id = $data_device_array[$i]['id'];

		// 	// 获取总的水泵次数
		// 	$sql_1 = prepare("select (main_sewage_pump_count+standby_sewage_pump_count+main_rain_pump_count) as pump_count from data where device_id = ?i order by id desc limit 1",array($device_id));
		// 	$total_pump_count += get_var($sql_1);

		// 	// 获取本月之前的水泵次数
		// 	$sql_2 = prepare("select (main_sewage_pump_count+standby_sewage_pump_count+main_rain_pump_count) as pump_count from ".$month_start_table." where device_id = ?i  order by id desc limit 1",array($device_id));
		// 	$last_pump_count += get_var($sql_2);
		// }

		// // 本月闸门次数
		// $current_pump_count = $total_pump_count - $last_pump_count;

		$start_time = date("Y-m",time())."-01 00:00:00";
		$end_time   = date("Y-m-d H:i:s",time());

		// 获取总的闸门次数
		$sql_pump_count = prepare("select count(*) from event where event like ?s and device_id in (select id from device where project_id = ?i and status = 1)",array('%泵%',$user_basic['project_id']));
		$total_pump_count = get_var($sql_pump_count) == null ? 0 :  get_var($sql_pump_count);

		// 获取本月之前的闸门次数
		$sql_current_pump_count = prepare("select count(*) from event where event like ?s and device_id in (select id from device where project_id = ?i and status = 1) and event_time >= ?s and event_time <= ?s",array('%泵%',$user_basic['project_id'],$start_time,$end_time));
		$current_pump_count = get_var($sql_current_pump_count) == null ? 0 :  get_var($sql_current_pump_count);
		
		$result = array("total_pump_count"=>$total_pump_count,'current_pump_count'=>$current_pump_count);

		return self::send_result($result);
	}

	// 闸门调控统计
	public function getOverviewGateLine()
	{
		$token = $_GET['token'];
		$type  = $_GET['type'] == '' ? $type = 'month' : $type = $_GET['type'];

		// 获取登录人员基本信息
		$user_basic = $this -> getLoginUserInfoByToken($token);

		// 获取当前项目中所有控制柜
		$sql = prepare("select id from device where project_id = ?i",array($user_basic['project_id']));

		$data_device_array = get_data($sql);

		$current_time = date("Y-m-d",time());

		switch ($type) {
			case 'month':
				// 时间处理
				$satrt_query_time = date("Y-m-d",time()-14*24*60*60).' 00:00:00';
				$end_query_time   = date("Y-m-d H:i:s",time());
				$month_time_array = $this -> getDateFromtime($satrt_query_time,$end_query_time);

				for ($i=0; $i < count($month_time_array); $i++) { 
					// 每天开始时间 和 结束时间
					// echo $month_time_array[$i];
					// if($month_time_array[$i] == $current_time)
					// {
					// 	$every_day_start_time_table = "data_".date("Ymd",strtotime($month_time_array[$i])-24*60*60);
					// 	$every_day_end_time_table   = "data";
					// }
					// else
					// {
					// 	$every_day_start_time_table = "data_".date("Ymd",strtotime($month_time_array[$i])-24*60*60);
					// 	$every_day_end_time_table   = "data_".date("Ymd",strtotime($month_time_array[$i]));
					// }

					$start_time = $month_time_array[$i]." 00:00:00";
					$end_time = $month_time_array[$i]." 23:59:59";
					

					$gate_count_1 = $gate_count_2 = 0;
					// 计算每天闸门调控的次数
					for ($j=0; $j < count($data_device_array); $j++) { 
						$device_id = $data_device_array[$j]['id'];

						$sql_current_gate_count = prepare("select count(*) from event where event like ?s and device_id =?i and event_time >= ?s and event_time <= ?s",array('%闸门%',$device_id,$start_time,$end_time));
						$gate_count_1 += get_var($sql_current_gate_count) == null ? 0 : get_var($sql_current_gate_count);
						// $sql_1 = prepare("select (gate_up_count+gate_down_count) as gate_count from ".$every_day_start_time_table." where device_id = ?i order by id desc limit 1",array($device_id));
						// $gate_count_1 += get_var($sql_1) == null ? 0 : get_var($sql_1);
						// // 获取本月之前的闸门次数
						// $sql_2 = prepare("select (gate_up_count+gate_down_count) as gate_count from ".$every_day_end_time_table." where device_id = ?i order by id desc limit 1",array($device_id));
						
					}

					$result['count'][$i] = $gate_count_1;
					$result['time'][$i] = date("d",strtotime($month_time_array[$i]));
				}
			break;
			
			case 'year':
				// 时间处理
				$year_time_array = $this -> getYearMonthTime();
				
				for ($i=0; $i < count($year_time_array); $i++) { 
					// 每月开始时间 和 结束时间
					$every_month_start_time = $year_time_array[$i].'-01 00:00:00';
					$every_month_end_time   = $year_time_array[$i].'-31 23:59:59';
					// echo $every_month_start_time.'-------'.$every_month_end_time."======================\r\n";
					$gate_count_1 = $gate_count_2 = 0;
					// 计算每天闸门调控的次数
					for ($j=0; $j < count($data_device_array); $j++) { 
						$device_id = $data_device_array[$j]['id'];
						$sql_current_gate_count = prepare("select count(*) from event where event like ?s and device_id =?i and event_time >= ?s and event_time <= ?s",array('%闸门%',$device_id,$every_month_start_time,$every_month_end_time));
						$gate_count_1 += get_var($sql_current_gate_count) == null ? 0 : get_var($sql_current_gate_count);
						// $sql_1 = prepare("select (gate_up_count+gate_down_count) as gate_count from data where device_id = ?i and `current_time`<?s order by id desc limit 1",array($device_id,$every_month_start_time));
						// $gate_count_1 += get_var($sql_1) == null ? 0 : get_var($sql_1);
						// // 获取本月之前的闸门次数
						// $sql_2 = prepare("select (gate_up_count+gate_down_count) as gate_count from data where device_id = ?i and `current_time`<?s order by id desc limit 1",array($device_id,$every_month_end_time));
						// $gate_count_2 += get_var($sql_2) == null ? 0 : get_var($sql_2);
					}

					$result['count'][$i] = $gate_count_1;
					$result['time'][$i] = date("m-d",strtotime($year_time_array[$i]));
				}
			break;
		}
		self::send_result($result);
	}

	// 水泵调控统计
	public function getOverviewPumpLine()
	{
		$token = $_GET['token'];
		$type  = $_GET['type'] == '' ? $type = 'month' : $type = $_GET['type'];

		// 获取登录人员基本信息
		$user_basic = $this -> getLoginUserInfoByToken($token);

		// 获取当前项目中所有控制柜
		$sql = prepare("select id from device where project_id = ?i",array($user_basic['project_id']));

		$data_device_array = get_data($sql);
		$current_time = date("Y-m-d",time());
		switch ($type) {
			case 'month':
				// 时间处理
				$satrt_query_time = date("Y-m-d",time()-14*24*60*60).' 00:00:00';
				$end_query_time   = date("Y-m-d H:i:s",time());
				$month_time_array = $this -> getDateFromtime($satrt_query_time,$end_query_time);

				for ($i=0; $i < count($month_time_array); $i++) { 
					// 每天开始时间 和 结束时间
					// echo $month_time_array[$i];
					// if($month_time_array[$i] == $current_time)
					// {
					// 	$every_day_start_time_table = "data_".date("Ymd",strtotime($month_time_array[$i])-24*60*60);
					// 	$every_day_end_time_table   = "data";
					// }
					// else
					// {
					// 	$every_day_start_time_table = "data_".date("Ymd",strtotime($month_time_array[$i])-24*60*60);
					// 	$every_day_end_time_table   = "data_".date("Ymd",strtotime($month_time_array[$i]));
					// }

					$start_time = $month_time_array[$i]." 00:00:00";
					$end_time = $month_time_array[$i]." 23:59:59";

					$pump_count_1 = $pump_count_2 = 0;
					// 计算每天闸门调控的次数
					for ($j=0; $j < count($data_device_array); $j++) { 
						$device_id = $data_device_array[$j]['id'];
						$sql_current_pump_count = prepare("select count(*) from event where event like ?s and device_id =?i and event_time >= ?s and event_time <= ?s",array('%泵%',$device_id,$start_time,$end_time));
						$pump_count_1 += get_var($sql_current_pump_count) == null ? 0 : get_var($sql_current_pump_count);
						// $sql_1 = prepare("select (main_sewage_pump_count+standby_sewage_pump_count+main_rain_pump_count) as pump_count from ".$every_day_start_time_table." where device_id = ?i order by id desc limit 1",array($device_id));
						// $pump_count_1 += get_var($sql_1) == null ? 0 : get_var($sql_1);
						// // 获取本月之前的闸门次数
						// $sql_2 = prepare("select (main_sewage_pump_count+standby_sewage_pump_count+main_rain_pump_count) as pump_count from ".$every_day_end_time_table." where device_id = ?i order by id desc limit 1",array($device_id));
						// $pump_count_2 += get_var($sql_2) == null ? 0 : get_var($sql_2);
					}

					$result['count'][$i] = $pump_count_1;
					$result['time'][$i] = date("d",strtotime($month_time_array[$i]));
				}
			break;
			
			case 'year':
				// 时间处理
				$year_time_array = $this -> getYearMonthTime();
				
				for ($i=0; $i < count($year_time_array); $i++) { 
					// 每月开始时间 和 结束时间
					$every_month_start_time = $year_time_array[$i].'-01 00:00:00';
					$every_month_end_time   = $year_time_array[$i].'-31 23:59:59';
					// echo $every_month_start_time.'-------'.$every_month_end_time."======================\r\n";
					$pump_count_1 = $pump_count_2 = 0;
					// 计算每天闸门调控的次数
					for ($j=0; $j < count($data_device_array); $j++) { 
						$device_id = $data_device_array[$j]['id'];
						$sql_current_pump_count = prepare("select count(*) from event where event like ?s and device_id =?i and event_time >= ?s and event_time <= ?s",array('%泵%',$device_id,$every_month_start_time,$every_month_end_time));
						$pump_count_1 += get_var($sql_current_pump_count) == null ? 0 : get_var($sql_current_pump_count);
						// $sql_1 = prepare("select (main_sewage_pump_count+standby_sewage_pump_count+main_rain_pump_count) as pump_count from data where device_id = ?i and `current_time`<?s order by id desc limit 1",array($device_id,$every_month_start_time));
						// $pump_count_1 += get_var($sql_1) == null ? 0 : get_var($sql_1);
						// // 获取本月之前的闸门次数
						// $sql_2 = prepare("select (main_sewage_pump_count+standby_sewage_pump_count+main_rain_pump_count) as pump_count from data where device_id = ?i and `current_time`<?s order by id desc limit 1",array($device_id,$every_month_end_time));
						// $pump_count_2 += get_var($sql_2) == null ? 0 : get_var($sql_2);
					}

					$result['count'][$i] = $pump_count_1;
					$result['time'][$i] =  date("m-d",strtotime($year_time_array[$i]));
				}
			break;
		}
		self::send_result($result);
	}


	// 通过session中token获取登录人员基本信息
	function getLoginUserInfoByToken($token)
	{
		$sql = prepare("select project_id,name,mobile from user where token = ?s limit 1",array($token));

		$data = get_line($sql);

		return $data;
	}


	// 通过token获取场站和设备信息
	public function getTerminalDeviceInfoByToken()
	{
		$token = $_GET['token'];

		// 获取project_id 根据type 判断是否显示全部设备
		$sql = prepare("select project_id,type,device_str from user where token = ?s limit 1",array($token));
		$project_id = get_line($sql)['project_id'];
		$type 		= get_line($sql)['type'];
		$device_str = get_line($sql)['device_str'];

		if($type == 2)
		{
			// 项目内全部设备 	
			$sql_1 = prepare("select device.id,device.name,terminal.address as addr,device.name as device_name,device.device_no,device.register_address,device.status from device left join terminal on terminal.id = device.terminal_id where device.project_id = ?i",array($project_id));
		}
		else
		{
			// 负责的设备
			if(!empty($device_str))
			{
				// 判断是否包含 - 
				if(strpos($device_str,'-') !== false)
				{
					$device_id_array = explode('-', $device_str);

					for ($i=0; $i < count($device_id_array); $i++) 
					{ 
						$sql_str .= "device.id = ".$device_id_array[$i]." or ";	
					}

					// 去掉最后的or

					$new_sql_str = substr($sql_str, 0, strlen($sql_2)-3);

					$final_sql_str = "(".$new_sql_str.")";
					
					$sql_1 = prepare("select device.id,device.name,terminal.address as addr,device.name as device_name,device.device_no,device.register_address,device.status from device left join terminal on terminal.id = device.terminal_id where device.project_id = ?i and ".$final_sql_str,array($project_id));
				}
				else
				{
					$sql_1 = prepare("select device.id,device.name,terminal.address as addr,device.name as device_name,device.device_no,device.register_address,device.status from device left join terminal on terminal.id = device.terminal_id where device.project_id = ?i and device.id = ?i",array($project_id,$device_str));
				}
				
			}
		}
		$data = get_data($sql_1);

		if(!empty($data))
		{
			for ($i=0; $i < count($data); $i++) 
			{ 
				$result[$i]['id'] = $data[$i]['id'];
				$result[$i]['name'] = $data[$i]['name'];
				$result[$i]['addr'] = $data[$i]['addr'];
				$result[$i]['status'] = $data[$i]['status'] == 1 ? '在线' : '安装中';
				
				if($data[$i]['status'] == 1)
				{
					$sql_2 = prepare("select created_at from data where device_id = ?i order by created_at desc limit 1",array($data[$i]['id']));
					$result[$i]['last_time'] = date("m-d H:i",strtotime(get_var($sql_2)));
				}
				else
				{
					$result[$i]['last_time'] = '01-01 08:00';
				}
			}
		}
		else
		{
			$result = 'false';
		}
		

		return self::send_result($result);
	}




	// 通过device_id获取场站和设备信息
	public function getTerminalDeviceInfoBydeviceId()
	{
		$device_id = $_GET['device_id'];

		// 通过project_id获取device信息
		$sql_1 = prepare("select device.id,terminal.name,terminal.address as addr,device.name as device_name,device.device_no,device.register_address,device.status from device left join terminal on terminal.id = device.terminal_id where device.id = ?i limit 1",array($device_id));
		$data = get_line($sql_1);

		if(!empty($data))
		{
			$result['id'] = $data['id'];
			$result['name'] = $data['name'];
			$result['addr'] = $data['addr'];
			$result['status'] = $data['status'] == 1 ? '在线' : '安装中';

			// 查询参数
			$sql_2 = prepare("select ph_data,elec_conductivity_tds_data,level_data,ammonia_data,rainsnow,rainfall_data,gate_up,gate_down,main_sewage_pump,standby_sewage_pump,main_rain_pump,created_at from data where device_id = ?i order by created_at desc limit 1",array($data['id']));
			$data_2= get_line($sql_2);
			$result['ph_data'] = number_format($data_2['ph_data'],2);
			$result['elec_conductivity_tds_data'] = number_format($data_2['elec_conductivity_tds_data'],2);
			$result['level_data'] = number_format($data_2['level_data'],2);
			$result['ammonia_data'] = number_format($data_2['ammonia_data'],2);
			$result['rainsnow'] = number_format($data_2['rainsnow'],2);
			$result['rainfall_data'] = number_format($data_2['rainfall_data'],2);
			$result['created_at'] = $data_2['created_at'];
			if($data_2['main_sewage_pump'] == 1){
				$result['main_sewage_pump'] = '启动';
			}else if($data_2['main_sewage_pump'] == 2){
				$result['main_sewage_pump'] = '停止';
			}else{
				$result['main_sewage_pump'] = '报警';
			}

			if($data_2['standby_sewage_pump'] == 1){
				$result['standby_sewage_pump'] = '启动';
			}else if($data_2['standby_sewage_pump'] == 2){
				$result['standby_sewage_pump'] = '停止';
			}else{
				$result['standby_sewage_pump'] = '报警';
			}

			if($data_2['main_rain_pump'] == 1){
				$result['main_rain_pump'] = '启动';
			}else if($data_2['main_rain_pump'] == 2){
				$result['main_rain_pump'] = '停止';
			}else{
				$result['main_rain_pump'] = '报警';
			}

			if($data_2['gate_up'] == 1)
			{
				$result['gate_status'] = '上升';
			}
			else
			{
				if($data_2['gate_down'] == 1)
				{
					$result['gate_status'] = '下降';
				}
				else
				{
					$result['gate_status'] = '停止';
				}
			}
			
		}
		

		return self::send_result($result);
	}

	public function getDeviceFdid()
	{
		$device_id = $_GET['device_id'];

		// 通过project_id获取device信息
		$sql = prepare("select f_did from device where id = ?i limit 1",array($device_id));

		$data = get_var($sql);
		
		return self::send_result($data);
	}

	public function getDeviceName()
	{
		$device_id = $_GET['device_id'];

		// 通过project_id获取device信息
		$sql = prepare("select name from device where id = ?i limit 1",array($device_id));

		$data = get_var($sql);
		
		return self::send_result($data);
	}
	
	// 获取两个指定日期之间的每一天
	function getDateFromtime($starttime,$endtime)
	{
		
		$dt_start = strtotime($starttime);
	    $dt_end   = strtotime($endtime);

	    while ($dt_start <= $dt_end){

	    	$array[] = date('Y-m-d',$dt_start);
	       
	        $dt_start = strtotime('+1 day',$dt_start);
	    }

	    return $array;
	}

	function getYearMonthTime()
	{
		// 获取本月是几月
		$m = date("m",time());
	
		for ($i=1; $i < ($m+1); $i++) { 

			$month = date("Y",time())."-".$i;

			$array[] = date("Y-m",strtotime($month));

		}

		return $array;
	}

}	
?>
