<?php
// ini_set("display_errors",1);
header("P3P: CP=CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR");
header("Content-type: text/html; charset=utf-8");
define("IN_OK",true);
require_once('include/global.php');
require_once($www_path."/lib/common/ip.class.php");
require_once($www_path."/lib/common/place_data.php");
require_once($www_path."/lib/common/Visitor.class.php");
require_once($www_path."/include/memcache.webClient.class.php");

$pcClient = new PcClient();
$pcClient->main();
/**
* PC访客端
*/
class PcClient
{
	public $company_id;//公司id
	public $arg;//公司arg
	public $style;//风格编号
	public $style_id;//风格id
	public $comInfo;//redis中公司相关信息
	public $company_config;//风格下详细设置
	public $company_config_no_style;//风格下详细设置
	public $redis;//redis操作对象
	public $lnkopentime;//访客端打开，服务器时间
	public $http;//协议
	public $cloud_service;
	public $alias;
	public $localArgs;//局部变量，部分方法调用
	public $cfg;
	public $tpl;
	public $talkpage;//咨询页面

	function __construct(){
		global $cfg,$tpl;
		$this->cfg = $cfg;
		$this->tpl = $tpl;

		$this->redis = new KfRedis();
		/** 记录当天该文件的访问量 start */
		$this->redis->incrby('fkd.webCompany',1);
		$current_time = date('Y-m-d H:i:s');
		$next_time = date('Y-m-d',strtotime("+1 day")).' 00:00:00';
		$second = strtotime($next_time)-strtotime($current_time);
		$this->redis->expire('fkd.webCompany',$second);
		/** 记录当天该文件的访问量 end */

		$this->setHttpType();
		$this->checkArg();
		$this->checkClient();
		if (array_key_exists('fk_debug',$this->cfg['fk_debug']) && in_array($this->company_id, $this->cfg['fk_debug'])) {
			file_put_contents('/tmp/fk_debug_tmpDebug_'.date('Ymd').'.log', '[' . date('Y-m-d_H:i:s') . ']' . ' ip: '.get_ip() . ' company_id: ' . $this->company_id . ' [error_info] webCompany start ' . PHP_EOL, FILE_APPEND);
		}
	}

	//检测咨询地址和来源是否合规
	function checkClient(){
		$this->lnkopentime = time();
		$this->cfg["master_host"] .= "." . $this->cfg["base_host"];
		// 根据arg获取公司表信息
		$domain_name = strtolower($this->cfg["prefix"].$this->arg);
		$sql = "SELECT id,name FROM company WHERE domain_name='$domain_name'";
		$re_com = db_query1($sql);
		if ($re_com === false || count($re_com) <= 0) {
			header("location:{$this->http}://".$this->cfg['master_host']."/webCompany.php?".$_SERVER["QUERY_STRING"]);
			exit;
		}
		$this->company_id = $re_com['id'];
		$this->setLocalArgs('company_name',$re_com['name']);
		//手机的话跳转到m.php
		if (is_mobile_os()) {
			$get_zdkf_type = $this->getValue("zdkf_type",'');
			$get_id6d = $this->getValue("id6d",'');
			if ($get_zdkf_type == '4' && $get_id6d){
				header("location:{$this->http}://".$_SERVER["HTTP_HOST"]."/m.php?cid={$this->company_id}&".str_replace("tfrom=3","tfrom=57",$_SERVER["QUERY_STRING"]));
				exit;
			}
			header("location:{$this->http}://".$_SERVER["HTTP_HOST"]."/m.php?cid={$this->company_id}&".$_SERVER["QUERY_STRING"]);
			exit;
		}
		// 获取公司相关信息
		$this->getCompanyInfo();
		// 公司被拉黑 终止程序  注：安全平台上的拉黑，由金华客服人员操作  1:拉黑 2.可疑
		if ($this->comInfo['isblack'] == '1' || $this->comInfo['isblack'] == '2') exit('isblack');
		// 未通过认证 终止程序 未认证且不是客服端模拟咨询进来不允许继续访问,但未认证且做过1分钱认证且已开户时可以继续访问
		$consult_trial = $this->redis->get('consult.trial.'.$this->company_id);//客服端模拟咨询不验证
		if (($this->comInfo['facilitator_id'] == '1' || $this->comInfo['facilitator_id'] == '') && $this->comInfo['expiration_date'] != '-1' && $consult_trial != '1') {
			if ($this->comInfo['paymentVerification'] != '-1' || $this->comInfo['open_account'] != '') {
				exit('expiration');//未通过认证	
			}
		}
		// 模拟咨询情况下给予安全提醒
		$try_remind = 0;
		if ($this->comInfo['expiration_date'] != '-1' && $consult_trial == '1') $try_remind = 1;
		// 华为云分组号问题
		//if (strtolower($this->comInfo['alias']) != strtolower($_SERVER["HTTP_HOST"])) {
			//header("location:{$this->http}://".$this->comInfo['alias']."/webCompany.php?" . $_SERVER["QUERY_STRING"]);
			//exit;
		//}
		//范围区域
		$check_area = $this->check_area();
		if ($check_area) {
			echo 'var err_53kf_code = 10010';
			exit;
		}

		
		//检测海外版套餐账号在国内登录过（国内访客是否可以被接待）
		$area_info = ipinfo(get_ip());
		$is_domestic = true;  //默认true是国内,false国外
		if ($area_info['country_cn'] != '中国' || ($area_info['country_cn'] == '中国' && ($area_info['city_cn'] == 'taiwan' || $area_info['city_cn'] == 'hk' || $area_info['city_cn'] == 'mc'))) {
		    $is_domestic = false;
		}
		if ($is_domestic) {
			$version = $this->redis->get('kfxt.version.'.$this->company_id); // 1=国际版
			$login = $this->redis->get("kfxt.haiwai.login.china.".$this->company_id); //1=国际版在国内登录过
			if ($version && !$login) {
				echo 'var err_53kf_code = 10014';
				exit;
			}
		}

		$this->checkSignCode();//检测挂码拼接参数
		$this->setPages();//设置页面信息
		$this->checkFacDomain();//服务商-商城版域名检测
		$this->checkCompanySite();//检测公司站点
		$this->checkChatStyle();//访客端定制

		$this->tpl->assign("lnkopentime", $this->lnkopentime);
		$this->tpl->assign("company_id", $this->company_id);
		$this->tpl->assign("try_remind", $try_remind);
	}

	//获取公司相关信息
	function getCompanyInfo(){
		$this->redis = new KfRedis();
		$this->comInfo = $this->redis->hgetall('com.info.{'.$this->company_id.'}');
		$client_host = $this->redis->get('com.client_host.{'.$this->company_id.'}');
		if ($client_host != ''){
			$this->cfg['base_host'] = $client_host;
			$this->comInfo['alias'] = $client_host;
		}
		//风格
		$this->style = $this->getValue("style", 1) + 0;
		$this->style_id = $this->getStyleRealId($this->style);
		//公司风格设置相关
		$sql = "SELECT config_id,config_value FROM company_config WHERE style_id={$this->style_id} AND company_id={$this->company_id}";
		$this->companyConfig = db_query($sql);

		//公司系统设置信息
		$sql = "SELECT config_id,config_value FROM company_config WHERE style_id=0 and company_id={$this->company_id}";
		$this->companyConfigNoStyle = db_query($sql);

		//公司主账号
		$adminId6d = $this->redis->hget("com.info.{".$this->company_id."}","id6d");
		$admini_account = $this->redis->hget('work.info.{'.$this->company_id.'}.'.$adminId6d,'account');
		
		$this->tpl->assign("style", $this->style);
		$this->tpl->assign("style_id", $this->style_id);
		$this->tpl->assign("admini_account", $admini_account);
	}

	//设置页面相关信息
	function setPages(){
		//咨询页面
		if (isset($_SERVER["HTTP_REFERER"])) {
			$referer = $this->getValue("referer", $_SERVER["HTTP_REFERER"]);
		} else {
			$referer = $this->getValue("referer", "");
		}
		if(strpos($referer,'{hz6d_referer}')) {
			$referer = $_SERVER["HTTP_REFERER"] ? $_SERVER["HTTP_REFERER"]:''; 
		}
		$adid = $this->getValue("adid", "");
		$requestid = $this->getValue("requestid", "");
		if ($adid != ''){
			if(strrpos($referer, '?')){
				$referer = $referer.'&adid='.$adid;
			}else{
				$referer = $referer.'?adid='.$adid;
			}
		}
		if ($requestid != ''){
			if(strrpos($referer, '?')){
				$referer = $referer.'&requestid='.$requestid;
			}else{
				$referer = $referer.'?requestid='.$requestid;
			}
		}
		$referer = str_replace('"','',$referer);
		$referer = str_replace("'",'',$referer);
		$referer = str_replace("<",'&lt',$referer);
		$this->talkpage = $referer;

		//设置着陆页面
		if($_COOKIE["uuid_53kf_".$this->company_id]) {
			$uuid_53kf = $_COOKIE["uuid_53kf_".$this->company_id];
		}else{
			$uuid_53kf = $this->getValue("uuid_53kf");
		}
		if ($uuid_53kf == '') {
			$guest_information = array();
		} else {
			$sen_redis = new LdRedis($this->cfg['redis_sentinel']);
			$guest_information = $sen_redis->hgetall('guest.information.'.$this->company_id.'.'.$uuid_53kf);
		}
		if ($guest_information['land_page']) {
			$landpage = $guest_information['land_page'];
		} else {
			$landpage = $referer;
		}

		if ($guest_information['from_page']) {
			$kword = $guest_information['from_page'];
		} else {
			$kword = $this->getValue("keyword");
		}

		if ($guest_information['talk_title']) {
			$talktitle = $guest_information['talk_title'];
		} else {
			$talktitle = $this->getValue("talktitle");
		}
		// if(!$_COOKIE["land_page_{$this->company_id}"] && $this->cfg['fkd_cookie'] != 1) {
		// 	setcookie("land_page_{$this->company_id}", $referer, 0, "/", '.' . $this->cfg['base_host'],$this->cfg['cookie_secure'],$this->cfg['cookie_HttpOnly']);
		// 	$landpage = $referer;
		// }else{
		// 	$landpage = $_COOKIE["land_page_{$this->company_id}"];
		// }
		$this->setLocalArgs('landpage',$landpage);


		//来源页面
		// if(!$_COOKIE["from_page_{$this->company_id}"]){
		// 	$kword = $this->getValue("keyword");
		// }else{
		// 	$kword = $_COOKIE["from_page_{$this->company_id}"]; 
		// }
		$dzh_main = $this->comInfo['dzh_main'];
		if($dzh_main != ""){
			$ShareSource = $this->redis->hget("group.config.{".$dzh_main."}","ShareSource");//多账号共享来源开关
			if($ShareSource == 1){
				if($_COOKIE["main_from_page_$dzh_main"] != ""){
					$kword = $_COOKIE["main_from_page_$dzh_main"];
				}else if($kword != ""){
					setcookie("main_from_page_$dzh_main", $kword, 0, "/", '.' .$_SERVER["HTTP_HOST"],$this->cfg['cookie_secure'],$this->cfg['cookie_HttpOnly']);
				}
			}
		}
		
		$visitor = new Visitor($this->redis);
		$search = $visitor->parseKeyword($kword);
		$search_engine = $search[0];
		$keyword = $search[1];
		$source = $search[2];
		if(($search_engine == "手机百度" || $search_engine == "Baidu") && $keyword == ""){
			$keyword = $this->getBaiduApi($kword);
			$keyword = urldecode($keyword);
		}

		if (parse_keyword($kword)[2] == 'sohu' || parse_keyword($landpage)[2] == 'sohu') {
			$rawurl = true;
		} else {
			$rawurl = false;
		}

		/** 来源或者着陆页里含有qz_gdt参数的，即认定为腾讯来的，关键词搜索词从着陆页的bidword或者query取 */
		if ($kword || $landpage) {
			$k = parse_url($kword);
			$k = $k['query'];
			$l = parse_url($landpage);
			$l = $l['query'];
			if (array_key_exists('qz_gdt',str_to_arr($k)) || array_key_exists('qz_gdt',str_to_arr($l))){
				$source = '腾讯';
				if(array_key_exists('bidword',str_to_arr($l))){
					$keyword = urldecode(str_to_arr($l)['bidword']);
				}elseif(array_key_exists('query',str_to_arr($l))){
					$keyword = urldecode(str_to_arr($l)['query']);
				}
			}
		}
		$this->setLocalArgs('source',$source);
		$this->setLocalArgs('frompage',$kword);
		$this->tpl->assign("search_engine",$search_engine);
		$this->tpl->assign("keyword",$keyword);
		$this->tpl->assign("frompage",$this->pageDecode($kword,$rawurl));
		$this->tpl->assign("talkpage",$this->pageDecode($referer,$rawurl));
		$this->tpl->assign('landpage',$this->pageDecode($landpage,$rawurl));
		$this->tpl->assign('talktitle',$this->pageDecode($talktitle,$rawurl));
	}

	//范围区域
	function check_area()
	{
		$ip = get_ip();
		$ipinfo = ipinfo($ip);
		$city = $ipinfo['city'];
		$province = $ipinfo['province'];
		$country_cn = $ipinfo['country_cn'];

		//数据库区域数据
		$sql = "select config_id,config_value from company_config where company_id = ".$this->company_id. " and style_id = ".$this->style_id." and config_id in ('area_type', 'pc_area')";
		$res = db_query($sql);
		$area_type = $res[0]['config_value'];
		$area_data = $res[1]['config_value'];
		if (empty($area_type) && !empty($area_data)) {
			$area_type = 2;
		}

		if ($area_type == 2) {
			if (!empty($area_data)) {
				$check_areas = explode(',', $area_data);
				foreach ($check_areas as $key => $value) {
					$areas = explode('-', $value);
					if (!empty($areas[1])) {
						if ($areas[1] == $city || $areas[1].'市' == $city) {
							return false;
						}
					}elseif ($areas[0] == $province ||  $areas[0].'市' == $province) {
						return false;
					}
				}
				return true;
			}else{
				return false;
			}
		}

		if ($area_type == 3) {
			if (!empty($area_data)) {
				$check_areas = explode(',', $area_data);
				foreach ($check_areas as $key => $value) {
					$areas = explode('-', $value);
					if (!empty($areas[1])) {
						if ($areas[1] == $city || $areas[1].'市' == $city) {
							return true;
						}
						if ($areas[1] == '国外' && $country_cn != '中国') {
							return true;
						}
					}elseif ($areas[0] == $province ||  $areas[0].'市' == $province) {
						return true;
					}elseif ($areas[0] == '国外' && $country_cn != '中国') {
						return true;
					}
				}
				return false;
			}else{
				return false;
			}
		}
		return false;
	}

	//主程序
	function main(){
		$this->setLanguage();//设置语言包
		$this->getGuestId();//获取访客编号
		$this->getAllPrompt();//获取所有提示语
		$this->getKfSignInfo();//获取kf_sign信息
		$this->getConfigInfo();//获取相关设置信息
		$this->checkBlack();//检测黑名单
		$this->checkWarn();//检测预警
		$this->setFireWall();//防火墙
		$this->getApiInfo();//获取第三方信息
		$this->getAllGroupWorkers();//获取所有客服及在线情况
		$this->getSchedule();//获取排班信息
		$this->setReg();//访客咨询前注册设置
		$this->setLword();//留言设置
		$this->setVisitorForm();//自定义访客表单
		$this->setReceptionRules();//接待规则
		$this->setRobot();//机器人信息
		$this->setSensitiveWords();//敏感词
		$this->setCountCode();//加载第三方统计代码
		$this->authenticationInfo();//认证信息
		$this->showHtml();//显示模板
	}

	function getKfSignInfo(){
		$kf_sign = $this->getValue("kf_sign");
		if (!$kf_sign) {
			file_put_contents("/tmp/kf_sign_null.log", print_r($this->company_id,true).PHP_EOL,FILE_APPEND);
		} else {
			$kf_sign = urldecode($kf_sign);
			$sign = base64_decode(substr($kf_sign,5,5).substr($kf_sign,0,5).substr($kf_sign,10,strlen($kf_sign)-10));
			$sign_time = intval(substr($sign,0,10));
			if((abs(time()-$sign_time) > 72*60*60)){
				file_put_contents("/tmp/kf_sign_overdue.log", print_r($this->company_id,true).PHP_EOL,FILE_APPEND);
			}
		}
	}

	//语言包处理
	function setLanguage(){
		// 语种
		$language = $this->getConfigValue("language", 'cn');
		if($language == 'zh-cn' || empty($language)) $language='cn';
		// 评分相关
		require_once("lang/vote_value.php");
		eval("\$vote_arr=\$".$language."_vote_arr;");
		krsort($vote_arr);
		$vote_arr = array_values($vote_arr);
		// 访客端语言包
		$lang_kh = require_once("lang/$language/lang_kh_new.php");
		if ($language == 'cn') {
			$prompt_default = array(
				'conn_prompt'=>'您好，欢迎您的咨询，请问有什么需要帮助的吗？',
				'busy_prompt'=>"对不起,线路繁忙,请稍候,您也可以给我们留言！",
				'close_prompt'=>"感谢您的咨询！谢谢，再见！",
				'reject_prompt'=>"无法连接客服，您已被阻止！",
				'kf_auto_tip_phrase'=>"不好意思，客服现在正忙，请稍等……",
				'disconnect_prompt'=>'您已经很长时间没有发送信息了，再过3分钟，系统将会自动断开对话'
			);
		}elseif($language == 'tw'){
			$prompt_default = array(
				'conn_prompt'=>"您好，歡迎您的諮詢，請問有什麼需要幫助的嗎？",
				'busy_prompt'=>"對不起,線路繁忙,請稍候,您也可以給我們留言！",
				'close_prompt'=>"感謝您的咨詢！謝謝，再見！",
				'reject_prompt'=>"無法連接客服，您已被阻止！",
				'kf_auto_tip_phrase'=>"不好意思，客服現在正忙，請稍等……",
				'disconnect_prompt'=>'您已經很長時間沒有發送信息了，再過3分鐘，系統將會自動斷開對話'
			);
		}else{
			$prompt_default = array(
				'conn_prompt'=>"Hello, welcome to your consultation，What can I do for you?",
				'busy_prompt'=>"Sorry, the line is busy, please wait, you can also give us the message!",
				'close_prompt'=>"Thank you for your advice! Thank you, goodbye!",
				'reject_prompt'=>"Unavailable to the Customer Service",
				'kf_auto_tip_phrase'=>"Sorry, customer service is busy, please wait……",
				'disconnect_prompt'=>"You haven't sent a message for a long time. In three minutes, the system will automatically disconnect the conversation"
			);
		}

		$lang_default = [
			'reg_prompt' => $lang_kh['default'][0],
			'lword_prompt' => $lang_kh['default'][1],
			'autograph' => $lang_kh['default'][2],
			'name' => $lang_kh['default'][3],
			'mobile' => $lang_kh['default'][4],
			'email' => $lang_kh['default'][5],
			'weixin' => $lang_kh['default'][6],
			'company' => $lang_kh['default'][7],
			'addr' => $lang_kh['default'][8],
			'bname' => $lang_kh['default'][9],
			'zdkf_prompt' => $lang_kh['default'][10],
			'powerby_text' => $lang_kh['htm'][51],
			'three_star_guide' => $lang_kh['default'][11],
			'two_star_guide' => $lang_kh['default'][12],
			'one_star_guide' => $lang_kh['default'][12]
		];
		$this->lang_default = array_merge($lang_default,$prompt_default);

		$this->tpl->assign('language',$language);
		$this->tpl->assign('lang_htm',$lang_kh['htm']);
		$this->tpl->assign('lang_js',json_encode($lang_kh['js']));
		$this->tpl->assign("vote_arr",json_encode($vote_arr));
		$this->tpl->assign("lang_face",json_encode($lang_kh['face']));
	}

