<?php
namespace Addons\QyWechat\Controller\Api\Callback;
use Models\BaseModel as Model;
use Addons\QyWechat\Helper;
use Addons\QyWechat\Services\QyWechatApi;
require_once(DOXCX_FRAME_PATH . 'fun/library/QyWxCypto/WXBizMsgCrypt.php');
 
class Users 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->user_aes;
				  $token = $config->user_tokent;
				  $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->user_aes;
			  $token = $config->user_tokent;
			  $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['ChangeType'] == 'create_user'){
					  $this->create_user($arr);
				  }elseif($arr['ChangeType'] == 'update_user'){
					   $this->update_user($arr);
				  }elseif($arr['ChangeType'] == 'delete_user'){
					  $this->delete_user($arr);
				  }
			  } else {
				  diy_log("解密失败ERR: " . $errCode . "\n\n");
			  }
			  echo "success";
			  exit();
		  }
	  }
	  
	  //新增成员
	  public function create_user($arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  $userApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->user_secret);
		  //获取部门列表
		  $departmentRes = $userApp->department->list();
		  $departmentList = $departmentRes['department'];
		  $departmentArr = array_column($departmentList,'name','id');
		
		  $department_name = [];
	  	  foreach($arr['Department'] as $departmentId){
			  $department_name[] = $departmentArr[$departmentId];
		  }
		  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
		  $qyUser->wid = $qyConfig->wid;
		  $qyUser->userid = $arr['UserID'];
		  $qyUser->name = Helper::getInstance()->filterEmoji($arr['Name']);
		  $qyUser->mobile = $arr['Mobile'];
		  $qyUser->department = json_encode($arr['Department']);
		  $qyUser->department_name = json_encode($department_name,320);
		  $qyUser->position = $arr['Position'];
		  $qyUser->gender = $arr['Gender'];
		  $qyUser->email = $arr['Email'];
		  $qyUser->is_leader_in_dept = json_encode($arr['IsLeaderInDept']);
		  $qyUser->avatar = $arr['Avatar'];
		  $qyUser->telephone = $arr['Telephone'];
		  $qyUser->alias = $arr['Alias'];
		  $qyUser->extattr = json_encode($arr['ExtAttr']);
		  $qyUser->status = $arr['Status'];
		  $qyUser->address = $arr['Address'];
		  $qyUser->is_del = 0;
		  $qyUser->save();
	  }
	  
	  //更新成员
	  public function update_user($arr){
		  $CorpID = $arr['ToUserName'];//企业微信CorpID
		  $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$CorpID]);
		  $QyWechatApi = QyWechatApi::getInstance();
		  $userApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->user_secret);
		  
		  $qyUser = (new Model('qy_user_list'))->find(['wid'=>$qyConfig->wid,'userid'=>$arr['UserID']]);
		  if(!$qyUser->id){
			  return '未找到该用户';
		  }
		  $oldUserid = $qyUser->userid;
		  
		  if($arr['Department']){
			  //获取部门列表
			  $departmentRes = $userApp->department->list();
			  $departmentList = $departmentRes['department'];
			  $departmentArr = array_column($departmentList,'name','id');
			
			  $department_name = [];
			  foreach($arr['Department'] as $departmentId){
				  $department_name[] = $departmentArr[$departmentId];
			  }
		  }
		  
		  $qyUser->userid = $arr['NewUserID']?$arr['NewUserID']:$oldUserid;
		  $qyUser->name = $arr['Name']?Helper::getInstance()->filterEmoji($arr['Name']):$qyUser->name;
		  $qyUser->mobile = $arr['Mobile']?$arr['Mobile']:$qyUser->mobile;
		  if($arr['Department']){
			  $qyUser->department = json_encode($arr['Department']);
			  $qyUser->department_name = json_encode($department_name,320);
		  }
		  $qyUser->position = $arr['Position']?$arr['Position']:$qyUser->position;
		  $qyUser->gender = $arr['Gender']?$arr['Gender']:$qyUser->gender;
		  $qyUser->email = $arr['Email']?$arr['Email']:$qyUser->email;
		  $qyUser->is_leader_in_dept = $arr['IsLeaderInDept']?json_encode($arr['IsLeaderInDept']):$qyUser->is_leader_in_dept;
		  $qyUser->avatar = $arr['Avatar']?$arr['Avatar']:$qyUser->avatar;
		  $qyUser->telephone = $arr['Telephone']?$arr['Telephone']:$qyUser->telephone;
		  $qyUser->alias = $arr['Alias']?$arr['Alias']:$qyUser->alias;
		  $qyUser->extattr = $arr['ExtAttr']?json_encode($arr['ExtAttr']):$qyUser->extattr;
		  $qyUser->status = $arr['Status']?$arr['Status']:$qyUser->status;
		  $qyUser->address = $arr['Address']?$arr['Address']:$qyUser->address;
		  $qyUser->is_del = 0;
		  $qyUser->save();
	  }
	  
	  //删除成员
	  public function delete_user($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']]);
		  $qyUser->is_del = 1;
		  $qyUser->save();
	  }
	 
}
