<?php
/**
 * [WeEngine System] Copyright (c) 2014 WE7.CC
 * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
 */
defined('IN_IA') or exit('Access Denied');
$_W['page']['title'] = '发送客服消息 - 粉丝管理 - 粉丝管理';
$dos = array('keyword', 'fans', 'transmit', 'post', 'tpl', 'log', 'end');
$do = in_array($do, $dos) ? $do : 'fans';
define('ACTIVE_FRAME_URL', url('mc/fans/tpl'));
if($do == 'keyword') {
	if($_W['isajax']) {
		$condition = '';
		$key_word = trim($_GPC['key_word']);
		if(!empty($key_word)) {
			$condition = " AND content LIKE '%{$key_word}%' AND (module = 'news' OR module = 'cover')";
		} else {
			$condition = " AND (module = 'news' OR module = 'cover')";
		}

		$data = pdo_fetchall('SELECT content, module, rid FROM ' . tablename('rule_keyword') . " WHERE uniacid = :uniacid AND status != 0 " . $condition . ' ORDER BY uniacid DESC,displayorder DESC LIMIT 100', array(':uniacid' => $_W['uniacid']));
		$exit_da = array();
		if(!empty($data)) {
			foreach($data as $da) {
				$exit_da[] = array('content' => $da['content'], 'rid' => $da['rid']);
			}
		}
		exit(json_encode($exit_da));
	}
	exit('error');
}

if($do == 'fans') {
	$fanid = intval($_GPC['fanid']);
	$fans = pdo_fetch('SELECT acid,openid FROM ' . tablename('mc_mapping_fans') . ' WHERE uniacid = :uniacid AND fanid = :fanid', array(':uniacid' => $_W['uniacid'], ':fanid' => $fanid));
	template('mc/notice');
	exit();
}