	//获取访客编号
	function getGuestId(){
		$browser_finger = $this->getConfigValueNoStyle("browser_finger",'0');//浏览器指纹开关，0关闭,1指纹，2ip
		$is_get_guest_id = '0';
		$time = strtotime('2030-01-01');
		$ip = get_ip();
		$guest_id = $_COOKIE["guest_id"] + 0;

		if (isset($_GET['guest_id']) && !is_numeric($_GET['guest_id'])) exit();
		
		$guest_id_from_get = $_GET['guest_id']+0;
		$is_new_guest_id = false;
		if($guest_id == 0){
			if($browser_finger == 1 && $_COOKIE["finger_guest_id"] != ""){
				$guest_id = $_COOKIE["finger_guest_id"] + 0;
			}else if($browser_finger == 2 && $_COOKIE["ip_guest_id"] != ""){
				$guest_id = $_COOKIE["ip_guest_id"] + 0;
			}
			//if ($guest_id == 0 && $guest_id_from_get) {
				// 当cookie获取不到时，从redis再获取看看，redis存的是get获取到的访客编号和上次实际对话发生变化了的访客编号的对应关系
				//$guest_id = $this->redis->get('reset.guest.id.{'.$this->company_id.'}.'.$guest_id_from_get) + 0;
			//}
			$isSetIpGuestId = false;
			if($browser_finger == 2 && $guest_id == 0){
				$ip_guest_id = intval(curl_get($this->http."://".$this->cfg['finger_host']."/fingerprintjs?cmd=get&fn=".$ip));
				if($ip_guest_id){
					$guest_id = $ip_guest_id;
				}else{
					$isSetIpGuestId = true;
				}
			}
			// 从kf_sign中解析访客编号
			// if ($guest_id == 0) {
			// 	$kf_sign = $this->getValue("kf_sign");
			// 	$kf_sign = urldecode($kf_sign);
			// 	$sign = base64_decode(substr($kf_sign,5,5).substr($kf_sign,0,5).substr($kf_sign,10,strlen($kf_sign)-10));
			// 	$sign_company = substr($sign,-strlen($this->company_id));
			// 	$sign_time = intval(substr($sign,0,10));
			// 	$sign_guestid = substr($sign,10,strlen($sign)-(10+strlen($this->company_id)));
			// 	if((abs(time()-$sign_time) < 24*60*60) && $sign_company == $this->company_id){
			// 		$guest_id = $sign_guestid + 0;
			// 	}
			// }
			// 生成talk_id作为访客编号
			if($guest_id == 0){
				$redis_browser_finger = $this->redis->hget('com.info.{'.$this->company_id.'}','browser_finger');
				if ($redis_browser_finger == 3) {
					$guest_id = intval(ip2long(get_ip())+5000000000);
				} else {
					db_execute("INSERT INTO talk_id VALUES()");
					$guest_id = db_lastinsertid();
					if (!$guest_id) $guest_id = intval(ip2long(get_ip())+5000000000);	//防止没插成功默认一个访客编号
				}
				$is_new_guest_id = true;
			}
			$is_get_guest_id = $browser_finger;
			setcookie("guest_id", $guest_id, $time, "/", '.' . $this->cfg['base_host']);
			if ($isSetIpGuestId) {
				curl_get($this->http."://".$this->cfg['finger_host']."/fingerprintjs?cmd=set&fn=".$ip."&guestid=".$guest_id);
				setcookie("ip_guest_id", $guest_id, $time, "/", '.' . $_SERVER['HTTP_HOST']);
			}
		}

		$redis_browser_finger = $this->redis->hget('com.info.{'.$this->company_id.'}','browser_finger');
		if ($redis_browser_finger == 3) {
			$guest_id = intval(ip2long(get_ip())+5000000000);
			$is_get_guest_id = 3;
			setcookie("guest_id", $guest_id, $time, "/", '.' . $this->cfg['base_host']);
			setcookie("guest_id", $guest_id, $time, "/", '.' . $_SERVER["HTTP_HOST"]);
		}

		$ucust_id = '';
		if(!empty($_GET['u_cust_id']) && !empty($_GET['u_cust_name'])) {
			$ucust_id = $_GET['u_cust_id'];
		}else{
			// $ucust_id = $_COOKIE["u_cust_id_".$this->company_id];
			// if ($ucust_id == '') {
				$uid = $this->getValue("uid",'');
				if($uid == '' && isset($_COOKIE["uid"])) $uid = $_COOKIE["uid"];
				if($uid != '') {
					$ucust_id = $this->redis->get('api.user.ucust_id.'.$uid);
					file_put_contents('/tmp/ucust_id_'.date('Ymd').'.log', date('H:i:s').'[line: ' . __LINE__ . ']' .'ip3: '. get_ip() . ' [uid：]' . var_export('api.user.ucust_id.'.$uid, true) . PHP_EOL, FILE_APPEND);
				}
			// }
		}
		$this->setLocalArgs('ucust_id',$ucust_id);
		
		$use_cust_guestid = 0;
		$guest_dock_id = $this->getConfigValueNoStyle('guest_dock_id','0');
		if ($guest_dock_id == '1' && $ucust_id != '') {
			$u_cust_id = addslashes($ucust_id);
			$sql = "SELECT guest_id FROM member_dock WHERE company_id={$this->company_id} AND u_cust_id='$u_cust_id'";
			$res = db_query1($sql);
			if (!empty($res)) {
				$guest_id = $res['guest_id'];
				$use_cust_guestid = 1;
			}else{
				if (!$is_new_guest_id) {
					$redis_browser_finger = $this->redis->hget('com.info.{'.$this->company_id.'}','browser_finger');
					if ($redis_browser_finger == 3) {
						$guest_id = intval(ip2long(get_ip())+5000000000);
					}else{
						db_execute("INSERT INTO talk_id VALUES()");
						$guest_id = db_lastinsertid();
						if (!$guest_id) $guest_id = intval(ip2long(get_ip())+5000000000);	//防止没插成功默认一个访客编号
					}
				}
				$sql = "INSERT INTO member_dock (company_id,guest_id,u_cust_id) VALUES({$this->company_id},'$guest_id','$u_cust_id')";
				$res = db_execute($sql);
				if ($res) {
					$use_cust_guestid = 1;
				}
			}
		}
		
		$this->guest_id = $guest_id;
		$this->setLocalArgs('ip',$ip);
		$this->setLocalArgs('ipinfo',ipinfo($ip));
		$this->tpl->assign("guest_id",$guest_id);
		$this->tpl->assign("guest_id_from_get",$guest_id_from_get);
		$this->tpl->assign("use_cust_guestid",$use_cust_guestid);
		$this->tpl->assign("finger_id",$_GET["finger_id"]);
		$this->tpl->assign("is_get_guest_id",$is_get_guest_id);
		$this->tpl->assign("ip",$ip);
		$this->tpl->assign("finger_host",$this->cfg['finger_host']);
		$this->tpl->assign("base_host",$this->cfg['base_host']);
		$this->tpl->assign("kfs3_host",$this->cfg['kfs3_host']);
	}

	//检测是否在黑名单  如果在则显示黑名单页面
	function checkBlack() {
		$time = time();
		$sql = "SELECT distinct(guest_id) FROM block_user WHERE company_id={$this->company_id} AND release_time>=$time AND guest_id != ''";
		$re = db_query($sql);
		foreach ($re as $v) {
			if ($this->guest_id == $v['guest_id']){
				$this->showHtml('black');
			}
		}
		$ip = $this->getLocalArgs('ip');
		$ips = explode('.', $ip);
		$ip_tmp = intval($ips[0]) * 16777216 + intval($ips[1]) * 65536 + intval($ips[2]) * 256 + intval($ips[3]);

		$sql = "SELECT start_ip,end_ip FROM block_user WHERE company_id={$this->company_id} AND release_time>=$time AND start_ip>0";
		$re = db_query($sql);

		foreach ($re as $v) {
			if ($v['start_ip'] <= $ip_tmp && $ip_tmp <= $v['end_ip']) {
				$this->showHtml('black');
			}
		}
	}

	//检测预警  同个公司下 同一个ip 2分钟内访客编号变化5次 则记录预警
	function checkWarn(){
		$ip = $this->getLocalArgs('ip');
		$warnKey = "talk.warn.{$this->company_id}.".$ip;//预警redis键
		$warn = $this->redis->hmget($warnKey,array("guest_id","number"));
		if($warn != false && count($warn) > 0){
			$guest_ids = explode(",",$warn["guest_id"]);
			if(!in_array($this->guest_id,$guest_ids)){
				$data["guest_id"] = $warn["guest_id"].",".$this->guest_id;
				$data["number"] = intval($warn["number"])+1;
				$this->redis->hmset($warnKey,$data);
				$this->redis->expire($warnKey,120);
				if($data["number"]==5){//超出5次，记录预警记录，黑名单redis,每次攻击记一次
					$socre = $this->getMillisecond();
					if ($this->comInfo['cloud_service'] != '' && $this->comInfo['cloud_service'] != 'jh') {
						sync_view_redis($this->company_id,"RADD","sortedset",'talk.warn.list',array($socre=>$warnKey.".".$socre),"cluster");
					}else{
						$this->redis->zadd("talk.warn.list", $socre, $warnKey.".".$socre);
					}
				}
			}
		}else{
			$data["guest_id"] = $this->guest_id;
			$data["number"] = 1;
			$this->redis->hmset($warnKey,$data);
			$this->redis->expire($warnKey,120);
		}
	}

	//防火墙处理
	function setFireWall(){
		$fire_wall_info = $this->redis->getFirewall($this->style_id,$this->company_id);
		//是否开启防火墙
		$nstatus = isset($fire_wall_info['nstatus']) ? $fire_wall_info['nstatus'] : '0';
		//是否开启点触式验证码  未开启:被过滤掉的访客无法对话  开启:验证码验证通过后可进行咨询
		$verify_code = isset($fire_wall_info['ncode_stasus']) ? $fire_wall_info['ncode_stasus'] : '0';
		//过滤等级
		$fire_level = isset($fire_wall_info['fire_level']) ? $fire_wall_info['fire_level'] : '1';
		
		$verify_key = md5($this->guest_id.microtime());
		$verify_arr = [0,0,0,0,0];
		$is_verify = 0;   // 0:不需要验证 1:需要验证

		if($nstatus == '1') {
			//第一级，验证是否通过正常挂码过来  检测是否在24小时内，访客id是否变化
			$kf_sign = $this->getValue("kf_sign");
			$kf_sign = urldecode($kf_sign);
			$sign = base64_decode(substr($kf_sign,5,5).substr($kf_sign,0,5).substr($kf_sign,10,strlen($kf_sign)-10));
			$sign_time = intval(substr($sign,0,10));
			$sign_guestid = substr($sign,10,strlen($sign)-(10+strlen($this->company_id)));
			if((abs(time()-$sign_time) > 24*60*60) || ($sign_guestid != $this->guest_id)){
				if($verify_code == 0){
					die('异常访问，您已被阻止!');
				}else{
					$verify_arr[1] = '1';
				}
			}
			//第二级，过滤频繁攻击的ip
			if($fire_level >= 2){
				//ip黑名单数据来源于运维
				$block_level = $this->redis->hgetall("talk.black.ip.".$this->getLocalArgs('ip'));
				if($block_level != false && $block_level["grade"]==9){
					if($verify_code == 0){

						die('异常访问，您已被阻止!');
					}else{
						$verify_arr[1] = '1';
					}
				}
			}
			//第三级，过滤有攻击过的ip
			if($fire_level >= 3){
				if($block_level != false && $block_level["grade"]==1){
					if($verify_code == 0){
						die('异常访问，您已被阻止!');
					}else{
						$verify_arr[2] = '1';
					}
				}
			}
			if(!in_array(1,$verify_arr) && $verify_code == 1){
				$this->redis->setFirecode($this->company_id,$verify_key,$this->guest_id,3*60);
			}
			if(in_array(1,$verify_arr)){
				$is_verify = 1;
			}
		}


		$firewall_uuid = php_uuid();//防火墙  uuid 作为页面识别
		$str1 = substr($firewall_uuid,0,4);//将UUID后的数据前后互换
		$str2 = substr($firewall_uuid,28);
		$str = substr($firewall_uuid,4,24);
		$new_firewall_uuid = $str2.$str.$str1;
		$tmp_mem = new webClientMem();
		$tmp_mem->mem_set($new_firewall_uuid,json_encode(array('firewall'=>0)),600);
		$tmp_mem->close();

		$this->setLocalArgs("nstatus",$nstatus);
		$this->tpl->assign('nstatus',$nstatus);
		$this->tpl->assign('verify_key',$verify_key);
		$this->tpl->assign('fire_level',$fire_level);
		$this->tpl->assign("is_verify",$is_verify);
		$this->tpl->assign("verify_code",$verify_code);
		$this->tpl->assign("firewall_uuid",$firewall_uuid);
	}

	//获取 访客API 传递过来的信息
	function getApiInfo(){
		$uid = $this->getValue("uid",'');
		if($uid == "" && isset($_COOKIE["uid"])) $uid = $_COOKIE["uid"];
		//图文链接信息
		$comeinfo = array('logo' => '','title' => '','content' => '','curl' => '','sendtype' => '');
		$custmsg = "";//对话前访客信息
		if($uid != ""){
			$comeinfo_arr =$this->redis->hmget('api.come.info.'.$uid.'.'.$this->company_id,array('logo','title','content','curl','sendtype'));
			$comeinfo = array(
				"logo" => $comeinfo_arr["logo"] ? preg_replace('/<[^>]*>/','',$comeinfo_arr["logo"]) : "",
				"title" => $comeinfo_arr["title"] ? htmlspecialchars($comeinfo_arr["title"]) : "",
				"content" => $comeinfo_arr["content"] ? htmlspecialchars($comeinfo_arr["content"]) : "",
				"curl" => $comeinfo_arr["curl"] ? preg_replace('/<[^>]*>/','',$comeinfo_arr["curl"]) : "",
				"sendtype" => $comeinfo_arr["sendtype"]+0
			);

			$custmsg = $this->redis->hget('api.cust.msg.'.$uid.'.'.$this->company_id,"msg");
			if($custmsg != ""){
				$custmsg = urldecode($custmsg);
				$this->redis->del('api.cust.msg.'.$uid.'.'.$this->company_id);
			}
		}
		$this->tpl->assign("comeinfo", json_encode($comeinfo));
		$this->tpl->assign("custmsg", $custmsg);

		//第三方自定义信息
		$u_custom_info = '';
		if(!empty($_GET['u_custom_info']) && strlen($_GET['u_custom_info'])<=40){
		$u_custom_info = $_GET['u_custom_info'];
		if($uid == "") $uid = php_uuid();
		$this->redis->set('api.user.custom.'.$uid,$_GET['u_custom_info']);
		$this->redis->expire('api.user.custom.'.$uid,14400);
		if($this->comInfo["cloud_service"] != "" && $this->comInfo["cloud_service"] != "jh") 
			sync_view_redis($this->company_id,"RADD","string",'api.user.custom.'.$uid,$_GET['u_custom_info'],"cluster","14400");
		}
		$this->tpl->assign('uid',htmlspecialchars($uid, ENT_QUOTES));
		$this->tpl->assign('u_custom_info',htmlspecialchars($u_custom_info, ENT_QUOTES));
		$this->setLocalArgs('uid',$uid);

		//第三方产品id和名称
		$prod_id = '';
		$prod_name = '';
		if ($uid != "") {
			$prod_arr = $this->redis->hgetall('api.page.tag.'.$uid);
			$prod_id = urldecode($prod_arr['prod_id']);
			$prod_name = urldecode($prod_arr['prod_name']);
		}
		$this->tpl->assign('prod_id',htmlspecialchars($prod_id, ENT_QUOTES));
		$this->tpl->assign('prod_name',htmlspecialchars($prod_name, ENT_QUOTES));

		//第三方会员
		$ucust_id = $this->getLocalArgs('ucust_id');
		if(!empty($_GET['u_cust_id']) && !empty($_GET['u_cust_name'])) {
			// if ($_GET['guest_id'] != '') {
				// 为建立对话时访客编号发生变化用(用新的访客编号重新注册一次)
				$data = ['u_cust_id'=>$_GET['u_cust_id'],'u_cust_name'=>$_GET['u_cust_name']];
				if ($_GET['guest_id'] != '') { 
					$key = 'talk.kfapi.guest.'.$this->company_id.'.'.$_GET['guest_id'];
				} else {
					$key = 'talk.kfapi.guest.'.$this->company_id.'.'.$this->guest_id;
				}
				$this->redis->hmset($key,$data);
				$this->redis->expire($key,60*60);
			// }
			// $time = strtotime('2030-01-01');
			setcookie("u_cust_id_$this->company_id", $ucust_id, 0, "/", '.' . $this->cfg['base_host']);
			$data = array('u_cust_id'=>$ucust_id,'company_id'=>$this->company_id,'u_cust_name'=>$_GET['u_cust_name'],'guest_id'=>$this->guest_id);
			curl_post($_SERVER['HTTP_HOST'] . '/reg_m.php',$data);
		}
		$this->tpl->assign("ucust_id",htmlspecialchars($ucust_id, ENT_QUOTES));

		//第三方数据统计ID
		$u_stat_id = '';
		if(!empty($_GET['u_stat_id'])){
			$u_stat_id = trim($_GET['u_stat_id']);
		}
		$this->tpl->assign("u_stat_id",htmlspecialchars($u_stat_id, ENT_QUOTES));

		//获取渠道
		$channel = $this->getChannel();
		$this->tpl->assign("channel", $channel);
	}

	//获取渠道
	function getChannel(){
		$channel = "";
		$landpage = $this->getLocalArgs('landpage');
		if($landpage != ""){
			$promote = $this->redis->smembers("promote." . $this->company_id);
			$promote_infos = array();
			$promotes = array();
			foreach ($promote as $key => $value) {
				$promote_info = $this->redis->hgetall("promote." . $this->company_id . "." . $value);
				$promote_infos[$promote_info['pname']] = $promote_info['link_init'];
				$k = substr($value, 12);
				$promotes[$k] = $promote_info;
			}
			ksort($promotes);
			foreach ($promotes as $key => $value) {
				if(strpos($landpage, $value["link_init"]) !== false){
					$channel = $value["pname"];
					break;
				}
			}
			if($channel == ""){
				$url_arr = parse_url($this->talkpage);
				if(count($url_arr)>0 && $url_arr["query"]){
					$params = explode("&",$url_arr["query"]);
					foreach ($params as $key => $value) {
						$param = explode("=",$value);
						if($param[0] == "custom_channel" && strlen($param[1]) <= 50){
							$channel = $param[1];
							if(!is_utf8_encode($channel)){
								$channel = iconv("GBK", "UTF-8", $channel);
							}
							break;
						}
					}
				}
			}
		}
		if($channel == ""){
			$get_channel = $this->getValue("custom_channel");
			if($get_channel != "" && strlen($get_channel) <= 50){
				$channel = $get_channel;
				if(!is_utf8_encode($channel)){
					$channel = iconv("GBK", "UTF-8", $channel);
				}
			}
		}
		return $channel;
	}

