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

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

class Reply extends BaseAdmin
{	
    public function quick_reply(){
		$wid = Session::get('wid');
		$quickReply = new Model('qy_quick_reply_list');
		//name 模糊查询
		$name = $_GET['name'];
		if(trim($name)!=''){
			$where['name@~'] = $name;	
		}
		//类型查询
		$type = $_GET['type'];
		if(trim($type)!=''){
			$where['type'] = $type;
		}
		$where['wid'] = $wid;
		$p = new \Pagination();		
		$res = $p->model_list($quickReply->where($where)->order('id desc'));
		foreach($res as $k=>$v){
			if($v->type == 1){
				$typeMsg = '文本';
			}elseif($v->type == 2){
				$typeMsg = '图片';
			}elseif($v->type == 3){
				$typeMsg = '视频';
			}elseif($v->type == 4){
				$typeMsg = '文件';
			}elseif($v->type == 5){
				$typeMsg = '链接';
			}
			$res[$k]->typeMsg = $typeMsg;
		}
		$h = Helper::getInstance();
		$replyConfig = (new Model('qy_reply_config'))->find(['wid'=>$wid]);
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$toolbarUrl = $h->get_http_server_name().'/Addons/QyWechat/H5/Reply/index.html?corp_id='.$qyConfig->corp_id.'&agent_id='.$replyConfig->agent_id;
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("name", $name);
		$this->assign("type", $type);
		$this->assign("toolbarUrl", $toolbarUrl);
		return $this->show();
	}

	public function add_quick_reply(){
		$wid = Session::get('wid');
		$quickReply = new Model('qy_quick_reply_list');
		if(\Request::get(1)){
			$quickReply->find(\Request::get(1));
		}
		if(is_post()){
			setApi();
			if(!$quickReply->id){
				$quickReply->wid = $wid;
				$quickReply->ctime = date('Y-m-d H:i:s');
			}
			$quickReply->name = $_POST['name'];
			$quickReply->type = $_POST['shareType'];
			$quickReply->groupid = json_encode(explode(',',$_POST['selectedGroup']),320);
			$quickReply->text_content = $_POST['text_content'];
			$quickReply->pic_path = $_POST['pic'];
			$quickReply->video_path = $_POST['video_path'];
			$quickReply->video_name = $_POST['video_name'];
			$quickReply->file_path = $_POST['file_path'];
			$quickReply->file_name = $_POST['file_name'];
			$quickReply->link_url = $_POST['link_url'];
			$quickReply->link_title = $_POST['link_title'];
			$quickReply->link_pic = $_POST['link_pic'];
			$quickReply->link_desc = $_POST['link_desc'];
			if($quickReply->save()){
				sendSuccess('操作成功');
			}
		}
		$group = new Model('qy_quick_reply_group');
		$grouparr = $group->where(array('wid'=>$wid))->map_array('keyid', 'name');
		$this->assign("quickReply", $quickReply);
		$this->assign("grouparr", $grouparr);
		return $this->show();
	}
	
	public function upload_file(){
		setApi();
		$path = './qy';
		$field = 'file';
		// sendSuccess($_FILES);
		if (!$_FILES[$field]) sendError('文件不存在');
		$ext = explode('.', $_FILES[$field]["name"]);
        $ext = $ext[count($ext) - 1];
        if (strtolower($ext) == 'php') {
            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;
			$result = upload_oss_qiniu($filePath);
			if($result['realUrl']){
				sendSuccess('上传成功',['filePath'=>$result['realUrl'],'fileName'=>$_FILES[$field]["name"]]);
			}else{
				sendError($result['msg']);
			}
		}else{
			sendError('上传失败');
		}
	}
	
	public function del_quick_reply(){
		setApi();
		$wid = Session::get('wid');
		$id = $_POST['id'];
		if($id){
			$quickReply = (new Model('qy_quick_reply_list'))->find($id);
		}else{
			sendError('参数错误');
		}
		$quickReply->delete();
		sendSuccess('操作成功');
	}
	
