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

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

class Trace extends \BaseController
{
	public function entry(){
		$getData = base64_decode(\Request::get(1));
		$wid =  explode("_", $getData)[0];
		$user_id =  explode("_", $getData)[1];
		if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'wxwork') !== false){
			//企业微信
			$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
			$appConfig = (new Model('qy_moments_app_config'))->find(['wid'=>$wid]);
			if($_GET['code']){
				$code = $_GET['code'];
				$app = QyWechatApi::getInstance()->get_qy_agent_app($qyConfig->corp_id,$appConfig->agent_id,$appConfig->secret);
				$accessToken = $app->access_token;
				$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
				$url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$token.'&code='.$code;
				$resArr = json_decode(curlGet($url),1);
				$qyUser = (new Model('qy_user_list'))->find(['id'=>$user_id]);
				if($resArr['UserId'] != $qyUser->userid){
					$pyqUrl = Helper::getInstance()->get_http_server_name().'/Addons/Moments/H5/Trace/moment-'.base64_encode($wid.'_'.$user_id).'-see.html';
					\Redirect::to("{$pyqUrl}");
					return ;
				}
				$pyqUrl = Helper::getInstance()->get_http_server_name().'/Addons/Moments/H5/Trace/moment-'.base64_encode($wid.'_'.$user_id).'.html';
				\Redirect::to("{$pyqUrl}");
				return;
			}else{
				$redirect_uri = urlencode(Helper::getInstance()->get_http_server_name().'/Addons/Moments/H5/Trace/entry-'.base64_encode($wid.'_'.$user_id).'.html');
				$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$qyConfig->corp_id.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
				\Redirect::to("{$url}");
			}
		}
		$pyqUrl = Helper::getInstance()->get_http_server_name().'/Addons/Moments/H5/Trace/moment-'.base64_encode($wid.'_'.$user_id).'.html';
		\Redirect::to("{$pyqUrl}");
	}

	public function moment(){
		$getData = base64_decode(\Request::get(1));
		$wid =  explode("_", $getData)[0];
		$user_id =  explode("_", $getData)[1];
		$qyUser = (new Model('qy_user_list'))->find(['wid'=>$wid,'id'=>$user_id]);
		$userBackground = (new Model('qy_moments_user_background'))->find(['wid'=>$wid,'user_id'=>$user_id]);
		$res = (new Model('qy_moments_user_publish'))->where(['wid'=>$wid,'user_id'=>$user_id])->order('ctime desc')->list_all();
		$videos = [];
		foreach($res as $k=>$v){
			$res[$k]->pics = json_decode($v->pics,1);
			if($v->type == 3){
				$videos[] = ['id'=>$v->id,'video'=>$v->video];
			}
		}
		$this->assign('qyUser', $qyUser);
		$this->assign('userBackground', $userBackground);
		$this->assign('res', $res);
		$this->assign('videos', $videos);
		$this->assign('h', Helper::getInstance());
		if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'wxwork') !== false && \Request::get(2) != 'see'){
			//企业微信
			return $this->show('H5/Trace/pyq');
		}else{
			return $this->show('H5/Trace/see_pyq');
		}
	}
	
	public function replace_background(){
		setApi();
		$wid = \Request::get(1);
		$user_id = \Request::get(2);
		if(!$wid || !$user_id){
			sendError('缺少必要参数');
		}
		$path = 'qy';
		$field = 'file';
		$type = ["jpg","png","bmp","jpeg"];
		if (!$_FILES[$field]) sendError('文件不存在');
		$ext = explode('.', $_FILES[$field]["name"]);
        $ext = $ext[count($ext) - 1];
        if (!in_array(strtolower($ext),$type)) {
            sendError('文件后缀不允许');
        }
		// 创建文件夹
        try {
            mkdir($path);
        } catch (\Exception $e) {
            // 防止文件夹已存在
        }
		$path = $path . '/' . md5_file($_FILES[$field]['tmp_name']) . '.' . $ext;
        $saveImg = move_uploaded_file($_FILES[$field]['tmp_name'], $path);
		if($saveImg){
			$filePath = $saveImg ? $path : $saveImg;
			$filePath = Helper::getInstance()->get_http_server_name().'/'.$filePath;
			$userBackground = (new Model('qy_moments_user_background'))->find(['wid'=>$wid,'user_id'=>$user_id]);
			$userBackground->wid = $wid;
			$userBackground->user_id = $user_id;
			$userBackground->background = $filePath;
			$userBackground->save();
			sendSuccess('上传成功',$filePath);
		}else{
			sendError('上传失败');
		}
	}
	
	public function upload_pic(){
		setApi();
		$path = 'qy';
		$field = 'file';
		$type = ["jpg","png","bmp","jpeg"];
		if (!$_FILES[$field]) sendError('文件不存在');
		$ext = explode('.', $_FILES[$field]["name"]);
        $ext = $ext[count($ext) - 1];
        if (!in_array(strtolower($ext),$type)) {
            sendError('文件后缀不允许');
        }
		// 创建文件夹
        try {
            mkdir($path);
        } catch (\Exception $e) {
            // 防止文件夹已存在
        }
		$path = $path . '/' . md5_file($_FILES[$field]['tmp_name']) . '.' . $ext;
        $saveImg = move_uploaded_file($_FILES[$field]['tmp_name'], $path);
		if($saveImg){
			$filePath = $saveImg ? $path : $saveImg;
			$filePath = Helper::getInstance()->get_http_server_name().'/'.$filePath;
			sendSuccess('上传成功',$filePath);
		}else{
			sendError('上传失败');
		}
	}
	
	public function upload_video(){
		setApi();
		$path = 'qy';
		$field = 'file';
		$type = ["mp4","mov"];
		if (!$_FILES[$field]) sendError('文件不存在');
		$ext = explode('.', $_FILES[$field]["name"]);
        $ext = $ext[count($ext) - 1];
        if (!in_array(strtolower($ext),$type)) {
            sendError('文件后缀不允许');
        }
		// 创建文件夹
        try {
            mkdir($path);
        } catch (\Exception $e) {
            // 防止文件夹已存在
        }
		$path = $path . '/' . md5_file($_FILES[$field]['tmp_name']) . '.' . $ext;
        $saveImg = move_uploaded_file($_FILES[$field]['tmp_name'], $path);
		if($saveImg){
			$filePath = $saveImg ? $path : $saveImg;
			$filePath = Helper::getInstance()->get_http_server_name().'/'.$filePath;
			sendSuccess('上传成功',$filePath);
		}else{
			sendError('上传失败');
		}
	}
	
	public function publish_text(){
		$wid = \Request::get(1);
		$user_id = \Request::get(2);
		if(!$wid || !$user_id){
			die('缺少必要参数');
		}
		if(is_post()){
			setApi();
			$writing = $_POST['writing'];
			if(!$writing){
				sendError('不能空呀！');
			}
			$userPublish = new Model('qy_moments_user_publish');
			$userPublish->wid = $wid;
			$userPublish->user_id = $user_id;
			$userPublish->type = 1;
			$userPublish->writing = $writing;
			$userPublish->ctime = time();
			$userPublish->save();
			sendSuccess('操作成功');
		}
		$this->assign('wid', $wid);
		$this->assign('user_id', $user_id);
		return $this->show();
	}
	
	public function publish_pic(){
		$wid = \Request::get(1);
		$user_id = \Request::get(2);
		if(!$wid || !$user_id){
			die('缺少必要参数');
		}
		if(is_post()){
			setApi();
			$pics = $_POST['pics'];
			if(!count(json_decode($pics,1))){
				sendError('图片不能空呀！');
			}
			$userPublish = new Model('qy_moments_user_publish');
			$userPublish->wid = $wid;
			$userPublish->user_id = $user_id;
			$userPublish->type = 2;
			$userPublish->writing = $_POST['writing'];
			$userPublish->pics = $pics;
			$userPublish->ctime = time();
			$userPublish->save();
			sendSuccess('操作成功');
		}
		$this->assign('wid', $wid);
		$this->assign('user_id', $user_id);
		return $this->show();
	}
	
	public function publish_video(){
		$wid = \Request::get(1);
		$user_id = \Request::get(2);
		if(!$wid || !$user_id){
			die('缺少必要参数');
		}
		if(is_post()){
			setApi();
			$video = $_POST['video'];
			if(!$video){
				sendError('视频不能空呀！');
			}
			$userPublish = new Model('qy_moments_user_publish');
			$userPublish->wid = $wid;
			$userPublish->user_id = $user_id;
			$userPublish->type = 3;
			$userPublish->writing = $_POST['writing'];
			$userPublish->video = $video;
			$userPublish->ctime = time();
			$userPublish->save();
			sendSuccess('操作成功');
		}
		$this->assign('wid', $wid);
		$this->assign('user_id', $user_id);
		return $this->show();
	}
	
	public function publish_imagetext(){
		$wid = \Request::get(1);
		$user_id = \Request::get(2);
		if(!$wid || !$user_id){
			die('缺少必要参数');
		}
		if(is_post()){
			setApi();
			$link_url = $_POST['link_url'];
			if(!$link_url){
				sendError('链接不能空呀！');
			}
			$userPublish = new Model('qy_moments_user_publish');
			$userPublish->wid = $wid;
			$userPublish->user_id = $user_id;
			$userPublish->type = 4;
			$userPublish->writing = $_POST['writing'];
			$userPublish->link_url = $link_url;
			$userPublish->ctime = time();
			$userPublish->save();
			sendSuccess('操作成功');
		}
		$this->assign('wid', $wid);
		$this->assign('user_id', $user_id);
		return $this->show();
	}
	
	public function del_publish(){
		setApi();
		$id = $_POST['id'];
		$userPublish = (new Model('qy_moments_user_publish'))->find(['id'=>$id]);
		if($userPublish->id){
			$userPublish->delete();
			sendSuccess('操作成功');
		}else{
			sendError('操作失败');
		}
	}
	
}