	//获取所有提示语 及提示时间
	function getAllPrompt(){
		//公司接通提示语
		$conn_prompt = $this->getConfigValue('conn_prompt',$this->lang_default['conn_prompt']);
		$conn_prompt = $this->dealPrompt($conn_prompt,true);
		$this->tpl->assign("conn_prompt",$conn_prompt);
		//所有客服的个人接通提示语
		$conn_prompt_list = $this->getConnPromptList();
		$this->tpl->assign("conn_prompt_list",json_encode($conn_prompt_list));

		//公司设置 结束提示语
		$close_prompt = $this->getConfigValue('close_prompt',$this->lang_default['close_prompt']);
		$close_prompt = $this->dealPrompt($close_prompt,true);
		$this->tpl->assign("close_prompt",$close_prompt);
		//所有客服的个人结束提示语
		$close_prompt_list = $this->getWorkerConfigValue('close_prompt');
		$this->tpl->assign("close_prompt_list",json_encode($close_prompt_list));

		//公司设置 客服繁忙提示语
		$kf_auto_tip_phrase = $this->getConfigValue('kf_auto_tip_phrase',$this->lang_default['kf_auto_tip_phrase']);
		$kf_auto_tip_phrase = $this->dealPrompt($kf_auto_tip_phrase,true);
		$this->tpl->assign("kf_auto_tip_phrase",$kf_auto_tip_phrase);
		//公司设置 客服繁忙提示时间
		$kf_auto_tip = $this->getConfigValue('kf_auto_tip','0');
		$this->tpl->assign("kf_auto_tip",$kf_auto_tip);

		//所有客服 个人繁忙提示语
		$busy_prompt_list = $this->getWorkerConfigValue('kf_auto_tip_phrase');
		$this->tpl->assign("busy_prompt_list",json_encode($busy_prompt_list));
		//所有客服 个人繁忙提示时间
		$busy_prompt_time_list = $this->getWorkerConfigValue('busy_prompt_time');
		$this->tpl->assign("busy_prompt_time_list",json_encode($busy_prompt_time_list));
		// IM客服无响应时间(s)
		$this->tpl->assign("imkf_no_talk_time", 600);

		//系统断开前提示
		$disconnect_prompt = $this->getConfigValueNoStyle('disconnect_prompt',$this->lang_default['disconnect_prompt']);
		$disconnect_prompt = $this->dealPrompt(htmlspecialchars_decode($disconnect_prompt),true);
		$this->tpl->assign("disconnect_prompt",$disconnect_prompt);
		//访客无响应自动断开  0:表示关闭  不为0表示断开需等待分钟数(大于3)
		$auto_disconnect = $this->getConfigValueNoStyle('auto_disconnect','0');
		$this->tpl->assign("auto_disconnect",$auto_disconnect);

		//公司设置 黑名单阻止提示语
		$reject_prompt = $this->getConfigValue('reject_prompt',$this->lang_default['reject_prompt']);
		$reject_prompt = $this->dealPrompt($reject_prompt,true);
		$this->tpl->assign("reject_prompt",$reject_prompt);

		//接待规则设置  手动选择提示语
		$zdkf_prompt = $this->getConfigValue('zdkf_prompt',$this->lang_default['zdkf_prompt']);
		$zdkf_prompt = $this->dealPrompt($zdkf_prompt,true);
		$this->tpl->assign("zdkf_prompt",$zdkf_prompt);
	}

	// 获取个人接通提示
	function getConnPromptList(){
		$list = array();
		$list1 = array();
		$sql = "SELECT id6d,config_id,config_value FROM worker_config WHERE company_id={$this->company_id} AND (config_id='carousel_prompt_new' OR config_id='conn_prompt' OR config_id LIKE 'carousel%')";
		$res = db_query($sql);
		if ($res !== false && count($res)>0) {
			foreach ($res as $re) {
				if ($re['config_id'] == 'carousel_prompt_new') {
					$list[$re['id6d']][$re['config_id']] = json_decode($re['config_value'],true);
				}else{
					$list[$re['id6d']][$re['config_id']] = $this->dealPrompt($re["config_value"]);
				}
			}
			foreach ($list as $id6d => $prompt) {
				if (isset($prompt['carousel_prompt_new'])) {
					for ($i=1;$i<=8;$i++) {
						$list1[$id6d]["carousel_prompt".$i] = $this->dealPrompt($prompt['carousel_prompt_new'][$i-1]['content']);
						$list1[$id6d]["carousel_time".$i] = $prompt['carousel_prompt_new'][$i-1]['time'];
						$list1[$id6d]["type".$i] = $prompt['carousel_prompt_new'][$i-1]['type']?$prompt['carousel_prompt_new'][$i-1]['type']:'';
					}
				}elseif (isset($prompt['carousel_prompt1'])) {
					if(strstr($prompt['carousel_prompt1'],"[*SEP*]")){
						$carousel_prompts = explode("[*SEP*]",$prompt['carousel_prompt1']);
						for ($i=1;$i<=8;$i++) {
							$list1[$id6d]["carousel_prompt".$i] = $carousel_prompts[$i-1];
							$list1[$id6d]["carousel_time".$i] = $prompt['carousel_interval'];
							$list1[$id6d]["type".$i] = $prompt['type']?$prompt['type']:'';
						}
					}
				}
				$list1[$id6d]['carousel_num'] = $prompt['carousel_num'];
				$list1[$id6d]['conn_prompt'] = $prompt['conn_prompt'];
				$list1[$id6d]['carousel'] = $prompt['carousel'];
			}
		}else{
			$referer = $_SERVER['HTTP_REFERER'];
			$ip = get_ip();
			$referer_ip = $this->redis->get('consult.trial.ip.'.$this->company_id);
			if ($ip == $referer_ip && strpos($referer, $this->cfg['mtalk_host'])) {
				$kefu_code = $this->getWorkerConfigValue('kefu_code');
				$id6ds = $this->redis->sMembers('saas.work.company.{'.$this->company_id.'}');
				//获取专属客服信息
				$url = "https://" . $this->cfg['cloud_host'] . "/interface/?controller=service_manage&action=get_inner_user_info_single&key=" . md5($this->cfg['interface_key'] . $this->company_id);
				$post_data = [
					'company_id' => $this->company_id
				];
				$res = curl_post($url, $post_data);
				$res_arr = json_decode($res, true);
				$kefu_qrcode = array();
				$phone_num = empty($res_arr['msg']['phone_num']) ? '15395796937' : $res_arr['msg']['phone_num']; //未获取到专属客服号码默认为杨东健的号码
				foreach ($id6ds as $key => $value) {
					//专属客服经理二维码
					$kefu_qrcode[$value] = !empty($res_arr['msg']['wechat_img']) ? $res_arr['msg']['wechat_img'] : '';
					//模拟体验默认接通提示语
					$list1[$value]['carousel_prompt1'] = '您好，欢迎您的咨询，请问有什么需要帮助的吗？';
					$list1[$value]['carousel_time1'] = '';
					$list1[$value]['type1'] = '';
					$list1[$value]['carousel_prompt2'] = '我是您的专属客服经理，我的电话：'.$phone_num.'（微信同号）';
					$list1[$value]['carousel_time2'] = '1';
					$list1[$value]['type2'] = '';
					$list1[$value]['carousel_num'] = '1';
					$list1[$value]['conn_prompt'] = '';
					$list1[$value]['carousel'] = '1';
				}
				$this->kefu_qrcode = $kefu_qrcode;
			}
		}
		return $list1;
	}

	//获取个人设置
	function getWorkerConfigValue($config_id){
		$sql = "SELECT id6d,config_id,config_value FROM worker_config WHERE company_id={$this->company_id} AND config_id='$config_id'";
		$res = db_query($sql);
		$list = array();
		if($res!==false && count($res)>0){
			foreach($res as $re){
				if ($config_id == 'close_prompt' || $config_id == 'kf_auto_tip_phrase') {
					$re["config_value"] = $this->dealPrompt($re["config_value"]);
				}
				$list[$re["id6d"]] = $re["config_value"];
			}
		}
		return $list;
	}

	//获取配置信息
	function getConfigInfo(){
		// 主账号昵称
		$adminId6d = $this->redis->hget("com.info.{".$this->company_id."}","id6d");
		$adminBname = $this->redis->hget("work.info.new.{".$this->company_id."}.".$adminId6d,"bname");
		if($adminBname == false) $adminBname = "";
		$this->setLocalArgs('adminBname',$adminBname);
		$this->tpl->assign("admin_bname",$adminBname); 
		$this->tpl->assign("adminId6d",$adminId6d); 
		// 主账号头像
		$adminHeaderUrl = $this->redis->hget("work.info.new.{".$this->company_id."}.".$adminId6d,"fk_header_url");
		if($adminHeaderUrl == false) $adminHeaderUrl = "";
		$adminHeaderUrl = str_replace(array('http://','https://'),$this->http.'://',$adminHeaderUrl);
		$this->setLocalArgs('adminHeaderUrl',$adminHeaderUrl);
		$this->tpl->assign("adminHeaderUrl",$adminHeaderUrl);

		// 所有客服微信二维码
		$kefuCodeList = $this->getWorkerConfigValue('kefu_code');
		if (!empty($this->kefu_qrcode)) {
			$kefuCodeList = $this->kefu_qrcode;
		}
		$this->tpl->assign("kefuCodeList",json_encode($kefuCodeList));

		// 所有客服的  访客操作和行为轨迹 开关
		$visitorPathSwitchList = $this->getWorkerConfigValue('visitor_path_switch');
		$this->tpl->assign("visitorPathSwitchList",json_encode($visitorPathSwitchList));

		// 1:图标 2:邀请框 3:固定链接 5:移动版 6:省钱宝 7:头条 8:百度 9:腾讯 10:快手
		//50:图标 51:邀请框 52:微博 53:微信 54:通用网址 55:二维码 56:其他 57:固定链 58:头条 59:百度 60:微信 61:APP 62:SDK 63:快手 64:抖音 99:腾讯
		$tfrom = $this->getValue("tfrom") + 0;
		if ($tfrom == 0) $tfrom = 3;
		$this->setLocalArgs('tfrom',$tfrom);
		$this->tpl->assign("tfrom",$tfrom);

		// 1:集团挂码
		if(!$_COOKIE["is_group_{$this->company_id}"]) {
			$is_group = $this->getValue("is_group");
			if($is_group=="") $is_group = 0;
			setcookie("is_group_$this->company_id", $is_group, 0, "/", '.' . $this->cfg['base_host'],$this->cfg['cookie_secure'],$this->cfg['cookie_HttpOnly']);
		}else{
			$is_group = $_COOKIE["is_group_{$this->company_id}"];
		}
		$this->tpl->assign("is_group",htmlspecialchars($is_group, ENT_QUOTES));

		
		//活动公告
		$company_activity = $this->getConfigValue('company_activity','');
		$this->tpl->assign("company_activity",str_replace(array("\r\n","\n","\r"),array("<br>","<br>","<br>"), $company_activity));
		//公司名称	默认: 在线客服
		$company_name = htmlspecialchars($this->getConfigValue('company_name',$this->getLocalArgs('company_name')),ENT_QUOTES);
		if($company_name == '') $company_name = $this->lang_default['bname'];
		$this->tpl->assign("company_name",$company_name);
		//签名	默认: 为您在线解答售前(5×8)、售后咨询(7×24)服务
		$autograph = $this->getConfigValue('autograph',$this->lang_default['autograph']);
		$this->tpl->assign("autograph",$autograph);
		//公司简介
		$company_notes = $this->getConfigValue('company_notes','');
		$this->tpl->assign("company_notes",$company_notes);
		//公司logo
		$company_logo = $this->getConfigValue('company_logo','');
		if (strpos($company_logo,$this->cfg["fastdfs_host"]) === false && strpos($company_logo,$this->cfg["hwe_upload"]["visitor_name"]) === false && strpos($company_logo,$this->cfg["file_upload_url"]) === false  && strpos($company_logo,$this->cfg["minio_upload_url"]) === false) {
			$company_logo = preg_replace("/((http|https):\/\/)?\w+\.\w+\.\w+\//",'',$company_logo);
			$company_logo = str_replace('../','',$company_logo);
			if ($company_logo != '') {
				$company_logo = $this->http.'://'.$_SERVER['HTTP_HOST'].'/'.$company_logo;
			}
		}
		$this->tpl->assign("company_logo",$company_logo);
		//是否展示客服名片
		$this->tpl->assign("kf_card",$this->getConfigValue('kf_card','1'));
		//访客端音效
		$this->tpl->assign("fk_music",$this->getConfigValue('fk_music',''));
		//显示历史聊天记录
		$this->tpl->assign("fk_history",$this->getConfigValue('fk_history','0'));
		$company_tpl = $this->getLocalArgs('company_tpl');
		//网络回呼功能
		$config_id = $company_tpl == 'newchat' ? 'net_callBack' : 'mini_net_callBack';
		$this->tpl->assign("net_callBack",$this->getConfigValue($config_id,'0'));
		//网络回呼按钮颜色
		$config_id = $company_tpl == 'newchat' ? 'color_callBack' : 'minicolor_callBack';
		$this->tpl->assign("color_callBack",$this->getConfigValue($config_id,'#CE3A5E'));
		//发送文件及图片
		$config_id = $company_tpl == 'newchat' ? 'fk_fswjjtp' : 'mini_fk_fswjjtp';
		$this->tpl->assign("fk_fswjjtp",$this->getConfigValue($config_id,'1'));
		//表情按钮
		$config_id = $company_tpl == 'newchat' ? 'face_show' : 'mini_face_show';
		$this->tpl->assign("face_show",$this->getConfigValue($config_id,'1'));
		//截图
		$config_id = $company_tpl == 'newchat' ? 'snapshot' : 'mini_snapshot';
		$this->tpl->assign("snapshot",$this->getConfigValue($config_id,'1'));
		//聊天记录下载
		$config_id = $company_tpl == 'newchat' ? 'saverec' : 'mini_saverec';
		$this->tpl->assign("saverec",$this->getConfigValue($config_id,'0'));
		//热点问题
		// $config_id = $company_tpl == 'newchat' ? 'hotspot' : 'mini_hotspot';
		// $this->tpl->assign("hotspot",$this->getConfigValue($config_id,'1'));
		$this->tpl->assign("hotspot",'0');	//2020.8.18 产品经理要求下架此功能
		//客服评分
		$config_id = $company_tpl == 'newchat' ? 'kfpf' : 'mini_kfpf';
		$this->tpl->assign("kfpf",$this->getConfigValue($config_id,'1'));
		// 评价方式
		$this->tpl->assign("evaluate_way",$this->getConfigValue('evaluate_way','0'));
		//默认星值
		$this->tpl->assign("default_star",$this->getConfigValue('default_star','5'));
		//3星评价引导语
		$this->tpl->assign("three_star_guide",$this->getConfigValue('three_star_guide',$this->lang_default['three_star_guide']));
		//2星评价引导语
		$this->tpl->assign("two_star_guide",$this->getConfigValue('two_star_guide',$this->lang_default['two_star_guide']));
		//1星评价引导语
		$this->tpl->assign("one_star_guide",$this->getConfigValue('one_star_guide',$this->lang_default['one_star_guide']));
		//评价填写要求
		$this->tpl->assign("evaluate_ask",$this->getConfigValue('evaluate_ask','0'));
		//头部背景  主题色
		$config_id = $company_tpl == 'newchat' ? 'color_tbbj' : 'minicolor_tbbj';
		$this->tpl->assign("color_tbbj",$this->getConfigValue($config_id,'rgb(31, 140, 235)'));
		//客服气泡颜色
		$config_id = $company_tpl == 'newchat' ? 'color_kfqp' : 'minicolor_kfqp';
		$this->tpl->assign("color_kfqp",$this->getConfigValue($config_id,'rgb(239, 243, 246)'));
		//客服消息颜色
		$config_id = $company_tpl == 'newchat' ? 'color_kfxx' : 'minicolor_kfxx';
		$this->tpl->assign("color_kfxx",$this->getConfigValue($config_id,'rgb(58, 60, 76)'));
		//访客气泡颜色
		$config_id = $company_tpl == 'newchat' ? 'color_fkqp' : 'minicolor_fkqp';
		$this->tpl->assign("color_fkqp",$this->getConfigValue($config_id,'rgb(31, 140, 232)'));
		//访客消息颜色
		$config_id = $company_tpl == 'newchat' ? 'color_fkxx' : 'minicolor_fkxx';
		$this->tpl->assign("color_fkxx",$this->getConfigValue($config_id,'rgb(255, 255, 255)'));
		//发送按钮颜色
		$config_id = $company_tpl == 'newchat' ? 'color_fsan' : 'minicolor_fsan';
		$this->tpl->assign("color_fsan",$this->getConfigValue($config_id,'rgb(30, 137, 230)'));
		//浮动窗口尺寸	1:360×460  2:360×400
		$this->tpl->assign("mini_size",$this->getConfigValue('mini_size','1'));
		//访客端音效		1:标准尺寸800×600  2:自适应
		$this->tpl->assign("newwindow_size",$this->getConfigValue('newwindow_size','1'));
		//PC访客端微信引流
		$this->tpl->assign("wx_drainage",$this->getConfigValue('wx_drainage','1'));
		//是否绑定公总号
		$appid = $this->redis->getWxAppid($this->company_id, $this->style_id);
		$wx_public_account = $appid == null ? '0' : '1';
		$this->tpl->assign("wx_public_account", $wx_public_account);
		//对话过程中手机号验证
		$this->tpl->assign("check_phone",$this->getConfigValue('check_phone','0'));
		//是否是违法行业
		$is_illegal = false;
		if (strpos($this->comInfo['industry'],'321') !== false) {
			$is_illegal = true;
		}
		//默认客服头像
		$default_header = 'style/chat/new2017/image/png/company-logo-default.png';
		if ($is_illegal) {
			$default_header = 'style/chat/new2017/image/png/illegal-logo-default.png';
		}
		$this->tpl->assign("default_header",$default_header);
		//隐藏外链  (53KF 提供软件支持)  注：后台没有实际的设置项,客户有需求时，经确认后直接在数据库中插入数据
		if ((isset($this->cfg['hidden_powerby']) && $this->cfg['hidden_powerby'] == '1') || $is_illegal) {
			$hidden_powerby = '1';
		}else{
			$hidden_powerby = $this->getConfigValueNoStyle('hidden_powerby','0');
		}
		$this->tpl->assign("hidden_powerby",$hidden_powerby);
		//隐藏新窗口右边部分  注：后台没有实际的设置项，客户有需求时，经确认后直接在数据库中插入数据
		if ((isset($this->cfg['hidden_right']) && $this->cfg['hidden_right'] == '1') || $is_illegal) {
			$hidden_right = '1';
		}else{
			$hidden_right = $this->getConfigValueNoStyle('hidden_right','0');
		}
		$this->tpl->assign("hidden_right",$hidden_right);
		//版权信息 (默认：53KF 提供软件支持)  注：后台没有实际的设置项，客户有需求时，经确认后直接在数据库中插入数据
		$powerby_text = $this->getConfigValueNoStyle('powerby_text','');
		$iszdy_powerby = '1';//是否是自定义的版权信息
		if ($powerby_text == '') {
			$iszdy_powerby = '0';
			$powerby_text = $this->lang_default['powerby_text'];
		}
		
		if ($this->comInfo['facilitator_id'] && $this->comInfo['facilitator_id'] != 1 && $this->comInfo['facilitator_id'] != 12) {
			// 要求服务商账号版权信息都不显示
			$powerby_text = '';
		}
		$this->tpl->assign("powerby_text",$powerby_text);
		$this->tpl->assign("iszdy_powerby",$iszdy_powerby);
		// 是否隐藏发送文件功能
		$hidden_upload_file = 0;
		if (strpos($this->comInfo['industry'],'321') !== false) {
			$hidden_upload_file = 1;
		}
		$this->tpl->assign("hidden_upload_file",$hidden_upload_file);
		// 新窗口右下角广告区域
		$right_ads = [
			1 => [
				'zdyad' => $this->getConfigValue('zdylogo',''),
				'zdyad_url' => $this->getConfigValue('zdylogo_url','')
			],
			2 => [
				'zdyad' => $this->getConfigValue('zdylogo2',''),
				'zdyad_url' => $this->getConfigValue('zdylogo2_url','')
			],
			3 => [
				'zdyad' => $this->getConfigValue('zdylogo3',''),
				'zdyad_url' => $this->getConfigValue('zdylogo3_url','')
			]
		];
		foreach ($right_ads as $key => $value) {
			if (empty($value['zdyad'])) {
				unset($right_ads[$key]);
			}
		}
		$right_ads_is_empty = empty($right_ads) ? 1 : 0;
		$this->tpl->assign("right_ads_is_empty", $right_ads_is_empty);
		$this->tpl->assign("right_ads", $right_ads);

		// 自定义logo接口  若为设置右下角广告区域内容  则用该接口替代
		$logo = $this->getValueSpecial("logo");
		$logo = str_replace(array('http://','https://'),$this->http.'://',$logo);
		if ($logo == '') {
			 $logo = "{$this->http}://".$_SERVER['HTTP_HOST']."/iframe_logo.php?arg={$this->arg}&style_id={$this->style_id}&is_zdylogo=1&company_id={$this->company_id}&key=1&ykey=1";
		}
		$this->tpl->assign("logo", $logo);

		// 互动菜单
		$pc_inertact_menu = $this->getConfigValue('pc_inertact_menu','');
		if ($pc_inertact_menu != '') {
			$pc_inertact_menu = str_replace(array("\r","\n","\r\n"),'<br>', $pc_inertact_menu);
			$pc_inertact_menu = json_decode($pc_inertact_menu,true);
			if (!empty($pc_inertact_menu)) {
				foreach ($pc_inertact_menu as $key => $value) {
					$pc_inertact_menu[$key]['name'] = html_entity_decode($value['name'],ENT_QUOTES);
					if ($value['type'] == '1') {
						$pc_inertact_menu[$key]['content'] = html_entity_decode($value['content'],ENT_QUOTES);
					}else{
						$tmp = array();
						foreach ($value['content'] as $k => $v) {
							$tmp[] = html_entity_decode($v,ENT_QUOTES);
						}
						$pc_inertact_menu[$key]['content'] = $tmp;
					}
				}
			}
		}else{
			$pc_inertact_menu = array();
		}
		$this->tpl->assign("pc_inertact_menu",json_encode($pc_inertact_menu));
		// 自动隐藏互动菜单点击次数
		$this->tpl->assign("pcMenuHideTimes",$this->getConfigValue('pcMenuHideTimes','0'));
		// 互动菜单快问快答的回答时间间隔 单位毫秒
		$inertactMenuAnswerTime = 500;
		if (isset($this->cfg['inertactMenuAnswerTime']) && $this->cfg['inertactMenuAnswerTime'] != '') {
			$inertactMenuAnswerTime = $this->cfg['inertactMenuAnswerTime'];
		}
		$this->tpl->assign("inertactMenuAnswerTime",$inertactMenuAnswerTime);
		// 浮动窗口尺寸类型
		$this->tpl->assign("mini_size",$this->getConfigValue('mini_size','1'));
		//ip信息
		$ipinfo = $this->getLocalArgs('ipinfo');
		$this->tpl->assign("guest_ip_info", $ipinfo['ip_info']);
		//视音频上传接口
		$this->tpl->assign("kfs3_host",$this->cfg['kfs3_host']);
		//mtalk项目域名
		$this->tpl->assign("mtalk_host",$this->cfg["mtalk_host"]);
		$this->tpl->assign("talk_host",$_SERVER['HTTP_HOST']);
		$this->tpl->assign("host",$_SERVER['HTTP_HOST']);
		$this->tpl->assign("master_host",$this->cfg['master_host']);
		//随机数
		$this->tpl->assign("rand_num",mt_rand(1000000,9999999));
		//聊天记录下载验证码
		global $company_id;
		$company_id = $this->company_id;
		$this->tpl->assign("saverec_code",encrypt_6d($this->guest_id.'*'.time()));
		// LNK 校验
		$this->tpl->assign("lnk_param",hz6d_encode(time()));
		// LNK fire 校验
		$lnk_fire = encrypt_6d_lnk($this->company_id.$this->guest_id.time());
		$this->tpl->assign("lnk_fire",$lnk_fire);
		//  webClient.js的版本参数，需要通过参数方式上发给服务端
		$commond_version = (isset($this->cfg["commond_version"])&&$this->cfg["commond_version"]!="")?$this->cfg["commond_version"]:"no_version";
		$this->tpl->assign("commond_version", $commond_version);
		// 新窗口自定义icon
		$this->tpl->assign("client_icon",$this->cfg["client_icon"]);
		//信息识别  微信 qq 电话
		$btn_switch = json_encode(['wechat','qq','phone']);
		$this->tpl->assign("btn_switch",$this->getConfigValue('btn_switch',$btn_switch));
		//访客发送手机号时记录浏览器指纹日志
		$mobile_finger_log = 0;
		if (isset($this->cfg['mobile_finger_log']) && $this->cfg['mobile_finger_log'] == 1) {
			$mobile_finger_log = 1;
		}
		$mobile_finger_company_ids = $this->redis->smembers('setlog.mobile.finger.companyids');
		if (!empty($mobile_finger_company_ids) && in_array($this->company_id, $mobile_finger_company_ids)) {
			$mobile_finger_log = 1;
		}
		$this->tpl->assign("mobile_finger_log",$mobile_finger_log);

		//访客建立对话时记录浏览器指纹检测开关
		$talk_finger_log = 0;
		$talk_finger_company_ids = $this->redis->smembers('setlog.talk.finger.companyids');
		if (in_array($this->company_id, $talk_finger_company_ids)) {
			$talk_finger_log = 1;
		}
		$this->tpl->assign("talk_finger_log",$talk_finger_log);
		
		// 消息中手机号加密规则
		$encrypt_code = $this->cfg['fkd_encrypto'] ? $this->cfg['fkd_encrypto']: '';
		$this->tpl->assign("encrypt_code",$encrypt_code);

		// 用户信息保护
		$information_switch = $this->getConfigValueNoStyle('information_switch','0');	//开关 默认0未开,1开
		$information_guide = $this->getConfigValueNoStyle('information_guide','我已阅读并同意');	//引导文本
		$information_info = $this->getConfigValueNoStyle('information_info',json_encode(array()));	//协议名称
		if ($information_info) {
			$information_info = stripslashes($information_info);
			$information_info = json_decode($information_info,true);
			foreach ($information_info as $ik => $iv) {
				$information_info[$ik]['weburl'] = substr($iv['url'],0,strrpos($iv['url'],'.')).'.html';
			}
			$information_info = json_encode($information_info,256);
		}
		$information_button = $this->getConfigValueNoStyle('information_button','同意，继续咨询');	//按钮文本
		$this->tpl->assign("information_switch",$information_switch);
		$this->tpl->assign("information_guide",$information_guide);
		$this->tpl->assign("information_info",$information_info);
		$this->tpl->assign("information_button",$information_button);

		$message_view_status = $this->getConfigValueNoStyle('message_view_status',0);		//消息已读回执	1启用 0关闭
		if ($message_view_status !== '1') $message_view_status = 0;
		$this->tpl->assign("message_view_status",$message_view_status);

		if (array_key_exists('fk_debug',$this->cfg['fk_debug']) && in_array($this->company_id, $this->cfg['fk_debug'])) {
			$this->tpl->assign("fk_debug",true);
		} else {
			$this->tpl->assign("fk_debug",false);
		}

		//接通提示语气泡框背景颜色
		$this->tpl->assign("conn_prompt_bgcolor",$this->getConfigValue('conn_prompt_bgcolor',''));

		//网页回呼号码验证开关
		$check_phone_callback = $this->getConfigValue('check_phone_callback','');
		$chech_num = $this->redis->get('thousand.sms.num.'.$this->company_id);
		if (empty($chech_num) || $chech_num <= 0) {
			$check_phone_callback = 0;
		}
		$this->tpl->assign("check_phone_callback",$check_phone_callback);
		
		//获取用户机器上连接到 Web 服务器所使用的端口号
		$remote_port = $_SERVER['HTTP_X_REAL_PORT']?$_SERVER['HTTP_X_REAL_PORT']:$_SERVER['REMOTE_PORT'];
		if (!$remote_port) $remote_port = '';
		$remote_port = $remote_port?$remote_port:'';
		$this->tpl->assign("remote_port",$remote_port);
		
	}