if($do == 'post') {
	$msgtype = trim($_GPC['msgtype']);
	$acid = $_W['acid'];
	$send['touser'] = trim($_GPC['openid']);
	$send['msgtype'] = $msgtype;
	$fans = pdo_fetch('SELECT salt,acid,openid FROM ' . tablename('mc_mapping_fans') . ' WHERE acid = :acid AND openid = :openid', array(':acid' => $acid, ':openid' => $send['touser']));
	if($msgtype == 'text') {
		$send['text'] = array('content' => urlencode($_GPC['content']));
	} elseif($msgtype == 'image') {
		$send['image'] = array('media_id' => $_GPC['media_id']);
	} elseif($msgtype == 'voice') {
		$send['voice'] = array('media_id' => $_GPC['media_id']);
	} elseif($msgtype == 'video') {
		$send['video'] = array(
			'media_id' => $_GPC['media_id'],
			'thumb_media_id' => $_GPC['thumb_media_id'],
			'title' => urlencode($_GPC['title']),
			'description' => urlencode($_GPC['description'])
		);
	} elseif($msgtype == 'music') {
		$send['music'] = array(
			'musicurl' => tomedia($_GPC['musicurl']),
			'hqmusicurl' => tomedia($_GPC['hqmusicurl']),
			'title' => urlencode($_GPC['title']),
			'description' => urlencode($_GPC['description']),
			'thumb_media_id' => $_GPC['thumb_media_id'],
		);
	} elseif($msgtype == 'news') {
		$rid = intval($_GPC['ruleid']);
		$rule = pdo_fetch('SELECT module,name FROM ' . tablename('rule') . ' WHERE id = :rid', array(':rid' => $rid));
		if(empty($rule)) {
			exit(json_encode(array('status' => 'error', 'message' => '没有找到指定关键字的回复内容，请检查关键字的对应规则')));
		}
		$idata = array('rid' => $rid, 'name' => $rule['name'], 'module' => $rule['module']);
		$module = $rule['module'];
		$reply = pdo_fetchall('SELECT * FROM ' . tablename($module . '_reply') . ' WHERE rid = :rid', array(':rid' => $rid));
		if($module == 'cover') {
			$idata['do'] = $reply[0]['do'];
			$idata['cmodule'] = $reply[0]['module'];
		}
		if(!empty($reply)) {
			foreach($reply as $c) {
				$row = array();
				$row['title'] = urlencode($c['title']);
				$row['description'] = urlencode($c['description']);
				!empty($c['thumb']) && ($row['picurl'] = tomedia($c['thumb']));

				if(strexists($c['url'], 'http://') || strexists($c['url'], 'https://')) {
					$row['url'] = $c['url'];
				} else {
					$pass['time'] = TIMESTAMP;
					$pass['acid'] = $fans['acid'];
					$pass['openid'] = $fans['openid'];
					$pass['hash'] = md5("{$fans['openid']}{$pass['time']}{$fans['salt']}{$_W['config']['setting']['authkey']}");
					$auth = base64_encode(json_encode($pass));
					$vars = array();
					$vars['__auth'] = $auth;
					$vars['forward'] = base64_encode($c['url']);
					$row['url'] =  $_W['siteroot'] . 'app/' . murl('auth/forward', $vars);
				}
				$news[] = $row;
			}
			$send['news']['articles'] = $news;
		} else {
			$idata = array();
			$send['news'] = '';
		}
	}

	if($acid) {
		$acc = WeAccount::create($acid);
		$data = $acc->sendCustomNotice($send);
		if(is_error($data)) {
			exit(json_encode(array('status' => 'error', 'message' => $data['message'])));
		} else {
						$account = account_fetch($acid);
			$message['from'] = $_W['openid'] = $send['touser'];
			$message['to'] = $account['original'];
			if(!empty($message['to'])) {
				$sessionid = md5($message['from'] . $message['to'] . $_W['uniacid']);
				load()->classs('wesession');
				load()->classs('account');
				session_id($sessionid);
				WeSession::start($_W['uniacid'], $_W['openid'], 300);
				$processor = WeUtility::createModuleProcessor('chats');
				$processor->begin(300);
			}

			if($send['msgtype'] == 'news') {
				$send['news'] = $idata;
			}
						pdo_insert('mc_chats_record',array(
				'uniacid' => $_W['uniacid'],
				'acid' => $acid,
				'flag' => 1,
				'openid' => $send['touser'],
				'msgtype' => $send['msgtype'],
				'content' => iserializer($send[$send['msgtype']]),
				'createtime' => TIMESTAMP,
			));
			exit(json_encode(array('status' => 'success', 'message' => '消息发送成功')));
		}
		exit();
	}
}

if($do == 'tpl') {
	$fanid = intval($_GPC['id']);
	$fans = pdo_fetch('SELECT fanid,acid,uid,tag,openid FROM ' . tablename('mc_mapping_fans') . ' WHERE uniacid = :uniacid AND fanid = :id', array(':uniacid' => $_W['uniacid'], ':id' => $fanid));
	$account = account_fetch($fans['acid']);
	if(empty($account['original'])) {
		message('发送客服消息前,您必须完善公众号原始ID', url('account/post', array('acid' => $fans['acid'], 'uniacid' => $_W['uniacid'])));
	}
	$maxid = pdo_fetchcolumn('SELECT id FROM ' . tablename('mc_chats_record') . ' WHERE acid=:acid AND openid = :openid  ORDER BY id DESC LIMIT 1', array(':acid' => $fans['acid'], ':openid' => $fans['openid']));
	$maxid = ($maxid - 5) > 0 ? ($maxid - 5) : 0;
	if(!empty($fans)) {
		if (is_base64($fans['tag'])){
			$fans['tag'] = base64_decode($fans['tag']);
		}
		if (is_serialized($fans['tag'])) {
			$fans['tag'] = iunserializer($fans['tag']);
		}
	}
	if(!empty($fans['tag']['nickname'])) {
		$nickname = $fans['tag']['nickname'];
	} else {
		$nickname = $fans['openid'];
	}
	template('mc/notice');
}