	public function quick_reply_steps(){
		$wid = Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$replyConfig = (new Model('qy_reply_config'))->find(['wid'=>$wid]);
		$this->assign("replyConfig", $replyConfig);
		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 quick_reply_set(){
		$wid = Session::get('wid');
		$config = (new Model('qy_reply_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();
	}
	
	public function group_manage(){
		$wid = Session::get('wid');
		$group = new Model('qy_quick_reply_group');
		//name 模糊查询
		$name = $_GET['name'];
		if(trim($name)!=''){
			$where['name@~'] = $name;	
		}
		$where['wid'] = $wid;
		$p = new \Pagination();		
		$res = $p->model_list($group->where($where)->order('sort'));
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("name", $name);
		return $this->show();
	}
	
	public function del_group(){
		setApi();
		$wid = Session::get('wid');
		$id = $_POST['id'];
		if($id){
			$group = (new Model('qy_quick_reply_group'))->find($id);
		}else{
			sendError('参数错误');
		}
		$group->delete();
		sendSuccess('操作成功');
	}
	
	public function add_group(){
		$wid = Session::get('wid');
		$group = new Model('qy_quick_reply_group');
		if(\Request::get(1)){
			$group->find(\Request::get(1));
		}
		if(is_post()){
			setApi();
			if(!$group->id){
				$group->wid = $wid;
				$group->ctime = time();
			}
			$group->name = $_POST['name'];
			$group->sort = $_POST['sort'];
			$rs = $group->save();
			if($rs->id){
				$rs->keyid = 'C'.$rs->id.'J';
				$rs->save();
				sendSuccess('操作成功');
			}
		}
		$this->assign("group", $group);
		return $this->show();
	}
	
	public function select_group(){
		$wid = Session::get('wid');
		if(\Request::get('name')){
			$where['name@~'] = \Request::get('name');
		}
		$where['wid'] = $wid;
		$group = (new Model('qy_quick_reply_group'))->where($where)->order('sort')->list_all_array();
		$this->assign("group", $group);
		$this->assign("count", count($group));
		$this->assign("name", \Request::get('name'));
		return $this->show();
	}

	public function daoru_huashu(){
		$wid = Session::get('wid');
		if(is_post()){
			//引入excel组件
			header("Content-Type:application/json;charset=utf-8");
			require_once DOXCX_FRAME_PATH . '/fun/library/PHPExcel.php';
			require_once DOXCX_FRAME_PATH . "/fun/library/PHPExcel/IOFactory.php";
			require_once DOXCX_FRAME_PATH . '/fun/library/PHPExcel/Reader/Excel5.php';

			$fileName = $_POST['file_name'];
			$filePath = $_POST['file_path'];

			if(!$filePath){
				sendError('请上传表格');
			}

			$objReader = new \PHPExcel_Reader_Excel2007();
			$objPHPExcel = $objReader ->load($filePath);
			$data = $objPHPExcel->getActiveSheet()->toArray();

			$sheet = $objPHPExcel->getSheet(0);
			$highestRow = $sheet->getHighestRow(); // 取得总行数
			$highestColumn = $sheet->getHighestColumn(); // 取得总列数

			$contents = [];
			// sendSuccess('sssss',$data);
			// 重第六行开始读取
			for($j=6;$j<=count($data);$j++) {
				$content = $data[$j-1][0];//获取A列的值
				$fenzu = $data[$j-1][8];//获取B列的值;
				if($content){
					$contents[] = [$content,$fenzu];
				}
			}
			// // unlink($filePath);//删除文件
			// sendSuccess('sssss',$contents);
			// 
			$resdata = '';
			$ok = [];
			$error = [];
			foreach ($contents as $k => $val) {
				$quickReply = new Model('qy_quick_reply_list');
				if($val){
					$quickReply->wid = $wid;
					$quickReply->ctime = date('Y-m-d H:i:s');
					$quickReply->name = '-'; 
					$quickReply->type = 1;
					$quickReply->groupid = json_encode($this->get_group_keyid($val[1]));
					$quickReply->text_content = $val[0];
					// sendSuccess($quickReply->save());
					if($quickReply->save()){
						// sendSuccess('操作成功');
						$ok[] = $k+1; 
					}else{
						$error[] = $k+1;
					}

				}
			}
			if($error){
				sendSuccess('导入失败条目:'.implode(',', $error));
			}else{
				sendSuccess('操作成功');
			}
			
		}
		return $this->show();
	}

	public function huashu_download_excel(){
		$filePath = DOXCX_FRAME_PATH . '/Addons/QyWechat/View/static/reply/qiyehuashudaorumuban-v4.xlsx';
		//设置头信息
		header('Content-Disposition:attachment;filename=Excel企业话术导入模板 .xlsx');
		header('Content-Length:' . filesize($filePath));
		//读取文件并写入到输出缓冲
		readfile($filePath);
	}

	private function get_group_keyid($name=''){
		$result = [];
		$wid = Session::get('wid');
		$group = new Model('qy_quick_reply_group');
		if(!empty($name)){
			$namearr = explode(',', trim($name));
			foreach ($namearr as $namea) {
				if($group->has(['wid'=>$wid, 'name'=>trim($namea)])){
					$keyidm = $group->find(['wid'=>$wid, 'name'=>trim($namea)]);
					$result[] = $keyidm->keyid;
				}else{
					$group->name = $namea;
					$group->wid = $wid;
					$group->ctime = time();
					$group->sort = 0;
					$rs = $group->save();
					// sendSuccess($rs);
					if($rs->id){
						$rs->keyid = 'C'.$rs->id.'J';
						$rs->save();
						$result[] = $rs->keyid;
					}
				}
			}		
		}
		return $result;
	}
	
}