	//访客表单
	function setVisitorForm(){
		$sql = "SELECT * FROM visitor_form WHERE company_id={$this->company_id} OR company_id=0";
		$res = db_query($sql);
		$visitor_form = array();
		if ($res !== false && count($res)>0) {
			foreach ($res as $key => $value) {
				$tmp = array();
				$tmp['field_type'] = $value['field_type'];
				if ($value['name'] == '姓名' || strpos($value['name'],'{{name}}') !== false) {
					$tmp['name'] = $value['name'] == '姓名' ? $this->lang_default['name'] : str_replace('{{name}}','', $value['name']);
					$tmp['field_name'] = 'name';
				}elseif ($value['name'] == '手机' || strpos($value['name'],'{{mobile}}') !== false) {
					$tmp['name'] = $value['name'] == '手机' ? $this->lang_default['mobile'] : str_replace('{{mobile}}','', $value['name']);
					$tmp['field_name'] = 'mobile';
				}elseif ($value['name'] == '邮箱' || strpos($value['name'],'{{email}}') !== false) {
					$tmp['name'] = $value['name'] == '邮箱' ? $this->lang_default['email'] : str_replace('{{email}}','', $value['name']);
					$tmp['field_name'] = 'email';
				}elseif ($value['name'] == '微信' || strpos($value['name'],'{{wechat}}') !== false) {
					$tmp['name'] = $value['name'] == '微信' ? $this->lang_default['weixin'] : str_replace('{{wechat}}','', $value['name']);
					$tmp['field_name'] = 'weixin';
				}elseif ($value['name'] == 'Q Q' || $value['name'] == 'QQ' || strpos($value['name'],'{{qq}}') !== false) {
					$tmp['name'] = ($value['name'] == 'Q Q' || $value['name'] == 'QQ') ? 'Q Q' : str_replace('{{qq}}','', $value['name']);
					$tmp['field_name'] = 'qq';
				}else{
					$tmp['name'] = $value['name'];
					$tmp['field_name'] = '';
				}
				if ($value['field_type'] != '1') {
					$tmp['option_config'] = json_decode($value['option_config'],true);
				}
				$visitor_form[$value['id']] = $tmp;
			}
		}
		$this->tpl->assign("visitor_form", json_encode($visitor_form));
	}

	// 访客敏感词
	function setSensitiveWords(){
		$words = [];
		$sql = "SELECT words FROM sensitive_words WHERE company_id={$this->company_id} AND type=2";
		$res = db_query($sql);
		if (!empty($res)) {
			foreach ($res as $val) {
				$words[] = $val['words'];
			}
		}
		$this->tpl->assign("sensitiveWords", json_encode($words));
	}

	//接待规则设置
	function setReceptionRules(){
		$queued_ly_buttton = $this->getConfigValue('queued_ly_buttton','0');//访客排队时显示留言按钮
		$shunt_type = $this->getConfigValue('shunt_type','1');//分流类型 1:指定客服  2:区域分流  3:来源分流  4:渠道分流 5:自定义（新增，2.3.4设置项废弃）
		if ($shunt_type == '1') {
			$zdkf_type = $this->getConfigValue('zdkf_type','1');//指定方式 1：人员 2：部门(弃用) 3:分组
			$dept_man_show = $this->getConfigValue('dept_man_show','1');//客服分组名称 1:显示 2:隐藏
			$kf_show = $this->getConfigValue('kf_show','1');//离线客服 1:显示 2:隐藏
			$kf_status = $this->getConfigValue('kf_status','1');//客服繁忙程度 1:显示 2：隐藏
			$kf_expand = $this->getConfigValue('kf_expand','1');//默认展开分组 1:开启 2：关闭
		}else{
			//除了指定客服模式  其余走默认设置
			$zdkf_type = $kf_show = $kf_status = $kf_expand = '1';
			$dept_man_show = '2';
		}
		$zdkf_auto = $this->getConfigValue('zdkf_auto','15');//自动连接 off:关闭
		if ($zdkf_auto == "on") $zdkf_auto="15";//兼容老数据
		$lnk_overflow = '0';//comet判断用 0:判断排班 1:不判断排班 2:直接进入留言
		
		//zdkf 分配方式	yes:手动选择 no:自动分配	 
		//kflist  是否展示客服列表  on:展示  off:不展示	(注：这里为了兼容图标邀请框的传参kflist)
		$kflist = $this->getConfigValue('zdkf','off');
		if ($kflist == 'yes') {
			$kflist = 'on';
		}else if ($show_kflist == 'no') {
			$kflist = 'off';
		}
		if ($this->getValue("kf") != "" && $this->getLocalArgs("nstatus") == 0){
			$kf = $this->getValue("kf");
			$kfArr = $kf=='' ? [] : explode(',', $kf);
			$zdkf_type = $this->getValue("zdkf_type",$zdkf_type);
			$kflist = $this->getValue("kflist","off");
			$lnk_overflow = $this->getValue("lnk_overflow",$lnk_overflow);
			$this->setLocalArgs("lnk_overflow",$lnk_overflow);
			$hasOnlineKf = $this->hasOnlineKf($kfArr,$zdkf_type);
		}else{
			if ($shunt_type == '1') {
				$kfArr = $this->setZdkf();
			}elseif ($shunt_type == '2') {
				$kfArr = $this->setQyflKf();
			}elseif ($shunt_type == '3') {
				$kfArr = $this->setSourceKf();
			}elseif ($shunt_type == '4') {
				$kfArr = $this->setChannelKf();
			}
			$hasOnlineKf = $this->hasOnlineKf($kfArr,$zdkf_type);
			if (!$hasOnlineKf) {
				$kf_overflow = $this->getConfigValue('kf_overflow','0');//溢出开关  0:关闭  1:开启
				if ($kf_overflow == '1') {
					$kf_show = $kf_status = $kf_expand = '1';
					$dept_man_show = '2';
					$overFlow = $this->getOverFlowKf();
					$lnk_overflow = $overFlow['lnk_overflow'];
					$this->setLocalArgs("lnk_overflow",$lnk_overflow);
					$kfArr = $overFlow['kfArr'];
					$zdkf_type = $overFlow['zdkf_type'];
					$hasOnlineKf = $this->hasOnlineKf($kfArr,$zdkf_type);
				}
			}
			//获取不到客服列表  表示没有可参与接待的客服  直接进留言
			if ($kfArr === null) {
				$kfArr = '';
				//$kflist = 'off';
				$lnk_overflow = '2';
				$this->setLocalArgs("lnk_overflow",$lnk_overflow);
			}
		}
		if (!$hasOnlineKf) $this->checkGroupOverFlow();
		if (empty($kfArr)) {
			$worker_ids = '';
		}else{
			$worker_ids = $zdkf_type=='1' ? implode(',',$kfArr) : implode(',',$this->getWorkerIdByGroupId($kfArr));
		}
		$robotassign = $this->getConfigValue('robotassign','0');//接待优先   0:客服优先 1:机器人优先 2:智能引导 3:场景引导
		$frobotassign = $this->getConfigValue('frobotassign','0');//离线优先  0:留言 1:机器人优先 2:场景引导 
		$is_ontalk = $this->redis->exists("talk.status.link.{".$this->company_id."}.".$this->guest_id);//是否在对话中

		//已经建立对话的  接待优先走客服优先  并且不展示客服列表
		if ($is_ontalk) {
			$robotassign = '0';
			$kflist = 'off';
		}
		//手动选择模式 走客服优先
		if ($kflist == 'on') {
			$robotassign = '0';
		}
		$this->setReceptionList($kflist,$kfArr,$zdkf_type,$dept_man_show);//组装 手动选择模式下的客服列表

		if ($robotassign == '1') {
			//处理 接待优先为机器人优先模式下 勾选了 对话结束后的15分钟内再次咨询直接进人工 的情况
			$talk_again = $this->getConfigValue('talk_again','0');//对话结束后的15分钟内再次咨询直接进人工 的 选项开关
			if ($talk_again) {
				//talkover15  是否在15分钟内  redis数据由 java 在对话结束后写入  过期时间15分钟
				$talkover15 = $this->redis->get("robot.minute.".$this->company_id.'.'.$this->guest_id);
				if ($talkover15) $robotassign = '0';
			}

			//处理 接待优先为机器人优先模式下 勾选了 指定渠道 直接人工接待
			$robotchannelswitch = $this->getConfigValue('robotchannelswitch','0');//机器人优先时指定渠道 直接人工接待 0=关 1=开
			if ($robotchannelswitch == '1') {
				//判断渠道
				$source = $this->getLocalArgs('source');
				$robotchannel = $this->getConfigValue('robotchannel','');//机器人优先时指定渠道
				if (strpos($robotchannel, $source) !== false && $robotchannel != '') {
					$robotassign = '0';
				}
			}
		}
		
		$robotassign = $this->setIntelligentGuidance($robotassign);
		$this->setSceneGuidance($robotassign,$frobotassign);

		$hasOnlineKf = $hasOnlineKf ? 1 : 0;

		$get_zdkf_type = $this->getValue("zdkf_type",'');
		$get_id6d = $this->getValue("id6d",'');
		if ($get_zdkf_type == '4' && $get_id6d) {	//指定id6d(不走接待规则\溢出\排班)
			$worker_ids = $this->allWorkers[$get_id6d]['worker_id'];
			$hasOnlineKf = 1;		//1:默认在线
			$robotassign = 0;		//0:客服优先
			$frobotassign = 0;		//0:留言
			$lnk_overflow = 1;		//1:不判断排班
			$dept_man_show = '2';	//客服分组名称 2:隐藏
			$kf_show = '2';			//离线客服 2:隐藏
			$kf_status = '2';		//客服繁忙程度 2：隐藏
			$kf_expand = '2';		//默认展开分组 2：关闭
			$kflist = 'off';		//是否展示客服列表 off:不展示
			$zdkf_type = '1';		//指定方式 1：人员
		}

		$this->tpl->assign('zdkf_type',htmlspecialchars($zdkf_type,ENT_QUOTES));
		$this->tpl->assign('queued_ly_buttton',$queued_ly_buttton);
		$this->tpl->assign('dept_man_show',$dept_man_show);
		$this->tpl->assign('kf_show',$kf_show);
		$this->tpl->assign('kf_status',$kf_status);
		$this->tpl->assign('kf_expand',$kf_expand);
		$this->tpl->assign('kflist',htmlspecialchars($kflist,ENT_QUOTES));
		$this->tpl->assign('hasOnlineKf',$hasOnlineKf);
		$this->tpl->assign('worker_ids',htmlspecialchars($worker_ids,ENT_QUOTES));
		$this->tpl->assign('lnk_overflow',htmlspecialchars($lnk_overflow,ENT_QUOTES));
		$this->tpl->assign('zdkf_auto',$zdkf_auto);
		$this->tpl->assign('robotassign',$robotassign);
		$this->tpl->assign('frobotassign',$frobotassign);
	}

	// 集团溢出
	function checkGroupOverFlow(){
		$overFlowInfo = $this->redis->hgetall('group.over.'.$this->company_id.'.'.$this->style);
		if ($overFlowInfo['company_id'] != '' && $overFlowInfo['style'] != '') {
			$overCompanyArg = $this->redis->hget('com.info.{'.$overFlowInfo['company_id'].'}','dn');
			$params = 'arg='.$overCompanyArg.'&style='.$overFlowInfo['style'].'&keyword='.urlencode($this->getLocalArgs('frompage')).'&referer='.urlencode($this->talkpage).'&tpl='.$_GET["tpl"].'&uid='.$this->getLocalArgs('uid').'&tfrom='.$this->getLocalArgs('tfrom').'&iscswh=1&iscswh_companyId='.$this->company_id;

			$code_type = $this->redis->get("com.code.type.".$overCompanyArg);
			$code_ttl = $this->redis->ttl("com.code.type.".$overCompanyArg);

			if($code_type != 1 || ($code_type == 1 && $code_ttl > 0)){
				$sql = "SELECT arg_code FROM company_arg WHERE company_id = '".$overFlowInfo['company_id']."'";
				$code_arg = db_query11($sql);
				$params .= '&code_arg='.$code_arg;
			}
			header("location:{$this->http}://".$_SERVER["HTTP_HOST"]."/webCompany.php?".$params);
			exit;
		}
	}

