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

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

class Externalcontact extends BaseAdmin
{	
    public function manages(){
		return $this->show();
	}
	
	public function customer_list(){
		$wid = Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$QyWechatApi = QyWechatApi::getInstance();
		
		$qyCustomer = new Model('qy_externalcontact_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($qyCustomer->where($where)->order('id'));
		foreach($res as $k=>$v){
			//$res[$k]->follow_user = json_decode($v->follow_user,1);
			$res[$k]->tags = json_decode($v->tags,1);
			$res[$k]->user = (new Model('qy_user_list'))->find(['id'=>$v->user_id]);
		}
		/**$etTagArr = (new Model('qy_externalcontact_tag'))->where(['wid'=>$wid])->list_all_array();
		foreach($etTagArr as $v){
			foreach(json_decode($v['tags'],1) as $v2){
				$newEtTagArr[] = $v['group_name'].'_'.$v2['name'];
			}
		}*/
		$etTagArr = Helper::getInstance()->get_et_tags($wid);
		$this->assign('tj', $tj);
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("etTagArr", $etTagArr);
		return $this->show();
	}
	
	public function customer_info(){
		$wid = Session::get('wid');
		$etId = \Request::get(1);
		$et = (new Model('qy_externalcontact_list'))->find($etId);
		$et->tags = json_decode($et->tags,1);
		$et->user = (new Model('qy_user_list'))->find(['id'=>$et->user_id]);
		if(!$et->id){
			die('未知客户');
		}
		$qyEtGroupchat = (new Model('qy_et_groupchat'))->where(['wid'=>$wid])->list_all();
		$groupchat = [];
		foreach($qyEtGroupchat as $qyetgroupchat){
			$member_list = json_decode($qyetgroupchat->member_list,1);
			foreach($member_list as $member){
				if($member['userid'] == $et->external_userid){
					$groupchat[] = $qyetgroupchat;
				}
			}
		}
		/**$follow_user = json_decode($et->follow_user,1);
		foreach($follow_user as $k=>$v){
			$user = (new Model('qy_user_list'))->find(['wid'=>$wid,'userid'=>$v['userid']])->get_model_array();
			$follow_user[$k]['user'] = $user;
		}*/
		$etAll = (new Model('qy_externalcontact_list'))->where(['id@!='=>$etId,'wid'=>$wid,'external_userid'=>$et->external_userid])->list_all();
		foreach($etAll as $k=>$v){
			$etAll[$k]->tags = json_decode($v->tags,1);
			$etAll[$k]->user = (new Model('qy_user_list'))->find(['id'=>$v->user_id]);
		}
		$qyEtDynamic = (new Model('qy_et_dynamic'))->where(['wid'=>$wid,'external_userid'=>$et->external_userid])->order('ctime desc')->list_all_array();
		$etDynamic = [];
		foreach($qyEtDynamic as $qyetdynamic){
			$etDynamic[date('m_d',$qyetdynamic['ctime'])][] = $qyetdynamic;
		}
		$h = Helper::getInstance();
		$etTagArr = $h->get_et_tags($wid);
		$addWayArr = $h->add_way_arr();
		$this->assign("et", $et);
		$this->assign("etAll", $etAll);
		$this->assign("etTagArr", $etTagArr);
		$this->assign("addWayArr", $addWayArr);
		$this->assign("groupchat", $groupchat);
		$this->assign("etDynamic", $etDynamic);
		$this->assign("h", $h);
		return $this->show();
	}
	
	public function et_tag_set(){
		$wid = Session::get('wid');
		$etTagArr = (new Model('qy_externalcontact_tag'))->where(['wid'=>$wid])->list_all_array();
		/**foreach($etTagArr as $v){
			foreach(json_decode($v['tags'],1) as $v2){
				$newEtTagArr[$v['group_name'].'_'.$v2['name']] = $v2['id'];
			}
		}*/
		$etId = \Request::get(1);
		if($etId){
			$et = (new Model('qy_externalcontact_list'))->find($etId);
			$etTags = json_decode($et->tags,1);
		}else{
			die('未知客户');
		}
		$qyUser = (new Model('qy_user_list'))->find(['id'=>$et->user_id]);
		if(is_post()){
			setApi();
			$checkTag = $_POST['tags'];
			$add_tag = [];
			$remove_tag = [];
			foreach($checkTag as $v){
				if(!in_array($v,$etTags)){
					$add_tag[] = $v;
				}
			}
			foreach($etTags as $v){
				if(!in_array($v,$checkTag)){
					$remove_tag[] = $v;
				}
			}
			if(!$add_tag && !$remove_tag){
				sendError('您未做任何修改');
			}
			$QyWechatApi = QyWechatApi::getInstance();
			$param = [
				'userid' => $qyUser->userid,
				'external_userid' => $et->external_userid,
				'add_tag' => $add_tag,
				'remove_tag' => $remove_tag
			];
			$editEtTagRes = $QyWechatApi->edit_et_tag($param);
			if($editEtTagRes['errcode'] == 0){
				$et->tags = json_encode($checkTag,320);
				if($et->save()){
					sendSuccess('操作成功');
				}else{
					sendError('数据库操作失败');
				}
			}else{
				sendError('操作失败'.$editEtTagRes['errmsg']);
			}			
		}
		$this->assign("etTagArr", $etTagArr);
		$this->assign("etTags", $etTags);
		return $this->show();
	}
	
	public function tag_manage(){
		$wid = Session::get('wid');
		
		$eTag = new Model('qy_externalcontact_tag');
		$tj = new \SampleModel('tj');
		$where = $tj->load_array_from_get();
		//name 模糊查询
		if(trim($where['group_name'])!=''){
			$where['group_name@~'] = $where['group_name'];	
		}
		unset($where['group_name']);
		$where['wid'] = $wid;
		$p = new \Pagination();		
		$res = $p->model_list($eTag->where($where)->order('id'));
		foreach($res as $k=>$v){
			$res[$k]->tags = json_decode($v->tags,1);
		}		
		$this->assign('tj', $tj);
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		return $this->show();
	}
	
	public function add_tag(){
		$wid = Session::get('wid');
		$group_id = \Request::get(1);
		if(is_post()){
			setApi();
			$QyWechatApi = QyWechatApi::getInstance();
			$tag_name = $_POST['tag_name'];
			$param = [
				'group_id' => $group_id,
				'tag' => [
					['name'=>$tag_name],
				]
			];
			$addTagRes = $QyWechatApi->add_corp_tag($param);
			if($addTagRes['errcode'] == 0){
				$tag_group = $addTagRes['tag_group'];
				$qyTag = (new Model('qy_externalcontact_tag'))->find(['wid'=>$wid,'group_id'=>$tag_group['group_id']]);
				$qyTags = json_decode($qyTag->tags,1);
				foreach($tag_group['tag'] as $tag){
					array_push($qyTags,$tag);
				}
				$qyTag->tags = json_encode($qyTags,320);
				if($qyTag->save()){
					sendSuccess('操作成功');
				}else{
					sendError('数据库操作失败');
				}
			}else{
				sendError('操作失败'.$addTagRes['errmsg']);
			}			
		}
		return $this->show();
	}
	
	public function edit_tag(){
		$wid = Session::get('wid');
		$id =  \Request::get('id');
		$tagid =  \Request::get('tagid');
		$qyTag = (new Model('qy_externalcontact_tag'))->find(['wid'=>$wid,'id'=>$id]);
		$tagArr = json_decode($qyTag->tags,1);
		$tagName = '';
		foreach($tagArr as $k=>$v){
			if($v['id'] == $tagid){
				$tagName = $v['name'];
			}
		}
		if(is_post()){
			setApi();
			$QyWechatApi = QyWechatApi::getInstance();
			$param = [
				'id' => $tagid,
				'name' => $_POST['tag_name']
			];
			$editTagRes = $QyWechatApi->edit_corp_tag($param);
			if($editTagRes['errcode'] == 0){
				foreach($tagArr as $k=>$v){
					if($v['id'] == $tagid){
						$tagArr[$k]['name'] = $_POST['tag_name'];
					}
				}
				$qyTag->tags = json_encode($tagArr);
				$qyTag->save();
				sendSuccess('操作成功');
			}else{
				sendError('操作失败'.$editTagRes['errmsg']);
			}
		}
		$this->assign("tagName", $tagName);
		return $this->show();
	}
	
	public function del_tag(){
		$wid = Session::get('wid');
		if(is_post()){
			setApi();
			$QyWechatApi = QyWechatApi::getInstance();
			$id = $_POST['id'];
			$tagid = $_POST['tagid'];
			$qyTag = (new Model('qy_externalcontact_tag'))->find(['wid'=>$wid,'id'=>$id]);
			$param = [
				'tag_id' => $tagid,
				//'group_id' => $qyTag->group_id
			];
			$delTagRes = $QyWechatApi->del_corp_tag($param);
			if($delTagRes['errcode'] == 0){
				$tagArr = json_decode($qyTag->tags,1);
				foreach($tagArr as $k=>$v){
					if($v['id'] == $tagid){
						unset($tagArr[$k]);
					}
				}
				$qyTag->tags = json_encode($tagArr);
				$qyTag->save();
				//标签组下所有的标签均被删除 则删除组
				if(!count(json_decode($qyTag->tags,1))){
					$qyTag->delete();
				}
				sendSuccess('操作成功');
			}else{
				sendError('操作失败'.$delTagRes['errmsg']);
			}
		}
	}
	
	public function add_tag_group(){
		$wid = Session::get('wid');
		if(is_post()){
			setApi();
			$QyWechatApi = QyWechatApi::getInstance();
			$group_name = $_POST['group_name'];
			$tag_name = $_POST['tag_name'];
			$param = [
				'group_name' => $group_name,
				'tag' => [
					['name'=>$tag_name],
				]
			];
			$addTagRes = $QyWechatApi->add_corp_tag($param);
			if($addTagRes['errcode'] == 0){
				$tag_group = $addTagRes['tag_group'];
				$qyTag = (new Model('qy_externalcontact_tag'))->find(['wid'=>$wid,'group_id'=>$tag_group['group_id']]);
				if($qyTag->id){
					$qyTags = json_decode($qyTag->tags,1);
					foreach($tag_group['tag'] as $tag){
						array_push($qyTags,$tag);
					}
				}else{
					$qyTags = $tag_group['tag'];
				}
				$qyTag->wid = $wid;
				$qyTag->group_id = $tag_group['group_id'];
				$qyTag->group_name = $tag_group['group_name'];
				$qyTag->create_time = $tag_group['create_time'];
				$qyTag->order = $tag_group['order'];
				$qyTag->deleted = $tag_group['deleted'];
				$qyTag->tags = json_encode($qyTags,320);
				if($qyTag->save()){
					sendSuccess('操作成功');
				}else{
					sendError('数据库操作失败');
				}
			}else{
				sendError('操作失败'.$addTagRes['errmsg']);
			}
		}
		return $this->show();
	}
	
	public function del_tag_group(){
		$wid = Session::get('wid');
		if(is_post()){
			setApi();
			$QyWechatApi = QyWechatApi::getInstance();
			$group_id = $_POST['group_id'];
			$param = [
				'group_id' => $group_id,
			];
			$delTagRes = $QyWechatApi->del_corp_tag($param);
			if($delTagRes['errcode'] == 0){
				(new Model('qy_externalcontact_tag'))->delete(['wid'=>$wid,'group_id'=>$group_id]);
				sendSuccess('操作成功');
			}else{
				sendError('操作失败'.$delTagRes['errmsg']);
			}
		}	
	}
	
	public function tongbu_tag(){
		setApi();
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$tagRes = $QyWechatApi->get_corp_tag_list();
		if($tagRes['errcode'] == 0){
			$tagList = $tagRes['tag_group'];
			(new Model('qy_externalcontact_tag'))->delete(['wid'=>$wid]);
			foreach($tagList as $tag){
				$eTag = new Model('qy_externalcontact_tag');
				$eTag->wid = $wid;
				$eTag->group_id = $tag['group_id'];
				$eTag->group_name = $tag['group_name'];
				$eTag->create_time = $tag['create_time'];
				$eTag->order = $tag['order'];
				$eTag->deleted = $tag['deleted'];
				$eTag->tags = json_encode($tag['tag'],320);
				$eTag->save();
			}
		}
		sendSuccess('已同步');
	}
	

	// public function tongbu_customer(){
	// 	set_time_limit(0);
	// 	setApi();
	// 	$wid = Session::get('wid');
	// 	$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
	// 	$QyWechatApi = QyWechatApi::getInstance();
	// 	$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
	// 	$ProvidersApi = ProvidersApi::getInstance();
	// 	$work = $ProvidersApi->get_work($qyConfig->corp_id);
	// 	//获取通讯录列表
	// 	$qyUser = (new Model('qy_user_list'))->where(['wid'=>$wid])->list_all();
	// 	$customer_list_arr = [];
	// 	foreach($qyUser as $qyuser){
	// 		//获取客户列表
	// 		$customer_list_res = $etApp->external_contact->list($qyuser->userid);
	// 		$customer_list_res2 = $work->external_contact->list($qyuser->userid);
	// 		if($customer_list_res['errcode'] == 0 && $customer_list_res2['errcode'] == 0 && count($customer_list_res['external_userid']) && count($customer_list_res2['external_userid'])){
	// 			$customer_list_arr[$qyuser->id] = [$customer_list_res['external_userid'],$customer_list_res2['external_userid']];
	// 		}
	// 	}
	// 	//导数据
	// 	foreach($customer_list_arr as $user_id => $customer_list){
	// 		foreach($customer_list[0] as $customer){
	// 			//获取客户详情
	// 			$customer_info_res = $etApp->external_contact->get($customer);
	// 			if($customer_info_res['errcode'] == 0){
	// 				$customer_info = $customer_info_res;
	// 				$qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$wid,'user_id'=>$user_id,'external_userid'=>$customer_info['external_contact']['external_userid']]);
	// 				$qyUserById = (new Model('qy_user_list'))->find(['id'=>$user_id]);

	// 				$user = '';
	// 				$tags = [];
	// 				foreach($customer_info['follow_user'] as $followuser){
	// 					if($qyUserById->userid == $followuser['userid']){
	// 						$user = $followuser;
	// 						foreach($followuser['tags'] as $ftag){
	// 							$tags[] = $ftag['tag_id'];
	// 						}
	// 					}
	// 				}						
	// 				$qyCustomer->wid = $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 = $user_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();
										
	// 			}
	// 		}
	// 		foreach($customer_list[1] as $customer){
	// 			//获取客户详情
	// 			$customer_info_res = $work->external_contact->get($customer);
	// 			if($customer_info_res['errcode'] == 0){
	// 				$customer_info = $customer_info_res;
	// 				$qyCustomer = (new Model('qy_providers_externalcontact_list'))->find(['wid'=>$wid,'user_id'=>$user_id,'external_userid'=>$customer_info['external_contact']['external_userid']]);
	// 				$qyUserById = (new Model('qy_user_list'))->find(['id'=>$user_id]);
					
	// 				$user = '';
	// 				$tags = [];
	// 				foreach($customer_info['follow_user'] as $followuser){
	// 					if($qyUserById->userid == $followuser['userid']){
	// 						$user = $followuser;
	// 						foreach($followuser['tags'] as $ftag){
	// 							$tags[] = $ftag['tag_id'];
	// 						}
	// 					}
	// 				}						
	// 				$qyCustomer->wid = $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 = $user_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();
										
	// 			}
	// 		}
	// 	}
	// 	sendSuccess('已同步');
	// }

	public function tongbu_customer(){
		set_time_limit(0);
		setApi();
		$wid = Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$QyWechatApi = QyWechatApi::getInstance();
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		//获取通讯录列表
		$qyUser = (new Model('qy_user_list'))->where(['wid'=>$wid])->list_all();
		$customer_list_arr = [];
		foreach($qyUser as $qyuser){
			//获取客户列表
			$customer_list_res = $etApp->external_contact->list($qyuser->userid);
			if($customer_list_res['errcode'] == 0  && count($customer_list_res['external_userid'])){
				$customer_list_arr[$qyuser->id] = $customer_list_res['external_userid'];
			}
		}
		//导数据
		foreach($customer_list_arr as $user_id => $customer_list){
			foreach($customer_list as $customer){
				//获取客户详情
				$customer_info_res = $etApp->external_contact->get($customer);
				if($customer_info_res['errcode'] == 0){
					$customer_info = $customer_info_res;
					$qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$wid,'user_id'=>$user_id,'external_userid'=>$customer_info['external_contact']['external_userid']]);
					$qyUserById = (new Model('qy_user_list'))->find(['id'=>$user_id]);

					$user = '';
					$tags = [];
					foreach($customer_info['follow_user'] as $followuser){
						if($qyUserById->userid == $followuser['userid']){
							$user = $followuser;
							foreach($followuser['tags'] as $ftag){
								$tags[] = $ftag['tag_id'];
							}
						}
					}						
					$qyCustomer->wid = $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 = $user_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();
										
				}
			}
		}
		sendSuccess('已同步');
	}
	
	public function groupchat_manage(){
		return $this->show();
	}
	
	public function groupchat_list(){
		$wid = Session::get('wid');
		$etGroupchat = new Model('qy_et_groupchat');
		$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($etGroupchat->where($where)->order('id'));
		foreach($res as $k=>$v){
			$user = (new Model('qy_user_list'))->find(['wid'=>$wid,'id'=>$v->user_id]);
			$res[$k]->user = $user;
			$res[$k]->member_list = json_decode($v->member_list,1);
		}		
		$this->assign('tj', $tj);
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		return $this->show();
	}
	
	public function groupchat_info(){
		setApi();
		$wid = Session::get('wid');
		$chatid = $_POST['chatid'];
		foreach ($chatid as $key => $value) {
			$etGroupchat[] = (new Model('qy_et_groupchat'))->find(['wid'=>$wid,'chat_id'=>$value]);
		}
		foreach ($etGroupchat as $keys => $values) {
			if($values->name == ""){
				$values->name = "默认群名";
			}
		}
		sendSuccess('获取成功',$etGroupchat);
	}
	
	public function user_creat_groupchat_statistic(){
		if(\Request::get('dates')){
			$dates = \Request::get('dates');
		}else{
			$dates = date('Y-m-d',strtotime("-1 day"));//昨天
		}
		$wid = Session::get('wid');
		$qyUser = new Model('qy_user_list');
		$where['wid'] = $wid;
		$p = new \Pagination();		
		$res = $p->model_list($qyUser->where($where)->order('id'));
		//获取客户群统计数据
		$QyWechatApi = QyWechatApi::getInstance();
		$etGroupchatStatistic = $QyWechatApi->get_et_groupchat_statistic(strtotime($dates))['items'];
		foreach($res as $k=>$v){
			foreach($etGroupchatStatistic as $statistic){
				if($v->user_id == $statistic['owner']){
					$res[$k]->groupchatStatistic = $statistic['data'];
					break;
				}
			}
		}
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("dates", $dates);
		return $this->show();
	}
	
	/**public function tongbu_groupchat(){
		set_time_limit(0);
		setApi();
		$wid = Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$QyWechatApi = QyWechatApi::getInstance();
		//获取群列表
		$groupChatList = [];
		$groupchatListRes = $QyWechatApi->get_et_groupchat_list();
		if($groupchatListRes['errcode'] == 0){
			$groupChatList = $groupchatListRes['group_chat_list'];
		}
		(new Model('qy_et_groupchat'))->delete(['wid'=>$wid]);
		foreach($groupChatList as $groupChat){
			$status = $groupChat['status'];
			//获取群详情
			$groupChatInfoRes = $QyWechatApi->get_et_groupchat_info($groupChat['chat_id']);
			if($groupChatInfoRes['errcode'] == 0){
				$groupChatInfo = $groupChatInfoRes['group_chat'];
				$etGroupchat = new Model('qy_et_groupchat');
				$etGroupchat->wid = $wid;
				$etGroupchat->chat_id = $groupChatInfo['chat_id'];
				$etGroupchat->status = $status;
				$etGroupchat->name = $groupChatInfo['name'];
				$etGroupchat->owner = $groupChatInfo['owner'];
				$etGroupchat->create_time = $groupChatInfo['create_time'];
				$etGroupchat->notice = Helper::getInstance()->filterEmoji($groupChatInfo['notice']);
				$etGroupchat->member_list = json_encode($groupChatInfo['member_list'],320);
				$etGroupchat->save();
			}
		}
		sendSuccess('已同步');
	}*/

	public function tongbu_groupchat(){
		set_time_limit(0);
		setApi();
		$wid = Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$QyWechatApi = QyWechatApi::getInstance();
		//获取群列表
		$groupChatList = [];
		$groupchatListRes = $QyWechatApi->get_et_groupchat_list();
		if($groupchatListRes['errcode'] == 0){
			$groupChatList = $groupchatListRes['group_chat_list'];
		}
		foreach($groupChatList as $groupChat){
			$status = $groupChat['status'];
			//获取群详情
			$groupChatInfoRes = $QyWechatApi->get_et_groupchat_info($groupChat['chat_id']);
			if($groupChatInfoRes['errcode'] == 0){
				$groupChatInfo = $groupChatInfoRes['group_chat'];
				$qyUser = (new Model('qy_user_list'))->find(['wid'=>$wid,'userid'=>$groupChatInfo['owner']]);
				$etGroupchat = (new Model('qy_et_groupchat'))->find(['wid'=>$wid,'chat_id'=>$groupChatInfo['chat_id']]);
				$etGroupchat->wid = $wid;
				$etGroupchat->chat_id = $groupChatInfo['chat_id'];
				$etGroupchat->status = $status;
				$etGroupchat->name = $groupChatInfo['name'];
				$etGroupchat->user_id = $qyUser->id;
				$etGroupchat->create_time = $groupChatInfo['create_time'];
				$etGroupchat->notice = Helper::getInstance()->filterEmoji($groupChatInfo['notice']);
				$etGroupchat->member_list = json_encode($groupChatInfo['member_list'],320);
				$etGroupchat->save();
			}
		}
		sendSuccess('已同步');
	}
	
	public function auto_pull_group(){
		$wid = Session::get('wid');
		$contactWay = new Model('qy_et_contact_way');
		//name 模糊查询
		$name = $_GET['name'];
		if(trim($name)!=''){
			$where['name@~'] = $name;	
		}
		$where['wid'] = $wid;
		$where['is_auto_pull_group'] = 1;
		$p = new \Pagination();		
		$res = $p->model_list($contactWay->where($where)->order('id desc'));
		foreach($res as $k=>$v){
			$res[$k]->users = json_decode($v->users,1);
			$res[$k]->select_label = json_decode($v->select_label,1);
			$group_chat_list = json_decode($v->group_chat_list,1);
			$isHaveLr = 0;
			$customTotalNum = 0;
			foreach($group_chat_list as $k2=>$group_chat){
				$etGroupchat = (new Model('qy_et_groupchat'))->find(['wid'=>$wid,'chat_id'=>$group_chat['chatid']]);
				$customNum = count(json_decode($etGroupchat->member_list,1));
				$customTotalNum += $customNum;
				$group_chat_list[$k2]['name'] = $group_chat['name']."({$customNum}/200)";
				if($customNum < $group_chat['people'] && $isHaveLr == 0){
					$isHaveLr = 1;
					$group_chat_list[$k2]['status'] = 1;//0未开始 1拉人中 2已结束
				}elseif($customNum < $group_chat['people']){
					$group_chat_list[$k2]['status'] = 0;
				}elseif($customNum >= $group_chat['people']){
					$group_chat_list[$k2]['status'] = 2;
				}
			}
			$res[$k]->customTotalNum = $customTotalNum;
			$res[$k]->group_chat_list = $group_chat_list;
		}
		$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 add_auto_pull_group(){
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$contactWay = new Model('qy_et_contact_way');
		$id = \Request::get(1);
		if($id){
			$contactWay->find(['wid'=>$wid,'id'=>$id]);
		}
		if(is_post()){
			setApi();
			if(!$_POST['checkUser']){
				sendError('请添加使用人员');
			}
			if($_POST['auto_label'] && !$_POST['checkLable']){
				sendError('请添加标签');
			}
			$type = 2;
			$scene = 2;//2-通过二维码联系
			$users = explode(',',$_POST['checkUser']);
			if($contactWay->id){
				$configId = $contactWay->config_id;
				$state = $contactWay->state;
				$config = [
				   'skip_verify' => $_POST['skip_verify']?true:false,
				   'user' => Helper::get_userid($users)
				];
				$updateRes = $etApp->contact_way->update($configId, $config);
				if($updateRes['errcode'] == 0){
					$contactWay->wid = $wid;
				}else{
					sendError('操作失败');
				}
			}else{
				$maxId = (new Model('qy_et_contact_way'))->max('id');
				$state = $maxId + 1;//企业自定义的state参数，用于区分不同的添加渠道
				$config = [
				   'skip_verify' => $_POST['skip_verify']?true:false,//外部客户添加时是否无需验证
				   'state' => $state,
				   'user' => Helper::get_userid($users),
				];
				$createRes = $etApp->contact_way->create($type, $scene, $config);
				if($createRes['errcode'] == 0){
					$config_id = $createRes['config_id'];
					$getContactWay = $etApp->contact_way->get($config_id)['contact_way'];
					$contactWay->wid = $wid;
					$contactWay->config_id = $config_id;
					$contactWay->qr_code = $getContactWay['qr_code'];
					$contactWay->ctime = date('Y-m-d H:i:s');
				}else{
					sendError('操作失败');
				}
			}
			$itemId = $_POST['item_id'];
			$itemChatid = $_POST['item_chatid'];
			$itemName = $_POST['item_name'];
			$itemPeople = $_POST['item_people'];
			$itemImg = $_POST['item_img'];
			$itmeArr = [];
			foreach($itemId as $k=>$id){
				$itmeArr[$k]['id'] = $id;
				$itmeArr[$k]['chatid'] = $itemChatid[$k];
				$itmeArr[$k]['name'] = $itemName[$k];
				$itmeArr[$k]['people'] = $itemPeople[$k];
				$itmeArr[$k]['img'] = $itemImg[$k];
			}
			$contactWay->group_chat_list = json_encode($itmeArr,320);
			$contactWay->name = $_POST['name'];
			$contactWay->skip_verify = $_POST['skip_verify'];
			$contactWay->state = $state;
			$contactWay->users = json_encode($users,320);
			$contactWay->type = $type;
			$contactWay->auto_label = $_POST['auto_label']?1:0;
			$contactWay->select_label = json_encode(explode(',',$_POST['checkLable']),320);
			$contactWay->text_content = $_POST['text_content'];
			$contactWay->other_type = 2;
			$contactWay->is_auto_pull_group = 1;
			$contactWay->save();
			sendSuccess('操作成功');
		}
		$this->assign("contactWay", $contactWay);
		$this->assign("group_chat_list", json_decode($contactWay->group_chat_list,1));
		$this->assign("h", Helper::getInstance());
		return $this->show();
	}
	
	public function del_auto_pull_group(){
		setApi();
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$id = $_POST['id'];
		if($id){
			$contactWay = (new Model('qy_et_contact_way'))->find($id);
		}else{
			sendError('参数错误');
		}
		$configId = $contactWay->config_id;
		$deleteRes = $etApp->contact_way->delete($configId);
		if($deleteRes['errcode'] == 0){
			$contactWay->delete();
			sendSuccess('操作成功');
		}else{
			sendError('操作失败');
		}
		
	}
	
	public function group_welcome_template(){
		$wid = Session::get('wid');
		$groupWelcome = new Model('qy_group_welcome_template');
		//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($groupWelcome->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;
		}
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("name", $name);
		return $this->show();
	}
	
	public function add_group_welcome(){
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$groupWelcome = new Model('qy_group_welcome_template');
		if(\Request::get(1)){
			$groupWelcome->find(\Request::get(1));
		}
		if(is_post()){
			setApi();
			$msg = [
				'text'=>[
					'content' => $_POST['text_content']
				]
			];
			if($_POST['shareType'] == 2){
				$msg['image'] = [
					'media_id' => $etApp->media->uploadImage($_POST['image'])['media_id'],
				];
			}elseif($_POST['shareType'] == 3){
				$msg['link'] = [
					'title' => $_POST['link_title'],
					'picurl' => $_POST['link_pic'],
					'desc' => $_POST['link_desc'],
					'url' => $_POST['link_url'],
				];
			}elseif($_POST['shareType'] == 4){
				$msg['miniprogram'] = [
					'title' => $_POST['miniprogram_title'],
					'pic_media_id' => $etApp->media->uploadImage($_POST['miniprogram_pic'])['media_id'],
					'appid' => $_POST['miniprogram_appid'],
					'page' => $_POST['miniprogram_page'],
				 ];
			}
			if($groupWelcome->id){
				$msg['template_id'] = $groupWelcome->template_id;
				$editRes = $QyWechatApi->edit_group_welcome_template($msg);
				if($editRes['errcode'] == 0){
					$groupWelcome->wid = $wid;
				}else{
					sendError('操作失败'.$editRes['errmsg']);
				}
			}else{
				$addRes = $QyWechatApi->add_group_welcome_template($msg);
				if($addRes['errcode'] == 0){
					$groupWelcome->wid = $wid;
					$groupWelcome->template_id = $addRes['template_id'];
					$groupWelcome->ctime = date('Y-m-d H:i:s');
				}else{
					sendError('操作失败'.$addRes['errmsg']);
				}
			}
			$groupWelcome->text_content = $_POST['text_content'];
			$groupWelcome->other_type = $_POST['shareType'];
			$groupWelcome->image_url = $_POST['image'];
			$groupWelcome->link_title = $_POST['link_title'];
			$groupWelcome->link_picurl = $_POST['link_pic'];
			$groupWelcome->link_desc = $_POST['link_desc'];
			$groupWelcome->link_url = $_POST['link_url'];
			$groupWelcome->miniprogram_name = $_POST['miniprogram_name'];
			$groupWelcome->miniprogram_title = $_POST['miniprogram_title'];
			$groupWelcome->miniprogram_url = $_POST['miniprogram_pic'];
			$groupWelcome->miniprogram_appid = $_POST['miniprogram_appid'];
			$groupWelcome->miniprogram_page = $_POST['miniprogram_page'];
			$groupWelcome->save();
			sendSuccess('操作成功');
		}
		$this->assign("groupWelcome", $groupWelcome);
		return $this->show();
	}
	
	public function del_group_welcome(){
		setApi();
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$id = $_POST['id'];
		if($id){
			$groupWelcome = (new Model('qy_group_welcome_template'))->find($id);
		}else{
			sendError('参数错误');
		}
		$delRes = $QyWechatApi->del_group_welcome_template($groupWelcome->template_id);
		if($delRes['errcode'] == 0){
			$groupWelcome->delete();
			sendSuccess('操作成功');
		}else{
			sendError('操作失败:'.$delRes['errmsg']);
		}
	}
	
	public function msg_template(){
		$wid = Session::get('wid');
		$msgTemplate = new Model('qy_et_msg_template');
		//name 模糊查询
		$name = $_GET['name'];
		if(trim($name)!=''){
			$where['name@~'] = $name;	
		}
		$where['wid'] = $wid;
		$p = new \Pagination();		
		$res = $p->model_list($msgTemplate->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;
		}
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("name", $name);
		return $this->show();
	}
	
	public function add_msg_template(){
		$wid = Session::get('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(is_post()){
			setApi();
			$msgTemplate = new Model('qy_et_msg_template');
			$msgTemplate->wid = $wid;
			$msgTemplate->name = $_POST['name'];
			$msgTemplate->send_to = $_POST['shareuser'];
			$msgTemplate->send_tag = json_encode(explode(',',$_POST['checkLable']),320);
			$msgTemplate->send_user = json_encode(explode(',',$_POST['checkUser']),320);
			$msgTemplate->send_mode = $_POST['selectTime'];
			$msgTemplate->timing_time = $_POST['timing_time'];
			$msgTemplate->text_content = $_POST['text_content'];
			$msgTemplate->other_type = $_POST['shareType'];
			$msgTemplate->image_url = $_POST['image'];			
			$msgTemplate->link_title = $_POST['link_title'];
			$msgTemplate->link_picurl = $_POST['link_pic'];
			$msgTemplate->link_desc = $_POST['link_desc'];
			$msgTemplate->link_url = $_POST['link_url'];
			$msgTemplate->miniprogram_name = $_POST['miniprogram_name'];
			$msgTemplate->miniprogram_appid = $_POST['miniprogram_appid'];
			$msgTemplate->miniprogram_page = $_POST['miniprogram_page'];
			$msgTemplate->miniprogram_title = $_POST['miniprogram_title'];
			$msgTemplate->miniprogram_picurl = $_POST['miniprogram_pic'];
			$msgTemplate->ctime = date('Y-m-d H:i:s');
			if($msgTemplate->save()){
				if($msgTemplate->send_mode == 1){
					$externalcontact = (new Model('qy_externalcontact_list'))->where(['wid'=>$wid])->list_all_array();
					$external_userids = [];
					if($msgTemplate->send_to == 1){
						foreach($externalcontact as $et){
							$external_userids[] = $et['external_userid'];
						}
					}elseif($msgTemplate->send_to == 2){
						foreach($externalcontact as $et){
							if(array_intersect(json_decode($et['tags'],1),json_decode($msgTemplate->send_tag,1))){
								$external_userids[] = $et['external_userid'];
							}
						}
					}elseif($msgTemplate->send_to == 3){
						foreach($externalcontact as $et){
							// $follow_user = json_decode($et['follow_user'],1);
							// foreach($follow_user as $user){
							// 	if(in_array($user['userid'],json_decode($msgTemplate->send_user,1))){
							// 		$external_userids[] = $et['external_userid'];
							// 		break;
							// 	}
							// }
							if(in_array($et['user_id'],json_decode($msgTemplate->send_user,1))){
								$external_userids[] = $et['external_userid'];
								break;
							}
						}
					}
					
					$msg['external_userid'] = $external_userids;
					$msg['text'] = ['content'=>$msgTemplate->text_content];
					if($msgTemplate->other_type == 2){//图片
						//$image_url_arr = explode("/", $msgTemplate->image_url);
						//$image_media_id = $etApp->media->uploadImage("./tmpImg/{$image_url_arr[count($image_url_arr)-1]}")["media_id"];
						$msg['image'] = ['media_id'=>$etApp->media->uploadImage($msgTemplate->image_url)['media_id']];
					}elseif($msgTemplate->other_type == 3){//图文
						$msg['link'] = [
							'title'=>$msgTemplate->link_title,
							'picurl'=>$msgTemplate->link_picurl,
							'desc'=>$msgTemplate->link_desc,
							'url'=>$msgTemplate->link_url
						];
					}elseif($msgTemplate->other_type == 4){//小程序
						//$miniprogram_pic_arr = explode("/", $msgTemplate->miniprogram_picurl);
						//$miniprogram_pic_media_id = $etApp->media->uploadImage("./tmpImg/{$miniprogram_pic_arr[count($miniprogram_pic_arr)-1]}")["media_id"];
						$msg['miniprogram'] = [
							'title'=>$msgTemplate->miniprogram_title,
							'pic_media_id'=>$etApp->media->uploadImage($msgTemplate->miniprogram_picurl)['media_id'],
							'appid'=>$msgTemplate->miniprogram_appid,
							'page'=>$msgTemplate->miniprogram_page
						];
					}
					
					$messageRes = $etApp->external_contact_message->submit($msg);
					if($messageRes['errcode'] == 0){
						$msgTemplate->status = 1;
						$msgTemplate->msgid = $messageRes['msgid'];
						$msgTemplate->save();
					}else{
						$msgTemplate->status = 2;
						$msgTemplate->save();
					}
				}
				sendSuccess('操作成功');
			}else{
				sendError('操作失败');
			}
		}
		return $this->show();
	}
	
	public function msg_result(){
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$msgid = \Request::get(1);
		$msgResult = $etApp->external_contact_message->get($msgid?$msgid:'');
		$hasSent = [];
		$hasSentUser = [];
		$notSent = [];
		$notSentUser = [];
		foreach($msgResult['detail_list'] as $detaillist){
			if($detaillist['status'] == 1 && !in_array($detaillist['external_userid'],$hasSent)){
				$hasSent[] = $detaillist['external_userid'];
				$hasSentUser[] = (new Model('qy_externalcontact_list'))->find(['wid'=>$wid,'external_userid'=>$detaillist['external_userid']])->get_model_array();
			}else if($detaillist['status'] == 0 && !in_array($detaillist['external_userid'],$notSent) && !in_array($detaillist['external_userid'],$hasSent)){
				$notSent[] = $detaillist['external_userid'];
				$notSentUser[] = (new Model('qy_externalcontact_list'))->find(['wid'=>$wid,'external_userid'=>$detaillist['external_userid']])->get_model_array();
			}
		}
		$this->assign("hasSentUser", $hasSentUser);
		$this->assign("notSentUser", $notSentUser);
		return $this->show();
	}
	
	public function select_tag(){
		$wid = Session::get('wid');
		$etTagArr = (new Model('qy_externalcontact_tag'))->where(['wid'=>$wid])->list_all_array();
		foreach ($etTagArr as $key => $value) {
			$count += count(json_decode($value['tags'],1));
		}
		$this->assign("etTagArr", $etTagArr);
		$this->assign("count",$count);
		return $this->show();
	}
	
	public function select_user(){
		$wid = Session::get('wid');
		if(\Request::get('username')){
			$where['name@~'] = \Request::get('username');
		}
		$where['wid'] = $wid;
		$userList = (new Model('qy_user_list'))->where($where)->list_all_array();
		$this->assign("userList", $userList);
		$this->assign("count", count($userList));
		$this->assign("username", \Request::get('username'));
		return $this->show();
	}
	
	public function select_group_chat(){
		$wid = Session::get('wid');
		$groupchatList = (new Model('qy_et_groupchat'))->where(['wid'=>$wid])->list_all_array();
		$this->assign("count", count($groupchatList));
		$this->assign("groupchatList", $groupchatList);
		return $this->show();
	}
	
	public function contact_way(){
		$wid = Session::get('wid');
		$contactWay = new Model('qy_et_contact_way');
		//name 模糊查询
		$name = $_GET['name'];
		if(trim($name)!=''){
			$where['name@~'] = $name;	
		}
		$where['wid'] = $wid;
		$where['is_auto_pull_group'] = 0;
		$p = new \Pagination();		
		$res = $p->model_list($contactWay->where($where)->order('id desc'));
		foreach($res as $k=>$v){
			$res[$k]->users = json_decode($v->users,1);
		}
		
		/**$h = Helper::getInstance();
		$startDate = date('Y-m-d', strtotime('-1 week'));
		$endDate = date('Y-m-d', strtotime('-1 day'));
		$dateRange = $h->getDateRange($startDate,$endDate);
		$statistics_date = json_encode($dateRange);
		$statistics_data = [];
		foreach($dateRange as $dates){
			$add_num = (new Model('qy_et_contact_way_statistics'))->where(['wid'=>$wid,'ctime'=>strtotime($dates)])->sum('add_num');
			$statistics_data[] = $add_num?$add_num:0;
		}
		//近一周各渠道新增客户数
		$week_add_num = (new Model('qy_et_contact_way_statistics'))->where(
		[
			'wid'      => $wid,
			'ctime@>=' => strtotime($startDate),
			'ctime@<=' => strtotime($endDate),
		])->sum('add_num');*/

		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("name", $name);
		$this->assign("h", Helper::getInstance());
		/**$this->assign("startDate", $startDate);
		$this->assign("endDate", $endDate);
		$this->assign("statistics_date", $statistics_date);
		$this->assign("statistics_data", json_encode($statistics_data));
		$this->assign("week_add_num", $week_add_num?$week_add_num:0);*/
		return $this->show();
	}
	
	public function contact_way_statistics(){
		$wid = Session::get('wid');
		$h = Helper::getInstance();
		$startDate = date('Y-m-d', strtotime('-1 week'));
		$endDate = date('Y-m-d', strtotime('-1 day'));
		$dateRange = $h->getDateRange($startDate,$endDate);
		$statistics_date = json_encode($dateRange);
		$statistics_data = [];
		foreach($dateRange as $dates){
			$add_num = (new Model('qy_et_contact_way_statistics'))->where(['wid'=>$wid,'ctime'=>strtotime($dates)])->sum('add_num');
			$statistics_data[] = $add_num?$add_num:0;
		}
		//近一周各渠道新增客户数
		$week_add_num = (new Model('qy_et_contact_way_statistics'))->where(
		[
			'wid'      => $wid,
			'ctime@>=' => strtotime($startDate),
			'ctime@<=' => strtotime($endDate),
		])->sum('add_num');

		$this->assign("startDate", $startDate);
		$this->assign("endDate", $endDate);
		$this->assign("statistics_date", $statistics_date);
		$this->assign("statistics_data", json_encode($statistics_data));
		$this->assign("week_add_num", $week_add_num?$week_add_num:0);
		return $this->show();
	}
	
	public function download_qrcode(){
		$id = \Request::get(1);
		$contactWay = (new Model('qy_et_contact_way'))->find($id);
		//设置头信息
		header('Content-Disposition:attachment;filename='.$contactWay->name.'.png');
		header('Content-Length:' . filesize($contactWay->qr_code));
		//读取文件并写入到输出缓冲
		readfile($contactWay->qr_code);
	}
	
	public function get_contact_way_statistics(){
		setApi();
		$wid = Session::get('wid');
		$h = Helper::getInstance();
		if($_POST['type']){
			if($_POST['type'] == 'one_week'){
				$startDate = date('Y-m-d', strtotime('-1 week'));
				$endDate = date('Y-m-d', strtotime('-1 day'));
			}elseif($_POST['type'] == 'two_week'){
				$startDate = date('Y-m-d', strtotime('-2 week'));
				$endDate = date('Y-m-d', strtotime('-1 day'));
			}elseif($_POST['type'] == 'one_month'){
				$startDate = date('Y-m-d', strtotime('-1 month'));
				$endDate = date('Y-m-d', strtotime('-1 day'));
			}
		}else{
			$startDate =  $_POST['startDate'];
			$endDate = $_POST['endDate'];
		}
		
		$dateRange = $h->getDateRange($startDate,$endDate);
		$statistics_date = $dateRange;
		$statistics_data = [];
		foreach($dateRange as $dates){
			$add_num = (new Model('qy_et_contact_way_statistics'))->where(['wid'=>$wid,'ctime'=>strtotime($dates)])->sum('add_num');
			$statistics_data[] = $add_num?$add_num:0;
		}
		$data = [
			'startDate'=>$startDate,
			'endDate'=>$endDate,
			'statistics_date'=>$statistics_date,
			'statistics_data'=>$statistics_data,
		];
		sendSuccess('获取成功',$data);
	}
	
	public function add_contact_way(){
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$contactWay = new Model('qy_et_contact_way');
		if(is_post()){
			setApi();
			if(!$_POST['checkUser']){
				sendError('请添加使用人员');
			}
			if($_POST['auto_label'] && !$_POST['checkLable']){
				sendError('请添加标签');
			}
			$users = explode(',',$_POST['checkUser']);

			if(count($users) == 1){
				$type = 1;
			}elseif(count($users) > 1){
				$type = 2;
			}

			$scene = 2;//2-通过二维码联系
			$maxId = (new Model('qy_et_contact_way'))->max('id');
			$state = $maxId + 1;//企业自定义的state参数，用于区分不同的添加渠道
			// sendError(json_encode(Helper::get_userid($users)));
			$config = [
			   'remark' => $_POST['bz'],//联系方式的备注信息
			   'skip_verify' => $_POST['skip_verify']?true:false,//外部客户添加时是否无需验证
			   'state' => $state,
			   // 'user' => $users,
			   'user' => Helper::get_userid($users),
			];

			$createRes = $etApp->contact_way->create($type, $scene, $config);
			if($createRes['errcode'] == 0){
				$config_id = $createRes['config_id'];
				$getContactWay = $etApp->contact_way->get($config_id)['contact_way'];
				$contactWay->wid = $wid;
				$contactWay->name = $_POST['name'];
				$contactWay->skip_verify = $_POST['skip_verify'];
				$contactWay->state = $state;
				$contactWay->users = json_encode($users,320);
				$contactWay->type = $type;
				$contactWay->bz = $_POST['bz'];
				$contactWay->config_id = $config_id;
				$contactWay->qr_code = $getContactWay['qr_code'];
				$contactWay->auto_label = $_POST['auto_label']?1:0;
				$contactWay->select_label = json_encode(explode(',',$_POST['checkLable']),320);
				$contactWay->auto_welcome_msg = $_POST['auto_welcome_msg']?1:0;
				$contactWay->text_content = $_POST['text_content'];
				$contactWay->other_type = $_POST['shareType'];
				$contactWay->image_url = $_POST['image'];
				$image_url_arr = explode("/", $_POST['image']);
				$contactWay->image_media_id = $etApp->media->uploadImage("./tmpImg/{$image_url_arr[count($image_url_arr)-1]}")["media_id"];
				$contactWay->link_title = $_POST['link_title'];
				$contactWay->link_picurl = $_POST['link_pic'];
				$contactWay->link_desc = $_POST['link_desc'];
				$contactWay->link_url = $_POST['link_url'];
				$contactWay->miniprogram_title = $_POST['miniprogram_title'];
				$contactWay->miniprogram_name = $_POST['miniprogram_name'];
				$contactWay->miniprogram_url = $_POST['miniprogram_pic'];
				$miniprogram_pic_arr = explode("/", $_POST['miniprogram_pic']);
				$contactWay->miniprogram_pic_media_id = $etApp->media->uploadImage("./tmpImg/{$miniprogram_pic_arr[count($miniprogram_pic_arr)-1]}")["media_id"];
				$contactWay->miniprogram_appid = $_POST['miniprogram_appid'];
				$contactWay->miniprogram_page = $_POST['miniprogram_page'];
				$contactWay->ctime = date('Y-m-d H:i:s');
				$contactWay->save();
				sendSuccess('操作成功');
			}else{
				sendError('操作失败');
			}
		}
		$this->assign("contactWay", $contactWay);
		return $this->show();
	}
	
	public function edit_contact_way(){
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$id = \Request::get(1);
		if($id){
			$contactWay = (new Model('qy_et_contact_way'))->find($id);
		}else{
			die('缺少必要参数');
		}
		if(is_post()){
			setApi();
			if(!$_POST['checkUser']){
				sendError('请添加使用人员');
			}
			if($_POST['auto_label'] && !$_POST['checkLable']){
				sendError('请添加标签');
			}
			$contactWay->name = $_POST['name'];
			$contactWay->auto_label = $_POST['auto_label']?1:0;
			$contactWay->select_label = json_encode(explode(',',$_POST['checkLable']),320);
			$contactWay->auto_welcome_msg = $_POST['auto_welcome_msg']?1:0;
			$contactWay->text_content = $_POST['text_content'];
			$contactWay->other_type = $_POST['shareType'];
			$contactWay->image_url = $_POST['image'];
			$image_url_arr = explode("/", $_POST['image']);
			$contactWay->image_media_id = $etApp->media->uploadImage("./tmpImg/{$image_url_arr[count($image_url_arr)-1]}")["media_id"];
			$contactWay->link_title = $_POST['link_title'];
			$contactWay->link_picurl = $_POST['link_pic'];
			$contactWay->link_desc = $_POST['link_desc'];
			$contactWay->link_url = $_POST['link_url'];
			$contactWay->miniprogram_title = $_POST['miniprogram_title'];
			$contactWay->miniprogram_name = $_POST['miniprogram_name'];
			$contactWay->miniprogram_url = $_POST['miniprogram_pic'];
			$miniprogram_pic_arr = explode("/", $_POST['miniprogram_pic']);
			$contactWay->miniprogram_pic_media_id = $etApp->media->uploadImage("./tmpImg/{$miniprogram_pic_arr[count($miniprogram_pic_arr)-1]}")["media_id"];
			$contactWay->miniprogram_appid = $_POST['miniprogram_appid'];
			$contactWay->miniprogram_page = $_POST['miniprogram_page'];
			$contactWay->save();
			
			$users = explode(',',$_POST['checkUser']);
			$configId = $contactWay->config_id;
			$config = [
			   'remark' => $_POST['bz'],
			   'skip_verify' => $_POST['skip_verify']?true:false,
			   'user' => Helper::get_userid($users)
			];
			$updateRes = $etApp->contact_way->update($configId, $config);
			if($updateRes['errcode'] == 0){
				$getContactWay = $etApp->contact_way->get($contactWay->config_id)['contact_way'];
				$contactWay->skip_verify = $_POST['skip_verify'];
				$contactWay->users = json_encode($users,320);
				$contactWay->bz = $_POST['bz'];
				$contactWay->qr_code = $getContactWay['qr_code'];
				$contactWay->save();
				sendSuccess('操作成功');
			}else{
				sendError('操作失败');
			}
		}
		$this->assign("contactWay", $contactWay);
		$this->assign("h", Helper::getInstance());
		return $this->show();
	}
	
	public function del_contact_way(){
		setApi();
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$id = $_POST['id'];
		if($id){
			$contactWay = (new Model('qy_et_contact_way'))->find($id);
		}else{
			sendError('参数错误');
		}
		$configId = $contactWay->config_id;
		$deleteRes = $etApp->contact_way->delete($configId);
		if($deleteRes['errcode'] == 0){
			$contactWay->delete();
			sendSuccess('操作成功');
		}else{
			sendError('操作失败 '.$deleteRes['errmsg']);
		}
		
	}
	
	public function contact_way_statistic(){
		return $this->show();
	}
	
	public function del_follow_user_record(){
		$wid = Session::get('wid');
		$record = new Model('qy_del_follow_user_record');
		$where['wid'] = $wid;
		$p = new \Pagination();		
		$res = $p->model_list($record->where($where)->order('id desc'));
		foreach($res as $k=>$v){
			$et = (new Model('qy_externalcontact_list'))->find(['wid'=>$v->wid,'user_id'=>$v->user_id,'external_userid'=>$v->external_userid]);
			$res[$k]->tags = json_decode($et->tags_info,1);
			//$res[$k]->follow_user = json_decode($v->follow_user,1);
		}
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("h", Helper::getInstance());
		return $this->show();
	}
}