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

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

class QyWechat extends BaseAdmin
{	
    public function qy_set(){
		$wid = Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$h = Helper::getInstance();
		if(is_post()){
			setApi();
			if($qyConfig->try_post()){
				if(!$qyConfig->id && $qyConfig->is_real('corp_id')){
					sendError('绑定失败：企业已存在');
				}
				$QyWechatApi = QyWechatApi::getInstance();
				$app = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
				$externalcontactToken  = $app->access_token->getToken();
				if(!$externalcontactToken){
					sendError('绑定失败：请检查配置');
				}
				$app = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->user_secret);
				$userToken  = $app->access_token->getToken();
				if(!$userToken){
					sendError('绑定失败：请检查配置');
				}
				
				if(!$qyConfig->has_id()){
					$qyConfig->externalcontact_token = $h->getRandStr(15);
					$qyConfig->externalcontact_aes = $h->getRandStr(42);
					$qyConfig->user_tokent = $h->getRandStr(15);
					$qyConfig->user_aes = $h->getRandStr(42);
					$qyConfig->ctime = date("Y-m-d H:i:s");
				}
				$qyConfig->wid = $wid;
				if($qyConfig->save()){
					sendSuccess('绑定成功！');
				}else{
					sendError('操作失败！');
				}
			}
		}
		$this->assign("h", $h);
		$this->assign("qyConfig", $qyConfig);
		return $this->show();
	}	
}