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

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

class Moments extends BaseAdmin
{	
	public function pyq(){
		$wid = Session::get('wid');
		$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]->pyqurl = Helper::getInstance()->get_http_server_name().'/Addons/Moments/H5/Trace/entry-'.base64_encode($wid.'_'.$v->id).'.html';
		}
		$this->assign('tj', $tj);
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		return $this->show();
	}

	public function quick_reply_steps(){
		$wid = Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$appConfig = (new Model('qy_moments_app_config'))->find(['wid'=>$wid]);
		$this->assign("appConfig", $appConfig);
		$this->assign("appPage", Helper::getInstance()->get_http_server_name().'/Addons/Moments/H5/AppPage.html?corp_id='.$qyConfig->corp_id);
		return $this->show();
	}
	
	public function quick_reply_set(){
		$wid = Session::get('wid');
		$config = (new Model('qy_moments_app_config'))->find(['wid'=>$wid]);
		if(is_post()){
			setApi();
			$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
			$QyWechatApi = QyWechatApi::getInstance();
			$agentApp = $QyWechatApi->get_qy_agent_app($qyConfig->corp_id,$_POST['agent_id'],$_POST['secret']);
			$appInfo = $agentApp->agent->get($_POST['agent_id']);
			if($appInfo['errcode'] == 0){
				if(!$config->id){
					$config->wid = $wid;
					$config->ctime = date('Y-m-d H:i:s');
				}
				$config->agent_id = $_POST['agent_id'];
				$config->secret = $_POST['secret'];
				$config->name = $appInfo['name'];
				$config->square_logo_url = $appInfo['square_logo_url'];
				$config->description = $appInfo['description'];
				if($config->save()){
					sendSuccess('操作成功',$config);
				}else{
					sendError('数据库操作失败');
				}
			}else{
				sendError('操作失败:请检查配置');
			}
		}
		$this->assign("config", $config);
		return $this->show();
	}
}