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

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

class MessageSend extends BaseAdmin
{	
	public function message_send_set(){
		$wid = Session::get('wid');
		$config = (new Model('qy_message_send_config'))->find(['wid'=>$wid]);
		/**if(is_post()){
			setApi();
			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'];
			if($config->save()){
				sendSuccess('操作成功');
			}else{
				sendError('操作失败');
			}
		}*/
		$this->assign("config", $config);
		return $this->show();
	}

	public function upload_txt(){
		setApi();
		$field = 'file';
		if (!$_FILES[$field]) sendError('文件不存在');
		$ext = explode('.', $_FILES[$field]["name"]);
        $ext = $ext[count($ext) - 1];
        if (strtolower($ext) != 'txt') {
            sendError('上传文件不合法');
        }
		$path = './'.$_FILES[$field]["name"];
		if(!file_exists($path)){
			$saveImg = move_uploaded_file($_FILES[$field]['tmp_name'], $path);
			if($saveImg){
				$filePath = $saveImg ? $path : $saveImg;
				sendSuccess('上传成功',['filePath'=>$filePath,'fileName'=>$_FILES[$field]["name"]]);
			}else{
				sendError('上传失败');
			}	
		}else{
			 sendError('文件已存在');
		}
	}

	public function app_set(){
		$wid = Session::get('wid');
		$config = (new Model('qy_message_send_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();
	}
}