	//场景引导
	function setSceneGuidance($robotassign,$frobotassign){
		$scene_guide_list = [];
		$scene_guide_default[1] = [
			'option_id' => '1',
			'option_cont' => [
				0 => [
					'type' => 'message',
					'cont' => '欢迎你的咨询'
				]
			],
			'action' => '',
			'option_btn' => []
		];
		if ($robotassign == '3' || $frobotassign == '2') {
			$sql = "SELECT * FROM scene_guide WHERE company_id={$this->company_id} AND style_id={$this->style_id} ORDER BY scene_order";
			$rows = db_query($sql);
			if (!empty($rows)) {
				foreach ($rows as $row) {
					$scene['option_id'] = $row['scene_id'];//场景序号
					$scene['action'] = $row['action'];//动作 可以为空  option(选项卡)/tokf(转人工)/end(结束)
					$scene['option_btn'] = json_decode($row['btn'],true);//按钮集合  name:名称  point:指向
					$option_cont = json_decode($row['content'],true);//场景内容  type:message(消息)/form(表单) cont:消息内容/表单栏目
					foreach ($option_cont as $k => $v) {
						if ($v['type'] == 'message') {
							$option_cont[$k]['cont'] = $this->dealPrompt(htmlspecialchars_decode($v['cont']));
						}else{
							if (!is_array($option_cont[$k]['cont'][0])) {
								$option_cont[$k]['cont'] = $this->getSceneFormData($option_cont[$k]['cont']);//处理老数据
							}
						}
					}
					$scene['option_cont'] = $option_cont;
					$scene_guide_list[$row['scene_id']] = $scene;
				}
			}
		}
		if (empty($scene_guide_list)) $scene_guide_list = $scene_guide_default;
		//场景引导已经展示的步骤
		$scene_guide_step = $this->redis->get("scene.step.".$this->company_id.".".$this->style.".".$this->guest_id);
		if (!$scene_guide_step) $scene_guide_step = '';
		//场景引导服务 域名
		if($this->comInfo["cloud_service"] != "" && $this->comInfo["cloud_service"] != "jh"){
			$scene_host = $this->comInfo["alias"];
		}else{
			$scene_host = $this->cfg["scene_host"]; 
		}

		$this->tpl->assign("scene_guide_list",json_encode($scene_guide_list));
		$this->tpl->assign("scene_guide_step",$scene_guide_step);
		$this->tpl->assign("scene_host",$scene_host);
	}

	//处理场景引导老的表单数据
	function getSceneFormData($data){
		$form_data = array();
		$arr = [
			'name' => '姓名',
			'phone' => '手机号码',
			'wechat' => '微信',
			'qq' => 'QQ',
			'address' => '地址',
			'email' => '邮箱'
		];
		foreach ($data as $k => $field) {
			if (isset($arr[$field])) {
				$form_data[$k] = [
					'name' => $field,
					'bname' => $arr[$field],
					'is_must' => 1
				];
				if ($field == 'phone') $form_data[$k]['is_check'] = 0;
			}
		}
		return $form_data;
	}

	//智能引导
	function setIntelligentGuidance($robotassign){
		$prompt_guide_size = $this->redis->get("rotation.size.".$this->company_id.".".$this->guest_id);
		if($prompt_guide_size == false) $prompt_guide_size = 0;

		$guidance_type = $this->getConfigValue('guidance_type','1');//智能引导建立对话类型 1:发送消息建立对话 2:键入时建立对话
		$guidance_time = $this->getConfigValue('guidance_time','00:00-23:59');//智能引导生效时间
		//不在智能引导设置时间内，关闭智能引导
		if ($robotassign == '2') {
			if($guidance_time != ""){
				$guidance_time = explode("-",$guidance_time);
				$guidance_start_time = $guidance_time[0];
				$guidance_end_time = $guidance_time[1];
			}
			$now_time = date("H:i");
			if($guidance_start_time < $guidance_end_time){
				if(($now_time < $guidance_start_time) || ($now_time > $guidance_end_time)) $robotassign = '0';
			}else if($guidance_start_time > $guidance_end_time){
				if(($now_time < $guidance_start_time) && ($now_time > $guidance_end_time)) $robotassign = '0';
			}
			//访客对话前有消息关闭智能引导
			if($this->getLocalArgs("custmsg") != "") $robotassign = '0';
		}

		$prompt_guide_list = $this->getPromptGuide();
		$this->setLocalArgs("prompt_guide_list",$prompt_guide_list);
		//智能引导服务 域名
		if($this->comInfo["cloud_service"] != "" && $this->comInfo["cloud_service"] != "jh"){
			$wait_host = $this->comInfo["alias"];
		}else{
			$wait_host = $this->cfg["wait_host"]; 
		}

		//达内兼容，智能引导是不是只使用【其他】的内容
		$guide_type = 0;
		if ($this->cfg['guide_type'] == 1 || (isset($this->cfg['guide_compnay_ids']) && in_array($this->company_id, $this->cfg['guide_compnay_ids']))) $guide_type = 1;

		$this->tpl->assign('prompt_guide_size',$prompt_guide_size);
		$this->tpl->assign('guidance_type',$guidance_type);
		$this->tpl->assign('prompt_guide_list',json_encode($prompt_guide_list));
		$this->tpl->assign('wait_host',$wait_host);
		$this->tpl->assign('guide_type',$guide_type);
		return $robotassign;
	}


	/**
	* 获取智能引导列表
	* title 		关键词(当talkpage_link不为空时表示咨询页标题)
	* promote_link 	推广链接ID
	* talkpage_link 咨询页链接或关键字符
	* prompt 		提示语内容
	*/
	function getPromptGuide(){
		if (!empty($this->getLocalArgs('prompt_guide_list'))) return $this->getLocalArgs('prompt_guide_list');
		$prompt_guide_list = array(
			"0"=>array(
				"title"=>"其他",
				"id"=>"0",
				"prompt"=>array()
			)
		);
		$sql = "SELECT id,title,prompt,promote_link,talkpage_link FROM prompt_guide WHERE company_id={$this->company_id} AND style_id={$this->style_id} ORDER BY prompt_order,id";
		$rows = db_query($sql);
		if (!empty($rows)) {
			$i = 1;
			foreach ($rows as $row) {
				$prompt_guide = array(
					'title' => $row['title'],
					'id' => $row['id'],
					'promote_link' => $row["promote_link"] == '' ? '' : $row["promote_link"],
					'talkpage_link' => $row['talkpage_link'] == '' ? '' : $row["talkpage_link"]
				);
				if($row["promote_link"] != ""){
					$promote_link = $this->getConfigValueNoStyle($row["promote_link"],'');
					$promote_link = json_decode($promote_link,true);
					$prompt_guide["link_init"] = $promote_link['link_init'];
				}else{
					$prompt_guide["link_init"] = "";
				}
				$prompt = $row["prompt"] == "" ? array() : json_decode($row["prompt"],true);
				foreach ($prompt as $k => $v) {
					$prompt[$k]["prompt_content"] = $this->dealPrompt(htmlspecialchars_decode($v["prompt_content"]));
				}
				$prompt_guide["prompt"] = $prompt;
				if($row["title"] == "其他") {
					$prompt_guide_list[0] = $prompt_guide;
				}else{
					$prompt_guide_list[$i] = $prompt_guide;
					$i++;
				}
			}
		}
		return $prompt_guide_list;
	}

	//处理访客手动选择模式下的接待列表
	function setReceptionList($kflist,$kfArr,$zdkf_type,$dept_man_show){
		$receptionList = [];
		if ($kflist == 'on'){
			if ($zdkf_type == '1') {
				if ($dept_man_show == '1') {
					$kf_unselected = $this->getConfigValue('kf_unselected','');
					$unselected_group_id = explode(',',$kf_unselected);
					foreach ($this->allGroups as $group_id => $group) {
						if ($group_id != 0 && in_array($group_id, $unselected_group_id)) {
							continue;
						}
						foreach ($group['workers'] as $id6d => $worker) {
							if (in_array($worker['worker_id'],$kfArr) || empty($kfArr)) {
								if (!isset($receptionList[$group_id])) {
									$receptionList[$group_id]['group_name'] = $group['group_name'];
									$receptionList[$group_id]['group_id'] = $group_id;
									$receptionList[$group_id]['online_num'] = 0;
								}
								$nowlink = $this->redis->hget("status.kf.{".$this->company_id."}.".$id6d,'nowlink');
								if ($nowlink === false) $nowlink = 0;
								$worker['nowlink'] = $nowlink;
								if ($worker['is_online'] == 1 && $this->isWorkTime($id6d)) {
									$worker['state'] = 1;
									$receptionList[$group_id]['online_num']++;
								}else{
									$worker['state'] = 0;
								}
								$receptionList[$group_id]['workers'][] = $worker;
							}
						}
					}
					$receptionList = array_values($receptionList);
				}else{
					foreach ($this->allWorkers as $id6d => $worker) {
						if (in_array($worker['worker_id'],$kfArr) || empty($kfArr)) {
							$nowlink = $this->redis->hget("status.kf.{".$this->company_id."}.".$id6d,'nowlink');
							if ($nowlink === false) $nowlink = 0;
							$worker['nowlink'] = $nowlink;
							$worker['state'] = ($worker['is_online'] == 1 && $this->isWorkTime($id6d)) ? 1 : 0;
							$receptionList[] = $worker;
						}
					}
				}
			}elseif ($zdkf_type == '3') {
				foreach ($this->allGroups as $group_id => $group) {
					if ($group_id != 0 && (in_array($group_id,$kfArr) || empty($kfArr))) {
						$tmp_group = [
							'group_id' => $group_id,
							'group_name' => $group['group_name'],
							'online_num' => 0
						];
						foreach ($group['workers'] as $worker) {
							if (isset($tmp_group['worker_ids'])) {
								$tmp_group['worker_ids'] .= ','.$worker['worker_id'];
							}else{
								$tmp_group['worker_ids'] = $worker['worker_id'];
							}
							if ($worker['is_online'] == 1 && $this->isWorkTime($worker['id6d'])) $tmp_group['online_num']++;
						}
						$receptionList[] = $tmp_group;
					}
				}
			}
		}
		$this->tpl->assign('receptionList',json_encode($receptionList));
	}

	//获取溢出模式指定的客服列表	lnk_overflow 0:判断排班 1:不判断排班 2:直接进入留言
	function getOverFlowKf(){
		$overflow_type = $this->getConfigValue('overflow_type','1');//溢出指定类型   1:人员  2:值班  3:分组
		$overflow_value = $this->getConfigValue('overflow_value','');//溢出指定的客服  worker_id or group_id or schedule_id
		$kfArr = $overflow_value == '' ? [] : explode(',', $overflow_value);
		//溢出模式下 指定人员和指定分组 不考虑排班;		指定排班模式访客端展示为指定人员
		if ($overflow_type == '2') {
			$lnk_overflow = '0';
			$zdkf_type = '1';
			$kfArr = $this->getWorkerIdByScheduleId($kfArr);
		}else{
			$zdkf_type = $overflow_type;
			$lnk_overflow = '1';
		}
		return array('kfArr'=>$kfArr,'zdkf_type'=>$zdkf_type,'lnk_overflow'=>$lnk_overflow);
	}

	//指定客服模式  数据处理
	function setZdkf(){
		$kf = $this->getConfigValue('kf','');//指定的值 空指所有
		$kfArr = $kf=='' ? [] : explode(',', $kf);
		return $kfArr;
	}

	//判断客服是否可接待
	function hasOnlineKf($kflist,$zdkf_type){
		if ($kflist === null) return false;
		if (empty($kflist)) {
			if (empty($this->onlineId6ds)) return false;
			foreach ($this->onlineId6ds as $id6d) {
				if ($this->isWorkTime($id6d)) return true;
			}
		}else{
			if ($zdkf_type == '3') {
				foreach ($kflist as $group_id) {
					if (isset($this->allGroups[$group_id])) {
						foreach ($this->allGroups[$group_id]['workers'] as $id6d => $worker) {
							if ($worker['is_online'] && $this->isWorkTime($id6d)) return true;
						}
					}
				}
			}else{
				foreach ($kflist as $worker_id) {
					foreach ($this->allWorkers as $id6d => $worker) {
						if ($worker['worker_id'] === $worker_id) {
							if ($worker['is_online'] && $this->isWorkTime($id6d)) return true;
							break;
						}
					}
				}
			}
		}
		return false;
	}

	//根据排班判断该客服是否在工作时间		注：若设置了排班信息，但没给某个客服设置排班，则该客服不在工作时间内
	function isWorkTime($id6d){
		if (empty($this->schedule)) return true;
		if ($this->getLocalArgs('lnk_overflow') == '1') return true;
		$week = date("w");//星期
		if ($week == '0') $week = '7';
		foreach ($this->schedule[$id6d] as $v) {
			if(strpos($v['schedule_days'], $week) !== false){
				if(strtotime($v['start_time']) < $this->lnkopentime && strtotime($v['end_time']) > $this->lnkopentime)
				return true;
			}
		}
		return false;
	}

	//根据排班id获取工号
	function getWorkerIdByScheduleId($schedule_ids){
		if (empty($this->schedule)) return null;
		$kf_worker = array();
		foreach ($this->schedules as $id6d => $schedule) {
			foreach ($schedule as $schedule_id => $value) {
				if (in_array($schedule_id,$schedule_ids) || empty($schedule_ids)) {
					$kf_worker[] = $this->allWorkers[$id6d]['worker_id'];
					break;
				}
			}
		}
		return $kf_worker;
	}

	//获取排班情况
	function getSchedule(){
		$schedule = array();
		$sql = "SELECT * FROM kf_schedule a LEFT JOIN kf_schedule_detail b ON a.schedule_id=b.schedule_id WHERE a.company_id={$this->company_id}";
		$re = db_query($sql);
		foreach ($re as $v) {
			if($v['schedule_type'] == 1){//分组
				if(count($this->allGroups[$v['schedule_obj']]['workers'])>0){
					foreach ($this->allGroups[$v['schedule_obj']]['workers'] as $key => $value) {
						$schedule[$key][$v['schedule_id']]['schedule_days']=$v['schedule_days'];
						$schedule[$key][$v['schedule_id']]['start_time']=$v['start_time'];
						$schedule[$key][$v['schedule_id']]['end_time']=$v['end_time'];
					}
				}
			}elseif($v['schedule_type'] == 2){//人员
				$schedule[$v['schedule_obj']][$v['schedule_id']]['schedule_days']=$v['schedule_days'];
				$schedule[$v['schedule_obj']][$v['schedule_id']]['start_time']=$v['start_time'];
				$schedule[$v['schedule_obj']][$v['schedule_id']]['end_time']=$v['end_time'];
			}
		}
		$this->schedule = $schedule;
	}

	// 渠道分流
	function setChannelKf(){
		$landpage = $this->getLocalArgs('landpage');
		if ($landpage == '') return null;

		$kf_group = array();// 分组
		$kf_worker = array();// 人员

		//zd_type 1:指定人员;2:指定分组  zd_id 指定人员的情况下是id6d 指定分组的情况下是group_id  shunt_value 渠道(promote_link1,promote_link2,promote_link3...)
		$sql = "SELECT zd_type,zd_id,shunt_value FROM kf_shunt WHERE company_id={$this->company_id} AND style_id={$this->style_id} AND shunt_type=4 ORDER BY id";
		$rows = db_query($sql);
		if (!empty($rows)) {
			foreach ($rows as $row) {
				$valArr = explode(",",$row['shunt_value']);
				if (count($valArr) > 0) {
					foreach ($valArr as $val) {
						$promote_link = $this->getConfigValueNoStyle($val,'');
						if ($promote_link != '') {
							$promote_link = json_decode($promote_link,true);
							if (strpos($landpage,$promote_link['link_init']) !== false) {
								if ($row['zd_type'] == 1) {
									if (isset($this->allWorkers[$row['zd_id']])) {
										$kf_worker[] = $this->allWorkers[$row['zd_id']]['worker_id'];
									}
								}else{
									$kf_group[] = $row['zd_id'];
								}
								break;
							}
						}
					}
				}
			}
		}
		$kf_group = $this->getWorkerIdByGroupId($kf_group);
		$kflist = array_unique(array_merge($kf_worker,$kf_group));
		if (empty($kflist)) return null;
		return $kflist;
	}

	// 来源分流
	function setSourceKf(){
		$source = $this->getLocalArgs('source');
		if ($source == '') return null;

		$kf_group = array();// 分组
		$kf_worker = array();// 人员

		//zd_type 1:指定人员;2:指定分组  zd_id 指定人员的情况下是id6d 指定分组的情况下是group_id  shunt_value 来源(baidu,360,sogou...)
		$sql = "SELECT zd_type,zd_id,shunt_value FROM kf_shunt WHERE company_id={$this->company_id} AND style_id={$this->style_id} AND shunt_type=3 ORDER BY id";
		$rows = db_query($sql);

		if (!empty($rows)) {
			foreach ($rows as $row) {
				$valArr = explode(",",$row['shunt_value']);
				if (count($valArr) > 0) {
					foreach ($valArr as $val) {
						if ($val == $source) {
							if ($row['zd_type'] == 1) {
								if (isset($this->allWorkers[$row['zd_id']])) {
									$kf_worker[] = $this->allWorkers[$row['zd_id']]['worker_id'];
								}
							}else{
								$kf_group[] = $row['zd_id'];
							}
							break;
						}
					}
				}
			}
		}
		$kf_group = $this->getWorkerIdByGroupId($kf_group);
		$kflist = array_unique(array_merge($kf_worker,$kf_group));
		if (empty($kflist)) return null;
		return $kflist;
	}

	//区域分流模式  数据处理
	function setQyflKf(){
		$sql = "SELECT prov,city,group_id,worker_id,kfassign_group_id,style_id FROM area_kf WHERE company_id={$this->company_id} AND style_id={$this->style_id} ORDER BY style_id";
		$rows = db_query($sql);
		$area_ry = $area_fz = array();
		if(count($rows) > 0){
			foreach($rows as $row){
				$group_id = $row['group_id'];
				$worker_id = $row['worker_id'];
				$kfassign_group_id = $row['kfassign_group_id'];
				$prov = $row['prov'];
				$city = $row['city'];

				if($prov != '' || $city != ''){
					$area = $city != '' ? $city : $prov;
					if($worker_id != '' && $worker_id != '-1'){//人员
						$area_ry[$worker_id][] = $area;
					}

					if($kfassign_group_id != 0 && $worker_id != "-1" && ($group_id == '' || $group_id == '0')){//分组
						$area_fz[$kfassign_group_id][] = $area;
					}
				}
			}
		}
		if (empty($area_ry) && empty($area_fz)) return null;

		$ip_info = $this->getLocalArgs('ipinfo');
		$areas = array("安徽","北京","重庆","福建","甘肃","广东","广西","贵州","海南","河北","黑龙江","河南","湖北","湖南","江苏","江西","吉林","辽宁","宁夏","内蒙古","青海","上海","山西","山东","四川","陕西","天津","西藏","新疆","云南","浙江","台湾","香港","澳门");
		$ip_addr = "国外";
		$continents_arr = array("亚洲","欧洲","非洲","南美洲","北美洲","大洋洲","南极洲");
		$ip_cont = '';
		foreach ($areas as $area){
			if (strpos($ip_info['area'],$area) !== false) {
				$ip_addr = $ip_info['area'];
				break;
			}
		}
		foreach ($continents_arr as $con) {
			if (strpos($con, $ip_info['continents']) !== false){
				// $ip_cont = $ip_info['continents'];
				$ip_cont = $con;
				break;
			}
		}

		$kf_worker = $kf_group = array();
		foreach ($area_ry as $worker_id => $areas) {
			foreach ($areas as $area) {
				if (strpos($ip_addr,$area) !== false || strpos($ip_cont,$area) !== false) {
					$kf_worker[] = $worker_id;
					break;
				}
			}
		}
		foreach ($area_fz as $group_id => $areas) {
			foreach ($areas as $area) {
				if (strpos($ip_addr,$area) !== false || strpos($ip_cont,$area) !== false) {
					$kf_group[] = $group_id;
					break;
				}
			}
		}
		$kf_group = $this->getWorkerIdByGroupId($kf_group);
		$kflist = array_unique(array_merge($kf_worker,$kf_group));
		if (empty($kflist)) return null;
		return $kflist;
	}

