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

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

class Users extends BaseAdmin
{	
    public function user_list(){
		$wid = Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$QyWechatApi = QyWechatApi::getInstance();
		
		$qyUser = new Model('qy_user_list');
		$tj = new \SampleModel('tj');
		$where = $tj->load_array_from_get();
		//name 模糊查询
		if(trim($where['name'])!=''){
			$where['name@~'] = $where['name'];	
		}
		unset($where['name']);
		$where['wid'] = $wid;
		$p = new \Pagination();		
		$res = $p->model_list($qyUser->where($where)->order('id'));
		foreach($res as $k=>$v){
			$res[$k]->department_name = json_decode($v->department_name,1);
			$res[$k]->customer_count = (new Model('qy_externalcontact_list'))->where(['wid'=>$wid,'user_id'=>$v->id])->count();
		}
		//获取配置了客户联系功能的成员列表
		$app = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$FollowUsers = $app->external_contact->getFollowUsers();
		$this->assign('tj', $tj);
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("FollowUsers", $FollowUsers['follow_user']);
		return $this->show();
	}
	
	//同步企业通讯录
	/**public function tongbu_user(){
		set_time_limit(0);
		setApi();
		$wid = Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$QyWechatApi = QyWechatApi::getInstance();
		$userApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->user_secret);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		//获取部门列表
		$departmentRes = $userApp->department->list();
		if($departmentRes['errcode'] == 0){
			$departmentList = $departmentRes['department'];
		}else{
			$errmsg = $departmentRes['errmsg'];
			sendError('获取部门列表失败：'.$errmsg);
		}
		$userLists = [];
		foreach($departmentList as $department){
			$userInfoRes = $userApp->user->getDetailedDepartmentUsers($department['id']);
			if($userInfoRes['errcode'] == 0){
				$userLists[] = $userInfoRes['userlist'];
			}
		}
		$departmentArr = array_column($departmentList,'name','id');
		
		(new Model('qy_user_list'))->delete(['wid'=>$wid]);
		foreach($userLists as $userList){
			foreach($userList as $user){
				$qyUser = (new Model('qy_user_list'))->find(['wid'=>$wid,'userid'=>$user['userid']]);
				if(!$qyUser->id){
					$department_name = [];
					foreach($user['department'] as $departmentId){
						$department_name[] = $departmentArr[$departmentId];
					}
					
					$qyUser->wid = $wid;
					$qyUser->userid = $user['userid'];
					$qyUser->name = Helper::getInstance()->filterEmoji($user['name']);
					$qyUser->mobile = $user['mobile'];
					$qyUser->department = json_encode($user['department']);
					$qyUser->department_name = json_encode($department_name,320);
					$qyUser->avatar = $user['avatar'];
					//$qyUser->customer_count = count($etApp->external_contact->list($user['userid'])['external_userid']);
					$qyUser->customer_count = 0;


					$pub = new Model('pubs');  //获取 mainuid 的值就是当前登录的id
					$pub->find(array('uid'=>Session::get('mainuid')));  //获取到id 查询 pubs 表中的uid于登录用户的id相等的数据
					$user = new Model('user');	
                    $user->find(array('id'=>$pub->uid)); 	//查询用户表中于当前登录用户相同的这条数据并查询出这条数据的会员等级
                    $usertype = new Model('user_type');
                    $usertype->find(array('typeid'=>$user->level_id)); //按照会员等级查询会员表中的这个等级的权限
                    $count =  Model('qy_user_list')->where(['wid'=>$pub->id])->count();	//然后查询当前登录用户已经存入几条数据
                    if($usertype->qouta == 0 || $usertype->qouta == ""){
						$qyUser->save();
                    }elseif($count<=$usertype->qouta){		//然后拿着当前存入条数去跟可插入几条的权限去对比
                        $qyUser->save();
                    }else{
                        sendError('已超过当前套餐最大员工数量限制,请联系客服或升级套餐后再试！');
                        break;
                    }
				}
			}
		}
		sendSuccess('已同步');
	}*/