if($do == 'log') {
	$fanid = intval($_GPC['fanid']);
	$id = intval($_GPC['id']);
	$type = trim($_GPC['type']) ? trim($_GPC['type']) : 'asc';
	$fans = pdo_fetch('SELECT fanid,acid,openid,tag FROM ' . tablename('mc_mapping_fans') . ' WHERE uniacid = :uniacid AND fanid = :id', array(':uniacid' => $_W['uniacid'], ':id' => $fanid));
	if(!empty($fans)) {
		if (is_base64($fans['tag'])){
			$fans['tag'] = base64_decode($fans['tag']);
		}
		if (is_serialized($fans['tag'])) {
			$fans['tag'] = iunserializer($fans['tag']);
		}
		if(!empty($fans['tag']['headimgurl'])) {
			$avatar = rtrim($fans['tag']['headimgurl'], '0');
		} else {
			$avatar = 'resource/images/noavatar_middle.gif';
		}
	}
	if($type == 'asc') {
		$data = pdo_fetchall('SELECT * FROM ' . tablename('mc_chats_record') . ' WHERE acid=:acid AND openid = :openid AND id > :id ORDER BY id ASC LIMIT 5', array(':acid' => $fans['acid'], ':openid' => $fans['openid'], ':id' => $id), 'id');
	} else {
		$data = pdo_fetchall('SELECT * FROM ' . tablename('mc_chats_record') . ' WHERE acid=:acid AND openid = :openid AND id < :id ORDER BY id DESC LIMIT 5', array(':acid' => $fans['acid'], ':openid' => $fans['openid'], ':id' => $id), 'id');
	}
	ksort($data);
	if(!empty($data)) {
		$str = '';
		foreach($data as &$da) {
			$da['content'] = is_serialized($da['content']) ? iurldecode(iunserializer($da['content'])) : iurldecode($da['content']);
			if($da['flag'] == 2) {
				if($da['msgtype'] == 'text') {
					$str .= tpl_chats_log(emotion($da['content']), $da['createtime']);
				} elseif($da['msgtype'] == 'image') {
					$imageurl = tomedia($da['content'], true);
					$content = '<a href="'.$imageurl.'" target="_blank"><img src="'.$imageurl.'" width="200"></a>';
					$str .= tpl_chats_log($content, $da['createtime']);
				} elseif($da['msgtype'] == 'link') {
					$content = '<a href="'.$da['content'].'" target="_blank">'.$da['content'].'</a>';
					$str .= tpl_chats_log($content, $da['createtime']);
				} elseif($da['msgtype'] == 'location') {
					$content = '<a target="_blank" href="http://st.map.soso.com/api?size=800*600&center='.$da['content']['location_y'].','.$da['content']['location_x'].'&zoom='.$da['content']['scale'].'&markers='.$da['content']['location_y'].','.$da['content']['location_x'].'"><img src="data:image/jpg;base64, "></a>';
					$str .= tpl_chats_log($content, $da['createtime']);
				}
			} else {
				if($da['msgtype'] == 'text') {
					$str .= tpl_chats_log(emotion($da['content']['content']), $da['createtime'], 1);
				} elseif($da['msgtype'] == 'image') {
					$image = media2local($da['content']['media_id']);
					$content = '<a href="'.$image.'" target="_blank"><img src="'.$image.'" width="200"></a>';
					$str .= tpl_chats_log($content, $da['createtime'], 1);
				} elseif($da['msgtype'] == 'voice') {
					$image = media2local($da['content']['media_id']);
					$content = '<a href="'.$image.'" target="_blank"><i class="fa fa-bullhorn"></i> 语音消息</a>';
					$str .= tpl_chats_log($content, $da['createtime'], 1);
				} elseif($da['msgtype'] == 'music') {
					$music = tomedia($da['content']['hqmusicurl']);
					if(empty($music)) {
						$music = tomedia($da['content']['musicurl']);
					}
					$content = '<a href="'.$music.'" target="_blank"><i class="fa fa-music"></i> 音乐消息</a>';
					$str .= tpl_chats_log($content, $da['createtime'], 1);
				} elseif($da['msgtype'] == 'video') {
					$video = media2local($da['content']['media_id']);
					$content = '<a href="'.$video.'" target="_blank"><i class="fa fa-video-camera"></i> 视频消息</a>';
					$str .= tpl_chats_log($content, $da['createtime'], 1);
				} elseif($da['msgtype'] == 'news') {
					if($da['content']['module'] == 'news') {
						$url = url('platform/reply/post', array('m' => 'news', 'rid' => $da['content']['rid']));
					} elseif($da['content']['module'] == 'cover') {
						if(in_array($da['content']['cmodule'], array('mc', 'site', 'card'))) {
							$url = url('platform/cover/' . $da['content']['cmodule']);
						} else {
							$eid = pdo_fetchcolumn('SELECT eid FROM ' . tablename('modules_bindings') . ' WHERE module = :m AND do = :do AND entry = :entry', array(':m' => $da['content']['cmodule'], ':do' => $da['content']['do'], ':entry' => 'cover'));
							$li['url'] = url('platform/cover/', array('eid' => $eid));
						}
					}
					$content = '<a href="'. $url .'" target="_blank"><i class="fa fa-file-image-o"></i> 图文消息：' . $da['content']['name'] . '</a>';
					$str .= tpl_chats_log($content, $da['createtime'], 1);
				}
			}
		}
		if($type == 'asc') {
			$exit = json_encode(array('code' => 1, 'str' => $str, 'id' => max(array_keys($data))));
		} else {
			$exit = json_encode(array('code' => 1, 'str' => $str, 'id' => min(array_keys($data))));
		}
	} else {
		$exit = json_encode(array('code' => 2, 'str' => '', 'id' => $id));
	}
	echo $exit;
	exit();
}