	//根据分组id获取worker_id
	function getWorkerIdByGroupId($group_ids){
		$workerIdArr = array();
		foreach ($group_ids as $group_id) {
			if (isset($this->allGroups[$group_id])) {
				foreach ($this->allGroups[$group_id]['workers'] as $worker) {
					$workerIdArr[] = $worker['worker_id'];
				}
			}
		}
		return array_unique($workerIdArr);
	}

	//获取所有分组及其下的所有客服
	function getAllGroupWorkers(){
		$this->onlineId6ds = $this->redis->smembers('status.com.{'.$this->company_id.'}');
		$expired_time = $this->redis->get('combo.expired.time')?$this->redis->get('combo.expired.time'):10;
		if (date('H') < $expired_time) {
			// 到期后还能允许使用一段时间
			$today = date('Ymd',strtotime("-1day")); 
		} else {
			$today = date('Ymd');
		}
		$sql = "SELECT 
					a.id6d AS id6d,
					a.worker_id AS worker_id,
					a.max_link AS max_link,
					a.name AS name,
					a.ly_auto_time As ly_auto_time,
					f.bname AS bname,
					g.group_id AS group_id,
					g.group_name AS group_name
				FROM worker a
				LEFT JOIN kfassign_group_worker w on a.id6d=w.id6d
				LEFT JOIN kfassign_group g on g.group_id=w.group_id
				LEFT JOIN worker_infos f on a.company_id=f.company_id AND a.id6d=f.id6d
				WHERE a.company_id={$this->company_id}
					AND exists (SELECT 
							1
						FROM module_new c
						WHERE c.company_id={$this->company_id}
							AND c.id6d = a.id6d
							AND c.module_id = 'kefu'
							AND c.enable = '1'
							AND c.exp_date >= $today
							AND a.resign_type = 0)
				ORDER BY a.number ASC";
		$res = db_query($sql);
		$allGroups = $allWorkers = $noGroupWorkers = array();
		foreach ($res as $k => $v) {
			$worker = [
				'id6d' => $v['id6d'],
				'worker_id' => $v['worker_id'],
				'name' => $v['name'],
				'bname' => $v['bname'],
				'max_link' => $v['max_link'],
				'ly_auto_time' => $v['ly_auto_time'],
				'is_online' => in_array($v['id6d'],$this->onlineId6ds) ? 1 : 0
			];
			if (!isset($allWorkers[$v['id6d']])) {
				$allWorkers[$v['id6d']] = $worker;
			}
			if ($v['group_id'] == null) {
				if (!isset($noGroupWorkers[$v['id6d']])) {
					$noGroupWorkers[$v['id6d']] = $worker;
				}
				continue;
			}
			if (!isset($allGroups[$v['group_id']])) {
				$allGroups[$v['group_id']] = [
					'group_id' => $v['group_id'],
					'group_name' => $v['group_name']
				];
			}
			if (!isset($allGroups[$v['group_id']]['workers'][$v['id6d']])) {
				$allGroups[$v['group_id']]['workers'][$v['id6d']] = $worker;
			}
		}
		if (!empty($noGroupWorkers)) {
			$allGroups[0] = [
				'group_id' => 0,
				'group_name' => '未分组',
				'workers' => $noGroupWorkers
			];
		}
		// $this->allGroups = $allGroups;
		$this->allGroups = $this->getOrderGroups($allGroups);
		$this->allWorkers = $allWorkers;
	}

	function getOrderGroups($allGroups){
		$orderGroups = [];
		$sql = "SELECT group_id FROM kfassign_group_show WHERE style_id={$this->style_id} ORDER BY kforder";
		$res = db_query($sql);
		foreach ($res as $key => $val) {
			if (isset($allGroups[$val['group_id']])) {
				$orderGroups[$val['group_id']] = $allGroups[$val['group_id']];
				unset($allGroups[$val['group_id']]);
			}
		}
		foreach ($allGroups as $group_id => $group) {
			if (!isset($orderGroups[$group_id])) {
				$orderGroups[$group_id] = $group;
			}
		}
		return $orderGroups;
	}

	//获取机器人相关信息
	function setRobot(){
		if($this->comInfo['facilitator_id'] == $this->cfg["huawei_fid"]){
			$rtask_open = 0;
			$hw_task = $this->redis->hmget("company.config.clue.".$this->company_id,array("total","use","switch"));
			if(($hw_task["switch"] == "open") && ($hw_task["total"]>$hw_task["use"])){
				$rtask_open = 1;//独立版
			}
		}else {
			$rtask_num = $this->redis->get("com.robot.task." . $this->company_id);//线索追问 剩余次数
			
			if ($rtask_num > 0) {
				$rtask_open = 2;
			} else {
				$rtask_year = $this->redis->get("task.robot.year.".$this->company_id);
				if ($this->comInfo["dzh_main"] != "") {
					$dzh_rtask = $this->redis->get("task.robot.dzh." . $this->comInfo["dzh_main"]);
				}
				if($rtask_year == '1' || $dzh_rtask == '1' || $this->cfg["rtask_open"] == '1' ) $rtask_open = 1;
			}
		}
		$this->setLocalArgs('task_hots',[]);
		$robotList = $this->getRobotList($rtask_open);
		$zsk_datas = array();//线索机器人节点信息
		foreach ($robotList as $robot_id => $robot_info) {
			if (isset($robot_info["robot_data_info"])) {
				$robotList[$robot_id]["task_robot_info"] = $robot_info["robot_data_info"]["robot_data"];
				$zsk_datas[$robot_id] = $robot_info["robot_data_info"]["zsk_data"];
				unset($robotList[$robot_id]["robot_data_info"]);
			}
		}
		
		//已选定的机器人
		$robot_id = $this->getConfigValue('robot_id','');
		$frobot_id = $this->getConfigValue('frobot_id','');

//		$robot_data_info = $this->getTaskInfo();
//		$task_robot_info = $robot_data_info["robot_data"];
//		$zsk_data = $robot_data_info["zsk_data"];

		$task_robot_info = array();//机器人线索追问信息

		//机器人对话信息
		$talk_robot_infos = $this->redis->hmget("talk.robot.".$this->company_id.".".$this->guest_id.".".$this->style,array("khnumber","task_zsk_id","index","index_times","guide_size"));
		if(!is_null($talk_robot_infos["khnumber"])){
			$talk_robot_info["khnumber"] = $talk_robot_infos["khnumber"];
			if (in_array($this->company_id, $this->cfg["robotnlp_company_id"])) {//纯问答AI模式机器人
				if (is_numeric($talk_robot_infos["task_zsk_id"])) {
					$talk_robot_info["task_zsk_id"] = "";
					$talk_robot_info["index"] = 0;
					$talk_robot_info["index_times"] = 0;
				} else {
					$talk_robot_info["task_zsk_id"] = $talk_robot_infos["index"] == "" ? "" : $talk_robot_infos["task_zsk_id"];
					$talk_robot_info["index"] = $talk_robot_infos["index"] == "" ? 0 : $talk_robot_infos["index"];
					$talk_robot_info["index_times"] = $talk_robot_infos["index_times"] == "" ? 0 : $talk_robot_infos["index_times"];
				}
			} else {//常规追问线索式流程机器人
				foreach ($zsk_datas as $key => $zsk_data) {
					if (isset($zsk_data[$talk_robot_infos["task_zsk_id"]])) {
						$talk_robot_info["now_task"] = $zsk_data[$talk_robot_infos["task_zsk_id"]];
						if ($zsk_data[$talk_robot_infos["task_zsk_id"]]["link_id"] != "0") {
							$talk_robot_info["task_zsk_id"] = $zsk_data[$talk_robot_infos["task_zsk_id"]]["link_id"];
						} else if ($zsk_data[$talk_robot_infos["task_zsk_id"]]["id"] != "0") {
							$talk_robot_info["task_zsk_id"] = $zsk_data[$talk_robot_infos["task_zsk_id"]]["id"];
						} else {
							$talk_robot_info["task_zsk_id"] = 0;
						}
						$talk_robot_info["index"] = $talk_robot_infos["index"] == "" ? 0 : $talk_robot_infos["index"];
						$talk_robot_info["index_times"] = $talk_robot_infos["index_times"] == "" ? 0 : $talk_robot_infos["index_times"];
						break;
					}
				}

				if (!isset($talk_robot_info["now_task"])) {
					if ($talk_robot_infos["task_zsk_id"] == 0) {
						$talk_robot_info["task_zsk_id"] = -1;
						$talk_robot_info["index"] = $talk_robot_infos["index"] == "" ? 0 : $talk_robot_infos["index"];
						$talk_robot_info["index_times"] = $talk_robot_infos["index_times"] == "" ? 0 : $talk_robot_infos["index_times"];
					} else {
						$talk_robot_info["task_zsk_id"] = 0;
						$talk_robot_info["index"] = 0;
						$talk_robot_info["index_times"] = 0;
					}
					$talk_robot_info["now_task"] = array();
				}
			}

			$talk_robot_info["guide_size"] = $talk_robot_infos["guide_size"] == "" ? -1 : $talk_robot_infos["guide_size"];
			$talk_robot_info["guest_id"] = $this->guest_id;

//			if(isset($zsk_data[$talk_robot_infos["task_zsk_id"]])){
//				$talk_robot_info["now_task"] = $zsk_data[$talk_robot_infos["task_zsk_id"]];
//
//				if($zsk_data[$talk_robot_infos["task_zsk_id"]]["link_id"] != "0"){
//					$talk_robot_info["task_zsk_id"] = $zsk_data[$talk_robot_infos["task_zsk_id"]]["link_id"];
//				}else if($zsk_data[$talk_robot_infos["task_zsk_id"]]["id"] != "0"){
//					$talk_robot_info["task_zsk_id"] = $zsk_data[$talk_robot_infos["task_zsk_id"]]["id"];
//				}else{
//					$talk_robot_info["task_zsk_id"] = 0;
//				}
//				$talk_robot_info["index"] = $talk_robot_infos["index"] == "" ? 0 : $talk_robot_infos["index"];
//				$talk_robot_info["index_times"] = $talk_robot_infos["index_times"] == "" ? 0 : $talk_robot_infos["index_times"];
//			}else{
//				if ($talk_robot_infos["task_zsk_id"] == 0) {
//					$talk_robot_info["task_zsk_id"] = -1;
//					$talk_robot_info["index"] = $talk_robot_infos["index"] == "" ? 0 : $talk_robot_infos["index"];
//					$talk_robot_info["index_times"] = $talk_robot_infos["index_times"] == "" ? 0 : $talk_robot_infos["index_times"];
//				}else{
//					$talk_robot_info["task_zsk_id"] = 0;
//					$talk_robot_info["index"] = 0;
//					$talk_robot_info["index_times"] = 0;
//				}
//				$talk_robot_info["now_task"] = array();
//			}
//			$talk_robot_info["guide_size"] = $talk_robot_infos["guide_size"] == "" ? -1 : $talk_robot_infos["guide_size"];
//			$talk_robot_info["guest_id"] = $this->guest_id;
		}else{
			$talk_robot_info = array();
		}

		$robot_prompt_guide = array();
		if ($robotList[$robot_id]['task_robot_use'] == '1' || $robotList[$frobot_id]['task_robot_use'] == '1') {
			$robot_prompt_guide = $this->getLocalArgs("prompt_guide_list");
		}

		$taskHotsInfo = $this->getTaskHotsInfo();

		//任务库match_first正则匹配优先，keyword_first关键词匹配优先
		$task_type = isset($this->cfg["task_type"]) ? $this->cfg["task_type"] : 'match_first';
		//机器人服务 域名
		if($this->comInfo["cloud_service"] != "" && $this->comInfo["cloud_service"] != "jh") {
			$robot_host = $this->comInfo["alias"];
		}else {
			$robot_host = $this->cfg["robot_host"];
		}

		//问答ai机器人启用开关
		$nlp_robot_use = 0;
		if (in_array($this->company_id, $this->cfg["robotnlp_company_id"])) $nlp_robot_use = 1;

		//常规ai回复延迟
		$robot_answer_delay = 1000;
		if (isset($this->cfg["robot_answer_delay"])) $robot_answer_delay = $this->cfg["robot_answer_delay"];

		//私有云是否强制显示机器人反馈
		if (!isset($this->cfg['cloud_robot_feedback'])) $this->cfg['cloud_robot_feedback'] = 0;

		$this->tpl->assign("robotList", json_encode($robotList));
		$this->tpl->assign("robot_id", $robot_id);
		$this->tpl->assign("frobot_id", $frobot_id);
		$this->tpl->assign("robot_answer_delay", $robot_answer_delay);
		$this->tpl->assign("nlp_robot_use", $nlp_robot_use);
		$this->tpl->assign("task_robot_info", json_encode($task_robot_info));
		$this->tpl->assign("talk_robot_info", json_encode($talk_robot_info));
		$this->tpl->assign("robot_prompt_guide", json_encode($robot_prompt_guide));
		$this->tpl->assign("taskHotsInfo", json_encode($taskHotsInfo));
		$this->tpl->assign("task_type", $task_type);
		$this->tpl->assign("cloud_robot_feedback", $this->cfg['cloud_robot_feedback']);
		$this->tpl->assign("robot_host", $robot_host);
	}

	function getTaskInfo($task_id){
		$robot_data = array(
			"task_id" => "init",
			"tconn_promet" => array(
				"type"=>"message",
				"content"=>array("您好，为了更好的为您提供服务，建议您留一下联系方式")
			),
			"tclose_promet" =>array(
				0 => array(
					"type"=>"message",
					"content"=>"抱歉，我暂时回答不了这个问题，您可以留下联系方式，我们会尽快回复您"
				)
			),
			"guide_content" => array(
				"0"=>array(
					0=>array(
						"id"=>"init_1",
						"title"=>"是否符合邮箱",
						"parent_id"=>"0",
						"answer"=>array(
							0=>array(
								"type"=>"message",
								"content"=>"收到",
								"time"=>"2"
							),
							1=>array(
								"type"=>"message",
								"content"=>"您这边方便再留一下手机吗？",
								"time"=>"2"
							)
						),
						"else"=>"",
						"question"=>array(
							0=>array(
								"type"=>"match",
								"regular"=>"email"
							)
						),
						"link_id"=>"0"
					),
					1=>array(
						"id"=>"init_2",
						"title"=>"是否符合手机",
						"parent_id"=>"0",
						"answer"=>array(
							0=>array(
								"type"=>"message",
								"content"=>"好的，我们会尽快联系您的",
								"time"=>"2"
							),
						),
						"else"=>"",
						"question"=>array(
							0=>array(
								"type"=>"match",
								"regular"=>"mobile"
							)
						),
						"link_id"=>"0"
					),
					2=>array(
						"id"=>"init_3",
						"title"=>"是否符合QQ",
						"parent_id"=>"0",
						"answer"=>array(
							0=>array(
								"type"=>"message",
								"content"=>"收到",
								"time"=>"2"
							),
							1=>array(
								"type"=>"message",
								"content"=>"您这边方便再留一下手机吗？",
								"time"=>"2"
							)
						),
						"else"=>"",
						"question"=>array(
							0=>array(
								"type"=>"match",
								"regular"=>"qq"
							)
						),
						"link_id"=>"0"
					),
					3=>array(
						"id"=>"init_4",
						"title"=>"是否符合微信",
						"parent_id"=>"0",
						"answer"=>array(
							0=>array(
								"type"=>"message",
								"content"=>"好的，我们会尽快联系您的",
								"time"=>"2"
							)
						),
						"else"=>"",
						"question"=>array(
							0=>array(
								"type"=>"match",
								"regular"=>"wechat"
							)
						),
						"link_id"=>"0"
					)
				)
			)
		);

		$sql = "SELECT a.id AS real_task_id,a.tconn_promet,a.tclose_promet,b.* FROM task_robot a LEFT JOIN task_robot_zsk b ON a.id = b.task_id WHERE a.company_id = {$this->company_id} AND a.id = '".$task_id."' ORDER BY b.id ASC";
		$task_robot = db_query($sql);

		if($task_robot && count($task_robot)>0){
			$robot_data['task_id'] = $task_robot[0]['real_task_id'];
			if ($task_robot[0]["tconn_promet"] != "") $robot_data['tconn_promet'] = json_decode($task_robot[0]["tconn_promet"],true);
			if ($task_robot[0]["tclose_promet"] != "") $robot_data['tclose_promet'] = json_decode($task_robot[0]["tclose_promet"],true);
			if ($robot_data['tconn_promet']['type'] == 'messages') {
				$task_hots = $this->getLocalArgs('task_hots');
				foreach ($robot_data['tconn_promet']['content'] as $promet) {
					if ($promet['type'] == 'ask_hots') {
						$task_hots = array_merge($task_hots,$promet['hots']);
					}
				}
				$this->setLocalArgs('task_hots',$task_hots);
			}
			
			$robot_data['guide_content'] = array();

			$zsk_data = array();//所有问答对列表，处理link使用
			foreach($task_robot as $task_zsk){
				if($task_zsk["id"] == "" || $task_zsk["unique_id"] == "") continue;
				$task_zsk["id"] = $task_zsk["unique_id"];
				unset($task_zsk["unique_id"]);
				$task_zsk_data = $this->processQuesData($task_zsk,$zsk_data);
				$zsk_data[$task_zsk["id"]] = $task_zsk_data;
				if ($task_zsk_data["parent_id"] == '') $task_zsk_data["parent_id"] = '0';
				if ($task_zsk_data["link_id"] == '') $task_zsk_data["link_id"] = '0';
				$robot_data["guide_content"][$task_zsk_data["parent_id"]][] = $task_zsk_data;
			}
		}
		$robot_data_info = array(
			"robot_data"=>$robot_data,
			"zsk_data"=>$zsk_data,
		);
		return $robot_data_info;
	}

	function processQuesData($task_zsk,$zsk_data){
		if($task_zsk["link_id"] != '' && $task_zsk["link_id"] != '0'  && isset($zsk_data[$task_zsk["link_id"]])){
			$task_zsk["question"] = $zsk_data[$task_zsk["link_id"]]["question"];
			$task_zsk["answer"] = $zsk_data[$task_zsk["link_id"]]["answer"];
			$task_zsk["un_answer"] = $zsk_data[$task_zsk["link_id"]]["else"];
		}else{
			if($task_zsk["question"] != ""){
				$task_zsk["question"] = json_decode($task_zsk["question"],true);
			}else{
				$task_zsk["question"] = array(
					0 => array(
						"type"=>"match",
						"regular"=>"",
					),
				);
			}
			if($task_zsk["answer"] != ""){
				$task_zsk["answer"] = json_decode( $task_zsk["answer"],true);
			}
			if($task_zsk["un_answer"] != ""){
				if($task_zsk["un_answer"] != "{}"){
					$task_zsk["un_answer"] = json_decode( $task_zsk["un_answer"],true);
				}else{
					$task_zsk["un_answer"] =array(
						0 => array(
							"type"=>"message",
							"content"=>"很抱歉，能否再描述一下您的问题，我不太理解",
						),
					);
				}
			}
		}
		$data = array(
			"id"=>$task_zsk["id"],
			"title"=>$task_zsk["title"],
			"parent_id"=>$task_zsk["parent_id"],
			"answer"=>$task_zsk["answer"],
			"un_answer"=>$task_zsk["un_answer"],
			"question"=>$task_zsk["question"],
			"link_id"=>$task_zsk["link_id"]
		);
		return $data;
	}