	public function tongbu_user(){
		set_time_limit(0);
		setApi();
		$wid = Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$QyWechatApi = QyWechatApi::getInstance();
		$userApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->user_secret);
		//获取部门列表
		$departmentRes = $userApp->department->list();
		if($departmentRes['errcode'] == 0){
			$departmentList = $departmentRes['department'];
		}else{
			$errmsg = $departmentRes['errmsg'];
			sendError('获取部门列表失败：'.$errmsg);
		}
		$userLists = [];
		foreach($departmentList as $department){
			$userInfoRes = $userApp->user->getDetailedDepartmentUsers($department['id']);
			if($userInfoRes['errcode'] == 0){
				$userLists[] = $userInfoRes['userlist'];
			}
		}
		$departmentArr = array_column($departmentList,'name','id');
		//导入数据
		foreach($userLists as $userList){
			foreach($userList as $user){
				$qyUser = (new Model('qy_user_list'))->find(['wid'=>$wid,'userid'=>$user['userid']]);
				$department_name = [];
				foreach($user['department'] as $departmentId){
					$department_name[] = $departmentArr[$departmentId];
				}
					
				$qyUser->wid = $wid;
				$qyUser->userid = $user['userid'];
				$qyUser->name = Helper::getInstance()->filterEmoji($user['name']);
				$qyUser->mobile = $user['mobile'];
				$qyUser->department = json_encode($user['department']);
				$qyUser->department_name = json_encode($department_name,320);
				$qyUser->order = json_encode($user['order']);
				$qyUser->position = $user['position'];
				$qyUser->gender = $user['gender'];
				$qyUser->email = $user['email'];
				$qyUser->is_leader_in_dept = json_encode($user['is_leader_in_dept']);
				$qyUser->avatar = $user['avatar'];
				$qyUser->thumb_avatar = $user['thumb_avatar'];
				$qyUser->telephone = $user['telephone'];
				$qyUser->alias = $user['alias'];
				$qyUser->extattr = json_encode($user['extattr']);
				$qyUser->status = $user['status'];
				$qyUser->qr_code = $user['qr_code'];
				$qyUser->external_profile = json_encode($user['external_profile']);
				$qyUser->external_position = $user['external_position'];
				$qyUser->address = $user['address'];
				$qyUser->open_userid = $user['open_userid'];
				$qyUser->main_department = $user['main_department'];
				$qyUser->is_del = 0;

				$pub = new Model('pubs');  //获取 mainuid 的值就是当前登录的id
				$pub->find(array('uid'=>Session::get('mainuid')));  //获取到id 查询 pubs 表中的uid于登录用户的id相等的数据
				$user = new Model('user');	
                $user->find(array('id'=>$pub->uid)); 	//查询用户表中于当前登录用户相同的这条数据并查询出这条数据的会员等级
                $usertype = new Model('user_type');
                $usertype->find(array('typeid'=>$user->level_id)); //按照会员等级查询会员表中的这个等级的权限
                $count =  (new Model('qy_user_list'))->where(['wid'=>$pub->id])->count();	//然后查询当前登录用户已经存入几条数据
                if($usertype->qouta == 0 || $usertype->qouta == ""){
					$qyUser->save();
                }elseif($count<=$usertype->qouta){		//然后拿着当前存入条数去跟可插入几条的权限去对比
                    $qyUser->save();
                }else{
                    sendError('已超过当前套餐最大员工数量限制,请联系客服或升级套餐后再试！');
                    break;
                }
				
			}
		}
		sendSuccess('已同步');
	}
	
	public function welcome_msg(){
		$wid = Session::get('wid');
		$welcomeMsg = new Model('qy_welcome_msg_list');
		//text_content 模糊查询
		$text_content = $_GET['text_content'];
		if(trim($text_content)!=''){
			$where['text_content@~'] = $text_content;	
		}
		$where['wid'] = $wid;
		$p = new \Pagination();		
		$res = $p->model_list($welcomeMsg->where($where)->order('id desc'));
		foreach($res as $k=>$v){
			if($v->other_type == 1){
				$sendType = '文本';
			}elseif($v->other_type == 2){
				$sendType = '图片';
			}elseif($v->other_type == 3){
				$sendType = '图文';
			}elseif($v->other_type == 4){
				$sendType = '小程序';
			}
			$res[$k]->sendType = $sendType;
			$res[$k]->users = json_decode($v->users,1);
		}
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("name", $name);
		$this->assign("h", Helper::getInstance());
		return $this->show();
	}
	
	public function del_welcome_msg(){
		setApi();
		$wid = Session::get('wid');
		$id = $_POST['id'];
		if($id){
			$welcomeMsg = (new Model('qy_welcome_msg_list'))->find($id);
		}else{
			sendError('参数错误');
		}
		$welcomeMsg->delete();
		sendSuccess('操作成功');
	}
	
	public function add_welcome_msg(){
		$wid = Session::get('wid');
		$welcomeMsg = new Model('qy_welcome_msg_list');
		if(\Request::get(1)){
			$welcomeMsg->find(\Request::get(1));
		}
		if(is_post()){
			setApi();
			if(!$welcomeMsg->id){
				$welcomeMsg->wid = $wid;
				$welcomeMsg->ctime = date('Y-m-d H:i:s');
			}
			$welcomeMsg->type = $_POST['shareuser'];
			$welcomeMsg->users = json_encode(explode(',',$_POST['selectUser']),320);
			$welcomeMsg->text_content = $_POST['text_content'];
			$welcomeMsg->other_type = $_POST['shareType'];
			$welcomeMsg->image_url = $_POST['image'];
			$welcomeMsg->link_title = $_POST['link_title'];
			$welcomeMsg->link_url = $_POST['link_url'];
			$welcomeMsg->link_desc = $_POST['link_desc'];
			$welcomeMsg->link_picurl = $_POST['link_pic'];
			$welcomeMsg->miniprogram_name = $_POST['miniprogram_name'];
			$welcomeMsg->miniprogram_title = $_POST['miniprogram_title'];
			$welcomeMsg->miniprogram_url = $_POST['miniprogram_pic'];
			$welcomeMsg->miniprogram_appid = $_POST['miniprogram_appid'];
			$welcomeMsg->miniprogram_page = $_POST['miniprogram_page'];
			if($welcomeMsg->save()){
				sendSuccess('操作成功');
			}
		}
		$tongy = (new Model('qy_welcome_msg_list'))->find(['wid'=>$wid,'type'=>1]);
		if($tongy->id){
			$isHideTy = 1;
		}
		$this->assign("isHideTy", $isHideTy);
		$this->assign("welcomeMsg", $welcomeMsg);
		$this->assign("h", Helper::getInstance());
		return $this->show();
	}
	
	public function select_user(){
		$wid = Session::get('wid');
		$id = \Request::get(1);
		$userList = (new Model('qy_user_list'))->where(['wid'=>$wid])->list_all_array();
		
		$checkedUser = [];
		$welcomeMsg = (new Model('qy_welcome_msg_list'))->where(['wid'=>$wid,'id@!='=>$id])->list_all();
		foreach($welcomeMsg as $msg){
			$checkedUser = array_merge($checkedUser,json_decode($msg->users,1));
		}
		$this->assign("checkedUser", $checkedUser);
		$this->assign("userList", $userList);
		$this->assign("count", count($userList));
		return $this->show();
	}
}