if($do == 'end') {
	$fanid = intval($_GPC['fanid']);
	$fans = pdo_fetch('SELECT fanid,acid,openid FROM ' . tablename('mc_mapping_fans') . ' WHERE uniacid = :uniacid AND fanid = :id', array(':uniacid' => $_W['uniacid'], ':id' => $fanid));
	$account = account_fetch($fans['acid']);
	$message['from'] = $_W['openid'] = $fans['openid'];
	$message['to'] = $account['original'];
	if(!empty($message['to'])) {
		$sessionid = md5($message['from'] . $message['to'] . $_W['uniacid']);
		load()->classs('wesession');
		load()->classs('account');
		session_id($sessionid);
		WeSession::start($_W['uniacid'], $_W['openid'], 300);
		$processor = WeUtility::createModuleProcessor('chats');
		$processor->end();
	}
	if(!empty($_GPC['from'])) {
		$url = base64_decode($_GPC['from']);
	} else {
		$url = url('mc/fans/', array('acid' => $fans['acid']));
	}
	header('Location:' . $url);
	exit();
}

function iurldecode($str) {
	if(!is_array($str)) {
		return urldecode($str);
	}
	foreach($str as $key => $val) {
		$str[$key] = iurldecode($val);
	}
	return $str;
}
function tpl_chats_log($content, $time, $flag = 2) {
	global $avatar;
	if($flag == 2) {
		$str = '<div class="pull-left col-lg-12 col-md-12 col-sm-12 col-xs-12">' .
					'<div class="pull-left">' .
						'<img src="' . $avatar . '" width="35"><br>' .
					'</div>' .
					'<div class="alert alert-info pull-left infol">' .
						$content . '<br>' . date('m-d H:i:s', $time) .
					'</div>' .
					'<div style="clear:both"></div>' .
				'</div>'.
				'<div style="clear:both"></div>';
	} else {
		$str = '<div class="pull-left col-lg-12 col-md-12 col-sm-12 col-xs-12">' .
					'<div class="pull-right">' .
						'<img src="resource/images/gw-wx.gif" width="35" style="border:2px solid #418BCA;border-radius:5px"><br>' .
					'</div>' .
					'<div class="alert alert-info pull-right infor">' .
						$content . '<br>' .  date('m-d H:i:s', $time) .
					'</div>' .
					'<div style="clear:both"></div>' .
				'</div>'.
				'<div style="clear:both"></div>';
	}
	return $str;
}