	function getTaskHotsInfo(){
		$hots = [];
		$task_hots = $this->getLocalArgs('task_hots');
		if (!empty($task_hots)) {
			$task_hots = array_unique($task_hots);
			$ids = implode("','", $task_hots);
			$sql = "SELECT id,question,answer FROM zsk_question WHERE company_id={$this->company_id} AND id IN ('$ids')";
			$res = db_query($sql);
			foreach ($res as $val) {
				$hots[$val['id']]['question'] = $val['question'];
				$answer = str_replace(array("\t","\n","\r"),array("","",""),$val["answer"]);
				$answer = htmlspecialchars($answer , ENT_QUOTES);
				$hots[$val['id']]['answer'] = str_replace(['&quot;','&#039;'],['\&quot;','\&#039;'],$answer);
			}
		}
		return $hots;
	}

	//根据机器人id获取机器人热点问题
	function getHotQuestions($robot_id){
		$hot_sql = "SELECT b.id, b.question, b.answer FROM robot_hot a LEFT JOIN zsk_question b ON a.question_id=b.id WHERE a.robot_id='$robot_id' ORDER BY 'order' DESC";
		$hot_questions = db_query($hot_sql);
		$hots = array();
		foreach ($hot_questions as $k=>$v) {
			if ($v["id"] != "") {
				$hot['id'] = $v["id"];
				$hot["question"] = $v["question"];
				//答案去掉表格换行符
				$answer = str_replace(array("\t","\n","\r"),array("","",""),$v["answer"]);
				$answer = htmlspecialchars($answer , ENT_QUOTES);
				$hot["answer"] = str_replace(['&quot;','&#039;'],['\&quot;','\&#039;'],$answer);
				$hots[] = $hot;
			}
		}
		return $hots;
	}

	//获取机器人变量信息
	public function getTaskVars($robot_id)
	{
		$vars = array();
		$time = $this->getMillisecond();

		/** 取redis存储变量的guest_id，默认使用get参数里面的guest_id */
		// $redis_var_guest = $_GET['guest_id'] != '' ? $_GET['guest_id'] : $this->guest_id;
		$redis_var_guest = $this->guest_id;

		/** 获取redis内存储的变量 */
		$redis_wechats[0] = $this->redis->get('53kf_'.$this->company_id.'_'.$robot_id.'_'.$redis_var_guest.'_answer_wechat_info');
		$redis_phones[0] =$this->redis->get('53kf_'.$this->company_id.'_'.$robot_id.'_'.$redis_var_guest.'_answer_phone_info');

		$wechats = $this->redis->zrangebyscore("com.task.variate.wechat.".$this->company_id.".".$robot_id,0,$time,array('limit'=>array(0,1)));
		$phones = $this->redis->zrangebyscore("com.task.variate.phone.".$this->company_id.".".$robot_id,0,$time,array('limit'=>array(0,1)));
		
		if ($redis_wechats[0] == '') {				//redis内没有对应变量则存储并设置过期时间为1天
			$this->redis->set('53kf_'.$this->company_id.'_'.$robot_id.'_'.$redis_var_guest.'_answer_wechat_info',$wechats[0]);
			$this->redis->expire('53kf_'.$this->company_id.'_'.$robot_id.'_'.$redis_var_guest.'_answer_wechat_info',24*60*60);
		}
		if ($redis_phones[0] == '') {
			$this->redis->set('53kf_'.$this->company_id.'_'.$robot_id.'_'.$redis_var_guest.'_answer_phone_info',$phones[0]);
			$this->redis->expire('53kf_'.$this->company_id.'_'.$robot_id.'_'.$redis_var_guest.'_answer_phone_info',24*60*60);
		}

		if ($redis_wechats[0] != '') {
			$vars[] = array("tag"=>"{{微信}}","val"=>$redis_wechats[0]);
		} elseif (count($wechats)>0 && $wechats[0] != "") {
			$vars[] = array("tag"=>"{{微信}}","val"=>$wechats[0]);
			$this->redis->zadd("com.task.variate.wechat.".$this->company_id.".".$robot_id,$time,$wechats[0]);
		} else {
			$vars[] = array("tag"=>"{{微信}}","val"=>'');
		}
		
		if ($redis_phones[0] != '') {
			$vars[] = array("tag"=>"{{手机}}","val"=>$redis_phones[0]);
		} elseif (count($phones)>0 && $phones[0] != "") {
			$vars[] = array("tag"=>"{{手机}}","val"=>$phones[0]);
			$this->redis->zadd("com.task.variate.phone.".$this->company_id.".".$robot_id,$time,$phones[0]);
		} else {
			$vars[] = array("tag"=>"{{手机}}","val"=>'');
		}


		return $vars;
	}

	//获取所有机器人详细信息
	function getRobotList($rtask_open){
		//普通机器人
		$sql = "SELECT * FROM robot WHERE company_id={$this->company_id} ORDER BY id";
		$robots = db_query($sql);
		//api机器人
		$api_robots = array();
		$api_auto_renews = array();
		$expired_time = $this->redis->get('combo.expired.time')?$this->redis->get('combo.expired.time'):10;
		if (date('H') < $expired_time) {
			// 到期后还能允许使用一段时间
			$today = date('Ymd',strtotime("-1day")); 
		} else {
			$today = date('Ymd');
		}
		// $today = date("Ymd");
		$sql = "SELECT api_id, auto_renew FROM api_module WHERE company_id={$this->company_id} AND exp_date>='$today' ORDER BY id";
		$res = db_query($sql);
		foreach($res as $re){
			$api_robots[$re["api_id"]] = 1;
			$api_auto_renews[$re["api_id"]] = $re["auto_renew"];
		}
		//处理机器人信息
		$robotList = array();
		foreach ($robots as $robot){
			$re = array();
			if($this->cfg["ly_open"][$this->company_id] == '1'){//来也机器人手动配置
//				$re["api_robot_id"] = $robot["id"];
//				$re["api_name"] = "ly";
			}else{
				if(isset($api_robots[$robot["api_robot_id"]])){
					$re["api_robot_id"] = $robot["api_robot_id"];
					$re["api_name"] = htmlspecialchars($robot["api_name"]);
				}else{
					$re["api_robot_id"] = "";//第三方机器人id
					$re["api_name"] = "";//第三方机器人名称
				}
			}
			//云问机器人的设置都在云问后台，所以部分信息要调接口获取
			if ($re["api_name"] == 'yw') {
				require_once 'lib/common/robot.class.php';
				$yunwen_robot = new RobotApi($this->company_id,'yw');
				$webConfig = $yunwen_robot->getWebConfig($robot["api_robot_id"],$this->guest_id);
				if (!empty($webConfig)) {
					$re["name"] = $webConfig['robotName'];
					$re["prompt"] = $webConfig['helloWord'];
					$re["un_prompt"] = $webConfig['unknownWord'];
					$re["zsktb_url"] = $this->getLocalArgs("adminHeaderUrl");
				}
			}else{
				// 机器人名称
				$re["name"] = htmlspecialchars($robot["name"]);
				// 机器人问候语
				$re["prompt"] = str_replace(array("\r\n", "\r", "\n"), '<br>', htmlspecialchars($robot["prompt"]));
				// 机器人未接通问候语
				$re["un_prompt"] = str_replace(array("\r\n", "\r", "\n"), '<br>', htmlspecialchars($robot["un_prompt"]));
				// 机器人头像
				if ($robot["zsktb_url"] == null) $robot["zsktb_url"] = "";
				$re["zsktb_url"] = $robot["zsktb_url"] == "" ? "/style/setting/ver07/img/task_robot_logo.png" : htmlspecialchars($robot["zsktb_url"]);
			}
			//机器人id
			$re["id"] = htmlspecialchars($robot["id"]);

			//自研ai机器人已到期，该机器人就不能用了
			if ($re["api_name"] == '' && $robot["api_name"] == "ai") continue;

			//自研ai机器人，且未到期
			if ($re["api_name"] == 'ai') {
				//自研ai非永久剩余次数
				$ai_num = $this->redis->get("robot.ai.".$this->company_id.".".$re["id"]);
				$ai_num = $ai_num == "" ? 0 : $ai_num;

				//自研ai永久剩余次数
				$ai_permanent_num = $this->redis->get("robot.ai.permanent.".$this->company_id.".".$re["id"]);
				$ai_permanent_num = $ai_permanent_num == "" ? 0 : $ai_permanent_num;

				//自研ai次数不够了，通过rabbitmq通知续费
				if ($api_auto_renews[$re["api_robot_id"]] == 1 && $ai_num <= 200 && $ai_permanent_num <= 200) {
					$order_rabbit_data = array(
						"action" => "ai_robot_times",
						"robot_id" => $re["id"]
					);
					$this->setOrderRabbit($order_rabbit_data);
				}

				//ai次数用完
				if ($ai_num <= 0 && $ai_permanent_num <= 0) continue;
			}


			//反馈开关，1开启，0关闭
			$re["feedback"] = $robot["feedback"];
			//留言在输入区域不显示，1开启，0关闭
			$re["lwswitch"] = $robot["lwswitch"];
			//1 自动转人工 0不自动转
			$re["zdzrg"] = $robot["zdzrg"];
			// 未回答次数达到多少次  自动转人工
			$re["unret_times"] = $robot["unret_times"];
			// 0 一直显示转人工按钮 1 访客说话，才显示转人工按钮 2一直不显示转人工按钮
			$re["admit_rule"] = $robot["admit_rule"];
			// 关键词转人工（json数组）array(0=>array('key_word'=>'人工','match_type'=>'0'));  0为精确匹配 1为模糊匹配
			$re["kw_trans"] = json_decode($robot["kw_trans"],true);
			if (empty($re["kw_trans"])) $re["kw_trans"] = [];
			//机器人启用任务库开关
			$re["task_robot_use"] = 0;

			//老版机器人，追问线索独立开关
			if(($rtask_open == 1 || ($rtask_open == 2 && $robot["task_robot_use"])) && $re["api_name"] != 'ai'){
				$re["task_robot_use"] = 1;
			}

			//新版自研ai机器人，只要未到期就开着
			if ($re["api_name"] == 'ai') $re["task_robot_use"] = 1;


			//变量设置
			$re["vars"] = array();
			if ($re["task_robot_use"] == 1) {
				$re["vars"] = $this->getTaskVars($robot["id"]);
				$re["robot_data_info"] = $this->getTaskInfo($robot["task_robot_id"]);
			}
			//机器人热点问题
			$re["hots"] = $this->getHotQuestions($robot["id"]);
			//机器人超时追问
			$re["robot_time"] = $this->getRTimeoutQues($robot["id"]);

			//任务问答开关
			$re['task_switch'] = $this->redis->get('robot.task.switch.'.$robot["id"]);
			$re['task_switch'] = $re['task_switch']?1:0;
			$robotList[$re["id"]] = $re;
		}
		return $robotList;
	}

	//机器人超时追问
	public function getRTimeoutQues($robot_id)
	{
		$sql = "SELECT switch,robot_timeout_data FROM robot_timeout_question WHERE company_id=".$this->company_id." AND robot_id='".$robot_id."'";
		$robot_time = db_query1($sql);

		if (!isset($robot_time["switch"])) {
			$robot_time = array(
				"switch" => 0,
				"robot_timeout_data" => array()
			);
		} else {
			$robot_time["robot_timeout_data"] = json_decode($robot_time["robot_timeout_data"], true);
		}

		//兼容switch 在ie老版本是关键字问题
		$robot_time["isopen"] = $robot_time["switch"];

		return $robot_time;
	}

	//咨询前注册(功能已弃用，为了不改变客户现有设置，目前只有开启的客户能在后台看到此功能，一旦设置为关闭后将不再显示)
	function setReg(){
		$reg = $this->getConfigValue("reg",'0');//访客注册开关  0:关闭  1:开启
		if ($reg != '1') {//没开启就不处理数据了
			$reg_prompt = '';
			$fkzc_fields = [];
		}else{
			//注册提示语
			$reg_prompt = $this->dealPrompt($this->getConfigValue('reg_prompt',$this->lang_default['reg_prompt']),true);
			//注册需填写字段
			$fkzc_fields = $this->getConfigValue("fkzc_fields",'');
			$fkzc_fields = json_decode($fkzc_fields,true);
			if (empty($fkzc_fields)) {
				$fkzc_fields[] = array('name' => '姓名','isMust' => '1','field_name' => 'name','order' => '0','isZdy' => '0');
				$fkzc_fields[] = array('name' => '手机','isMust' => '1','field_name' => 'mobile','order' => '1','isZdy' => '0');
			}
			foreach ($fkzc_fields as $key => $value) {
				if (isset($this->lang_default[$value['field_name']])) {
					$fkzc_fields[$key]['name'] = $this->lang_default[$value['field_name']];
				}
			}
		}

		//判断是否已经注册过
		$is_reg = 0;
		$cus_user_table = $this->comInfo['cus_user_table'];
		$sql = "SELECT 1 FROM $cus_user_table WHERE company_id={$this->company_id} AND guest_id='{$this->guest_id}'";
		$is_exists = db_exists($sql);
		if ($is_exists) $is_reg = 1;
		
		$this->tpl->assign("reg", $reg);
		$this->tpl->assign("reg_prompt", $reg_prompt);
		$this->tpl->assign("fkzc_fields", json_encode($fkzc_fields));
		$this->tpl->assign("is_reg", $is_reg);
	}

	//获取留言相关设置
	function setLword(){
		//留言提示语
		$lword_prompt = $this->dealPrompt($this->getConfigValue('lword_prompt',$this->lang_default['lword_prompt']),true);
		//留言需填写字段
		$fkly_fields = $this->getConfigValue("fkly_fields",'');
		$fkly_fields = json_decode($fkly_fields,true);
		if (empty($fkly_fields)) {
			$fkly_fields[] = array('name' => '姓名','isMust' => '1','field_name' => 'name','order' => '0','isZdy' => '0');
			$fkly_fields[] = array('name' => '手机','isMust' => '1','field_name' => 'mobile','order' => '1','isZdy' => '0');
		}
		foreach ($fkly_fields as $key => &$value) {
			$value['field_name'] = trim($value['field_name']);
			if (isset($this->lang_default[$value['field_name']])) {
				$value['name'] = $this->lang_default[$value['field_name']];
			}
		}
		//分配方式   0：手动分配   1：自动分配
		$ly_assign_type = $this->getConfigValue('ly_assign_type','1');
		//指定方式  zbkf：值班客服(新版已弃用)  zdgs：指定公司  zdfz：指定分组  zdkf：指定客服
		$ly_assign_obj = $this->getConfigValue('ly_assign_obj','zdgs');
		//指定对象  指定分组：分组id 指定客服：客服id6d 值班客服，公司：空
		$ly_assign_value = $this->getConfigValue('ly_assign_value','');
		//分配方式  留言验证码 1：开启 2：关闭
		$ly_captcha = $this->getConfigValue('ly_captcha','2');

		$get_zdkf_type = $this->getValue("zdkf_type",'');
		$get_id6d = $this->getValue("id6d",'');
		if ($get_zdkf_type == '4' && $get_id6d){
			$ly_assign_type = '1';	//分配方式 1：自动分配
			$ly_assign_obj = 'zdkf';	//指定方式 zdkf：指定客服
			$ly_assign_value = $get_id6d;	//指定对象 指定客服：客服id6d
			$ly_captcha = '2';	//留言验证码 2：关闭
		}

		$lwordObjectInfo = $this->getLwordObject($ly_assign_type,$ly_assign_obj,$ly_assign_value);

		$this->tpl->assign("lword_prompt", $lword_prompt);
		$this->tpl->assign("fkly_fields", json_encode($fkly_fields));
		$this->tpl->assign("ly_assign_type", $ly_assign_type);
		$this->tpl->assign("ly_assign_obj", $ly_assign_obj);
		$this->tpl->assign("ly_assign_value", $ly_assign_value);
		$this->tpl->assign("lwordObjectInfo", json_encode($lwordObjectInfo));
		$this->tpl->assign("ly_captcha", $ly_captcha);
	}

	//获取留言对象
	function getLwordObject($ly_assign_type,$ly_assign_obj,$ly_assign_value){
		$valueArr = $ly_assign_value == '' ? [] : explode(',',$ly_assign_value);
		$objectArr = [];
		$objectType = 'auto';
		$object = '';
		if ($ly_assign_type == '1') {
			if ($ly_assign_obj == 'zdkf') {
				foreach($this->allWorkers as $id6d => $worker){
					if (in_array($id6d,$valueArr) || empty($valueArr)) {
						$objectArr[$id6d] = $worker['ly_auto_time'];
					}
				}
				if (!empty($objectArr)) {
					asort($objectArr);
					$keys = array_keys($objectArr);
					$object = 'w#'.$keys[0];
				}
			}elseif ($ly_assign_obj == 'zdfz') {
				foreach($this->allGroups as $group_id => $group){
					if (in_array($group_id,$valueArr) || empty($valueArr)) {
						$objectArr[] = $group_id;
					}
				}
				if (!empty($objectArr)) {
					$rand_key = array_rand($objectArr);
					$object = 'g#'.$objectArr[$rand_key];
				}
			}
			// elseif ($ly_assign_obj == 'zbkf') {
			// 	foreach($this->allWorkers as $id6d => $worker){
			// 		if ($this->isWorkTime($id6d)) {
			// 			$objectArr[$id6d] = $worker['ly_auto_time'];
			// 		}
			// 	}
			// 	if (!empty($objectArr)) {
			// 		arsort($objectArr);
			// 		$keys = array_keys($objectArr);
			// 		$object = 'w#'.$keys[0];
			// 	}
			// }
		}else{
			if ($ly_assign_obj == 'zdkf') {
				foreach ($this->allGroups as $group_id => $group) {
					foreach($group['workers'] as $id6d => $worker){
						if (in_array($id6d,$valueArr) || empty($valueArr)) {
							if (!isset($objectArr[$group_id])) {
								$objectArr[$group_id]['group_name'] = $group['group_name'];
							}
							$objectArr[$group_id]['workers'][$id6d] = $worker['bname'];
						}
					}
				}
				if (!empty($objectArr)) {
					$object = $objectArr;
					$objectType = 'zdkf';
				}
			}elseif ($ly_assign_obj == 'zdfz') {
				foreach($this->allGroups as $group_id => $group){
					if (in_array($group_id,$valueArr) || empty($valueArr)) {
						$objectArr[$group_id] = $group['group_name'];
					}
				}
				if (!empty($objectArr)) {
					$object = $objectArr;
					$objectType = 'zdfz';
				}
			}
		}
		return ['objectType'=>$objectType,'object'=>$object];
	}

	//检测服务商-商城版域名
	function checkFacDomain(){
		$is_facDomain = true;
		if($this->comInfo["facilitator_type"] == "shop" && $this->comInfo["facilitator_id"] != "26"){
			$fac_domain = $this->redis->smembers("facilitator.domain.{".$this->comInfo["facilitator_id"]."}");
			if(is_array($fac_domain) && $this->talkpage != ""){
				$is_facDomain = false;
				foreach($fac_domain as $val){
					if(strpos($this->talkpage, $val) !== false){
						$is_facDomain = true;
						break;
					}
				}
			}
		}
		if($is_facDomain === false) die('异常链接，您已被阻止!');
	}

	//检测公司站点
	function checkCompanySite(){
		$companysite_switch = $this->getConfigValue("companysite_switch",'0');
		if ($companysite_switch == '1') {
			$companysite = json_decode($this->getConfigValue("companysite",''),true);//公司站点
			if (!empty($companysite)) {
				$isCompanySite = $start = false;
				foreach($companysite as $val){
					if($val['isstart'] == 'yes'){
						$start = true;
						if(strpos($this->talkpage, $val['sdomain']) !== false){
							$isCompanySite = true;
							break;
						}
					}
				}
				if (!$start) $isCompanySite = true;
				if (!$isCompanySite) die('异常链接，您已被阻止!');
			}
		}
	}

