<?php
namespace Addons\QyWechat\Controller\H5;

use Models\BaseModel as Model;
use Session;
use Addons\QyWechat\Helper;
use Addons\QyWechat\Services\QyWechatApi;
use Addons\QyWechat\Services\JsSdk;
use Addons\QyWechat\Services\Oauth2JsSdk; 

class Reply extends \BaseController
{	
    public function index(){
		$corp_id = \Request::get('corp_id');
		$agent_id = \Request::get('agent_id');
		$qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$corp_id]);
		$wid = $qyConfig->wid;
		$replyConfig = (new Model('qy_reply_config'))->find(['wid'=>$wid,'agent_id'=>$agent_id]);
		$quickReply = new Model('qy_quick_reply_list');
		//name 模糊查询
		$name = $_GET['name'];
		if(trim($name)!=''){
			$where['name@~'] = $name;
		}
		//类型
		$type = $_GET['type'];
		if($type){
			$where['type'] = $type;	
		}
		//分组
		$groupid = $_GET['groupid'];
		if($groupid){
			$where['groupid@~'] = $groupid;	
		}
		$where['wid'] = $wid;
		$pageIndex = 1;
		$pageSize = 10;
		//条数
        $lim = 	$pageSize*($pageIndex-1).','.$pageSize;
		$res = $quickReply->where($where)->limit($lim)->order('id')->list_all();
		//$p = new \Pagination();		
		//$res = $p->model_list($quickReply->where($where)->order('id desc'));
		$jsSdkServe = new JsSdk($corp_id,$agent_id,$replyConfig->secret);
		$wxConfig = $jsSdkServe->getSignPackage();
		$agentConfig = $jsSdkServe->getSignPackage('','agent');
		$group = new Model('qy_quick_reply_group');
		$grouparr = $group->where(array('wid'=>$wid))->order('sort')->map_array('keyid', 'name');
		$this->assign("corp_id", $corp_id);
		$this->assign("agent_id", $agent_id);
		$this->assign("name", $name);
		$this->assign("type", $type);
		$this->assign("groupid", $groupid);
		//$this->assign("p", $p);
		//$this->assign("P", $GLOBALS['P']);
		$this->assign("wid", $wid);
		$this->assign("res", $res);		
		$this->assign("wxConfig", $wxConfig);		
		$this->assign("agentConfig", $agentConfig);		
		$this->assign("grouparr", $grouparr);		
		$this->assign("h", Helper::getInstance());
		return $this->show();
	}
	
	public function load_more(){
		setApi();
		$wid = $_POST['wid'];
		$name = $_POST['name'];
		$pageIndex = $_POST['pageIndex'];
		if(trim($name)!=''){
			$where['name@~'] = $name;	
		}
		//类型
		$type = $_POST['type'];
		if($type){
			$where['type'] = $type;	
		}
		//分组
		$groupid = $_POST['groupid'];
		if($groupid){
			$where['groupid@~'] = $groupid;	
		}
		$where['wid'] = $wid;
		$pageIndex = $pageIndex;
		$pageSize = 10;
		//条数
        $lim = 	$pageSize*($pageIndex-1).','.$pageSize;
		$res = (new Model('qy_quick_reply_list'))->where($where)->limit($lim)->order('id')->list_all_array();
		sendSuccess('获取成功',$res);
	}
	
	public function get_reply_info(){
		set_time_limit(0);
		setApi();
		$corp_id = \Request::get(1);
		$agent_id = \Request::get(2);
		$qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$corp_id]);
		$replyConfig = (new Model('qy_reply_config'))->find(['wid'=>$qyConfig->wid,'agent_id'=>$agent_id]);
		$QyWechatApi = QyWechatApi::getInstance();
		$agentApp = $QyWechatApi->get_qy_agent_app($corp_id,$agent_id,$replyConfig->secret);
		$id = $_POST['id'];
		$quickReply = (new Model('qy_quick_reply_list'))->find($id);
		if($quickReply->type == 1){
			$data = [
				'type' => 1,
				'text_content' => $quickReply->text_content
			];
		}elseif($quickReply->type == 2){
			$pic_arr = explode("/", $quickReply->pic_path);
			$pic_path = "./tmpImg/{$pic_arr[count($pic_arr)-1]}";
			$mediaId = $agentApp->media->uploadImage($pic_path)["media_id"];
			$data = [
				'type' => 2,
				'media_id' => $mediaId
			];
		}elseif($quickReply->type == 3){
			$mediaId = $agentApp->media->uploadVideo($quickReply->video_path,$quickReply->video_name,'')["media_id"];
			$data = [
				'type' => 3,
				'media_id' => $mediaId
			];
		}elseif($quickReply->type == 4){
			$mediaId = $agentApp->media->uploadFile($quickReply->file_path)["media_id"];
			$data = [
				'type' => 4,
				'media_id' => $mediaId
			];
		}elseif($quickReply->type == 5){
			$data = [
				'type' => 5,
				'link_url' => $quickReply->link_url,
				'link_title' => $quickReply->link_title,
				'link_pic' => $quickReply->link_pic,
				'link_desc' => $quickReply->link_desc,
			];
		}
		sendSuccess('获取成功',$data);
	}

	public function radar(){
		$corp_id = \Request::get('corp_id');
		$agent_id = \Request::get('agent_id');
		$qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$corp_id]);
		$wid = $qyConfig->wid;
		$radar_list =  (new Model('qy_radar_list'))->where(['wid'=>$wid])->order('id desc')->list_all_array();
		foreach ($radar_list as $rekey => $re) {
			$radar_list[$rekey]['num_click_tatol'] = count(array_unique((new Model('qy_radar_record'))->field('externalcontact_id')->where(['wid'=>$re['wid'],'radar_id'=>$re['id']])->list_all_array(),SORT_REGULAR));
			$radar_list[$rekey]['num_click_tedaytatol'] = count(array_unique((new Model('qy_radar_record'))->field('externalcontact_id')->where(['wid'=>$re['wid'],'radar_id'=>$re['id'],'ctime@>'=>strtotime(date('Y-m-d'))])->list_all_array(),SORT_REGULAR));
		}

		$jsSdkServe = new JsSdk($corp_id,$agent_id,$replyConfig->secret);
		$wxConfig = $jsSdkServe->getSignPackage();
		$agentConfig = $jsSdkServe->getSignPackage('','agent');

		$this->assign("corp_id", $corp_id);
		$this->assign("agent_id", $agent_id);
		$this->assign("radar_list", $radar_list);
		$this->assign("wxConfig", $wxConfig);
		$this->assign("agentConfig", $agentConfig);	

		$this->assign("h", Helper::getInstance());
		return $this->show();
	}

	public function get_radar_info(){
		set_time_limit(0);
		setApi();
		$corp_id = \Request::get(1);
		$agent_id = \Request::get(2);
		$id = $_POST['id'];
		$radar = (new Model('qy_radar_list'))->find($id);

		$h = Helper::getInstance();
		$selfurl = $h->get_http_server_name().'/Addons/QyWechat/H5/Reply/collect_clcuser_infor.html?id='.$id.'&corp_id='.$corp_id.'&agent_id='.$agent_id;

		$data = [
			'link_url' => $selfurl,
			'link_title' => $radar->title,
			'link_pic' => $radar->image_url,
			'link_desc' => $radar->description,
		];
		sendSuccess('获取成功',$data);
	}

	public function collect_clcuser_infor(){
		$id = \Request::get('id');
		$corp_id = \Request::get('corp_id');
		$agent_id = \Request::get('agent_id');
		$radar = (new Model('qy_radar_list'))->find($id);
		if(!$radar->id){
			die('链接不存在');
		}	

		$wid = $radar->wid;
		$pub = (new Model('pubs'))->find($wid);
		$user = (new Model('user'))->find($pub->uid);
		if ($user->agid) {
	        $agency = (new Model('user_agency'))->find(['id' => $user->agid]);
	    } else {
	        $agency = (new Model('user_agency'))->find(['un' => 'admin']);
	    }

 		$oauth2jsSdk = Oauth2JsSdk::getInstance();
	    // $gzh = (new Model('qy_agency_gzh_config'))->find(['pid'=>$agency->id]);
		$redirect_url = urlencode(Helper::getInstance()->get_http_server_name().'/Addons/QyWechat/H5/Reply/collect_clcuser_infor.html?id='.$id.'&corp_id='.$corp_id.'&agent_id='.$agent_id);
		// $auth_url = $oauth2jsSdk->oauth2_authorize($gzh->appid,$redirect_url,'snsapi_userinfo');
		$auth_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$corp_id.'&redirect_uri='.$redirect_url.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
		$code = $_GET['code']??'';
		if($code){
				$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
				$sendConfig = (new Model('qy_message_send_config'))->find(['wid'=>$wid]);
				$QyWechatApi = QyWechatApi::getInstance();
				$app = $QyWechatApi->get_qy_agent_app($qyConfig->corp_id,$sendConfig->agent_id,$sendConfig->secret);
				$accessToken = $app->access_token;
				$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
				$url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$token.'&code='.$code;
				$resArr = json_decode(curlGet($url),1);
				if(isset($resArr['external_userid'])){
					$externalcontac = (new Model('qy_externalcontact_list'))->find(['wid'=>$wid,  'external_userid'=>$resArr['external_userid']]);
					if($externalcontac->id){
						$radar_record = (new Model('qy_radar_record'));
						$radar_record->wid = $wid;
						$radar_record->externalcontact_id = $externalcontac->id;
						$radar_record->radar_id = $id;
						$radar_record->ctime = time();
						if($radar_record->save()){
							// 发送提醒
							if($radar->behavior_inform == 1){
								$content = $externalcontac->name.'点击了标题是<'. $radar->link_title.'>的雷达链接';
								$this->send_remind($corp_id , $wid, '@all', $content);
							}
							//记录动态
							if($radar->dynamic_inform == 1){
								$dynamic = (new Model('qy_et_dynamic'));
								$dynamic->wid = $wid;
								$dynamic->external_userid = $externalcontac->external_userid;
								$dynamic->type = 5;
								$dynamic->ctime = time();
								$dynamic->glian_id = $id;
								$dynamic->save();
							}
							//打标签
							if($radar->ex_tag_inform == 1){
								$radar_tags = [];
								$radar_tags = json_decode($radar->ex_tag,1);
								$exter_tag = [];
								$exter_tag = json_decode($externalcontac->tags,1);
								$add_tag = [];
								if($radar_tags){
									foreach ($radar_tags as $tags_key => $radar_tag) {
										if(!in_array($radar_tag, $exter_tag)){
											$exter_tag[] = $radar_tag;
											$add_tag[] = $radar_tag;
										}
									}
								}
								if($add_tag){
									$h = Helper::getInstance();
									$param = [
									  'userid' => $h->get_user_by_id($wid,$externalcontac->user_id)['userid'],
									  'external_userid' => $externalcontac->external_userid,
									  'add_tag' => $exter_tag,
								  	];
								    $res = $QyWechatApi->edit_et_tag($param,$wid);
								    if($res['errmsg'] == 'ok'){
								    	$externalcontac->tags = json_encode($exter_tag,320);
										$externalcontac->save();
								    }   
								}
							}
						}
					}	
				}
			\Redirect::to($radar->link);
		}else{
			\Redirect::to($auth_url);
		}
	}


	public function send_remind($corp_id,$wid, $touser, $content){
		$QyWechatApi = QyWechatApi::getInstance();
		$sendConfig = (new Model('qy_message_send_config'))->find(['wid'=>$wid]);
		$messenger = null;
     	if($corp_id && $sendConfig->agent_id && $sendConfig->secret){
            $app = $QyWechatApi->get_qy_agent_app($corp_id,$sendConfig->agent_id,$sendConfig->secret);
         	$messenger = $app->messenger->ofAgent($sendConfig->agent_id);
     	}
     	if($messenger){
     		$messenger->toUser($touser)->send($content);
     	}
	}
}