<?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 aeratorController 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 getAllAeratorList()
	{
		$token = $_GET['token'];
		// 获取项目ID
		$basic_info = $this -> getLoginUserInfoByToken($token);

		$project_id = $basic_info['project_id'];

		$sql = prepare("select aerator.id,terminal.name as terminal_name,terminal.address,aerator.device_name,aerator.name,if(aerator.status=1,'开启','关闭') as status,aerator.count,aerator.created_at from aerator left join terminal on terminal.id = aerator.terminal_id where aerator.project_id = ?i",array($project_id));
		$data= get_data($sql);

		for ($i=0; $i < count($data); $i++) { 
			$data[$i]['title']['text'] = $data[$i]['name']; 
			$data[$i]['title']['color'] = '#000'; 
			$data[$i]['title']['size'] = 30;

			$data[$i]['tag']['text'] =  $data[$i]['status']."(".$data[$i]['count'].")";
			$data[$i]['tag']['color'] =  "#ed3f14";
			$data[$i]['tag']['size'] =  26;
		}

		return self::send_result($data);
	}

	// 获取选中曝气机基本信息
	public function getSelectAeratorTerminalInfo()
	{
		$aerator_id = $_GET['aerator_id'];

		$data = $this -> getAeratorBasicInfoById($aerator_id);

		return self::send_result($data);
	}

	// 获取选中曝气机的基本信息
	public function getSingleAeratorInfo()
	{
		$aerator_id = $_GET['aerator_id'];

		$aerator_array = $this -> getAeratorBasicInfoById($aerator_id);

		return self::send_result($aerator_array);
	}

	// 获取token值
	public function getAeratorToken($aerator_id)
	{
		$data =  $this -> getAeratorBasicInfoById($aerator_id);

		// 判断如果token为空 或者是 时间超过了1小时 重新生成token
		$duration = floor((time() - strtotime($data['created_at']))/10);
		$current_time = date("Y-m-d H:i:s",time());

		if(!isset($data['token']) or $data['token'] == '' or $duration > 10){

			$curl = curl_init();

			curl_setopt_array($curl, array(
			  CURLOPT_URL => $data['link'],
			  CURLOPT_RETURNTRANSFER => true,
			  CURLOPT_ENCODING => '',
			  CURLOPT_MAXREDIRS => 10,
			  CURLOPT_TIMEOUT => 0,
			  CURLOPT_FOLLOWLOCATION => true,
			  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			  CURLOPT_CUSTOMREQUEST => 'POST',
			  CURLOPT_POSTFIELDS => 'username='.$data['account'].'&pwd='.$data['password'],
			  CURLOPT_HTTPHEADER => array(
			    'Content-Type: application/x-www-form-urlencoded',
			    'Cookie: PHPSESSID=f53kjsucrafml6n92tolgum1o2'
			  ),
			));

			$response = curl_exec($curl);

			curl_close($curl);
			// $token = json_decode($response)->token;
			$token = substr($response,21,32);
			$sql_update = prepare("update aerator set token=?s,created_at=?s where id=?i",array($token,$current_time,$data['id']));
			run_sql($sql_update);

			return $token;

		}else{
			
			return $data['token'];
		}

	}

	// 获取曝气机属性
	public function getAeratorAttribute($aerator_id)
	{
		// 先更新token
		$this -> getAeratorToken($aerator_id);

		$data =  $this -> getAeratorBasicInfoById($aerator_id);

		$current_time = date("Y-m-d H:i:s",time());
		$curl = curl_init();

		curl_setopt_array($curl, array(
		  CURLOPT_URL => 'hk.tchjjc.com/api/thing/properties',
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => '',
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 0,
		  CURLOPT_FOLLOWLOCATION => true,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => 'POST',
		  CURLOPT_POSTFIELDS => 'token='.$data['token'].'&pk='.$data['pk'].'&deviceName='.$data['device_name'],
		  CURLOPT_HTTPHEADER => array(
		    'Content-Type: application/x-www-form-urlencoded',
		    'Cookie: PHPSESSID=f53kjsucrafml6n92tolgum1o2'
		  ),
		));

		$response = curl_exec($curl);

		curl_close($curl);
		$data = json_decode($response)->data;

		$csq_value = $data[0]->value;
		$wkmd_balue = $data[1]->value; 
		$imei_balue = $data[2]->value; 
		$imsi_balue = $data[5]->value; 
		$lcen_balue = $data[6]->value; 
		$rly1_balue = $data[7]->value; 
		$pwrs_balue = $data[8]->value; 
		$hold_balue = $data[9]->value; 
		$iccid_balue = $data[10]->value; 
		
		$sql_update = prepare("update aerator set imei=?s,imsi=?s,iccid=?s,csq=?s,status=?i where id = ?i",array($imei_balue,$imsi_balue,$iccid_balue,$csq_value,$rly1_balue,$aerator_id));
		run_sql($sql_update);
	}


	// 获取设备的属性面板
	public function getAeratorAttributePanel()
	{
		// 获取token值
		$token = $this->getAeratorToken();

		// 默认曝气机参数
		$pk = 'a1uZDeulr2x';
		$deviceName = 'H4GSAL0132202256465';

		$curl = curl_init();

		curl_setopt_array($curl, array(
		  CURLOPT_URL => 'hk.tchjjc.com/api/thing/tsl',
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => '',
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 0,
		  CURLOPT_FOLLOWLOCATION => true,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => 'POST',
		  CURLOPT_POSTFIELDS => 'token=FC33DA76E6179976298FDF91491295DC&pk=a1uZDeulr2x&deviceName=H4GSAL0132202256465',
		  CURLOPT_HTTPHEADER => array(
		    'Content-Type: application/x-www-form-urlencoded',
		    'Cookie: PHPSESSID=f53kjsucrafml6n92tolgum1o2'
		  ),
		));

		$response = curl_exec($curl);

		curl_close($curl);
		echo $response;
	}

	// 控制开关
	public function getAeratorRlyOn(){
		$aerator_id = $_GET['aerator_id'];

		// 推送最新得设备属性
		$this->getAeratorAttribute($aerator_id);
		
		$data = $this->getAeratorBasicInfoById($aerator_id);
		
		if($data['status'] == 0){
			$value = 1;
		}else{
			$value = 0;
		}

		$identifier = 'rly1';
		$new_count = $data['count'] + 1;
		$current_time = date("Y-m-d H:i:s",time());

		$curl = curl_init();

		curl_setopt_array($curl, array(
		  CURLOPT_URL => 'hk.tchjjc.com/api/thing/properties/set',
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => '',
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 0,
		  CURLOPT_FOLLOWLOCATION => true,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => 'POST',
		  CURLOPT_POSTFIELDS => 'token='.$data['token'].'&pk='.$data['pk'].'&deviceName='.$data['device_name'].'&identifier='.$identifier.'&value='.$value,
		  CURLOPT_HTTPHEADER => array(
		    'Content-Type: application/x-www-form-urlencoded',
		    'Cookie: PHPSESSID=f53kjsucrafml6n92tolgum1o2'
		  ),
		));

		$response = curl_exec($curl);

		curl_close($curl);
		echo $response;

		// 更新当前设备状态
		$sql_update = prepare("update aerator set status=?i,count=?i,created_at=?s where id = ?i",array($value,$new_count,$current_time,$aerator_id));
		
		run_sql($sql_update);
	}

	// 获取当前设备状态
	public function getAeratorDeviceStatus()
	{
		$token = $this->getAeratorToken();

		// 默认曝气机参数
		$pk = 'a1uZDeulr2x';
		$deviceName = 'H4GSAL0132202256465';
		$device_id = 1;
		$current_time = date("Y-m-d H:i:s",time());

		$curl = curl_init();

		curl_setopt_array($curl, array(
		  CURLOPT_URL => 'hk.tchjjc.com/api/thing/status',
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => '',
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 0,
		  CURLOPT_FOLLOWLOCATION => true,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => 'POST',
		  CURLOPT_POSTFIELDS => 'token='.$token.'&pk='.$pk.'&deviceName='.$deviceName,
		  CURLOPT_HTTPHEADER => array(
		    'Content-Type: application/x-www-form-urlencoded',
		    'Cookie: PHPSESSID=f53kjsucrafml6n92tolgum1o2'
		  ),
		));

		$response = curl_exec($curl);

		curl_close($curl);
		
		$status = json_decode($response)->data->status;

		$sql_update = prepare("update device set status = ?i,created_at = ?s where id = ?i",array($status,$current_time,$device_id));
		run_sql($sql_update);
	}


	// 通过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;
	}


	// 通过aerator_id获取曝气机基本信息
	function getAeratorBasicInfoById($aerator_id)
	{
		$sql = prepare("select aerator.id,project.name as project_name,terminal.name as terminal_name,terminal.address,aerator.link,aerator.account,aerator.password,aerator.token,aerator.pk,aerator.device_name,aerator.name,aerator.imei,aerator.imsi,aerator.iccid,aerator.csq,aerator.status,aerator.count,aerator.created_at from aerator left join project on project.id = aerator.project_id left join terminal on terminal.id = aerator.terminal_id where aerator.id = ?i limit 1",array($aerator_id));

		$data= get_line($sql);

		return $data;
	}

}	
?>