	//检查访客端定制，若是老版访客端定制，则跳到老版访客端
	function checkChatStyle(){
		$company_tpl = "newchat";
		if(isset($_GET["tpl"]) && $_GET["tpl"]=="minichat2") $company_tpl = "minichat";
		$minchat_style = $_GET['minchat_style'] ? $_GET['minchat_style']+0 : 1;
		$khchat_style = $this->getConfigValue("khchat_style",'0') + 0;
		if (($company_tpl == 'newchat' && $khchat_style > 0 && $khchat_style < 3) || ($company_tpl == 'minichat' && $minchat_style > 1 && $minchat_style < 21)) {
			header("location:{$this->http}://".$_SERVER["HTTP_HOST"]."/webCompany_old.php?".$_SERVER["QUERY_STRING"]);
			exit();
		}
		$this->setLocalArgs('company_tpl',$company_tpl);
		$this->setLocalArgs('minchat_style',$minchat_style);
		$this->setLocalArgs('khchat_style',$khchat_style);
		$this->tpl->assign("company_tpl",$company_tpl);
		$this->tpl->assign("minchat_style",$minchat_style);
		$this->tpl->assign("khchat_style",$khchat_style);
	}

	//检测是否通过新挂码过来（kf_sign为挂码拼接参数，如果通过php直接访问,不存在kf_sign,必须带上code_arg=加密挂码id）
	function checkSignCode(){
		$code_type = $this->redis->get('com.code.type.'.$this->arg);
		if($code_type != "1"){
			$is_error = true;
			$kf_sign = $this->getValue("kf_sign");
			if($kf_sign != ""){
				$kf_sign = urldecode($kf_sign);
				$sign = base64_decode(substr($kf_sign,5,5).substr($kf_sign,0,5).substr($kf_sign,10,strlen($kf_sign)-10));
				$sign_company = substr($sign,-strlen($this->company_id));
				if(is_numeric($sign) && $sign_company == $this->company_id) $is_error = false;
			}else{
				$is_error = true;
				$code_arg = $this->getValue("code_arg");
				if(strlen($code_arg)>8){
					$real_arg = $this->redis->get('com.code.arg.'.$code_arg);
					if($real_arg == $this->arg){
						$is_error = false;
					}else{
						if($real_arg == ""){
							$code_com = db_query11("SELECT company_id FROM company_arg WHERE arg_code = '$code_arg'");
							if($code_com == $this->company_id){
								$this->redis->set('com.code.arg.'.$code_arg,$this->arg);
								$is_error = false;
							}
						}
					}
				}
			}
			if($is_error){
				show_err($this->tpl,$this->cfg,"您访问的用户无效！");
				exit();
			}
		}
	}

	//获取百度关键词
	function getBaiduApi($kword){
		// $kword = htmlspecialchars_decode($kword);
		//bcp获取关键词
		//$wd = $this->getBcpKeyword($kword);
		//if($wd != "") return $wd;

		//是否能使用百度关键词获取付费接口
		$is_use = true;
		if($this->comInfo['facilitator_id'] == $this->cfg["huawei_fid"]){
			$hw_keyword = $this->redis->hmget("company.config.keyword.".$this->company_id,array("total","use"));
			if($hw_keyword["total"]<=$hw_keyword["use"]) $is_use = false;
		}else {
			$baidu_keyword_api = $this->redis->hmget("baidu.keyword.api.{" . $this->company_id . "}", array("switch", "number"));
			$last_kwapi_num = $baidu_keyword_api["number"];
			$last_switch = $baidu_keyword_api["switch"];

			if ($last_kwapi_num <= 200) {
				// if ($last_switch == "1") {
				// 	$this->setOrderRabbit();
				// 	$push_msg = array(
				// 		"company_id" => $this->company_id,
				// 		"alias" => $this->comInfo["alias"]
				// 	);
				// 	if ($this->comInfo["cloud_service"] != "" && $this->comInfo["cloud_service"] != "jh") {
				// 		sync_tojh_rabbit($push_msg, $this->cfg['order_Exchange'], $this->cfg['order_queue_name'], $this->company_id);
				// 	} else {
				// 		require_once("lib/common/rabbitmq.class.php");
				// 		$rabbitmq_config = array(
				// 			'host' => $this->cfg['rabbitmq_host'],
				// 			'port' => $this->cfg['rabbitmq_port'],
				// 			'login' => $this->cfg['rabbitmq_login'],
				// 			'password' => $this->cfg['rabbitmq_password'],
				// 			'vhost' => $this->cfg['rabbitmq_vhost'],
				// 		);
				// 		$rabbitmq = new RabbitMQ($rabbitmq_config, true);
				// 		$rabbitmq->setExchange($this->cfg['order_Exchange']);
				// 		$rabbitmq->publish(json_encode($push_msg), $this->cfg['order_queue_name']);
				// 	}
				// }
				if ($last_kwapi_num <= 0) $is_use = false;
			}
		}

		$wd = "";
		//付费接口获取
		if($is_use){
			$url_arr = parse_url($kword);
			if(count($url_arr)>0 && $url_arr["query"]){
				$params = explode("&",$url_arr["query"]);
				foreach ($params as $key => $value) {
					$param = explode("=",$value);
					if($param[0] == "eqid"){
						$eqid = $param[1];
					}
				}
			}

			require_once("lib/common/apiBaidu.class.php");
			$bdSmsApi = new BDSMSAPI();
			if($eqid != ""){
				$bdSmsApi::setOption("pay",array("baiduApi" => array("ak"=>"0b3c87d59a674af69b05922abf9aee82","sk"=>"03905e9a666a4ca69bb43b187e75cc38","host"=>"baiduapi.53kf.com")));
				$result = $bdSmsApi->getKeyWord("pay",array("eqid"=>$eqid));

				if($result["wd"] != ""){
					if($this->comInfo['facilitator_id'] == $this->cfg["huawei_fid"]){
						$set_hw_kwapi["use"] = $hw_keyword["use"]+1;
						$this->redis->hmset("company.config.keyword.".$this->company_id,$set_hw_kwapi);
					}else {
						$set_kwapi["number"] = $last_kwapi_num - 1;
						$this->redis->hmset("baidu.keyword.api.{" . $this->company_id . "}", $set_kwapi);
						if ($set_kwapi["number"] % 100 == 0) {
							$sql = "INSERT INTO talk_order_log(product_name,product_now_num,create_time,company_id) VALUES ('baidu_keyword','" . $set_kwapi["number"] . "',NOW(),'" . $this->company_id . "')";
							db_execute($sql);
						}
					}
					$wd = $result["wd"];
				}
			}
		}

		//api对接获取
		if($wd == ""){
			$ip = get_ip();
			$wd = $this->redis->get("baidu.keyword.".$this->company_id.".".$ip);
		}

		return $wd;
	}

	//次数不够时调用rabbitmq通知续费
	public function setOrderRabbit($push_msg = array())
	{
		$push_msg["company_id"] = $this->company_id;
		$push_msg["alias"] = $this->comInfo["alias"];

		if ($this->comInfo["cloud_service"] != "" && $this->comInfo["cloud_service"] != "jh") {
			sync_tojh_rabbit($push_msg, $this->cfg['order_Exchange'], $this->cfg['order_queue_name'], $this->company_id);
		} else {
			require_once("lib/common/rabbitmq.class.php");
			$rabbitmq_config = array(
				'host' => $this->cfg['rabbitmq_host'],
				'port' => $this->cfg['rabbitmq_port'],
				'login' => $this->cfg['rabbitmq_login'],
				'password' => $this->cfg['rabbitmq_password'],
				'vhost' => $this->cfg['rabbitmq_vhost'],
			);
			$rabbitmq = new RabbitMQ($rabbitmq_config, true);
			$rabbitmq->setExchange($this->cfg['order_Exchange']);
			$rabbitmq->publish(json_encode($push_msg), $this->cfg['order_queue_name']);
		}
	}

	function getBcpKeyword($kword)
	{
		global $cfg;

		$xst = "";
		$url_arr = parse_url($kword);
		if(count($url_arr)>0 && $url_arr["query"]){
			$params = explode("&",$url_arr["query"]);
			foreach ($params as $key => $value) {
				$param = explode("=",$value);
				if($param[0] == "xst"){
					$xst = $param[1];
					break;
				}
			}
		}

		if($xst != ""){
			$uniqid = $this->getMillisecond().$this->guest_id;
			$data = array(
				"type" => "user",
				"api_key" => $cfg["baidu_bcp"]["api_key"],
				"cookie" => $xst,
			);
			$postJosnData = json_encode($data);
			$sign = md5($postJosnData.$uniqid.$cfg["baidu_bcp"]["api_secret"]);

			$url = $cfg["baidu_bcp"]["host"]."/bcp/third/user/info?uniqid=".$uniqid."&sign=".$sign;

			$res = $this->curlBody($url,$postJosnData);

			$re = json_decode($res,true);
			if($re["status"] == "0" && $re["status"]["keyword"] != ""){
				$this->setLog("re",$re);
				return $re["status"]["keyword"];
			}else{
				$this->setLog("url",$url);
				$this->setLog("postJosnData",$postJosnData);
				$this->setLog("res",$res);
			}
		}

		return "";
	}

	function curlBody($url,$postJosnData){
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/json',
			'Content-Length: ' . strlen($postJosnData)
		));
		curl_setopt($ch, CURLOPT_POSTFIELDS, $postJosnData);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		$data = curl_exec($ch);
		curl_close($ch);

		return $data;
	}

	//获取毫秒级时间戳
	function getMillisecond() { 
		list($s1, $s2) = explode(' ', microtime());
		return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
	}

	//区分HTTP请求和HTTPS请求
	function setHttpType(){
		$http = 'http';
		if ((isset( $_SERVER["HTTPS"] ) && strtolower( $_SERVER["HTTPS"] ) == "on") || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https' )) {
			$http = 'https';
		}
		$this->http = $http;
	}

	//设置局部变量
	function setLocalArgs($key,$value){
		$this->localArgs[$key] = $value;
	}

	//获取局部变量
	function getLocalArgs($key){
		if(isset($this->localArgs[$key])) return $this->localArgs[$key];
		return "";
	}

	//提示语处理  将回车换行替换为<br>
	function dealPrompt($prompt,$type=false){
		if ($type) return str_replace(array("\r\n","\n","\r","\\",'"'),array("<br>","<br>","<br>","\\\\",'\"'),$prompt);
		return str_replace(array("\r\n","\n","\r","\\"),array("<br>","<br>","<br>","\\\\"),$prompt);
	}

	// 处理来源页面、着陆页面、咨询页面 url解码 若是gbk编码则转为utf8
	function pageDecode($page,$rawurl){
		if ($rawurl != false) {
			$page_de = rawurldecode($page);	//搜狐的要求保留+
		} else {
			$page_de = urldecode($page);
		}
		$page_de = str_replace(PHP_EOL, '', $page_de);
		if (!is_utf8_encode($page_de)) {
			$page_de = iconv("GBK", "UTF-8", $page_de);
			if ($page_de === false) $page_de = $page;
		}
		return htmlspecialchars($page_de,ENT_QUOTES);
	}

	//获取get数据，并防sql注入处理
	function getValue($get_name,$re=""){
		if(isset($_GET[$get_name]) && trim($_GET[$get_name])!=""){
			$re = filterSQL($_GET[$get_name]);
		}
		return $re;
	}

	//获取get数据，过滤html，并防sql注入处理
	function getValueSpecial($get_name,$re=""){
		if (isset($_GET[$get_name]) && trim($_GET[$get_name]) != ""){
			$re = filterSQL(htmlspecialchars($_GET[$get_name], ENT_QUOTES));
		}
		return $re;
	}

	//从公司风格设置信息中获取单个设置项的值
	function getConfigValue($config_id,$default_value){
		foreach ($this->companyConfig as $key => $value) {
			if($value["config_id"] == $config_id){
				return $value["config_value"];
			}
		}
		return $default_value;
	}

	//从系统设置信息（不区分风格的设置信息）中获取单个设置项的值
	function getConfigValueNoStyle($config_id,$config_value){
		foreach ($this->companyConfigNoStyle as $key => $value) {
			if($value["config_id"] == $config_id){
				return $value["config_value"];
			}
		}
		return $config_value;
	}

	//获取风格id
	function getStyleRealId($style_id){
		$style_sql_id = $style_id - 1;
		if ($style_sql_id < 0) $style_sql_id = 0;
		$sql = "SELECT id FROM company_style WHERE company_id={$this->company_id} ORDER BY id LIMIT $style_sql_id,1";
		$re = db_query1($sql);
		if ($re===false || count($re)<=0){
			if ($style_id==1) return 0;
			$style_id = 1;
			return $this->getStyleRealId($style_id);
		}
		return $re["id"];
	}

	//检测arg参数
	function checkArg(){
		if (!isset($_GET["arg"]) || $_GET["arg"] == '') {
			show_err($this->tpl,$this->cfg,"您访问的域名无效！");
			exit;
		}
		if (preg_match('/[a-zA-Z]/',$_GET["arg"])) {
			$param = $_SERVER["QUERY_STRING"];
			header("location:{$this->http}://tb.53kf.com/webCompany.php?".$param);
			exit;
		}
		$this->arg = $this->getValue('arg');
	}

	//加载第三方统计代码
	function setCountCode(){
		$count_code = $this->getConfigValue('count_code','');
		$count_code1 = str_replace(PHP_EOL, '', $count_code);
		$count_code1 = preg_replace('/\s/','',$count_code1);
		$pattern = '/\<script(.{0,30})\>(.*)\<\/script\>/';
		if(preg_match($pattern,$count_code1)){
			$count_code = preg_replace('/\<script(.{31,})\>(.*)\<\/script\>/','',$count_code);
			$count_code = preg_replace('/\<script(.{0,30})\>/','',$count_code);
			$count_code = str_replace('</script>','',$count_code);
			$count_script = "<script> try{".$count_code."}catch(e){} </script>";
		}
		$this->tpl->assign("count_script",$count_script);
	}

	//显示模板页  输出客户统计挂码 并终止程序
	function showHtml($type=''){
		$company_tpl = $this->getLocalArgs('company_tpl');
		if ($type == 'black') {
			if ($company_tpl == 'minichat') {
				$this->tpl->display("company_tpl_new/blackList/minichat.html");
			}else{
				$this->tpl->display("company_tpl_new/blackList/khchat.html");
			}
		}else{
			if ($company_tpl == 'minichat') {
				$minchat_style = $this->getLocalArgs('minchat_style');
				if ($minchat_style > 1) {
					$this->tpl->display("company_tpl_new/minichat/webCompany_dz" . $minchat_style .".html"); 
				}else{
					$this->tpl->display("company_tpl_new/minichat/webCompany.html");
				}
			}else{
				$khchat_style = $this->getLocalArgs('khchat_style');
				if ($khchat_style > 0) {
					$this->tpl->display("company_tpl_new/khdz/webCompany_dz".$khchat_style.".html");
				}else{
					$this->tpl->display("company_tpl_new/newchat/webCompany.html");
				}
			}
		}
		if (array_key_exists('fk_debug',$this->cfg['fk_debug']) && in_array($this->company_id, $this->cfg['fk_debug'])) {
			file_put_contents('/tmp/fk_debug_tmpDebug_'.date('Ymd').'.log', '[' . date('Y-m-d_H:i:s') . ']' . ' ip: '.get_ip() . ' company_id: ' . $this->company_id . ' [error_info] webCompany end ' . PHP_EOL, FILE_APPEND);
		}
		exit;
	}

	//账号认证信息
	function authenticationInfo()
	{
		$auth_info = [
			'ip_area' => '未知',
			'auth_type' => 0, //0=无认证信息 1=个人 2=企业 3=政府
			'name' => '',
			'card' => ''
		];
		//最后登录ip所在区域
		$ip = $this->redis->get('com.ip.{'.$this->company_id.'}');
		$kf_ipinfo = ipinfo($ip);
		if ($kf_ipinfo['province'] != '') {
			$auth_info['ip_area'] = $kf_ipinfo['province'];
		}
		if ($kf_ipinfo['city'] != '') {
			$auth_info['ip_area'] = $kf_ipinfo['city'];
		}
		
		// 显示设置认证信息
		$auth_info_list = $this->getConfigValue('auth_info_list','');
		$auth_info_list = str_replace('\\', '', $auth_info_list);
		if (!empty($auth_info_list)) {
			$auth_info_list = json_decode($auth_info_list, true);
			//访客ip所在区域
			$ip = get_ip();
			$fk_ipinfo = ipinfo($ip);
			//匹配访客区域
			$other_area = [];
			$is_true = 0;
			foreach ($auth_info_list as $key => $value) {
				// 其他区域单独处理
				if ($value['scope_area'] == 'other_areas') {
					$other_area = $auth_info_list[$key];
					continue;
				}
				foreach ($value['company_area'] as $k => $v) {
					// 洲
					if (strpos($v, $fk_ipinfo['continents']) !== false) {
						$is_true = 1;
						$auth_info['auth_type'] = $value['company_type'];
						$auth_info['name'] = $value['company_main'];
						$auth_info['card'] = $value['card'];
					}
					// 市
					$fk_ipinfo['province'] = str_replace('市', '', $fk_ipinfo['province']);
					if (strpos($v, '-') !== false) {
						if (strpos($v, $fk_ipinfo['city']) !== false && strpos($v, $fk_ipinfo['province']) !== false) {
							$is_true = 1;
							$auth_info['auth_type'] = $value['company_type'];
							$auth_info['name'] = $value['company_main'];
							$auth_info['card'] = $value['card'];
						}
					}else{
						// 省
						if (strpos($v, $fk_ipinfo['province']) !== false) {
							$is_true = 1;
							$auth_info['auth_type'] = $value['company_type'];
							$auth_info['name'] = $value['company_main'];
							$auth_info['card'] = $value['card'];
						}
					}
				}
			}
			// 其他区域匹配
			if (!empty($other_area) && $is_true != 1) {
				$auth_info['auth_type'] = $other_area['company_type'];
				$auth_info['name'] = $other_area['company_main'];
				$auth_info['card'] = $other_area['card'];
			}
			//个人认证（不需要展示认证信息）
			if ($auth_info['auth_type'] == 1) {
				$auth_info['name'] = '';
				$auth_info['card'] = '';
			}
		}else{
			// 显示基础认证信息
			$info = $this->redis->hgetall('company.auth.info.'.$this->company_id);
			$auth_type = $this->redis->hget('com.info.{'.$this->company_id.'}', 'auth_type');
			if (!empty($info) && !empty($auth_type)) {
				//个人认证（不需要展示认证信息）
				if ($auth_type == 1 && !empty($info['personalInfo'])) {
					$data['name'] = '';
					$data['card'] = '';
				}
				//公司认证 改为多组认证 取最新认证数据
				if ($auth_type == 2 && !empty($info['companyInfo'])) {
					$data = json_decode($info['companyInfo'], true);
					foreach ($data as $key => $value) {
						if (is_array($value)) {
							$data = $value;
						}
					}
				}
				//政府认证
				if ($auth_type == 3 && !empty($info['agencyInfo'])) {
					$data = json_decode($info['agencyInfo'], true);
				}
				if (!empty($data)) {
					$auth_info['auth_type'] = $auth_type;
					$auth_info['name'] = $data['name'];
					$auth_info['card'] = $data['card'];
				}
			}
		}
		$this->tpl->assign("auth_info", json_encode($auth_info));
	}

	function setLog($flag,$data,$log_name = "webcom_debug_")
	{
		file_put_contents('/tmp/'.$log_name.date('Ymd').'.log',date('Y-m-d H:i:s'). '[line: ' . __LINE__ . ']' . '['.$flag.']' . var_export($data, true) . PHP_EOL, FILE_APPEND);
	}
}


?>