<?php
namespace Addons\QyWechat\Controller\Api\Callback;
use Models\BaseModel as Model;
use Addons\QyWechat\Helper;
use Addons\QyWechat\Services\QyWechatApi;
use Addons\QyWechat\Services\ProvidersApi;
require_once(DOXCX_FRAME_PATH . 'fun/library/QyWxCypto/WXBizMsgCrypt.php');
 
class Externalcontact extends \BaseController
{
	  public function  index(){
		  if(isset($_GET['echostr'])){
			  //接受验证数据
		  	  $sVerifyMsgSig = $_GET['msg_signature'];
			  $sVerifyTimeStamp = $_GET['timestamp'];
			  $sVerifyNonce = $_GET['nonce'];
			  $sVerifyEchoStr = $_GET['echostr'];
			  $configList = (new Model('qy_wechat_config'))->list_all();
			  foreach($configList as $config){
				  $encodingAesKey = $config->externalcontact_aes;
				  $token = $config->externalcontact_token;
				  $corpId = $config->corp_id;
				  $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
				  // 需要返回的明文
				  $sEchoStr = "";
				  $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
				  if($errCode == 0){
					   echo $sEchoStr;
					   exit();
				  }
			  }
		  }else{
			  //搜集参数
			  $sReqMsgSig = $_GET['msg_signature'];
			  $sReqTimeStamp = $_GET['timestamp'];
			  $sReqNonce = $_GET['nonce'];
			  //获取xml冰去除特殊字符
			  $sReqData = preg_replace("/[\n\s]/", '', file_get_contents('php://input'));
			  //解密
			  $config = (new Model('qy_wechat_config'))->find(['corp_id'=>xml_to_array($sReqData)['ToUserName']]);
			  $encodingAesKey = $config->externalcontact_aes;
			  $token = $config->externalcontact_token;
			  $corpId = $config->corp_id;
			  $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
			  $sMsg = "";  // 解析之后的明文
			  $errCode = $wxcpt->DecryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sReqData, $sMsg);
			  if ($errCode == 0) {
				  // 解密成功，sMsg即为xml格式的明文
				  // TODO: 对明文的处理
				  /*
				  "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName>
				  <FromUserName><![CDATA[mycreate]]></FromUserName>
				  <CreateTime>1409659813</CreateTime>
				  <MsgType><![CDATA[text]]></MsgType>
				  <Content><![CDATA[hello]]></Content>
				  <MsgId>4561255354251345929</MsgId>
				  <AgentID>218</AgentID>
				  </xml>"
				  */
				  $arr = xml_to_array($sMsg);
				  if($arr['Event'] == 'change_external_contact'){
					  if($arr['ChangeType'] == 'add_external_contact'){
						  $this->add_external_contact($arr);
					  }elseif($arr['ChangeType'] == 'edit_external_contact'){
						  $this->edit_external_contact($arr);
					  }elseif($arr['ChangeType'] == 'del_external_contact'){
						  $this->del_external_contact($arr);
					  }elseif($arr['ChangeType'] == 'del_follow_user'){
						  $this->del_follow_user($arr);
					  }
				  }elseif($arr['Event'] == 'change_external_chat'){
					  $this->change_external_chat($arr);
				  }
				  
			  } else {
				  diy_log("解密失败ERR: " . $errCode . "\n\n");
			  }
			  echo "success";
			  exit();
		  }
	  }
	  
	  //添加企业客户
	  public function add_external_contact($arr){
		  $this->import_et_dynamic(1,$arr);
		  if($arr['State']){
			 $etContactWay = (new Model('qy_et_contact_way'))->find(['state'=>$arr['State']]);
			 $qyFission = (new Model('qy_fission'))->find(['state'=>$arr['State']]);
			 $fuser = (new Model('qy_fission_user'))->find(['state'=>$arr['State']]);
			 $qyEtQrcode = (new Model('qy_et_qrcode'))->find(['state'=>$arr['State']]);	
		  }
		  
		  if($etContactWay->id){
			  if($etContactWay->is_auto_pull_group == 1){
				  $this->add_et_by_autopullgroupcode($arr);
			  }else{
				  $this->add_et_by_code($arr);
			  }
		  }elseif($qyFission->id){
			  $this->add_et_by_fissioncode($arr);
		  }elseif($fuser->id){
			  $this->add_et_by_fusercode($arr);
		  }elseif($qyEtQrcode->id){
			  $this->add_et_by_etqrcode($arr);
		  }else{
			  $this->add_et($arr);
		  }
	  }
	  
	  public function add_et($arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		  
		  $customer_info_res = $etApp->external_contact->get($arr['ExternalUserID']);
		  foreach($customer_info_res['follow_user'] as $follow_user){
			  if($follow_user['userid'] == $arr['UserID']){
				  $remark_mobiles = $follow_user['remark_mobiles'];
				  $add_way = $follow_user['add_way'];
				  if($add_way == 2){//搜索手机号添加
				  	  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
					  $bafi= (new Model('qy_batch_add_friends_info'))->find(['wid'=>$qyConfig->wid,'phone'=>$remark_mobiles,'user_id'=>$qyUser->id]);
				  }
			  }
		  }
		  if($bafi->id){
			  $bafi->add_status = 1;
			  $bafi->save();
			  if($bafi->remarks){
				  $param = ['userid'=>$arr['UserID'],'external_userid'=>$arr['ExternalUserID'],'remark'=>$bafi->remarks];
				  $QyWechatApi->edit_et_remark($param,$qyConfig->wid);
			  }
			  $baf = (new Model('qy_batch_add_friends'))->find(['wid'=>$qyConfig->wid,'id'=>$bafi->pid]); 
		  }
		  if($baf->id){
			  $qyCustomer = $this->import_et_data(1,$baf->select_label,$arr);
		  }else{
			  $qyCustomer = $this->import_et_data('','',$arr);
		  }
		  
		  //发送欢迎语
		  if($arr['WelcomeCode']){
				$welcomeMsgList = (new Model('qy_welcome_msg_list'))->where(['wid'=>$qyConfig->wid,'type'=>2])->list_all();
				foreach($welcomeMsgList as $welcomeMsg){
				   $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
				   if(in_array($qyUser->id,json_decode($welcomeMsg->users,1))){
					  $welcomemsg = $welcomeMsg;
					  break;
				   }
				}
				if(!$welcomemsg->id){
					$welcomemsg = (new Model('qy_welcome_msg_list'))->find(['wid'=>$qyConfig->wid,'type'=>1]);
				}
				  
				if($welcomemsg->id){
					$welcomeCode = $arr['WelcomeCode'];
					$msg = [
						'text' => [
							'content' => $welcomemsg->text_content,
						]
					];
					if($welcomemsg->other_type == 2){//图片
						 $msg['image'] = [
							'media_id' => $etApp->media->uploadImage($welcomemsg->image_url)['media_id'],
						];
					}elseif($welcomemsg->other_type == 3){//图文
						 $msg['link'] = [
							'title' => $welcomemsg->link_title,
							'picurl' => $welcomemsg->link_picurl,
							'desc' => $welcomemsg->link_desc,
							'url' => $welcomemsg->link_url,
						 ];
					 }elseif($welcomemsg->other_type == 4){//小程序
						$msg['miniprogram'] = [
							'title' => $welcomemsg->miniprogram_title,
							'pic_media_id' => $etApp->media->uploadImage($welcomemsg->miniprogram_url)['media_id'],
							'appid' => $welcomemsg->miniprogram_appid,
							'page' => $welcomemsg->miniprogram_page,
						 ];
					 }
					 $etApp->external_contact_message->sendWelcome($welcomeCode, $msg);
				}
		  }
	  }
	  
	  public function add_et_by_code($arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		  
		  $etContactWay = (new Model('qy_et_contact_way'))->find(['state'=>$arr['State']]);
		  $qyCustomer = $this->import_et_data($etContactWay->auto_label,$etContactWay->select_label,$arr);
		  //渠道数据统计
		  if($etContactWay->id){
			  $today = strtotime(date("Y-m-d"),time());
			  $statistics = (new Model('qy_et_contact_way_statistics'))->find(['wid'=>$qyConfig->wid,'state'=>$etContactWay->state,'ctime'=>$today]);
			  $statistics->wid = $qyConfig->wid;
			  $statistics->state = $etContactWay->state;
			  $statistics->ctime = $today;
			  $statistics->add_num = $statistics->add_num + 1;
			  $statistics->save();
		  }
		  //发送欢迎语
		  if($arr['WelcomeCode']){
			  if($etContactWay->auto_welcome_msg == 1){
					$welcomeCode = $arr['WelcomeCode'];
					$msg = [
					   'text' => [
						  'content' => $etContactWay->text_content,
					   ]
				    ];
					if($etContactWay->other_type == 2){//图片
						$msg['image'] = [
							'media_id' => $etContactWay->image_media_id,
						 ];
					}elseif($etContactWay->other_type == 3){//图文
						 $msg['link'] = [
							'title' => $etContactWay->link_title,
							'picurl' => $etContactWay->link_picurl,
							'desc' => $etContactWay->link_desc,
							'url' => $etContactWay->link_url,
						 ];
					}elseif($etContactWay->other_type == 4){//小程序
						$msg['miniprogram'] = [
							'title' => $etContactWay->miniprogram_title,
							'pic_media_id' => $etContactWay->miniprogram_pic_media_id,
							'appid' => $etContactWay->miniprogram_appid,
							'page' => $etContactWay->miniprogram_page,
						];
					}
					$etApp->external_contact_message->sendWelcome($welcomeCode, $msg);
			   }
		  }
	  }
	  
	  public function add_et_by_autopullgroupcode($arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		  
		  $etContactWay = (new Model('qy_et_contact_way'))->find(['state'=>$arr['State']]);
		  $qyCustomer = $this->import_et_data($etContactWay->auto_label,$etContactWay->select_label,$arr); 
		  //发送欢迎语
		  if($arr['WelcomeCode']){
			  $welcomeCode = $arr['WelcomeCode'];
			  $msg = [
			     'text' => [
				   'content' => $etContactWay->text_content,
			     ]
			  ];
			  $group_chat_list = json_decode($etContactWay->group_chat_list,1);
			  $group_chat_now = [];
			  foreach($group_chat_list as $group_chat){
			     $etGroupchat = (new Model('qy_et_groupchat'))->find(['wid'=>$qyConfig->wid,'chat_id'=>$group_chat['chatid']]);
				 $customNum = count(json_decode($etGroupchat->member_list,1));
				 if($customNum < $group_chat['people']){
				    $group_chat_now = $group_chat;
					 break;
			     }
			  }
			  $msg['image'] = [
		           'media_id' => $etApp->media->uploadImage($group_chat_now['img'])['media_id'],
			  ];
		      $etApp->external_contact_message->sendWelcome($welcomeCode, $msg);
		  }
	  }
	  
	  public function add_et_by_fissioncode($arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		  
		  $qyUser = (new Model('qy_user_list'))->find(['userid'=>$arr['UserID']]);
		  $checkEt = (new Model('qy_externalcontact_list'))->find(['wid'=>$qyConfig->wid,'user_id'=>$qyUser->id,'external_userid'=>$arr['ExternalUserID']]);
		  $qyFission = (new Model('qy_fission'))->find(['state'=>$arr['State']]);
		  if(time() > $qyFission->end_time){
			  $this->del_expire_fission($qyFission);
		  }
		  $qyCustomer = $this->import_et_data($qyFission->auto_label,$qyFission->select_label,$arr);
		  //绑定用户
		 /**$bindUser = (new Model('qy_fission_bind_user'))->find(['wid'=>$qyCustomer->wid,'external_userid'=>$qyCustomer->external_userid,'userid'=>$arr['UserID']]);
		  $bindUser->wid = $qyCustomer->wid;
		  $bindUser->external_userid = $qyCustomer->external_userid;
		  $bindUser->userid = $arr['UserID'];
		  $bindUser->name = $qyCustomer->name;
		  $bindUser->avatar = $qyCustomer->avatar;
		  $bindUser->type = $qyCustomer->type;
		  $bindUser->gender = $qyCustomer->gender;
		  $bindUser->status = 1;
		  $bindUser->ctime = $arr['CreateTime'];
		  $bindUser->save();*/
		  //添加参加裂变活动用户
		  $fuser = (new Model('qy_fission_user'))->find(['wid'=>$qyCustomer->wid,'bind_uid'=>$qyCustomer->id,'fid'=>$qyFission->id]);
		  $fuser->wid = $qyCustomer->wid;
		  $fuser->bind_uid = $qyCustomer->id;
		  $fuser->fid = $qyFission->id;
		  $fuser->is_new_friend = $checkEt->id?0:1;
		  $fuser->ctime = $qyCustomer->createtime;
		  $fuser->save();
		  //发送欢迎语
		  if($arr['WelcomeCode']){
			  $welcomeCode = $arr['WelcomeCode'];
			  $msg = [
				  'text' => [
					  'content' => $qyFission->hy_text_content,
				  ]
			  ];
			  $msg['link'] = [
				  'title' => $qyFission->hy_link_title,
				  'picurl' => $qyFission->hy_link_picurl,
				  'desc' => $qyFission->hy_link_desc,
				  'url' => Helper::getInstance()->get_http_server_name().'/Addons/Fission/H5/Fission/activity_fission.html?fid='.$qyFission->id
			  ];
			  $etApp->external_contact_message->sendWelcome($welcomeCode, $msg);
		  }
	  }
	  
	  public function add_et_by_fusercode($arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		  
		  $qyUser = (new Model('qy_user_list'))->find(['userid'=>$arr['UserID']]);
		  $checkEt = (new Model('qy_externalcontact_list'))->find(['wid'=>$qyConfig->wid,'user_id'=>$qyUser->id,'external_userid'=>$arr['ExternalUserID']]);
		  $fuser = (new Model('qy_fission_user'))->find(['state'=>$arr['State']]);
		  $qyFission = (new Model('qy_fission'))->find($fuser->fid);
		  if(time() > $qyFission->end_time){
			  $this->del_expire_fission($qyFission);
		  }
		  $qyCustomer = $this->import_et_data($qyFission->auto_label,$qyFission->select_label,$arr);
		  //绑定用户
		  //$unionid = $work->external_contact->get($arr['ExternalUserID'])['external_contact']['unionid'];
		  // $bindUser = (new Model('qy_fission_bind_user'))->find(['wid'=>$qyCustomer->wid,'external_userid'=>$qyCustomer->external_userid,'userid'=>$arr['UserID']]);
		  // $bindUser->wid = $qyCustomer->wid;
		  // $bindUser->external_userid = $qyCustomer->external_userid;
		  // $bindUser->userid = $arr['UserID'];
		  // //$bindUser->unionid = $unionid;
		  // $bindUser->name = $qyCustomer->name;
		  // $bindUser->avatar = $qyCustomer->avatar;
		  // $bindUser->type = $qyCustomer->type;
		  // $bindUser->gender = $qyCustomer->gender;
		  // $bindUser->status = 1;
		  // $bindUser->ctime = $arr['CreateTime'];
		  // $bindUser->save();
		  //添加参加裂变活动用户
		  $fnewuser = (new Model('qy_fission_user'))->find(['wid'=>$qyCustomer->wid,'bind_uid'=>$qyCustomer->id,'fid'=>$qyFission->id]);
		  $fnewuser->wid = $qyCustomer->wid;
		  $fnewuser->bind_uid = $qyCustomer->id;
		  $fnewuser->fid = $qyFission->id;
		  $fnewuser->is_new_friend = $checkEt->id?0:1;
		  $fnewuser->ctime = $qyCustomer->createtime;
		  $fnewuser->save();
		  //绑定上下级
		  $helpUser = (new Model('qy_fission_help_user'))->find(['wid'=>$qyCustomer->wid,'pid'=>$fuser->id,'fid'=>$qyFission->id,'help_id'=>$fnewuser->id]);
		  $helpUser->wid = $qyCustomer->wid;
		  $helpUser->pid = $fuser->id;
		  $helpUser->fid = $qyFission->id;
		  $helpUser->help_id = $fnewuser->id;
		  $helpUser->help_bind_uid = $fnewuser->bind_uid;
		  if($qyFission->new_friends){//开启新好友才能助力
			  if($checkEt->id){
				  $helpUser->help_status = 0;
				  $helpUser->fail_status = 1;
			  }else{
				   $helpUser->help_status = 1;
			  }
		  }else{
			  $helpUser->help_status = 1;
		  }
		  //性别判断
		  if($qyFission->sex=1){  //男
			if($checkEt->igender=1){
				$helpUser->help_status = 1; //性别限制
			}else{
				$helpUser->help_status = 0;
				$helpUser->fail_status = 3;
			}
		}elseif($qyFission->sex=2){ //女
			if($checkEt->igender=2){
				$helpUser->help_status = 1;  //性别限制
			}else{
				$helpUser->help_status = 0;
				$helpUser->fail_status = 3;
			}
		}
		  
		  $helpUser->is_new_friend = $checkEt->id?0:1;
		  $helpUser->ctime = $fnewuser->ctime;
		  $helpUser->save();
		  $successCount = (new Model('qy_fission_help_user'))->where(['wid'=>$qyCustomer->wid,'pid'=>$fuser->id,'fid'=>$qyFission->id,'help_status'=>1])->count();
		  //增加兑换吗开关
		  if($qyFission->is_openhx){
		  if($successCount >= $qyFission->target_number){
			  if($qyFission->push_customer){
				  // $finishUser= (new Model('qy_fission_bind_user'))->find(['wid'=>$fuser->wid,'id'=>$fuser->bind_uid]);
			  	  $finishUser= (new Model('qy_externalcontact_list'))->find(['id'=>$fuser->bind_uid]);
				  $qfmsg['external_userid'] = [$finishUser->external_userid];
				  $qfmsg['text'] = ['content'=>$qyFission->push_text_content?$qyFission->push_text_content:'任务完成'];
				  $etApp->external_contact_message->submit($qfmsg);
				  //生成核销码 
				  $hxcode=new Model('qy_hxcode');
				  $randStr = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
					$rand = substr($randStr,0,8).$fuser->bind_uid;
				  $hxcode->hxcode=$rand;
				  $hxcode->finishuserid=$fuser->bind_uid;//客户id
				  $hxcode->status=0;
				  $hxcode->fid=$qyFission->id;
				  $hxcode->wid=$qyFission->wid;
				  $hxcode->ctime=time();
				  $hxcode->save();

			  }
		  }
		}
		  //发送欢迎语
		  if($arr['WelcomeCode']){
			  $welcomeCode = $arr['WelcomeCode'];
			  $msg = [
				  'text' => [
					  'content' => $qyFission->hy_text_content,
				  ]
			  ];
			  $msg['link'] = [
				  'title' => $qyFission->hy_link_title,
				  'picurl' => $qyFission->hy_link_picurl,
				  'desc' => $qyFission->hy_link_desc,
				  'url' => Helper::getInstance()->get_http_server_name().'/Addons/Fission/H5/Fission/activity_fission.html?fid='.$qyFission->id
			  ];
			  $etApp->external_contact_message->sendWelcome($welcomeCode, $msg);
		  }
	  }
	  function GetRandStr($length){
		$str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$len=strlen($str)-1;
		$randstr='';
		for($i=0;$i<$length;$i++){
		$num=mt_rand(0,$len);
		$randstr .= $str[$num];
		}
		return $randstr;
		}
	  
	  public function add_et_by_etqrcode($arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		  
		  $qyEtQrcode = (new Model('qy_et_qrcode'))->find(['state'=>$arr['State']]);
		  $qyCustomer = $this->import_et_data('','',$arr);
		  $qyEtQrcodeInvite = (new Model('qy_et_qrcode_invite'))->find(['wid'=>$qyConfig->wid,'qrcode_id'=>$qyEtQrcode->id,'et_userid'=>$qyCustomer->external_userid]);
		  $qyEtQrcodeInvite->wid = $qyConfig->wid;
		  $qyEtQrcodeInvite->qrcode_id = $qyEtQrcode->id;
		  $qyEtQrcodeInvite->et_userid = $qyCustomer->external_userid;
		  $qyEtQrcodeInvite->ctime = time();
		  $qyEtQrcodeInvite->save();
		  
		  //发送欢迎语
		  if($arr['WelcomeCode']){
				$welcomeMsgList = (new Model('qy_welcome_msg_list'))->where(['wid'=>$qyConfig->wid,'type'=>2])->list_all();
				foreach($welcomeMsgList as $welcomeMsg){
					$qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
				   if(in_array($qyUser->id,json_decode($welcomeMsg->users,1))){
					  $welcomemsg = $welcomeMsg;
					  break;
				   }
				}
				if(!$welcomemsg->id){
					$welcomemsg = (new Model('qy_welcome_msg_list'))->find(['wid'=>$qyConfig->wid,'type'=>1]);
				}
				  
				if($welcomemsg->id){
					$welcomeCode = $arr['WelcomeCode'];
					$msg = [
						'text' => [
							'content' => $welcomemsg->text_content,
						]
					];
					if($welcomemsg->other_type == 2){//图片
						 $msg['image'] = [
							'media_id' => $etApp->media->uploadImage($welcomemsg->image_url)['media_id'],
						];
					}elseif($welcomemsg->other_type == 3){//图文
						 $msg['link'] = [
							'title' => $welcomemsg->link_title,
							'picurl' => $welcomemsg->link_picurl,
							'desc' => $welcomemsg->link_desc,
							'url' => $welcomemsg->link_url,
						 ];
					 }elseif($welcomemsg->other_type == 4){//小程序
						$msg['miniprogram'] = [
							'title' => $welcomemsg->miniprogram_title,
							'pic_media_id' => $etApp->media->uploadImage($welcomemsg->miniprogram_url)['media_id'],
							'appid' => $welcomemsg->miniprogram_appid,
							'page' => $welcomemsg->miniprogram_page,
						 ];
					 }
					 $etApp->external_contact_message->sendWelcome($welcomeCode, $msg);
				}
		  }
	  }
	  
	  /**public function import_et_data($auto_label,$select_label,$arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		  //自动打标签
		  if($auto_label == 1){
			  $add_tag = json_decode($select_label,1);
			  $param = [
				  'userid' => $arr['UserID'],
				  'external_userid' => $arr['ExternalUserID'],
				  'add_tag' => $add_tag,
			  ];
			  if($add_tag){
				  $editEtTagRes = $QyWechatApi->edit_et_tag($param,$qyConfig->wid);
			  }
		  }
		  //获取企业标签库
		  $tagRes = $QyWechatApi->get_corp_tag_list([],$qyConfig->wid)['tag_group'];
		  //获取客户详情 导入数据
		  $customer_info_res = $etApp->external_contact->get($arr['ExternalUserID']);
		  if($customer_info_res['errcode'] == 0){
				$customer_info = $customer_info_res;
				$qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$qyConfig->wid,'external_userid'=>$customer_info['external_contact']['external_userid']]);
				$tags = [];
				foreach($customer_info['follow_user'] as $user){
					foreach($user['tags'] as $tag){
						if($tag['type'] == 1){
							//$tags[] = $tag['group_name'].'_'.$tag['tag_name'];
							foreach($tagRes as $tagres){
								if($tag['group_name'] == $tagres['group_name']){
									foreach($tagres['tag'] as $tagrestag){
										if($tagrestag['name'] == $tag['tag_name']){
											$tags[] = $tagrestag['id'];
										}
									}
								}
							}
						}
					}	
				}
				$qyCustomer->wid = $qyConfig->wid;
				$qyCustomer->external_userid = $customer_info['external_contact']['external_userid'];
				$qyCustomer->name = $customer_info['external_contact']['name'];
				$qyCustomer->avatar = $customer_info['external_contact']['avatar'];
				$qyCustomer->type = $customer_info['external_contact']['type'];
				$qyCustomer->gender = $customer_info['external_contact']['gender'];
				$qyCustomer->unionid = $customer_info['external_contact']['unionid'];
				$qyCustomer->follow_user = json_encode($customer_info['follow_user'],320);
				$qyCustomer->tags = json_encode(array_unique($tags),320);
				$qyCustomer->save();				
		  }
		  //增加企业员工客户数量
		  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
		  if($qyUser->id){
			  $qyUser->customer_count = $qyUser->customer_count+1;
			  $qyUser->save();
		  }
		  return $qyCustomer;
	  }*/

	  public function import_et_data($auto_label,$select_label,$arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		  //自动打标签
		  if($auto_label == 1){
			  $add_tag = json_decode($select_label,1);
			  $param = [
				  'userid' => $arr['UserID'],
				  'external_userid' => $arr['ExternalUserID'],
				  'add_tag' => $add_tag,
			  ];
			  if($add_tag){
				  $editEtTagRes = $QyWechatApi->edit_et_tag($param,$qyConfig->wid);
			  }
		  }
		  //获取客户详情 导入数据
		  $customer_info_res = $etApp->external_contact->get($arr['ExternalUserID']);
		  if($customer_info_res['errcode'] == 0){
		  		$qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
				$customer_info = $customer_info_res;
				$qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$qyConfig->wid,'user_id'=>$qyUser->id,'external_userid'=>$customer_info['external_contact']['external_userid']]);
				$user = '';
				$tags = [];
				foreach($customer_info['follow_user'] as $followuser){
					if($qyUser->userid == $followuser['userid']){
						$user = $followuser;
						foreach($followuser['tags'] as $ftag){
							$tags[] = $ftag['tag_id'];
						}
					}
				}	

				$qyCustomer->wid = $qyConfig->wid;
				$qyCustomer->external_userid = $customer_info['external_contact']['external_userid'];
				$qyCustomer->name = Helper::getInstance()->filterEmoji($customer_info['external_contact']['name']);
				$qyCustomer->avatar = $customer_info['external_contact']['avatar'];
				$qyCustomer->type = $customer_info['external_contact']['type'];
				$qyCustomer->gender = $customer_info['external_contact']['gender'];
				$qyCustomer->unionid = $customer_info['external_contact']['unionid'];
				$qyCustomer->position = $customer_info['external_contact']['position'];
				$qyCustomer->corp_name = $customer_info['external_contact']['corp_name'];
				$qyCustomer->corp_full_name = $customer_info['external_contact']['corp_full_name'];
				$qyCustomer->external_profile = json_encode($customer_info['external_contact']['external_profile']);
				$qyCustomer->user_id = $qyUser->id;
				$qyCustomer->remark = $user['remark'];
				$qyCustomer->description = $user['description'];
				$qyCustomer->createtime = $user['createtime'];
				$qyCustomer->tags_info = json_encode($user['tags']);
				$qyCustomer->tags = json_encode($tags);
				$qyCustomer->remark_corp_name = $user['remark_corp_name'];
				$qyCustomer->remark_mobiles = $user['remark_mobiles'];
				$qyCustomer->add_way = $user['add_way'];
				$qyCustomer->oper_userid = $user['oper_userid'];
				$qyCustomer->state = $user['state'];
				$qyCustomer->status = 0;
				$qyCustomer->save();	
		  }
		  return $qyCustomer;
	  }
	  
	  //编辑企业客户事件
	  /**public function edit_external_contact($arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		  
		  //获取企业标签库
		  $tagRes = $QyWechatApi->get_corp_tag_list([],$qyConfig->wid)['tag_group'];
		  //获取客户详情 导入数据
		  $customer_info_res = $etApp->external_contact->get($arr['ExternalUserID']);
		  if($customer_info_res['errcode'] == 0){
				$customer_info = $customer_info_res;
				$qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$qyConfig->wid,'external_userid'=>$customer_info['external_contact']['external_userid']]);
				$tags = [];
				foreach($customer_info['follow_user'] as $user){
					foreach($user['tags'] as $tag){
						if($tag['type'] == 1){
							//$tags[] = $tag['group_name'].'_'.$tag['tag_name'];
							foreach($tagRes as $tagres){
								if($tag['group_name'] == $tagres['group_name']){
									foreach($tagres['tag'] as $tagrestag){
										if($tagrestag['name'] == $tag['tag_name']){
											$tags[] = $tagrestag['id'];
										}
									}
								}
							}
						}
					}	
				}
				$qyCustomer->wid = $qyConfig->wid;
				$qyCustomer->external_userid = $customer_info['external_contact']['external_userid'];
				$qyCustomer->name = $customer_info['external_contact']['name'];
				$qyCustomer->avatar = $customer_info['external_contact']['avatar'];
				$qyCustomer->type = $customer_info['external_contact']['type'];
				$qyCustomer->gender = $customer_info['external_contact']['gender'];
				$qyCustomer->unionid = $customer_info['external_contact']['unionid'];
				$qyCustomer->follow_user = json_encode($customer_info['follow_user'],320);
				$qyCustomer->tags = json_encode(array_unique($tags),320);
				$qyCustomer->save();				
		  }
	  }*/
	  public function edit_external_contact($arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		  
		  //获取客户详情 导入数据
		  $customer_info_res = $etApp->external_contact->get($arr['ExternalUserID']);
		  if($customer_info_res['errcode'] == 0){
		  		$qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
				$customer_info = $customer_info_res;
				$qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$qyConfig->wid,'user_id'=>$qyUser->id,'external_userid'=>$customer_info['external_contact']['external_userid']]);
				$user = '';
				$tags = [];
				foreach($customer_info['follow_user'] as $followuser){
					if($qyUser->userid == $followuser['userid']){
						$user = $followuser;
						foreach($followuser['tags'] as $ftag){
							$tags[] = $ftag['tag_id'];
						}
					}
				}	

				$qyCustomer->wid = $qyConfig->wid;
				$qyCustomer->external_userid = $customer_info['external_contact']['external_userid'];
				$qyCustomer->name = Helper::getInstance()->filterEmoji($customer_info['external_contact']['name']);
				$qyCustomer->avatar = $customer_info['external_contact']['avatar'];
				$qyCustomer->type = $customer_info['external_contact']['type'];
				$qyCustomer->gender = $customer_info['external_contact']['gender'];
				$qyCustomer->unionid = $customer_info['external_contact']['unionid'];
				$qyCustomer->position = $customer_info['external_contact']['position'];
				$qyCustomer->corp_name = $customer_info['external_contact']['corp_name'];
				$qyCustomer->corp_full_name = $customer_info['external_contact']['corp_full_name'];
				$qyCustomer->external_profile = json_encode($customer_info['external_contact']['external_profile']);
				$qyCustomer->user_id = $qyUser->id;
				$qyCustomer->remark = $user['remark'];
				$qyCustomer->description = $user['description'];
				$qyCustomer->createtime = $user['createtime'];
				$qyCustomer->tags_info = json_encode($user['tags']);
				$qyCustomer->tags = json_encode($tags);
				$qyCustomer->remark_corp_name = $user['remark_corp_name'];
				$qyCustomer->remark_mobiles = $user['remark_mobiles'];
				$qyCustomer->add_way = $user['add_way'];
				$qyCustomer->oper_userid = $user['oper_userid'];
				$qyCustomer->state = $user['state'];
				$qyCustomer->status = 0;
				$qyCustomer->save();			
		  }
	  }
	  //删除企业客户
	  /**public function del_external_contact($arr){
		  $this->import_et_dynamic(2,$arr);
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$qyConfig->wid,'external_userid'=>$arr['ExternalUserID']]);
		  if(!$qyCustomer->id){
			  return;
		  }
		  $follow_user = json_decode($qyCustomer->follow_user,1);
		  foreach($follow_user as $k=>$v){
			  if($v['userid'] == $arr['UserID']){
				  unset($follow_user[$k]);
			  }
		  }
		  $qyCustomer->follow_user = json_encode($follow_user,320);
		  $qyCustomer->save();
		  //20201102 strat
		  $del_udexternal = (new Model('qy_del_udexternal_record'));
		  $del_udexternal->wid = $qyConfig->wid;
		  $del_udexternal->external_userid = $qyCustomer->external_userid;
		  $del_udexternal->name = $qyCustomer->name;
		  $del_udexternal->avatar = $qyCustomer->avatar;
		  $del_udexternal->gender = $qyCustomer->gender;
		  $del_udexternal->userid = $arr['UserID'];
		  $del_udexternal->follow_user = json_encode($del_follow_user,320);
		  $del_udexternal->ctime = date('Y-m-d H:i:s');
		  if($del_udexternal->save()){
		  	  //删除提醒
			  $QyWechatApi = QyWechatApi::getInstance();
			  $sendConfig = (new Model('qy_message_send_config'))->find(['wid'=>$qyConfig->wid]);
			  if($sendConfig->agent_id && $sendConfig->secret){
				  $app = $QyWechatApi->get_qy_agent_app($qyConfig->corp_id,$sendConfig->agent_id,$sendConfig->secret);
				  $messenger = $app->messenger->ofAgent($sendConfig->agent_id);
				  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$del_udexternal->userid]);
				  // $sendContent = "员工'{$qyUser->name}'把客户 '{$del_udexternal->name}'从好友列表中删除了.<a href='{$_SERVER['HTTP_HOST']}/Addons/QyWechat/H5/Portrait/customer_info.html?wid={$del_udexternal->wid}&etUserId={$del_udexternal->external_userid}&userId={$del_udexternal->userid}'>查看客戶详情</a>";
				  $sendContent = "员工'{$qyUser->name}'把客户 '{$del_udexternal->name}'从好友列表中删除了.";
				  $messenger->toUser('@all')->send($sendContent);
			  }
		  }
		  //20201102 end
		  if(!count(json_decode($qyCustomer->follow_user,1))){
			  $qyCustomer->delete();
		  }
		  //减少企业员工客户数量
		  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
		  if($qyUser->id){
			  $qyUser->customer_count = $qyUser->customer_count - 1;
			  $qyUser->save();
		  }
		  //是否是裂变用户
		  $f_bind_user = (new Model('qy_fission_bind_user'))->find(['wid'=>$qyConfig->wid,'external_userid'=>$arr['ExternalUserID'],'userid'=>$arr['UserID']]);
		  if($f_bind_user->id){
			  $f_bind_user->status = 0;
			  $f_bind_user->save();
			  $f_help_user = (new Model('qy_fission_help_user'))->where(['wid'=>$qyConfig->wid,'help_bind_uid'=>$f_bind_user->id])->list_all();
			  foreach($f_help_user as $helpuser){
				  $qyFission = (new Model('qy_fission'))->find($helpuser->fid);
				  if($qyFission->del_friends){
					  $helpuser->help_status = 0;
					  $helpuser->fail_status = 2;
					  $helpuser->save();
				  }
			  }
		  }
	  }*/
	  public function del_external_contact($arr){
		  $this->import_et_dynamic(2,$arr);
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
		  $qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$qyConfig->wid,'user_id'=>$qyUser->id,'external_userid'=>$arr['ExternalUserID']]);
		  if(!$qyCustomer->id){
			  return;
		  }
		  $qyCustomer->status = 1;
		  $qyCustomer->save();
		  /*20201102 strat*/
		  $del_udexternal = (new Model('qy_del_udexternal_record'));
		  $del_udexternal->wid = $qyConfig->wid;
		  $del_udexternal->external_userid = $qyCustomer->external_userid;
		  $del_udexternal->name = $qyCustomer->name;
		  $del_udexternal->avatar = $qyCustomer->avatar;
		  $del_udexternal->gender = $qyCustomer->gender;
		  $del_udexternal->user_id = Helper::getInstance()->get_user_by_userid($qyConfig->wid,$arr['UserID'])['id'];
		  $del_udexternal->follow_user = json_encode($del_follow_user,320);
		  $del_udexternal->ctime = date('Y-m-d H:i:s');
		  if($del_udexternal->save()){
		  	  //删除提醒
			  $QyWechatApi = QyWechatApi::getInstance();
			  $sendConfig = (new Model('qy_message_send_config'))->find(['wid'=>$qyConfig->wid]);
			  if($sendConfig->agent_id && $sendConfig->secret){
				  $app = $QyWechatApi->get_qy_agent_app($qyConfig->corp_id,$sendConfig->agent_id,$sendConfig->secret);
				  $messenger = $app->messenger->ofAgent($sendConfig->agent_id);
				  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'id'=>$del_udexternal->user_id]);
				  // $sendContent = "员工'{$qyUser->name}'把客户 '{$del_udexternal->name}'从好友列表中删除了.<a href='{$_SERVER['HTTP_HOST']}/Addons/QyWechat/H5/Portrait/customer_info.html?wid={$del_udexternal->wid}&etUserId={$del_udexternal->external_userid}&userId={$del_udexternal->userid}'>查看客戶详情</a>";
				  $sendContent = "员工'{$qyUser->name}'把客户 '{$del_udexternal->name}'从好友列表中删除了.";
				  $messenger->toUser('@all')->send($sendContent);
			  }
		  }
		  /*20201102 end*/
		  //是否是裂变用户
		  // $f_bind_user = (new Model('qy_fission_bind_user'))->find(['wid'=>$qyConfig->wid,'external_userid'=>$arr['ExternalUserID'],'userid'=>$arr['UserID']]);
		  // if($f_bind_user->id){
			 //  $f_bind_user->status = 0;
			 //  $f_bind_user->save();
			 //  $f_help_user = (new Model('qy_fission_help_user'))->where(['wid'=>$qyConfig->wid,'help_bind_uid'=>$f_bind_user->id])->list_all();
			 //  foreach($f_help_user as $helpuser){
				//   $qyFission = (new Model('qy_fission'))->find($helpuser->fid);
				//   if($qyFission->del_friends){
				// 	  $helpuser->help_status = 0;
				// 	  $helpuser->fail_status = 2;
				// 	  $helpuser->save();
				//   }
			 //  }
		  // }
		   $f_help_user = (new Model('qy_fission_help_user'))->where(['wid'=>$qyConfig->wid,'help_bind_uid'=>$qyCustomer->id])->list_all();
			  foreach($f_help_user as $helpuser){
				  $qyFission = (new Model('qy_fission'))->find($helpuser->fid);
				  if($qyFission->del_friends){
					  $helpuser->help_status = 0;
					  $helpuser->fail_status = 2;
					  $helpuser->save();
				  }
			  }
	  }
	  //成员被外部联系人删除时
	  /**public function del_follow_user($arr){
		  $this->import_et_dynamic(3,$arr);
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$qyConfig->wid,'external_userid'=>$arr['ExternalUserID']]);
		  if(!$qyCustomer->id){
			  return;
		  }
		  $follow_user = json_decode($qyCustomer->follow_user,1);
		  foreach($follow_user as $k=>$v){
			  if($v['userid'] == $arr['UserID']){
				  $del_follow_user = $follow_user[$k];
				  unset($follow_user[$k]);
			  }
		  }
		  $qyCustomer->follow_user = json_encode($follow_user,320);
		  $qyCustomer->save();
		  //导入删除记录
		  $record = new Model('qy_del_follow_user_record');
		  $record->wid = $qyConfig->wid;
		  $record->external_userid = $qyCustomer->external_userid;
		  $record->name = $qyCustomer->name;
		  $record->avatar = $qyCustomer->avatar;
		  $record->gender = $qyCustomer->gender;
		  $record->userid = $arr['UserID'];
		  $record->follow_user = json_encode($del_follow_user,320);
		  $record->ctime = date('Y-m-d H:i:s');
		  $record->save();
		  if(!count(json_decode($qyCustomer->follow_user,1))){
			//  $qyCustomer->delete();
		  }
		  //减少企业员工客户数量
		  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
		  if($qyUser->id){
			  $qyUser->customer_count = $qyUser->customer_count - 1;
			  $qyUser->save();
		  }
		  //被删除提醒
		  $QyWechatApi = QyWechatApi::getInstance();
		  $sendConfig = (new Model('qy_message_send_config'))->find(['wid'=>$qyConfig->wid]);
		  if($sendConfig->agent_id && $sendConfig->secret){
			  $app = $QyWechatApi->get_qy_agent_app($qyConfig->corp_id,$sendConfig->agent_id,$sendConfig->secret);
			  $messenger = $app->messenger->ofAgent($sendConfig->agent_id);
			  //$sendContent = "客户 '{$record->name}' 把你从好友列表中删除了";			  
			  $sendContent = "客户 '{$record->name}' 把你从好友列表中删除了.<a href='{$_SERVER['HTTP_HOST']}/Addons/QyWechat/H5/Portrait/customer_info.html?wid={$record->wid}&etUserId={$record->external_userid}&userId={$record->userid}'>查看客戶详情</a>";

			  $messenger->toUser($arr['UserID'])->send($sendContent);
		  }
		  //是否是裂变用户
		  $f_bind_user = (new Model('qy_fission_bind_user'))->find(['wid'=>$qyConfig->wid,'external_userid'=>$arr['ExternalUserID'],'userid'=>$arr['UserID']]);
		  if($f_bind_user->id){
			  $f_bind_user->status = 0;
			  $f_bind_user->save();
			  $f_help_user = (new Model('qy_fission_help_user'))->where(['wid'=>$qyConfig->wid,'help_bind_uid'=>$f_bind_user->id])->list_all();
			  foreach($f_help_user as $helpuser){
				  $qyFission = (new Model('qy_fission'))->find($helpuser->fid);
				  if($qyFission->del_friends){
					  $helpuser->help_status = 0;
					  $helpuser->fail_status = 2;
					  $helpuser->save();
				  }
			  }
		  }
	  }*/
	  public function del_follow_user($arr){
		  $this->import_et_dynamic(3,$arr);
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
		  $qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$qyConfig->wid,'user_id'=>$qyUser->id,'external_userid'=>$arr['ExternalUserID']]);
		  if(!$qyCustomer->id){
			  return;
		  }
		  $qyCustomer->status = 2;
		  $qyCustomer->save();
		  //导入删除记录
		  $record = new Model('qy_del_follow_user_record');
		  $record->wid = $qyConfig->wid;
		  $record->external_userid = $qyCustomer->external_userid;
		  $record->name = $qyCustomer->name;
		  $record->avatar = $qyCustomer->avatar;
		  $record->gender = $qyCustomer->gender;
		  $record->user_id = Helper::getInstance()->get_user_by_userid($qyConfig->wid,$arr['UserID'])['id'];
		  $record->follow_user = json_encode($del_follow_user,320);
		  $record->ctime = date('Y-m-d H:i:s');
		  $record->save();
		  //被删除提醒
		  $QyWechatApi = QyWechatApi::getInstance();
		  $sendConfig = (new Model('qy_message_send_config'))->find(['wid'=>$qyConfig->wid]);
		  if($sendConfig->agent_id && $sendConfig->secret){
			  $app = $QyWechatApi->get_qy_agent_app($qyConfig->corp_id,$sendConfig->agent_id,$sendConfig->secret);
			  $messenger = $app->messenger->ofAgent($sendConfig->agent_id);
			  //$sendContent = "客户 '{$record->name}' 把你从好友列表中删除了";			  
			  $sendContent = "客户 '{$record->name}' 把你从好友列表中删除了.<a href='{$_SERVER['HTTP_HOST']}/Addons/QyWechat/H5/Portrait/customer_info.html?wid={$record->wid}&etUserId={$record->external_userid}&userId={$record->user_id}'>查看客戶详情</a>";

			  $messenger->toUser($arr['UserID'])->send($sendContent);
		  }
		  //是否是裂变用户
		  // $f_bind_user = (new Model('qy_fission_bind_user'))->find(['wid'=>$qyConfig->wid,'external_userid'=>$arr['ExternalUserID'],'userid'=>$arr['UserID']]);
		  // if($f_bind_user->id){
			 //  $f_bind_user->status = 0;
			 //  $f_bind_user->save();
			 //  $f_help_user = (new Model('qy_fission_help_user'))->where(['wid'=>$qyConfig->wid,'help_bind_uid'=>$f_bind_user->id])->list_all();
			 //  foreach($f_help_user as $helpuser){
				//   $qyFission = (new Model('qy_fission'))->find($helpuser->fid);
				//   if($qyFission->del_friends){
				// 	  $helpuser->help_status = 0;
				// 	  $helpuser->fail_status = 2;
				// 	  $helpuser->save();
				//   }
			 //  }
		  // }
		  $f_help_user = (new Model('qy_fission_help_user'))->where(['wid'=>$qyConfig->wid,'help_bind_uid'=>$qyCustomer->id])->list_all();
			  foreach($f_help_user as $helpuser){
				  $qyFission = (new Model('qy_fission'))->find($helpuser->fid);
				  if($qyFission->del_friends){
					  $helpuser->help_status = 0;
					  $helpuser->fail_status = 2;
					  $helpuser->save();
				  }
			  }
	  }
	  //客户群变更事件
	  public function change_external_chat($arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  //获取群详情
		  $groupChatInfoRes = $QyWechatApi->get_et_groupchat_info($arr['ChatId'],$qyConfig->wid);
		  if($groupChatInfoRes['errcode'] == 0){
			  $groupChatInfo = $groupChatInfoRes['group_chat'];
			  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$groupChatInfo['owner']]);
			  $etGroupchat = (new Model('qy_et_groupchat'))->find(['wid'=>$qyConfig->wid,'chat_id'=>$arr['ChatId']]);
			  $memberList = json_decode($etGroupchat->member_list,1);
			  $etGroupchat->wid = $qyConfig->wid;
			  $etGroupchat->chat_id = $groupChatInfo['chat_id'];
			  $etGroupchat->name = $groupChatInfo['name'];
			  $etGroupchat->user_id = $qyUser->id;
			  $etGroupchat->create_time = $groupChatInfo['create_time'];
			  $etGroupchat->notice = $groupChatInfo['notice'];
			  $etGroupchat->member_list = json_encode($groupChatInfo['member_list'],320);
			  $etGroupchat->save();
			  $useridList = [];
			  foreach($memberList as $v){
				  $useridList[] = $v['userid'];
			  }
			  foreach($groupChatInfo['member_list'] as $member){
				  if($member['type'] == 2 && !in_array($member['userid'],$useridList)){
					  $arr['ExternalUserID'] = $member['userid'];
					  $this->import_et_dynamic(4,$arr);
				  }
			  }
		  }
	  }
	  
	  public function del_expire_fission($fission){
		 $wid = $fission->wid;
		 $QyWechatApi = QyWechatApi::getInstance();
		 $qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		 $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		 
		 if($fission->id && time() > $fission->end_time){
			 $deleteRes = $etApp->contact_way->delete($fission->config_id?$fission->config_id:'');
			 $fusers = (new Model('qy_fission_user'))->where(['wid'=>$wid,'fid'=>$fission->id])->list_all();
			 foreach($fusers as $fuser){
				 if($fuser->config_id){
					 $etApp->contact_way->delete($fuser->config_id);
				 }
			}
		 }
	  }
	  
	  public function import_et_dynamic($type,$data){
		  $CorpID = $data['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $etDynamic = new Model('qy_et_dynamic');
		  $etDynamic->wid = $qyConfig->wid;
		  $etDynamic->ctime = time();
		  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$data['UserID']]);
		  if($type == 1 || $type == 2 || $type == 3){
			  $etDynamic->external_userid = $data['ExternalUserID'];
			  $etDynamic->type = $type;
			  $etDynamic->user_id = $qyUser->id;
		  }elseif($type == 4){
			  $etDynamic->external_userid = $data['ExternalUserID'];
			  $etDynamic->type = $type;
			  $etDynamic->chat_id = $data['ChatId'];
		  }
		  $etDynamic->save();
	  }
	 
}
