<?php
namespace Addons\QyWechat\Services;

use Services\Service;
use Models\BaseModel as Model;
use Session;
use Addons\QyWechat\Helper;
use EasyWeChat\Factory;

class ProvidersApi extends Service
{
	public function get_thirdapp_setting(){
		$agency = (new Model('user_agency'))->find(['isadmin' => 1]);
		$thirdappsetting = (new Model('qy_agency_thirdappsetting'))->find(['pid'=>$agency->id]);
		return $thirdappsetting;
	}
		
	public function get_provider_app(){
		$thirdappsetting = $this->get_thirdapp_setting();
		// dump($thirdappsetting);
		$config = [
			 'corp_id'          => $thirdappsetting->corpid?$thirdappsetting->corpid:'',
			 'secret'           => $thirdappsetting->providerSecret?$thirdappsetting->providerSecret:'',
			 'suite_id'         => $thirdappsetting->suite_id?$thirdappsetting->suite_id:'',
			 'suite_secret'     => $thirdappsetting->suite_secret?$thirdappsetting->suite_secret:'',
			 'token'            => $thirdappsetting->token?$thirdappsetting->token:'',
			 'aes_key'          => $thirdappsetting->encodingAESKey?$thirdappsetting->encodingAESKey:'',
			 'reg_template_id'  => '',

		  ];
		  $app = Factory::openWork($config);
		  return $app;
	}
	
	//授权页网址
	public function get_rebind_url($redirect_uri,$state = []){
		$thirdappsetting = $this->get_thirdapp_setting();
		$app = $this->get_provider_app();
		// dump($app->corp->getPreAuthCode());die;
		$preAuthCode = $app->corp->getPreAuthCode()['pre_auth_code'];
		$auth_type = $thirdappsetting->auth_type == 1?0:1;
		$setSession = $app->corp->setSession($preAuthCode, ['auth_type'=>$auth_type]);
		$url = 'https://open.work.weixin.qq.com/3rdapp/install?suite_id='.$thirdappsetting->suite_id.'&pre_auth_code='.$preAuthCode.'&redirect_uri='.$redirect_uri.'&state='.json_encode($state);
		return $url;
	}
	
	//获取企业永久授权码
	public function get_permanent_code($auth_code){
		$wid = Session::get('wid');//当前登录的用户id
		$thirdappsetting = $this->get_thirdapp_setting();
		$app = $this->get_provider_app();
		$permanentByCode = $app->corp->getPermanentByCode($auth_code);
		if($permanentByCode['errcode'] == 0){
			$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
			if($qyConfig->corp_id && $qyConfig->corp_id != $permanentByCode['auth_corp_info']['corpid']){
				return false;//与绑定的企业不一致（针对老用户）
			}else if(!$qyConfig->id){
				$inspectCorpid = (new Model('qy_wechat_config'))->find(['corp_id'=>$permanentByCode['auth_corp_info']['corpid']]);
				if($inspectCorpid->id){
					return false;//企业已存在（新用户）
				}
			}
			$ppc = (new Model('qy_providers_permanent_code'))->find(['wid'=>$wid]);
			$ppc->wid = $wid;
			$ppc->suite_id = $thirdappsetting->suite_id;
			$ppc->corpid = $permanentByCode['auth_corp_info']['corpid'];
			$ppc->permanent_code = $permanentByCode['permanent_code'];
			$ppc->ctime = date('Y-m-d H:i:s');
			$ppc->save();
			if(!$qyConfig->has_id()){
				$h = Helper::getInstance();
				$qyConfig->externalcontact_token = $h->getRandStr(15);
				$qyConfig->externalcontact_aes = $h->getRandStr(42);
				$qyConfig->user_tokent = $h->getRandStr(15);
				$qyConfig->user_aes = $h->getRandStr(42);
				$qyConfig->ctime = date("Y-m-d H:i:s");
			}
			$qyConfig->wid = $wid;
			$qyConfig->corp_id = $ppc->corpid;
			$qyConfig->save();
			return $ppc->permanent_code;
		}else{
			return false;//授权失败
		}
	}
	
	public function get_work($corpid=''){
		if(!$corpid){
			$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>Session::get('wid')]);
			$corpid = $qyConfig->corp_id;
		}
		$app = $this->get_provider_app();
		$ppc = (new Model('qy_providers_permanent_code'))->find(['corpid'=>$corpid]);
		$work = $app->work($ppc->corpid,$ppc->permanent_code);
		return $work;
	}
	
	public function get_access_token($corpid=''){
		$work = $this->get_work($corpid);
		// 获取 access token 实例
		$accessToken = $work->access_token;
		$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
		return $token;
	}
	
	//获取企业标签库
	public function get_corp_tag_list($tag_id = []){
		$token = $this->get_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_corp_tag_list?access_token=" . $token,
			json_encode([
				"tag_id" => $tag_id
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//新增标签
	public function add_corp_tag($param){
		$token = $this->get_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_corp_tag?access_token=" . $token,
			json_encode([
				"group_id" => $param['group_id'],
				"group_name" => $param['group_name'],
				"tag" => $param['tag']
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//删除标签
	public function del_corp_tag($param){
		$token = $this->get_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_corp_tag?access_token=" . $token,
			json_encode([
				"tag_id" => $param['tag_id'],
				"group_id" => $param['group_id'],
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//编辑客户企业标签
	public function edit_et_tag($param,$corpid=''){
		$token = $this->get_access_token($corpid);
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/mark_tag?access_token=" . $token,
			json_encode([
				"userid" => $param['userid'],
				"external_userid" => $param['external_userid'],
				"add_tag" => $param['add_tag'],
				"remove_tag" => $param['remove_tag']
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//获取群列表
	public function get_et_groupchat_list(){
		$token = $this->get_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?access_token=" . $token,
			json_encode([
				"offset" => 0,
				"limit" => 1000,
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//获取群详情
	public function get_et_groupchat_info($chat_id,$corpid=''){
		$token = $this->get_access_token($corpid);
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token=" . $token,
			json_encode([
				"chat_id" => $chat_id
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//获取客户群统计数据
	public function get_et_groupchat_statistic($begin_time = ''){
		if(!$begin_time){
			$begin_time = strtotime("-1 day");
		}
		$token = $this->get_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/statistic?access_token=" . $token,
			json_encode([
				"day_begin_time" => $begin_time,
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//添加群欢迎语素材
	public function add_group_welcome_template($param = []){
		$token = $this->get_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/add?access_token=" . $token,
			json_encode($param)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//编辑群欢迎语素材
	public function edit_group_welcome_template($param = []){
		$token = $this->get_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/edit?access_token=" . $token,
			json_encode($param)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	//删除群欢迎语素材
	public function del_group_welcome_template($template_id){
		$token = $this->get_access_token();
		$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/del?access_token=" . $token,
			json_encode([
				'template_id'=>$template_id
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
}
