<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

error_reporting(E_ERROR|E_PARSE);

/**
    * 产生随机字串，可用来自动生成密码
    * 默认长度6位 字母和数字混合 支持中文
    * @param integer $len 长度
    * @param string $type 字串类型
    * 0 字母 1 数字 其它 混合
    * @param string $addChars 额外字符
    * @return 
    */
function get_rand_string($len=6,$type='',$addChars='') {
    $str ='';
    switch($type) {
        case 0:
            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.$addChars;
            break;
        case 1:
            $chars= str_repeat('0123456789',3);
            break;
        case 2:
            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ'.$addChars;
            break;
        case 3:
            $chars='abcdefghijklmnopqrstuvwxyz'.$addChars;
            break;
        case 4:
            $chars = "们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来分生对于学下级地个用同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然如应形想制心样干都向变关问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩康遵牧遭幅园腔订香肉弟屋敏恢忘编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航衣孙龄岭骗休借".$addChars;
            break;
        default :
            // 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
            $chars='ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars;
            break;
    }
    if($len>10 ) {//位数过长重复字符串一定次数
        $chars= $type==1? str_repeat($chars,$len) : str_repeat($chars,5);
    }
    if($type!=4) {
        $chars   =   str_shuffle($chars);
        $str     =   substr($chars,0,$len);
    }else{
        // 中文随机字
        for($i=0;$i<$len;$i++){
            $str.= msubstr($chars, floor(mt_rand(0,mb_strlen($chars,'utf-8')-1)),1,'utf-8',false);
        }
    }
    return $str;
}
/**
 * http_request的重写，只返回response,如果需要返回http_code 以及request信息，请调用http_request
 * 
 * @param $url 请求url地址
 * @param $method 请求方法 get post
 * @param null $postfields post数据数组
 * @param array $headers 请求header信息
 * @param bool|false $debug  调试开启 默认false
 * @return mixed
 * @author songdemei<songdemei@suxuantech.cn>
 */
function httpRequest($url, $method="GET", $postfields = null, $headers = array(), $debug = false) {
    $start = microtime(true);
    $res = http_request($url, $method, $postfields, $headers, $debug);
    $end = microtime(true);
    if(config('app_debug')){
        $content = 'Httprequest log '.($end - $start).'|'.$start.'|'.$end.'|'.$url.'|'.(is_array($postfields) ? http_build_query($postfields) : $postfields);
        $e = new Exception; 
        $content .= "\r\n".$e->getTraceAsString();
        textlog($content,'httprequest.log','log'.DS.date('Ym'));
        unset($content);
    }
    return $res['response'];
}
/**
 * CURL请求
 * @param $url 请求url地址
 * @param $method 请求方法 get post
 * @param null $postfields post数据数组
 * @param array $headers 请求header信息
 * @param bool|false $debug  调试开启 默认false
 * @return array();<br/>
 * code:http状态码；
 * response：响应内容；
 * request:请求信息；
 * @author songdemei<songdemei@suxuantech.cn>
 */
function http_request($url, $method="GET", $postfields = null, $headers = array(), $debug = false,$timeout = 60) {
    $method = strtoupper($method);
    $ci = curl_init();
    $contentLength = 0;
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $timeout); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, $timeout); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                $contentLength = strlen($tmpdatastr);
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if($ssl){
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    $headers[] = "Content-Length: ".$contentLength;
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        print_r($postfields);
        echo "=====info===== \r\n";
        print_r($requestinfo);
        echo "=====response=====\r\n";
        print_r($response);
    }
    curl_close($ci);
    //return $response;
    return array('code'=>$http_code, 'response'=>$response,'request'=>$requestinfo);
}


/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装） 
 * @return mixed
 */
function get_client_ip($type = 0,$adv=false) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if($adv){
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 发送HTTP状态
 * @param integer $code 状态码
 * @return void
 */
function send_http_status($code) {
    static $_status = array(
            // Informational 1xx
            100 => 'Continue',
            101 => 'Switching Protocols',
            // Success 2xx
            200 => 'OK',
            201 => 'Created',
            202 => 'Accepted',
            203 => 'Non-Authoritative Information',
            204 => 'No Content',
            205 => 'Reset Content',
            206 => 'Partial Content',
            // Redirection 3xx
            300 => 'Multiple Choices',
            301 => 'Moved Permanently',
            302 => 'Moved Temporarily ',  // 1.1
            303 => 'See Other',
            304 => 'Not Modified',
            305 => 'Use Proxy',
            // 306 is deprecated but reserved
            307 => 'Temporary Redirect',
            // Client Error 4xx
            400 => 'Bad Request',
            401 => 'Unauthorized',
            402 => 'Payment Required',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            406 => 'Not Acceptable',
            407 => 'Proxy Authentication Required',
            408 => 'Request Timeout',
            409 => 'Conflict',
            410 => 'Gone',
            411 => 'Length Required',
            412 => 'Precondition Failed',
            413 => 'Request Entity Too Large',
            414 => 'Request-URI Too Long',
            415 => 'Unsupported Media Type',
            416 => 'Requested Range Not Satisfiable',
            417 => 'Expectation Failed',
            // Server Error 5xx
            500 => 'Internal Server Error',
            501 => 'Not Implemented',
            502 => 'Bad Gateway',
            503 => 'Service Unavailable',
            504 => 'Gateway Timeout',
            505 => 'HTTP Version Not Supported',
            509 => 'Bandwidth Limit Exceeded'
    );
    if(isset($_status[$code])) {
        header('HTTP/1.1 '.$code.' '.$_status[$code]);
        // 确保FastCGI模式下正常
        header('Status:'.$code.' '.$_status[$code]);
    }
}

function api_check_login($sessionId='') {
    $sessionId = $sessionId?$sessionId:input('post.session_id');
    $loginInfo = db('s_session')->where('session_id', $sessionId)->find();
    if(!$loginInfo){
        return false;
    }
    if(time() > $loginInfo['expire_time']){
        //登录是否过期
        return false;
    }
    return $loginInfo;
}

//替换特殊字符
function replaceSpecialChar($strParam){
    $regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
    return preg_replace($regex,"",$strParam);
}
function saveLoginSessions($info){
    session('staff_id',$info['staff_id']);
    session('staff_name',$info['staffname']);
    session('staff_number',$info['staffnumber']);
    session('session_id',$info['session_id']);
    session('brandclass_id',$info['brandclass_id']);
    session('brandclass',$info['brandclass']);
    session('shop_name',$info['shop_name']);
    session('shop_code',$info['shop_code']);
    session('belong_shop_name',$info['belong_shop_name']);
    session('belong_shop_code',$info['belong_shop_code']);
    session('is_sk',$info['is_sk']);
    session('is_marketing',$info['is_marketing']);
    session('shop_type',$info['shop_type']);
    session('setkey',$info['setkey']);
    session('main_work_type',$info['main_work_type']);
    session('work_type',$info['work_type']);
    session('department_name',$info['department_name']);
    session('department_id',$info['department_id']);
    session('position_code',$info['position_code']);
    session('main_position_name',$info['main_position_name']);
    session('main_position_code',$info['main_position_code']);
    session('grade_type',$info['grade_type']);
    session('is_belong',$info['is_belong']);
    session('open_id', $info['open_id']);
    session('valid_date', $info['valid_date']);
    session('group_id',$info['group_id']);
    session('group_name',$info['group_name']);
    session('is_group',$info['is_group']);//是不是集团店:1:是,2:否
    session('telphone',$info['telphone']);//是不是集团店:1:是,2:否
}
/**
 * 判断是否登录状态
 * 正常判断session如果session里没有，则判断cookie是否自动登录，如果是，更新session
 * 如果没有，退出登录
 * @return [type] [description]
 */
function check_login($detailError = 0){
    $cookieStaffId = (int)cookie('staff_id');
    $sessionStaffId = session('staff_id');
    $cookieSessionId = cookie('session_id');
    $sessionId = session('session_id');
    if(!$cookieStaffId || !$cookieSessionId){
        //cookie内值一定要有，5天自动登录也就是cookie存在时间长一点而以。
        return false;
    }

    $cacheStaffInfo = cache('staffInfo_'.$cookieStaffId);
    if(!$cacheStaffInfo){
        //未登录
        return false;
    }
    if(cookie('current_position_code') && session('main_position_code') && cookie('current_position_code') != session('main_position_code')){
        changeMyPosition(cookie('current_position_code'));
    }
    if($cacheStaffInfo['session_id'] != $cookieSessionId){
        //如果设置了多地登陆,直接返回true
        if($cookieStaffId == $sessionStaffId && $cacheStaffInfo['more_login'] == 1){
            return true;
        }
        //如果是手机端登录的，返回true
        if(session('login_type') == 'WX' && $sessionId == $cookieSessionId){
            return true;
        }
        //cookie里与cache里不一至，直接退出。
        //注意，如果5天自动登录，有可能session里没有了。
        if($detailError){
            return array('code'=>ERR_LOGIN_OTHERLOGIN,'msg'=>'用户在别的地方登录','data'=>array());
        }else{
            return false;
        }
    }

    // $cacheStaffInfo['active'] = time();
    if(!$sessionStaffId || $sessionStaffId != $cookieStaffId || $sessionId != $cookieSessionId){
        //session 没了，但cookie还有，且与cache里一至
        //更新cache到session
        saveLoginSessions($cacheStaffInfo);
        $sessionStaffId = $cacheStaffInfo['staff_id'];
        $sessionId = $cacheStaffInfo['session_id'];
    }

    if($cookieStaffId == $sessionStaffId && $cookieSessionId == $sessionId){
        //登录没问题
        if($cacheStaffInfo['keep_login'] == 1){
            cache('staffInfo_'.$cookieStaffId, json_encode($cacheStaffInfo),432000);
        }else{
            cache('staffInfo_'.$cookieStaffId, json_encode($cacheStaffInfo));
        }
        return true;
    }else{
        //登录有问题
        if($detailError){
            if($cookieStaffId == $sessionStaffId){
                $res = array('code'=>ERR_LOGIN_OTHERLOGIN,'msg'=>'用户在别的地方登录','data'=>array());
            }else{
                $res = array('code'=>ERR_LOGIN_UNLOGIN,'msg'=>'用户未登录','data'=>array());
            }
        }else{
            $rse = false;
        }
        return $res;
    }
}

/**
 * 正常业务访问时，判断用户是否登录使用。此处只判断是否登录，如何处理，由调用处进行处理。
 * 
 * @return boolean
 */
function check_login_old() {
    $staffId = think_decrypt(cookie('auto_staff_id'),'');
    $session_id = think_decrypt(cookie('auto_session_id'),'');
    if(empty($session_id) || empty(intval($staffId))){//缓存里没有说明没有选择自动登录，验证普通登录
        $info = json_decode(think_decrypt(cache('staffInfo_'.cookie('staff_id'))),true);
        //print_r(cookie('session_id'));echo "|";print_r($info['session_id']);die;
        if( cookie('session_id') == $info['session_id'] ){
            if(empty(trim(cookie('session_id'))) || intval(cookie('staff_id') <= 0) || empty(trim(session('staff_id')))){
                cookie(null);
                session();
                return false;
            }
            $info['active'] = time();
             //if(cookie('status') == 1){
                cache('staffInfo_'.cookie('staff_id'), think_encrypt(json_encode($info)));
             //}
            return true;
        }else{
            cookie(null);
            session();
            return false;
        }
    }else{
        $info = json_decode(think_decrypt(cache('staffInfo_'.$staffId),''),true);
        // var_dump($session_id);
        // var_dump($info);
        if($info['session_id'] == $session_id){

            session('staff_id',$info['staff_id']);
            session('staff_name',$info['staffname']);
            session('staff_number',$info['staffnumber']);
            session('session_id',$info['session_id']);
            session('brandclass_id',$info['brandclass_id']);
            session('brandclass',$info['brandclass']);
            session('shop_name',$info['shop_name']);
            session('shop_code',$info['shop_code']);
            session('belong_shop_name',$info['belong_shop_name']);
            session('belong_shop_code',$info['belong_shop_code']);
            session('is_sk',$info['is_sk']);
            session('is_marketing',$info['is_marketing']);
            session('shop_type',$info['shop_type']);
            session('setkey',$info['setkey']);
            cookie('status',$info['status']);
            session('main_work_type',$info['main_work_type']);
            session('work_type',$info['work_type']);
            session('department_name',$info['department_name']);
            session('department_id',$info['department_id']);
            session('position_code',$info['position_code']);
            session('main_position_name',$info['main_position_name']);
            session('main_position_code',$info['main_position_code']);
            session('grade_type',$info['grade_type']);
            session('is_belong',$info['is_belong']);
            session('open_id', $info['open_id']);
            // if(cookie('status') == 1){
            $info['active'] = time();
            cache('staffInfo_'.cookie('staff_id'), think_encrypt(json_encode($info)));
            // }
            return true;
        }else{
            cookie(null);//不好使。。。。TP的BUG
            session();
            cookie('auto_staff_id',null);
            cookie('auto_session_id',null);
            return false;
        }
    }

}
/**
 * 把数据按key=value方式，使用&连接起来。
 * 
 * @param type $array
 * @return type String
 */
function arrayToParams($array){
    $ret = '';
    foreach($array as $k=>$v){
        $ret .= $k.'='.$v.'&';
    }
    $ret = trim($ret,'&');
    return $ret;
}
/**
 * 验证POST数据的access token签名是否正确。
 * 
 * @param String $appSecret 当前请求接口的应用密钥
 * @param String $accessToken 当前请求头信息内的token
 * 
 * @return boolean  验证通过返回true,验证失败返回false
 */
function checkAccessToken($appSecret,$accessToken) {
    $params = input('post.');
    unset($params['action'],$params['method']);
    ksort($params);
    $tokenStr = arrayToParams($params).$appSecret;
    //var_dump($tokenStr);
    if($accessToken != md5($tokenStr)){
        //验证失败的记录到数据库
        $log['action'] = 'token验证失败';
        $log['error_reason'] = 'Secret：'.$appSecret.';tokenStr：'.$tokenStr.';md5加密后：'.md5($tokenStr).';arrayToParams:'.arrayToParams($params).';params_json：'.json_encode($params);
        db('l_error_log')->insert($log);
        return false;           
    }
    return true;
}
/**
 * 记录API访问日志
 * 
 * @param type $logInfo
 */
function apiLog($logInfo) {
   // var_dump($logInfo);
   // exit();
    $logInfo['create_time'] = date('Y-m-d H:i:s');
    $logInfo['create_ip'] = get_client_ip();
    $res = db('api_logs','db_logs')->insert($logInfo);
    if(!$res){
        
    }
}
function api_log($logInfo){
    apiLog($logInfo);
}

/**
 * 操作日志记录，此日志需要在代码里手动记录。<br/>
 * 需要在application的common里面有model/actionLog.php的model类<br/>
 * 记录的module/controller/action如果不输入，为请求进来的，针对于API接口。因为做了单独调用，固需要手动指定一下<br/>
 * 
 * @param Mix $data        本次要记录的日志数据
 * @param Mix $oldData     修改前的数据
 * @param Int $customerId      当前操作的客户ID。
 * @param Int $staffId      当前登录员工ID，默认取session内的staff_id,针对API记录，需要手动传入。
 * @param Int $staffName      当前登录员工姓名
 * @param String $module      操作的模块，默认取当前请求的应用模块
 * @param String $controller  操作的控制器，默认取当前请求的控制器
 * @param String $action      操作的方法，默认取当前请求的方法
 */
function action_log($data,$oldData,$customerId = 0,$staffId = 0,$staffName='',$module='',$controller = '',$action='', $ip='', $create_time=''){
    if(!$module){
        $module = \think\Request::instance()->module();
    }
    if(!$controller){
        $controller = \think\Request::instance()->controller();
    }
    if(!$action){
        $action = \think\Request::instance()->action();
    }
    if(!$ip){
        $ip = \think\Request::instance()->ip();
    }
    if(!is_string($data)){
        $data = json_encode($data);
    }
    if(!is_string($oldData)){
        $oldData = json_encode($oldData);
    }
    static $log;
    $log = $log?$log:model('crm/ActionLog');
    $logData = [];
    $logData['old_data'] = $oldData;
    $logData['data'] = $data;
    $logData['action'] = $action;
    $logData['controller'] = $controller;
    $logData['module'] = $module;
    $logData['ip'] = $ip;
    $logData['customer_id'] = $customerId;
    $logData['staff_id'] = $staffId?$staffId:(int)session('staff_id');
    $logData['staff_name'] = $staffName?$staffName:session('staff_name');
    $logData['create_time']= $create_time ? $create_time : date('Y-m-d H:i:s');
    $log->startTrans();
    $res = $log->data($logData,true)->isUpdate(false)->save();
    // echo 'action_log==>>'.$res;
    if($res === false){
        // echo 'action_log==>>rollBack';
        $log->rollBack();
        \think\Log::error('日志保存错误:module:'.$module.';controller:'.$controller.';action:'.$action.';data:'.$data.';olddata:'.$oldData.';customerid:'.$customerId);       
    }else{
        // echo 'action_log==>>commit';
        $log->commit();
    }
}
/**
 * 素玄内部接口调用
 * 
 * @param type $interfaceHash
 * @param type $data
 * @param type $system
 * @param type $sessionId
 * @return string
 */
function sx_call($interfaceHash,$data,$system='sx_mc',$sessionId='') {
    //查询人员接口，用于判断是否包含离职人员
    $url = [
        '5b75341456d18',
        '5b20eb32badd8',
        '5af3c003b4cae',
        '5aafa4ac48058',
        '5a19201a33c20',
        '5a1510583e3a5',
        '5a0e6f272bb38',
        '5aec138a7bae9',
        '5a7424f13aa54',
        '5a01766b4a3dd',
    ];
    if(in_array($interfaceHash,$url)){
        //1:全部；2：在职
        $is_leave = db_config('is_leave');
        if($is_leave == 1){
            $data['get_leave'] = 1;
        }else{
            $data['get_leave'] = 2;
        }
    }
    $param = '';
    $system = $system?$system:'sx_mc';
    $ret = array('errid'=>0,'data'=>[]);
    foreach ($data as $k=>$v){
        if(is_null($v)){
            unset($data[$k]);
        }
    }
    if(!empty($data)){
        ksort($data);
        $param = arrayToParams($data);
    }
    $appConfig = config('ext.app_config');
    $secret = config('ext.app_secret');//$appConfig[strtolower($system)]['secret'];
    if(key_exists(strtolower($system), $appConfig)){
        $addr = $appConfig[strtolower($system)]['addr'];
        if(substr($addr,-1) != '/'){
            $addr .= '/';
        }
        $addr .= 'api/'.$interfaceHash;

    }else{
        $ret['error'] = '当前系统未安装应用：'.$system;
        return $ret;
    }
    $param .= $secret;
    $token = md5($param);
    $header = array('ACCESS-TOKEN: '.$token);
    if($sessionId){
        $header[] = 'SESSION-ID: '.$sessionId;
    }

    return json_decode(httpRequest($addr, 'POST', $data, $header),true);
}


/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key  加密密钥
 * @param int $expire  过期时间 单位 秒
 * @return string
 */
function think_encrypt($data, $key = '', $expire = 0) {
    $key  = md5(empty($key) ? config('AUTH_KEY') : $key);
    $data = base64_encode($data);
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    $str = sprintf('%010d', $expire ? $expire + time():0);

    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
    }
    return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));
}

/**
 * 系统解密方法
 * @param  string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param  string $key  加密密钥
 * @return string
 */
function think_decrypt($data, $key = ''){
    $key    = md5(empty($key) ? config('AUTH_KEY') : $key);
    $data   = str_replace(array('-','_'),array('+','/'),$data);
    $mod4   = strlen($data) % 4;
    if ($mod4) {
       $data .= substr('====', $mod4);
    }
    $data   = base64_decode($data);
    $expire = substr($data,0,10);
    $data   = substr($data,10);

    if($expire > 0 && $expire < time()) {
        return '';
    }
    $x      = 0;
    $len    = strlen($data);
    $l      = strlen($key);
    $char   = $str = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }else{
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}

/**
 * 存入redis消息队列
 * 
 * @param str listName      消息队列的名称
 * @param mix $msg          消息队列的内容
 *
 * @return boolean  
 */
function push_list($listName, $msg){
    $create_time = date('Y-m-d H:i:s');
    // $ip = \think\Request::instance()->ip();
    $ip = get_client_ip();
    $msg['ip'] = $ip;
    $msg['create_time'] = $create_time;
    switch ($listName) {
        // 数据统计队列
        case 'historyDataList':
            $msgIn = json_encode($msg);
            $data['message']    = $msgIn;
            $data['type']       = $msg['type'];
            $data['create_time']= $create_time;
            $res = db('c_history_data')->insertGetId($data);
            if (!$res) {
                return false;
            }
            
            $msg['hid'] = $res;
            $message = $msg;
            break;
        // 分配队列
        case 'fpCustomerList':
            $message = $msg;
            break;
        // excel导入队列
        case 'excelImportRedisList':
            $message = $msg;
            break;
        case 'erpLogs':
            $message = $msg;
            break;
    }
    return \app\common\lib\redisQueue::init()->rPush($listName, $message);
}



/**
 * 发送系统消息   发送人信息  为系统  四种类型（1：存库；2：redis订阅消息；3：微信消息；4：短信）
 * @param  data  
 *
 * @param  data['send_id']        发送消息的员工ID
 * @param  data['send_name']      发送消息的员工名字
 * @param  data['read_status']    阅读状态 （0：未读；1：已读）',
 * @param  data['read_time']      阅读时间
 * @param  data['send_mode']      消息模式（array('db'=>1, 'publish'=>1, 'wx'=>, 'sms'=>1)）
 * @param  data['save_msg']       是否记录message表   1：记录； 2：不记录
 * @param  data['send_type']      消息类型
 * @param  data['send_title']     消息标题
 * @param  data['send_msg']       发送的消息内容
 * @param  data['receive_id']     接收人id
 * @param  data['receive_name']   接收人name
 * @param  data['receive_status'] 接收状态
 * @param  data['operation_type'] 操作类型（1：可操作；2：不可操作）
 * @param  data['operation']      操作方法json（[0=>[button：按钮名称；url：按钮对应的URL带参数],1=>...]）
 * @param  data['time_out']       生存时间（600秒）
 * @return bool    
 * @author Eric
 */
function sendSystemMessage($data){
    // 频道名称
    $channel = 'notice';
    $time = time();
    if ($data['time_out']) {
        $timeOut = $time+$data['time_out'];
    }else{
        $timeOut = '';
    }
    $timeOut = $time+$data['time_out'];
    $inData = [
        'send_id'  => $data['send_id'] ? $data['send_id'] : '-1',
        'send_name'=> $data['send_name'] ? $data['send_name'] : 'syetem',
        'send_time'=> date('Y-m-d H:i:s', $time),
        'time_out' => $timeOut,
    ];
    $allData = array_merge($data, $inData);
    // 开启事务
    db()->startTrans();
    try {
        $message = $allData;
        if ($allData['save_msg'] == 2) {
            $res = \app\common\lib\redisQueue::init()->publish($channel, $message);
        }else{
            $id = db('c_message')->insertGetId($allData);
            $message['id'] = $id;
            $res = \app\common\lib\redisQueue::init()->publish($channel, $message);
        }
        
        db()->commit();
        return true;
    } catch (Exception $e) {
        db()->rollback();
        return false;
    }
}

/**
 * 发送系统消息   发送人信息  为系统  四种类型（1：存库；2：redis订阅消息；3：微信消息；4：短信）
 * @param  data  
 *
 * @param  data['send_mode']      消息模式（array('db'=>1, 'publish'=>1, 'wx'=>, 'sms'=>1)）
 * @param  data['send_type']      消息类型:1:短消息(弹窗)；2：通知',
 * @param  data['send_title']     消息标题
 * @param  data['send_msg']       发送的消息内容
 * @param  data['receive_id']     接收人id
 * @param  data['receive_name']   接收人name
 * @param  data['receive_status'] 接收状态
 * @param  data['operation_type'] 操作类型（1：可操作；2：不可操作）
 * @param  data['operation']      操作方法json（[0=>[button：按钮名称；url：按钮对应的URL带参数],1=>...]）
 * @param  data['time_out']       生存时间（600秒）
 * @return bool    
 * @author Eric
 */
function sendSystemMessage_back($data){
    
    $time = time();
    if ($data['time_out']) {
        $timeOut = $time+$data['time_out'];
    }else{
        $timeOut = '';
    }
    $timeOut = $time+$data['time_out'];
    $inData = [
        'send_id'  => '-1',
        'send_name'=> 'syetem',
        'send_time'=> date('Y-m-d H:i:s', $time),
        'time_out' => $timeOut,
    ];
    $allData = array_merge($data, $inData);

    // db模式
    if ( isset($data['send_mode']['db']) && $data['send_mode']['db'] == 1 ) {
        $id = db('c_message')->insertGetId($allData);
    }
    // redis订阅消息模式
    if ( isset($data['send_mode']['publish']) && $data['send_mode']['publish'] == 1 ) {
        // 频道名称
        $channel = 'notice';
        $message = $allData;
        $message['id'] = $id ? $id : 0;
        $res = \app\common\lib\redisQueue::init()->publish($channel, $message);
    }
    // 微信消息模式
    if ( isset($data['send_mode']['wx']) && $data['send_mode']['wx'] == 1 ) {
        # code...
    }
    // 短信消息模式
    if ( isset($data['send_mode']['sms']) && $data['send_mode']['sms'] == 1 ) {
        # code...
    }

}

function isOnline($staff_id){
    $info = cache('staffInfo_'.$staff_id ? $staff_id :session('staff_id'));
    if( (time() - $info['active'] > 160) || ($info['status'] != 1) ){
        return false;
    }else{
        return true;
    }
}

// 回调函数,这里写处理逻辑
function noticeCallBack($instance, $channelName, $message) {
    if ($message) {
        $message = json_decode($message,true);
        if ($message['send_type'] == 3) {
            $check_login = check_login();
            // $check_login = isOnline();
            if ($check_login === false) {
                exit(json_encode(array('code'=>ERR_LOGIN_UNLOGIN)));
            }else{
                exit(json_encode(array('code'=>302,'msg'=>'','data'=>array())));
            }
        }
        // 切换岗位
        if ($message['send_type'] == 4) {
            exit( json_encode( array('code'=>-4, 'staff_id'=>$message['receive_id'], 'p_new_code'=>$message['p_new_code'] ) ) );
        }
        $message['pop_status'] = 1;
        $message['operation'] = json_decode($message['operation'],true);
        #var_dump($message);
        foreach($message as $k=>$v){
            $message[$k]['time_out'] = $v['time_out'] - time();
        }
        if ((int)$message['id']) {
            $return['mid']        = (int)$message['id'];
            $return['noRead']     = controller("crm/Customer","lib")->getNewMessageNum();
            $return['popList']    = array($message);
            $return['messageList']= array($message);
            header("Content-Type:application/json;charset=utf-8");
            echo json_encode($return);
        }
        exit;
    }
    // file_put_contents("rNotice.txt", 'cName：'.$channelName.'；msg：'.$message.PHP_EOL, FILE_APPEND); 
}

/**
 * 发送模板消息
 * @param Integer  $content json格式模板消息内容
 * @param String   $brandclass_id 品牌id
 * @param String   $shop_code 店面唯一识别码
 * @author {wangyining}<{wangyining@suxuantech.cn}> 2017-10-17 $
 */
function sendMsg($data){
    $url="5a4b81bc26160";
    $res=sx_call($url,$data);
    if($res['code']==200){
        $detail=$res['data'];
        return $detail;
    }else{
        return $res;
    }
}

// 获取起始时间 $dataArea == today,near_week,near_month,last_week,last_month,this_week,this_month,last_jd,this_jd
function getdateArea($dataArea){
    switch ($dataArea) {
        // 昨天
        case 'yestoday':
        case 'last_day':
            $begin  = date('Y-m-d 00:00:00',strtotime('-1 day'));
            $end    = date('Y-m-d 23:59:59',strtotime('-1 day'));
            $return = array($begin,$end);
            break;
        // 今天
        case 'today':
            $begin  = date('Y-m-d 00:00:00');
            $end    = date('Y-m-d 23:59:59');
            $return = array($begin,$end);
            break;
        // 最近一周 前7天
        case 'near_week':
            $near_week_begin  = date('Y-m-d', strtotime('-7 days'));
            $near_week_end    = date('Y-m-d 23:59:59', strtotime('-1 days'));
            $return = array($near_week_begin,$near_week_end);
            break;
        // 最近一月 前30天
        case 'near_month':
            $near_month_begin = date('Y-m-d', strtotime('-30 days'));
            $near_month_end   = date('Y-m-d 23:59:59', strtotime('-1 days'));
            $return = array($near_month_begin,$near_month_end);
            break;
        // 上周
        case 'last_week':
        case 'last week':
            // $last_week_begin = date("Y-m-d",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1-7,date("Y")));
            // $last_week_end   = date("Y-m-d 23:59:59",mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y")));
            $last_week_begin = date('Y-m-d 00:00:00', strtotime('last week monday'));
            $last_week_end   = date('Y-m-d 23:59:59', strtotime('last week sunday'));
            $return = array($last_week_begin,$last_week_end);
            break;
        // 上月 
        case 'last_month':
        case 'last month':
            $last_month_begin = date("Y-m-d",mktime(0, 0 , 0,date("m")-1,1,date("Y")));
            $last_month_end   = date("Y-m-d 23:59:59",mktime(23,59,59,date("m") ,0,date("Y")));
            $return = array($last_month_begin,$last_month_end);
            break;
        // 本周
        case 'this_week':
        case 'week':
            // $this_week_begin = date("Y-m-d",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
            // $this_week_end   = date("Y-m-d 23:59:59",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
            $this_week_begin = date('Y-m-d 00:00:00', strtotime('this week monday'));
            $this_week_end   = date('Y-m-d 23:59:59', strtotime('this week sunday'));
            $return = array($this_week_begin,$this_week_end);
            break;
        // 本月 
        case 'this_month':
        case 'month':
            $this_month_begin = date("Y-m-d",mktime(0, 0 , 0,date("m"),1,date("Y")));
            $this_month_end   = date("Y-m-d 23:59:59",mktime(23,59,59,date("m"),date("t"),date("Y")));
            $return = array($this_month_begin,$this_month_end);
            break;
        // 上季度 
        case 'last_jd':
            $last_season   = ceil((date('n'))/3)-1;//上季度是第几季度
            $last_jd_begin = date('Y-m-d', mktime(0, 0, 0,$last_season*3-3+1,1,date('Y')));
            $last_jd_end   = date('Y-m-d 23:59:59', mktime(23,59,59,$last_season*3,date('t',mktime(0, 0 , 0,$last_season*3,1,date("Y"))),date('Y')));
            $return = array($last_jd_begin,$last_jd_end);
            break;
        // 本季度
        case 'this_jd':
            $this_season   = ceil((date('n'))/3);//当月是第几季度 
            $this_jd_begin = date('Y-m-d', mktime(0, 0, 0,$this_season*3-3+1,1,date('Y')));
            $this_jd_end   = date('Y-m-d 23:59:59', mktime(23,59,59,$this_season*3,date('t',mktime(0, 0 , 0,$this_season*3,1,date("Y"))),date('Y')));
            $return = array($this_jd_begin,$this_jd_end);
            break;
        default:
            $timestamp = strtotime( $dataArea );
            $this_jd_begin = date( 'Y-m-1 00:00:00', $timestamp );
            $mdays = date( 't', $timestamp );
            $this_jd_end = date( 'Y-m-' . $mdays . ' 23:59:59', $timestamp );
            $return = array($this_jd_begin,$this_jd_end);
            break;
    };
    return $return;
}

/**
 * 获取指定日期段内每一天的日期 时间区间
 * @param  Date  $startdate 开始日期
 * @param  Date  $enddate   结束日期
 * @return Array
 */
function getDateFromRange($startdate, $enddate){
    $stimestamp = strtotime($startdate);
    $etimestamp = strtotime($enddate);
    // 计算日期段内有多少天
    $days = intval(($etimestamp-$stimestamp)/86400)+1;

    // 保存每天日期
    $date = array();
    for($i=0; $i<$days; $i++){
        $date[] = date('Y-m-d', $stimestamp+(86400*$i));
    }
    return $date;
}

// 对应表中字段的中文 翻译
function translate($table='c_customerinfo', $key){
    $return = array(
        // 用户详情表
        'c_customerinfo' => array(
            'customer_id'          => 'ID',
            'cid'                  => 'ID',
            'id'                   => 'ID',
            'customer_number'      => '客户编号',
            'customer_name'        => '客户姓名',
            'customer_sex'         => '客户性别',
            'customer_tel'         => '客户手机',
            'customer_wechat'      => '客户微信',
            'customer_weibo'       => '客户微博',
            'customer_qq'          => '客户QQ',
            'add_friend_time'     => '加好友时间',
            'province'             => '所在省',
            'city'                 => '所在市',
            'county'               => '县（区）',
            'customer_address'     => '客户地址',
            'mate_name'            => '配偶姓名',
            'mate_sex'             => '配偶性别',
            'mate_tel'             => '配偶电话',
            'mate_wechat'          => '配偶微信',
            'mate_weibo'           => '配偶微博',
            'mate_qq'              => '配偶QQ',
            'mate_address'         => '配偶地址',
            'consultation_type'    => '消费类型',
            'customer_type'        => '客户类型',
            'consulation_shop_code'=> '意向店面编码',
            'consulation_shop'     => '意向店面',
            'customer_channel'     => '渠道名称',
            'customer_cource'      => '客户来源',
            'customer_intention'   => '客户意向',
            'customer_orderaddress'=> '接单点',
            'access_model'         => '获取方式',
            'customer_area'        => '客户分区',
            'customer_region'      => '客户地域',
            'is_intostore'         => '是否进店',
            'is_success'           => '是否成交',
            'is_valid'             => '是否有效',
            'yx_day'               => '标记有效日期',
            'is_urgent'            => '是否加急',
            'is_loss'              => '是否流失',
            'is_dive'              => '是否潜水',
            'is_sk'                => '筛客状态',
            'is_status'             => '是否删除',
            'is_next'              => '是否再约',
            'next_time'            => '再约时间',
            'op_signinfo'          => '追踪标记',
            'op_signday'           => '追踪标记日期',
            'customer_capacity'    => '消费能力',
            'photo_address'        => '拍照地',
            'customer_birthday'    => '客户生日',
            'customer_idtype'      => '客户证件类型',
            'customer_idnumber'    => '客户证件号',
            'mate_birthday'        => '配偶生日',
            'mate_idtype'          => '配偶证件类型',
            'mate_idnumber'        => '配偶证件号码',
            'wedding_date'         => '结婚日期',
            'fp_staff'             => '分配人员',
            'fp_time_out'          => '待接收客资超时时间',
            'sales_staff'          => '追踪人员',
            'yjd_day'              => '预约进店日期',
            'syjd_day'             => '实际进店日期',
            'yp_day'               => '预拍日期',
            'order_day'            => '成交订单日期',
            'totalpay_money'       => '消费金额',
            'order_number'         => '订单单号',
            'step_name'            => '追踪阶段名称',
            'order_type'           => '订单类型',
            'c_star_day'           => '客资追踪开始日期',
            'c_end_day'            => '客资追踪结束日期',
            'last_trackday'        => '最后一次追踪日期',
            'creator_day'          => '创建日期',
            'seles_error_reason'   => '追踪失败原因',
            'customer_remark'      => '客资备注',
            'photo_day'            => '实际拍照日期',
            'sel_day'              => '筛客日期',
            'sign_name'            => '客资标记',
            'tel_visit_num'        => '电访量',
            'loss_cause'           => '流失原因',
            'sk_staff'             => '筛客人姓名',
            'sk_time'              => '筛客时间',
            'tel_staff'            => '手机号录入者名字',
            'tel_time'             => '录入手机号时间',
            'is_already_sk'        => '是否已经筛客，1是2否',
            'is_first_tel'         => '第一次录入是否有手机号',
            'channel_plan_number'  => '推广编号',
            'ad_page'              => '广告落地页',
            'customer_key'         => '客资搜索关键词',
            'intostore_note'       => '进店备注',
            'ready_baby_day'       => '预产期',
            'baby_birthday'        => '宝宝生日',
            'baby_address'         => '宝宝出生地',
            'marry_day'            => '结婚日期',
            'ready_marry_day'      => '预计结期',
            'record_img'           => '聊天记录图片',
            'track_record'         => '最近三条追踪记录',
            'customer_label,'      => '客资标签',
            'budget'               => '预算',
            'fact_money'           => '实际收款',
            'order_start_time'     => '订单开始时间',
            'loss_day'             => '流失时间',
            'introducer_type'      => '转介绍类型',
            'introducer_name'      => '介绍人姓名',
            'introducer_tel'       => '介绍人手机',
            'introducer_number'    => '介绍人编号',
            'introducer_ordernum'  => '介绍人单号',
            'dj_staff'             => '登记人',
            'dj_day'               => '登记时间',
            'brandclass'           => '事业部',
            'shop_name'            => '归属店',
            'add_shop_name'        => '提报店',
            'reception_name'       => '接待人',
            'reject_reason'        => '驳回原因',
            'reject_remark'        => '驳回备注',
            'unvalid_reason'       => '无效原因',
            'erp_loss_reason'      => 'erp标记流失原因',
            'erp_loss_time'        => 'erp标记流失时间',
            'higher_level_name'    => '上级名字',
            'erp_wphone'           => 'erp女号',
            'erp_mphone'           => 'erp男号',
            'sales_department_id'  => '追踪部门',
            'is_examine'           => '是否需要审核',
            'examine_reason'       => '审核不通过原因',
            'baby_name'            => '宝宝姓名',
            'baby_sex'             => '宝宝性别',
            'home_phone'           => '座机',
            'email'                => '邮箱',
            'customer_names'       => '妈妈姓名',
            'customer_tels'        => '妈妈手机',
            'customer_wechats'     => '妈妈微信',
            'mate_names'           => '爸爸姓名',
            'mate_tels'            => '爸爸电话',
            'mate_wechats'         => '爸爸微信',
        )
    );
    return $return[$table][$key];
}

//导入模板表头对应的表字段  儿童
function import_header_child(){
    $title=array(
        'baby_name'    =>'宝宝姓名',
        'baby_sex'     =>'宝宝性别',
        'baby_birthday'=>'宝宝生日(格式20180101)',
        'ready_baby_day'=>'预产期',
        'customer_name'=>'妈妈姓名',
        // 'customer_sex'=>'性别',
        'customer_tel'=>'妈妈手机号',
        'customer_wechat'=>'微信',
        'customer_qq'=>'QQ',
        'customer_weibo'=>'微博',
        'mate_name' =>'爸爸姓名',
        'mate_tel' =>'爸爸手机号',
        'province'=>'省',
        'city'=>'市',
        'county'=>'区',
        'customer_address'=>'详细地址',
        'customer_type'=>'客户类型',
        'introducer_name'=>'介绍人',
        'customer_channel'=>'渠道名称',
        'access_model'=>'获取方式',
        'consultation_type'=>'消费类型',
        'customer_cource'=>'客户来源',
        'channel_plan_number'=>'推广编号',
        'ad_page'=>'广告落地页',
        'customer_area'=>'客户分区',
        'customer_intention'=>'客户意向',
        'consulation_shop'=>'意向店面',
        'customer_orderaddress'=>'接单点',
        'sales_staff'=>'追踪人',
        'customer_remark'=>'客资备注',
        'introduce_staff_name'=>'转介绍人',
        'customer_key'=>'关键字',
        'customer_label'=>'客资标签',
        'create_time'=>'获取时间(格式202101010900)',
        'dj_day'       => '登记日期',
    );
    return $title;
}
//导入模板表头对应的表字段 婚纱
function import_header(){
    $title=array(
        'customer_name'=>'客户姓名',
        'customer_sex'=>'性别',
        'customer_tel'=>'手机号',
        'customer_wechat'=>'微信',
        'customer_qq'=>'QQ',
        'customer_weibo'=>'微博',
        'province'=>'省',
        'city'=>'市',
        'county'=>'区',
        'customer_address'=>'详细地址',
        'customer_type'=>'客户类型',
        'introducer_name'=>'介绍人',
        'customer_channel'=>'渠道名称',
        'access_model'=>'获取方式',
        'consultation_type'=>'消费类型',
        'customer_cource'=>'客户来源',
        'channel_plan_number'=>'推广编号',
        'ad_page'=>'广告落地页',
        'customer_area'=>'客户分区',
        'customer_intention'=>'客户意向',
        'consulation_shop'=>'意向店面',
        'customer_orderaddress'=>'接单点',
        'sales_staff'=>'追踪人',
        'customer_remark'=>'客资备注',
        'introduce_staff_name'=>'转介绍人',
        'customer_key'=>'关键字',
        'customer_label'=>'客资标签',
        'create_time'=>'获取时间(格式202101010900)',
        'dj_day'       => '登记日期',
        // 'dj_staff'     => '登记人',
        // 'dj_staff_id'  => '录入员工id',
        // 'fp_staff'     => '分配人',
        // 'fp_staff_id'  => '分配人id',
        // 'fp_day'       => '分配日期',
        // 'jr_day'       => '接入日期',
        // 'add_shop_code'=> '录入员工部门code',
        // 'add_shop_name'=> '录入员工部门名',
        // 'brandclass'   => '事业部名',
        // 'brandclass_id'=> '事业部ID',
        // 'is_valid'     => '是否有效',
        // 'yx_day'       => '标记有效时间',
        // 'yjd_day'      => '预约进店时间',
        // 'is_intostore' => '是否进店',
        // 'syjd_day'     => '实际进店日期',
        // 'c_star_day'   => '开始追踪日期',
    );
    return $title;
}
//下载导入excel模板 婚纱
function template_header(){
    // $title=array('客户姓名','性别','手机号','微信','QQ','微博','省','市','区','详细地址','客户类型','客户渠道','获取方式','消费类型','客户来源','客户分区','客户意向','意向店面','接单点','追踪人','登记人','录入员工id','登记日期','分配人','分配人id','分配日期','接入日期','录入员工部门code','录入员工部门名','事业部名', '事业部ID','是否有效','标记有效时间','预约进店时间','是否进店','实际进店日期','开始追踪日期');
    $title=array('客户姓名','性别','手机号','微信','QQ','微博','省','市','区','详细地址','客户类型','介绍人','渠道名称','获取方式','消费类型','客户来源','推广编号','广告落地页','客户分区','客户意向','意向店面','接单点','追踪人','客资备注','转介绍人','关键字','客资标签','获取时间(格式202101010900)','登记日期');
    return $title;
}
//下载导入excel模板 儿童
function template_header_child(){
    // $title=array('客户姓名','性别','手机号','微信','QQ','微博','省','市','区','详细地址','客户类型','客户渠道','获取方式','消费类型','客户来源','客户分区','客户意向','意向店面','接单点','追踪人','登记人','录入员工id','登记日期','分配人','分配人id','分配日期','接入日期','录入员工部门code','录入员工部门名','事业部名', '事业部ID','是否有效','标记有效时间','预约进店时间','是否进店','实际进店日期','开始追踪日期');

    $title=array('宝宝姓名','宝宝性别','宝宝生日(格式20180101)','预产期','妈妈姓名','妈妈手机号','微信','QQ','微博','爸爸姓名','爸爸手机号','省','市','区','详细地址','客户类型','介绍人','渠道名称','获取方式','消费类型','客户来源','推广编号','广告落地页','客户分区','客户意向','意向店面','接单点','追踪人','客资备注','转介绍人','关键字','客资标签','获取时间(格式202101010900)','登记日期');

    return $title;
}

//导出excel模板表头
function export_header(){
    $title=array('客资ID','渠道名称', '客资标记','是否有效','追踪标记','编号', '姓名', '性别', '手机号', '微信', '微博', 'QQ','配偶姓名','配偶手机','配偶微信','省','城市','区县','关键字','婚期','预算','意向店面', '预约操作时间', '预约进店时间','推广编号','广告落地页','追踪记录','客资标签','是否进店', '进店时间', '是否成交','订单开始时间','订单时间','订单类型','订单金额','实际收款','一销实收','一销套系','流失原因','客户类型','登记日期','获取日期','是否分配', '是否流失', '登记人','追踪人','筛客人','转介绍人','老顾客姓名','老顾客电话','老顾客单号','老顾客类型','电访量','开始追踪时间','最后追踪时间', '消费类型', '客户来源', '客户意向','获取方式', '接单点', '客户分区','品牌','归属店','提报店','单号','客资备注','加好友时间','登记小组','追踪小组',
    );
    return $title;
}
//导出excel模板表头
function export_header_child(){
    $title=array('客资ID','渠道名称', '客资标记','是否有效','追踪标记','编号', '宝宝姓名', '宝宝性别','宝宝生日','预产期','妈妈姓名', '性别', '妈妈手机号', '妈妈微信', '微博', 'QQ','爸爸姓名','爸爸手机','爸爸微信','省','城市','区县','关键字','婚期','预算','意向店面', '预约操作时间', '预约进店时间','渠道编号','广告落地页','追踪记录','客资标签','是否进店', '进店时间', '是否成交','订单开始时间','订单时间','订单类型','订单金额','实际收款','一销实收','一销套系','流失原因','客户类型','登记日期','获取日期','是否分配', '是否流失', '登记人','追踪人','筛客人','转介绍人','老顾客姓名','老顾客电话','老顾客单号','老顾客类型','电访量','开始追踪时间','最后追踪时间', '消费类型', '客户来源', '客户意向','获取方式', '接单点', '客户分区','品牌','归属店','提报店','单号','客资备注','加好友时间','登记小组','追踪小组',
    );
    return $title;
}

/**
 * 字符串截取，支持中文和其他编码
 * @static
 * @access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * @return string
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
    if(function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }

    return ($suffix && (mb_strlen($str,$charset) > $length)) ? $slice.'...' : $slice;
}

// 排序根据二维数组的某个字段排序 
// SORT_DESC 降序；SORT_ASC 升序  SORT_NUMERIC数字顺序  SORT_STRING 字母顺序
function my_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){
    if ($sort_order == 'SORT_DESC') {
        $sort_order = SORT_DESC;
    }else{
        $sort_order = SORT_ASC;
    }
    if ($sort_type == 'SORT_STRING') {
        $sort_type = SORT_STRING;
    }else{
        $sort_type = SORT_NUMERIC;
    }
    if(is_array($arrays)){
        foreach ($arrays as $array){
            if(is_array($array)){
                $key_arrays[] = $array[$sort_key];
            }else{
                return false;
            }
        }
    }else{
        return false;
    }
    array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
    return $arrays;
}

/**
 * 获取或更新数据库配置键对应的值。
 * 
 * @param type $key
 * @param type $value
 * @return boolean
 */
function db_config($key,$value = '') {
    
    $cacheKey = 'db_config_'.$key;
    if('' === $value){
        
        if(cache('?'.$cacheKey)){
            
            return cache($cacheKey);
        }else{
            $value = db('c_sysconfig')->where('ckey',$key)->value('cvalue');
            if(!is_null( $value ) ){
                cache($cacheKey,$value);
            }
            // return $value;
            $val = json_decode($value, true);
            $return = $val ? $val : $value;
            return $return;
        }
    }elseif(null === $value){
        try{
            $count = db('c_sysconfig')->where('ckey',$key)->count();
            if($count>0){
                $res = db('c_sysconfig')->where('ckey',$key)->delete();
            }
            cache($cacheKey,null);
            return true;
        }catch(\Exception $e){
            return false;
        }
    }else{
        try{
            db()->startTrans();
            $count = db('c_sysconfig')->where('ckey',$key)->count();
            if($count>0){
                $res = db('c_sysconfig')->where('ckey',$key)->update(array('cvalue'=>$value));
            }else{
                $res = db('c_sysconfig')->insert(array('ckey'=>$key,'cvalue'=>$value));
            }
            if($res === false){
                db()->rollback();
                return false;
            }else{
                db()->commit();
                cache($cacheKey,null);
                // cache($cacheKey,$value);
                return true;
            }
        }catch(\Exception $e){
            return false;
        }
    }
}
//根据staff_id获取cache里的用户信息
function getStaffInfoById($staff_id){
    /*if(!empty(cache('staffInfo_'.$staff_id))) {
        return cache('staffInfo_'.$staff_id);
    }else{
        $res = controller('crm/Customer','lib')->get_staff_info(array('staff_id'=>$staff_id));
        if($res['code'] != 200){
            return [];
        }
        foreach($res['data'] as $k=>$v){
            $res['data'][$k]['staff_id'] = $v['id'];
            $res['data'][$k]['staff_name'] = $v['staffname'];
            $res['data'][$k]['staffnumber'] = $v['staffnumber'];
        }
        cache('staffInfo_'.$staff_id,$res['data']);
        return $res['data'];
    }*/

    $mc = new \app\common\lib\mcInterface();
    $staff = $mc->getOneStaff(['staff_id'=>$staff_id]);
    return $staff;
}

/**
 * 根据指定店和客资提报类型，返回这个店的客资应该的归属店有哪些
 * 手动分配时，不用传客资类型
 * 如果这个返回为空，则调用的地方就取操作者当前店，或是提报店
 * @param  [type]  $thisShopCode [description]
 * @param  integer $customerType [description]
 * @return [type]                [description]
 */
function getBelongShopList($thisShopCode,$customerType=1){
    $mc = new \app\common\lib\mcInterface();
    if($customerType == 2){
        //转介绍，取所有是专介绍接收店的店面。
        //这里暂时不加事业部
        $shop = $mc->getShopInfo(['is_dig'=>1]);
    }else{
        //取指定店的客资提报归属店，看有没有，
        //如果没有，则取CRM设置内的提报归属店配置内进行配置
        //如果当前店已经在MC内设置了提报客资归属店了，则CRM内配置不可见
        $shop = $mc->getShopInfo(['shop_code'=>$thisShopCode]);
        // $shop = controller('crm/Customer','lib')->get_shop(['shop_code'=>$thisShopCode]);
        if(empty($shop[0]['belong_shop_code'])){
            $shop = db_config('dj_shops_'.$thisShopCode);
            // if(empty($shop)){
            //     $shop = array(['shop_code'=>$thisShopCode,'shop_name'=>$data['shop_name']]);
            // }
        }else{
            $shop[0]['shop_code'] = $shop[0]['belong_shop_code'];
            $shop[0]['shop_name'] = $shop[0]['belong_shop_name'];
        }
    }
    return $shop;
}

// 根据时间获取对应的表明，c_hour_number，c_day_number
function getTable($day){
    $date = date('Ymd');
    $temp = date('Ymd', strtotime($day));
    if ($date == $temp) {
        // 时间表
        $return['table'] = 'c_hour_number';
        $return['useDay'] = date('YmdH', strtotime($day));
    }else{
        // 日期表
        $return['table'] = 'c_day_number';
        $return['useDay'] = date('Y-m-d', strtotime($day));
    }
    return $return;
}

/**
 * 把返回的数据集转换成Tree
 * @param $list
 * @param string $pk
 * @param string $pid
 * @param string $child
 * @param string $root
 * @return array
 */
function listToTree($list, $pk='id', $pid = 'fid', $child = '_child', $root = '0') {
    $tree = array();
    if(is_array($list)) {
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] = &$list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent = &$refer[$parentId];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}

function formatTree($list, $lv = 0, $title = 'menu_name'){
    $formatTree = array();
    foreach($list as $key => $val){
        $title_prefix = '';
        for( $i=0;$i<$lv;$i++ ){
            $title_prefix .= "|---";
        }
        $val['lv'] = $lv;
        $val['namePrefix'] = $lv == 0 ? '' : $title_prefix;
        $val['showName'] = $lv == 0 ? $val[$title] : $title_prefix.$val[$title];
        if(!array_key_exists('_child', $val)){
            array_push($formatTree, $val);
        }else{
            $child = $val['_child'];
            unset($val['_child']);
            array_push($formatTree, $val);
            $middle = formatTree($child, $lv+1, $title); //进行下一层递归
            $formatTree = array_merge($formatTree, $middle);
        }
    }
    return $formatTree;
}
function treeData($list,$fid){
    $tree = array();
    foreach($list as $k=>$row) {
        if($row['fid'] == $fid) {
            // 20191111
            $currentMenuUrlCon = request()->controller();
            $currentMenuUrlAct = request()->action();
            // 控制器 和 方法名 两个 都和menu_url相同，设为选中状态
            $menuUrlArr = explode('/',$row['menu_url']);
            $act = array_pop($menuUrlArr);
            $con = array_pop($menuUrlArr);
            
            if(strtolower($con)==strtolower($currentMenuUrlCon) && strtolower($act)==strtolower($currentMenuUrlAct)){
                $row['active'] = 1;
            }else{
                // 统计分析
                if (strtolower($currentMenuUrlCon)=='report'&&strtolower($currentMenuUrlAct)=='index'&&$row['menu_code']=='menu1512736477') {
                    $row['active'] = 1;
                }else{
                    $row['active'] = 0;
                }
            }
            $row['children'] = treeData($list, $row['id']);
            $temp = array_column($row['children'], 'active');
            if (in_array(1, $temp)) {
                $row['active'] = 1;
            }
            $tree[] = $row;
        }
    }
    return $tree;
}
/*
 * 将数据递归处理
 *  @param array $list
 *  @param string $fid
 */
function treeData_old($list,$fid){
    $tree = array();
    foreach($list as $k=>$row) {
        if($row['fid'] == $fid) {
            $currentMenuUrl = request()->action();
            //方法名和menu_url相同，设为选中状态
            if(strtolower(end(explode('/',$row['menu_url'])))==strtolower($currentMenuUrl)){
                $row['active'] = 1;
            }else{
                $row['active'] = 0;
            }
            $row['children'] = treeData($list, $row['id']);
            $tree[] = $row;
        }
    }
    return $tree;
}
function treeData1($list,$pid){
    $tree = array();
    foreach($list as $row) {
        if($row['pid'] == $pid) {
            $row['children'] = treeData($list, $row['id']);
            $tree[] = $row;
        }
    }
    return $tree;
}
//获取登录人左侧菜单信息
function getAuth($type){
    //$position_code=trim(session('main_position_code').','.session('position_code'),',');
    //$menuAll=db('s_position_menu')->where('position_code','in',$position_code)->select();
    if($type=='menu'){
        $menuList=cache('CRM_menuAll');
        if(!$menuList){
            $menuList=db('s_menu')->where('status',1)->order('sort asc')->select();
            // echo db()->getLastSql();die;
            //$menuList=array_column($menus,'menu_code');
            cache('CRM_menuAll',$menuList);
        }
    }elseif($type=='auth'){
        $menuList=cache('CRM_menuAllS');
        if(!$menuList){
            $menuList=db('s_menu')->where('status', '<>', '99')->select();
            //$menuList=array_column($menus,'menu_code');
            cache('CRM_menuAllS',$menuList);
        }
    }

    $work_type=explode(',',trim(session('main_work_type')));
    //$work_type=explode(',',session('work_type'));
    if(in_array(SYSTEM_AUTH_ADMIN,$work_type)){
        return $menuList;
    }else{
//        $position_code=array_unique(explode(',',trim(session('main_position_code').','.session('position_code'),',')));
//        $menuAll=array();
//        foreach($position_code as $k => $v){
//            //取这个岗位的所有MENU 逗号分隔的menu code
//            $menu=cache('CRM_menu_'.$position_code[$k]);
//            if(!$menu){
//                $data=db('s_position_menu')->where('position_code',$position_code[$k])->find();
//                $menu=$data['menu_code'];
//                cache('CRM_menu_'.$position_code[$k], $menu);
//            }
//            //array_merge($menuAll,$menu);
//            array_push($menuAll,$menu);
//        }
        $menuAll=cache('CRM_menu_'.session('main_position_code'));
        if(!$menuAll){
            $data=db('s_position_menu')->where('position_code',session('main_position_code'))->find();
            $menuAll=$data['menu_code'];
            cache('CRM_menu_'.session('main_position_code'), $menuAll);
        }
        //去重
        //$menuAll = array_unique($menuAll);
        $menuAll=array_unique(explode(',',$menuAll));
        //取所有menu的详细信息
        foreach ($menuList as $k=>$menuInfo){
            if(!in_array($menuInfo['menu_code'], $menuAll)){
                unset($menuList[$k]);
            }
        }
        //$menuList=array_unique(explode(',',implode(',',$menuAll)));
        return $menuList;
    }
}

//获取登录人所有权限菜单
function getMenu(){

}
/**
 * 获取所有目录
 * 
 * @return [type] [description]
 */
function getAllMenu($menu,$customize){
    $result = [];
    foreach ($menu as $key => $value) {
        //定制菜单，非定制企业不显示。
        if($value['customize']){
            $ccode = explode(',', $value['customize']);
            $remove = 0;
            foreach ($ccode as $code) {
                if(customize($code)){
                    $remove = 0;
                    break;
                }
                $remove = 1;
            }
            if($remove){
                unset($menu[$key]);
                continue;
            }
        }

        //有定制不一样的菜单，更换value值
        if(key_exists($value['menu_code'],$customize)){
            $value = $customize[$value['menu_code']];
        }
        if(!empty($value['children'])){
            $children = getAllMenu($value['children'],$customize);
            $value['children'] = $children;
        }
        $result[] = $value;
    }
    return $result;
}
/**
 * 根据树形目录结构，进行菜单的过虑，支持定制，权限等过虑，
 * 此函数返回的值，可用于前端菜单展示。
 * @param  [type] $menu      [description]
 * @param  [type] $type      [description]
 * @param  [type] $customize [description]
 * @return [type]            [description]
 */
function getAuthMenu($menu,$type,$customize){
    $work_type=explode(',',trim(session('main_work_type').','.session('work_type'),','));
    $active = 0;
    $result = [];
    foreach ($menu as $key => $value) {
        if($type == 'menu' && $value['status'] == 0){
            unset($menu[$key]);
            continue;
        }
        if(!in_array(SYSTEM_AUTH_ADMIN,$work_type)){
            $position_code=array_unique(explode(',',trim(session('main_position_code').','.session('position_code'),',')));
            $right = 0;
            foreach ($position_code as $k => $v) {
                if(checkPositionRight($v,$value['menu_code'])){
                    $right = 1;
                    break;
                }
            }
            if(!$right){
                unset($menu[$key]);
                continue;
            }
        }
        $currentMenuUrl = '/' . request()->module() . '/' . request()->controller() . '/' . request()->action();
        if (strtolower($value['menu_url']) == strtolower($currentMenuUrl)) {
            $value['active'] = 1;
            $active = 1;
        } else {
            $value['active'] = 0;
        }
        //定制菜单，非定制企业不显示。
        if($value['customize']){
            $ccode = explode(',', $value['customize']);
            $remove = 0;
            foreach ($ccode as $code) {
                if(customize($code)){
                    $remove = 0;
                    break;
                }
                $remove = 1;
            }
            if($remove){
                unset($menu[$key]);
                continue;
            }
        }
        //有定制不一样的菜单，更换value值
        if(key_exists($value['menu_code'],$customize)){
            $value = $customize[$value['menu_code']];
        }
        if(!empty($value['children'])){
            $children = getAuthMenu($value['children'],$type);
            if($children['active'] == 1){
                $value['active'] = 1;
                $active = 1;
            }
            $value['children'] = $children['list'];
        }
        $result[] = $value;
    }
    return ['list'=>$result,'active' => $active];
}

function checkPositionRight($position_code,$menu_code){
    $menu=cache('CRM_menu_'.$position_code);
    if(!$menu){
        $data = db('s_position_menu')->select();
        foreach ((array)$data as $value) {
            cache('CRM_menu_'.$value['position_code'], $value['menu_code']);
            if($position_code == $value['position_code']){
                $menu = $value['menu_code'];
            }
        }
    }
    $menu = trim($menu,',');
    $menu = explode(',', $menu);
    return in_array($menu_code, $menu)?true:false;
}

//判断是否安装某应用
function is_install($name){
    $all = config('ext.app_config');
    if(empty($all[$name])){
        return false;
    }else{
        $is_at = db_config($name.'_'.session('brandclass_id'));
        if($is_at){
            return true;
        }else{
            return false;
        }
    }
}
function ajax_return($data,$code = 200,$msg = ""){
    
    $ret = [
      'code'=>$code,
      'msg'=>$msg,
      'data'=>$data,
    ];
    return json($ret);
}
/**
 * 返回系统版本号，支持模块版本，和应用版本
 * 在application下的config.php配置的APP_VERSION版本号，为应用版本号
 * 在application/模块/config.php配置的MODULE_VERSION为模块版本号
 * 
 * @param type $type 版本类型，默认app
 * @return type
 */
function get_version($type ='') {
    $module = \think\Request::instance()->module();
    if(empty($type)){
        return strtolower($module) == 'index'?APP_VERSION:config('MODULE_VERSION');
    }else{
        if(strtolower($module) == 'index'){
            return APP_VERSION;
        }else{
            return strtolower($type) == 'app'?APP_VERSION:config('MODULE_VERSION');
        }
    }
}

//检测是否是管理员
function isAdministrator(){
    $main_work_type = (int)session('main_work_type');
    $work_type      = session('work_type');

    $allWorkType = explode(',',trim($main_work_type.','.$work_type,','));
    if(in_array(SYSTEM_AUTH_ADMIN,$allWorkType)){
        return true;
    }else{
        return false;
    }
}

// function check_right($code){
//     //判断是否有权限
//     $auth=getAuth($type='auth');
//     if(in_array($code,array_column($auth,'menu_code'))){
//         return true;
//     }else{
//         return false;
//     }
// }
//功能菜单menu_code
function check_right($code){
    if(isAdministrator()) return true;
    $position_code=array_unique(explode(',',trim(session('main_position_code').','.session('position_code'),',')));
    $right = 0;
    foreach ($position_code as $k => $v) {
        if(checkPositionRight($v,$code)){
            $right = 1;
            break;
        }
    }
    if(!$right){
        return false;
    }
    return true;
}
///判断是PC还是微信登录
function is_weixin(){
    if(config('ignore_weixin_oauth')) return false;
    if ( strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') !== false ) {
        return true;
    }else{
        return false;
    }
}
/**
 * 求两个日期之间相差的天数
 * (针对1970年1月1日之后，求之前可以采用泰勒公式)
 * @param string $day1
 * @param string $day2
 * @return number
 */
function diffBetweenTwoDays ($day1, $day2)
{
    $second1 = strtotime($day1);
    $second2 = strtotime($day2);

    if ($second1 < $second2) {
        $tmp = $second2;
        $second2 = $second1;
        $second1 = $tmp;
    }
    return ($second1 - $second2) / 86400;
}


/**
 * 队列中需要记录日志时，调用此方法
 * @param Mix $data           本次要记录的日志数据
 * @param Mix $oldData        修改前的数据
 * @param Int $customerId     当前操作的客户ID。
 * @param Int $staffId        当前登录员工ID，默认取session内的staff_id,针对API记录，需要手动传入。
 * @param Int $staffName      当前登录员工姓名
 * @param String $module      操作的模块，默认取当前请求的应用模块
 * @param String $controller  操作的控制器，默认取当前请求的控制器
 * @param String $action      操作的方法，默认取当前请求的方法
 */
function history_log($data,$oldData,$customerId,$staffId,$staffName,$module,$controller,$action,$ip,$create_time){
    if(!$module){
        $module = \think\Request::instance()->module();
    }
    if(!$controller){
        $controller = \think\Request::instance()->controller();
    }
    if(!$action){
        $action = \think\Request::instance()->action();
    }
    if(!$ip){
        $ip = \think\Request::instance()->ip();
    }
    if(!is_string($data)){
        $data = json_encode($data);
    }
    if(!is_string($oldData)){
        $oldData = json_encode($oldData);
    }
    if (!$create_time) {
        $create_time = date('Y-m-d H:i:s');
    }
    $logData = [
        'module'     => $module,
        'controller' => $controller,
        'action'     => $action,
        'old_data'   => $oldData,
        'data'       => $data,
        'customer_id'=> $customerId,
        'staff_name' => $staffName,
        'staff_id'   => $staffId,
        'ip'         => $ip,
        'create_time'=> $create_time,
    ];
    db()->startTrans();
    try {
        db('action_log','db_logs')->insert($logData);
        db()->commit();
    } catch (\Exception $e) {
        db()->rollback();
        \think\Log::error('日志保存错误:module:'.$module.';controller:'.$controller.';action:'.$action.';data:'.$data.';olddata:'.$oldData.';customerid:'.$customerId,'msg:'.$e->getMessage());
    }
}
//ip138查询手机归属地
function getData($mobile){
    $token = db_config('sx_secret_key_'.session('shop_code'));
    $handles = '';
    if ($token) {
        $datatype = 'txt';
        $url = 'http://api.ip138.com/mobile/?mobile='.$mobile.'&datatype='.$datatype;
        $header = array('token:'.$token);
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,3);
        $handles = curl_exec($ch);
        curl_close($ch);
    }
    return $handles;
}
function is_mobile(){
    /**
     * 各手机agent
     * iphone 7 :
     *     Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.0 Mobile/14G60 Safari/602.1
     * iphone 6:
     *     Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1
     * 阿里钉钉
     *     Mozilla/5.0 (Linux; U; Android 7.0; zh-CN; HUAWEI NXT-AL10 Build/HUAWEINXT-AL10) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/40.0.2214.89 UCBrowser/11.6.4.950 UWS/2.11.1.50 Mobile Safari/537.36 AliApp(DingTalk/4.5.5) com.alibaba.android.rimet/0 Channel/227200 language/zh-CN
     * 华为 meta 8 
     *     Mozilla/5.0 (Linux; Android 7.0; HUAWEI NXT-AL10 Build/HUAWEINXT-AL10) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Mobile Safari/537.36
     * 微信：
     *     Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_2 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) CriOS/30.0.1599.12 Mobile/11A501 Safari/8536.25 MicroMessenger/6.1.0
     * ipad air:
     * Mozilla/5.0 (iPad; CPU OS 12_4_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.2 Mobile/15E148 Safari/604.1
     * 
     **/
    if ( strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'mobile') !== false ) {
        return true;
    }else{
        return false;
    }

}
//百度地图：通过ip获取城市
function getCityByIp($ip){
    $ak = config('BAIDU_API');
    $url = "http://api.map.baidu.com/location/ip?ak=".$ak."&ip=$ip&coor=bd09ll";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    if(curl_errno($ch)){
        echo 'CURL ERROR Code: '.curl_errno($ch).', reason: '.curl_error($ch);
    }
    curl_close($ch);
    $city_info = json_decode($output, true);
    if($city_info['status'] == "0"){
       // $citytemp = $city_info['content']['address_detail']['city'];
       // $keywords = explode("市",$citytemp);
       // $city = iconv('utf-8','gbk',$keywords[0]);
        return $city_info['content']['address'];
    }else{
        return false;
    }
}
/**
 * 读取文件前几个字节 判断文件类型
 * @return String
 */
function checkFileType($filename){
    $file=fopen($filename, "rb");
    $bin=fread($file, 2); //只读2字节
    fclose($file);
    $strInfo =@unpack("c2chars", $bin);
    $typeCode=intval($strInfo['chars1'].$strInfo['chars2']);
    $fileType='';
    switch($typeCode){
        case 7790:
            $fileType='exe';
            break;
        case 7784:
            $fileType='midi';
            break;
        case 8297:
            $fileType='rar';
            break;
        case 255216:
            $fileType='jpg';
            break;
        case 7173:
            $fileType='gif';
            break;
        case 6677:
            $fileType='bmp';
            break;
        case 13780:
            $fileType='png';
            break;
        case 8273:
            $fileType='wav';
            break;
        default:
            $fileType='unknown'.$typeCode;
            break;
    }
    //Fix
    if($strInfo['chars1']=='-1' && $strInfo['chars2']=='-40'){
        return 'jpg';
    }
    if($strInfo['chars1']=='-119' && $strInfo['chars2']=='80'){
        return 'png';
    }
    return $fileType;
}

function requestERP($url,$content){
    $time      = time();
    $nonce     = rand(99999,999999);
    $signature = md5($time.$nonce.'oUWKYeqCEojOvbmsynvWTctJSAVeoMZv');
    $header    = array('timestamp:'.$time,'nonce:'.$nonce,'signature:'.$signature);
    $header[] = 'Content-Type: application/json; charset=utf-8';
    $header[] = 'Content-Length: ' . strlen($content);
    // var_dump($header);
    // exit;
    // $url = 'http://192.168.0.172:8082/OPimg/TDInfo?Token=^******^';
    // $a = tocurl($url, $header, $content);
    $a = http_request($url,'POST', $content,$header);
    // var_dump($a);
    // exit;
    $b = json_decode($a['response'], true);
    if($b['Code'] != 200){

        api_log($content);
        
        $log['request_url'] = $url;
        $log['request_data'] = json_encode($content);
        $log['response_code'] = $b['Code'];
        $log['response_data'] = $resData;
        $log['request_start_time'] = microtime(true);
        $log['request_end_time'] = microtime(true);
        $log['create_time'] = date('Y-m-d H:i:s');
        $log['create_ip'] = get_client_ip();
        common_log($log,'request_logs');
    }

    $resData = $a['response'];
    $len = strlen($resData);
    if ( ($len/1024) > 1024 ) {
        $resData = '';
    }
    unset($url);
    unset($content);
    unset($a);
    unset($resData);
    unset($log);
    return $b;
}

function requestWXERP($url,$content){
    $time      = time();
    $nonce     = rand(99999,999999);
    $signature = md5($time.$nonce.'oUWKYeqCEojOvbmsynvWTctJSAVeoMZv');
    $header    = array('timestamp:'.$time,'nonce:'.$nonce,'signature:'.$signature);
    $header[] = 'Content-Length: ' . strlen($content);
    // var_dump($header);
    // exit;
    // $url = 'http://192.168.0.172:8082/OPimg/TDInfo?Token=^******^';
    // $a = tocurl($url, $header, $content);
    $a = http_request($url,'POST', $content,$header);
    // var_dump($a);
    // exit;
    $b = json_decode($a['response'], true);
    if($b['Code'] != 200){
        unset($content['Token'],$content['Code']);

        api_log($content);
        
        $log['request_url'] = $url;
        $log['request_data'] = json_encode($content);
        $log['response_code'] = $b['Code'];
        $log['response_data'] = $resData;
        $log['request_start_time'] = microtime(true);
        $log['request_end_time'] = microtime(true);
        $log['create_time'] = date('Y-m-d H:i:s');
        $log['create_ip'] = get_client_ip();
        common_log($log,'request_logs');
    }

    $resData = $a['response'];
    $len = strlen($resData);
    if ( ($len/1024) > 1024 ) {
        $resData = '';
    }
    unset($url);
    unset($content);
    unset($a);
    unset($resData);
    unset($log);
    return $b;
}

function common_log($data,$table){
    if(strtolower(config('log_save')) == 'async'){
        //异步日志
        $content = [
            'table_name'=>$table,
            'data'=>$data
        ];
        return \app\common\lib\redisQueue::init()->rPush('crm_logs_queue', $content);
    }else{
        db($table,'db_logs')->insert($data);
    }
}
/**
 * 编号+1
 *  @param String  $my_number 编号
 * @author {wangyining}<{wangyining@suxuantech.cn}>  $
 */
function get_number($my_number){

    if(eregi("^[0-9]+$",$my_number)) {//纯数字
        if(strlen((int)$my_number+1)<strlen($my_number)){
            $count = str_pad((int)$my_number + 1, strlen($my_number), '0', STR_PAD_LEFT);
        }elseif(strlen((int)$my_number+1)>=strlen($my_number)){
            $count=(int)$my_number+1;
        }
        $number=$count;
    }else{//字母加数字

        $array=$this->check_array($my_number);
        $sort_array=array_reverse($array);

        for($i=0;$i<count($sort_array);$i++){
            if(!eregi("^[0-9]+$",$sort_array[$i])){
                $point=$i;
                break;
            }
        }
        $lenth=strlen($my_number);
        $str=substr($my_number,0,(int)$lenth - $point);
        $num=substr($my_number,-$point);
        if(strlen($num+1)<strlen($num)){
            $count = str_pad($num + 1, strlen($num), '0', STR_PAD_LEFT);
        }elseif(strlen($num+1)>=strlen($num)){
            $count=$num+1;
        }
        $number=$str.$count;
    }
    return $number;
}

//生成指定长度随机数
function generate_code($length = 4) {
    return rand(pow(10,($length-1)), pow(10,$length)-1);
}

/**
 * $msg 待提示的消息
 * $url 待跳转的链接
 * $time 弹出维持时间（单位秒）
 */
function alert($msg='',$url='',$time=3)
{
    $public  = config('view_replace_str');

    $str = '<script type="text/javascript" src="'.$public['__PUBLIC__'].'/js/jquery-1.7.1.min.js"></script><script type="text/javascript" src="'.$public['__PUBLIC__'].'/item/layui.all.js"></script></script>';//加载jquery和layer
    $time = (int)$time * 1000;
    if($url){
        $str .= '<script>$(function(){layer.alert("' . $msg . '");setTimeout(function(){self.location.href="' . $url . '"},'.$time.')});</script>';
    }else{
        $str .= '<script>$(function(){layer.alert("' . $msg . '");</script>';
    }
    
    echo $str;
}
// 根据开始结束时间， 返回各个月份内的开始结束时间
function getMonths($param){
    $start = $param['start'];
    $end   = $param['end'];
    $startM= date('Ym', strtotime($start));
    $endM  = date('Ym', strtotime($end));
    $months= [];
    if ($endM < $startM) {
        return json(array('error'=>'','code' => 200, 'msg' => '开始结束时间错误', 'count' => 0, 'data' => ''));
    }
    // 如果开始月份等于结束月份， 为当月
    if ( $startM == $endM ) {
        $months[$startM]['start'] = $start;
        $months[$startM]['end'] = $end;
    }else{
        $first = date('Y-m-01', strtotime($start));
        $months[$startM]['start'] = date('Y-m-d 00:00:00', strtotime($start));
        $months[$startM]['end']   = date('Y-m-d 23:59:59', strtotime("+1 months -1 day",strtotime($first)));

        $startM = date('Ym', strtotime("+1 months",strtotime($start)));
        $temp   = date('Ymd', strtotime("+1 months",strtotime($start)));
        while ( $startM != $endM ) {
            $months[$startM]['start'] = date('Y-m-01 00:00:00', strtotime($temp));
            $months[$startM]['end']   = date('Y-m-d 23:59:59', strtotime("+1 months -1 day",strtotime($months[$startM]['start'])));

            $temp   = date('Ymd', strtotime("+1 months",strtotime($temp)));
            $startM = date('Ym', strtotime($temp));
        }
        $months[$endM]['start'] = date('Y-m-01 00:00:00', strtotime($startM));
        $months[$endM]['end']   = $end;
    }
    return $months;
}
// 根据月份获取当前月份的每一天 默认当前月份
function getMonthDays($month = "this month", $format = "Y-m-d", $dateTimeZone = false) {
    if(!$dateTimeZone) $dateTimeZone = new DateTimeZone("Asia/Shanghai");
    $start = new DateTime("first day of $month", $dateTimeZone);
    $end = new DateTime("last day of $month", $dateTimeZone);

    $days = array();
    for($time = $start; $time <= $end; $time = $time->modify("+1 day")) {
        $days[] = $time->format($format);
    }
    return $days;
}
//获取星期方法
function get_week($date){
    //强制转换日期格式
    $date_str=date('Y-m-d',strtotime($date));
    //封装成数组
    $arr=explode("-", $date_str);
    //参数赋值
    //年
    $year=$arr[0];
    //月，输出2位整型，不够2位右对齐
    $month=sprintf('%02d',$arr[1]);
    //日，输出2位整型，不够2位右对齐
    $day=sprintf('%02d',$arr[2]);
    //时分秒默认赋值为0；
    $hour = $minute = $second = 0;
    //转换成时间戳
    $strap = mktime($hour,$minute,$second,$month,$day,$year);
    //获取数字型星期几
    $number_wk=date("w",$strap);
    //自定义星期数组
    $weekArr=array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
    //获取数字对应的星期
    return $weekArr[$number_wk];
}

/**验证手机号格式  只验证港澳台及大陆手机号码，不包含座机小灵通及区号等验证
 * $tel 手机号  
    规则说明：
    大陆手机号：13、14、15、16、17、18、19 开头，加9位数字。
    香港为852开头的，后面加8位数字。
 */
function check_tel($tel){
    // $preg_tel = '/^[1][3-9]\d{9}$|^([6|9])\d{7}$|^[0][9]\d{8}$|^[6]([8|6])\d{5}$/';
    $res = db('c_sysconfig')->field('cvalue')->where('ckey','tel_address_grant')->find();
    if (is_array(grtTelAddressRegular())) {
        foreach (grtTelAddressRegular() as $key => $value) {
            if (in_array($key, explode(",",$res['cvalue']))) {
                if(preg_match("/".$value['zc']."/",$tel)){
                    return true;exit;
                }
            }
        }
        return false;
    }else{
        return false;
    }
}
//提取 手机号配置 正则
function check_tel_arr(){
    $regular = '';
    $res = db('c_sysconfig')->field('cvalue')->where('ckey','tel_address_grant')->find();
    foreach (grtTelAddressRegular() as $key => $value) {
        if (in_array($key, explode(",",$res['cvalue']))) {
            $regular .= $value['zc'].",";
        }
    }
    return trim($regular,",");
}
/**
 * 获取当前配置内，上传文件的最大限制
 *
 * @return type
 */
function getMaxUploadSize(){

    $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
    $scan['g']  = 1073741824; //1024 * 1024 * 1024;
    $scan['mb'] = 1048576;
    $scan['m']  = 1048576;
    $scan['kb'] =    1024;
    $scan['k']  =    1024;
    $scan['b']  =       1;
    $upSize = strtolower(ini_get('upload_max_filesize'));
    $upSizeC = str_replace(intval($upSize) . '','',$upSize);
    $upSizeN = $scan[$upSizeC] * intval($upSize);
    $postSize = strtolower(ini_get('post_max_size'));
    $postSizeC = str_replace(intval($postSize) . '','',$postSize);
    $postSizeN = $scan[$postSizeC] * intval($postSize);

    $limit = $postSizeN>$upSizeN?$upSize:$postSize;

    return $limit;
    // $upSize = $scan[strtolower(ini_get('upload_max_filesize'))] ;

    // return ini_get('upload_max_filesize');

}

/**
 * 将截图粘贴到文本编辑器内的带BASE64的图片内容中的图片存为文件，返回可用于显示的内容。
 * 
 * @param  String $string 提交的编辑器内容，带bese64图片内容的文本内容
 * @param  String $path   图片保存目录，相对于网站访问跟目录的图片路径，默认pic目录下
 * @param  String $prefix 服务端路径前缀，与path变量组成可访问文件的绝对路径，默认ROOT_PATH/public/下
 * @return String         返回替换完后的内容。
 */
function save_clips_to_file($string,$path='',$prefix=''){
    if(!$string){return '';}
    $prefix = $prefix?$prefix:ROOT_PATH.DS.'public'.DS;
    $prefix = substr($prefix,-1) != DS?$prefix.DS:$prefix;
    $path = $path?$path:'pic'.DS;
    $path = trim($path,DS).DS;//拼路径时，去掉前面的路径分隔符，后面替换时，再加上。
    // preg_match_all('/<img.*?src=\"(.*?)\"/i', $string, $mat);
    preg_match_all('/\bsrc\b\s*=\s*[\'\"]?([^\'\"]*)[\'\"]?/i', $string, $mat);
    //var_dump($mat);
    foreach($mat[1] as $k=>$src){
        if(substr($src,0,4) == 'data'){
            //是data类型的图片地址
            $fileType = '.'.substr($src,strpos($src,'/')+1, strpos($src,';') - strpos($src,'/') - 1);
            $fileName = md5($src).$fileType;
            unset($fileType);
            $preDir = substr($fileName,0,2);
            //*//
            if(!file_exists($prefix.$path.$preDir)){
                $mkres = @mkdir($prefix.$path.$preDir,0777,true);
                if(!$mkres){
                    return false;
                }
            }//*/
            $fileName = $preDir.DS.$fileName;
            unset($preDir,$mkres);
            $content = base64_decode(substr($src, strpos($src,'base64,') +7 ));
            //echo $content;exit();
           if($content){
                //解压成功，则存文件，否则不处理。
                $save = @file_put_contents($prefix.$path.$fileName,$content);
                if(!$save){
                    return false;
                }
                //将文件路径转为URL可显示路径，解决WINDOWS的路径分隔符问题
                $saveFile = '/'.str_replace('\\', '/', $path.$fileName);
                $string = str_replace($src, $saveFile, $string);
            }
            unset($src,$fileName,$content,$save);
        }
    }
    return $string;
}
function getOrderTypeText($key){
    $status = [1=>'线上',2=>'线下'];
    return $status[$key] ? $status[$key] : '未知';
}
//客资是否删除获取器
function getIsStatusAttr($key){
    $status = [1=>'已删除',2=>'未删除'];
    return $status[$key] ? $status[$key] : '未删除';
}
//客资是否有效获取器
function getIsValidAttr($key){
    $valid = [1=>'有效',2=>'待定',3=>'无效',4=>'驳回',5=>'反驳回'];
    return $valid[$key] ? $valid[$key] : '待定';
}
//客资是否进店获取器
function getIsIntostore($key,$arr=''){
    $into = [1=>'未进店',2=>'进店进客',3=>'进店非进客',4=>'邀约流失',5=>'进店流失'];
    if ($arr) {
        return $into;
    }
    return $into[$key] ? $into[$key] : '未进店';
}
//客资是否成交获取器
function getIsSuccess($key,$arr=''){
    $succ = [1=>'已成交',2=>'未订单',3=>'已订金',4=>'本单作废'];
    if ($arr) {
        return $succ;
    }
    return $succ[$key] ? $succ[$key] : '未订单';
}
function getIsSuccesss($key,$arr=''){
    $succ = [1=>'已成交',2=>'未成交',3=>'已订金',4=>'本单作废'];
    if ($arr) {
        return $succ;
    }
    return $succ[$key] ? $succ[$key] : '未订单';
}
//客资是否分配获取器
function getIsFP($key){
    $fp = [1=>'已分配',2=>'未分配',3=>'待接收',4=>'分配失败'];
    return $fp[$key] ? $fp[$key] : '未分配';
}
//客资是否分配获取器
function getIsValid($key){
    $fp = [1=>'有效',2=>'待定',3=>'无效',4=>'驳回',5=>'反驳回'];
    return $fp[$key] ? $fp[$key] : '待定';
}
//客资是否不在追踪获取器
function getIsLoss($key){
    $fp = [1=>'是',2=>'否'];
    return $fp[$key] ? $fp[$key] : '否';
}
//客资是否流失获取器
function getErpLoss($key){
    $fp = [1=>'未流失',2=>'已流失'];
    return $fp[$key] ? $fp[$key] : '未流失';
}
//客资提报类型获取器
function getIntroducerType($key){
    $fp = [1=>'新客',2=>'现客',3=>'老客'];
    return $fp[$key] ? $fp[$key] : '新客';
}
//电访结果获取器
function getTelResult($key){
    $tel = [1=>'接通',2=>'未接通',3=>'空号','4'=>'不是本人'];
    return $tel[$key] ? $tel[$key] : '';
}
// 微信 状态
function getWxStatus($key){
	$wxStatus = [0=>'未标记',1=>'待通过',2=>'已加上',3=>'未加上'];
	return $wxStatus[$key] ? $wxStatus[$key] : '未标记';
}

//去除提交的table相关标签
function DeleteHtml($str)
{
//    return strip_tags($str);//用这个会把img标签去掉，图片不显示
//    $str=preg_replace("/\s+/"," ", $str);//过滤多余回车
//    $str=preg_replace("/<[]+/si","<",$str);//过滤<__("<"号后面带空格)
//    $str=preg_replace("/<\!--.*?-->/si","",$str);//注释
    $str=preg_replace("/<(\!.*?)>/si"," ",$str);//过滤DOCTYPE
    $str=preg_replace("/<(html.*?)>/si"," ",$str);//过滤html标签
    $str=preg_replace("/<(\/?html.*?)>/si"," ",$str);//过滤html标签
    $str=preg_replace("/<(head.*?)>/si"," ",$str);//过滤head标签
    $str=preg_replace("/<(\/?head.*?)>/si"," ",$str);//过滤head标签
    $str=preg_replace("/<(meta.*?)>/si"," ",$str);//过滤meta标签
    $str=preg_replace("/<(\/?meta.*?)>/si"," ",$str);//过滤meta标签
    $str=preg_replace("/<(body.*?)>/si"," ",$str);//过滤body标签
    $str=preg_replace("/<(\/?body.*?)>/si"," ",$str);//过滤body标签
    $str=preg_replace("/<(link.*?)>/si"," ",$str);//过滤link标签
    $str=preg_replace("/<(\/?link.*?)>/si"," ",$str);//过滤link标签
    $str=preg_replace("/<(form.*?)>/si"," ",$str);//过滤form标签
    $str=preg_replace("/<(\/?form.*?)>/si"," ",$str);//过滤form标签

    $str=preg_replace("/<(table.*?)>/si"," ",$str);//过滤table标签
    $str=preg_replace("/<(\/?table.*?)>/si"," ",$str);//过滤table标签
    $str=preg_replace("/<(thead.*?)>/si"," ",$str);//过滤tbody标签
    $str=preg_replace("/<(\/?thead.*?)>/si"," ",$str);//过滤tbody标签
    $str=preg_replace("/<(tbody.*?)>/si"," ",$str);//过滤tbody标签
    $str=preg_replace("/<(\/?tbody.*?)>/si"," ",$str);//过滤tbody标签
    $str=preg_replace("/<(tr.*?)>/si"," ",$str);//过滤tr标签
    $str=preg_replace("/<(\/?tr.*?)>/si"," ",$str);//过滤tr标签
    $str=preg_replace("/<(a.*?)>/si"," ",$str);//过滤a标签
    $str=preg_replace("/<(\/?a.*?)>/si"," ",$str);//过滤a标签
    $str=preg_replace("/<(br.*?)>/si"," ",$str);//过滤br标签
    $str=preg_replace("/<(\/?button.*?)>/si"," ",$str);//过滤th标签
    $str=preg_replace("/<(button.*?)>/si"," ",$str);//过滤th标签
    $str=preg_replace("/<(\/?datalist.*?)>/si"," ",$str);//过滤datalist标签
    $str=preg_replace("/<(datalist.*?)>/si"," ",$str);//过滤datalist标签
    $str=preg_replace("/<(th.*?)>/si"," ",$str);//过滤th标签
    $str=preg_replace("/<(\/?th.*?)>/si"," ",$str);//过滤th标签
    $str=preg_replace("/<(caption.*?)>/si"," ",$str);//过滤caption标签
    $str=preg_replace("/<(\/?caption.*?)>/si"," ",$str);//过滤caption标签
    $str=preg_replace("/<(iframe.*?)>/si"," ",$str);//过滤iframe标签
    $str=preg_replace("/<(\/?iframe.*?)>/si"," ",$str);//过滤iframe标签
    $str=preg_replace("/<(td.*?)>/si"," ",$str);//过滤td标签
    $str=preg_replace("/<(\/?td.*?)>/si"," ",$str);//过滤td标签
    $str=preg_replace("/<(colgroup.*?)>/si"," ",$str);//过滤colgroup标签
    $str=preg_replace("/<(\/?colgroup.*?)>/si"," ",$str);//过滤colgroup标签
    $str=preg_replace("/<(col.*?)>/si"," ",$str);//过滤col标签
    $str=preg_replace("/<(\/?col.*?)>/si"," ",$str);//过滤col标签
    $str=preg_replace("/<(ul.*?)>/si"," ",$str);//过滤ul标签
    $str=preg_replace("/<(\/?ul.*?)>/si"," ",$str);//过滤ul标签
    $str=preg_replace("/<(li.*?)>/si"," ",$str);//过滤li标签
    $str=preg_replace("/<(\/?li.*?)>/si"," ",$str);//过滤li标签
    $str=preg_replace("/<(dd.*?)>/si"," ",$str);//过滤dd标签
    $str=preg_replace("/<(\/?dd.*?)>/si"," ",$str);//过滤dd标签
    $str=preg_replace("/<(dt.*?)>/si"," ",$str);//过滤dt标签
    $str=preg_replace("/<(\/?dt.*?)>/si"," ",$str);//过滤dt标签
    $str=preg_replace("/<(dialog.*?)>/si"," ",$str);//过滤dialog标签
    $str=preg_replace("/<(\/?dialog.*?)>/si"," ",$str);//过滤dialog标签
    $str=preg_replace("/<(fieldset.*?)>/si"," ",$str);//过滤fieldset标签
    $str=preg_replace("/<(\/?fieldset.*?)>/si"," ",$str);//过滤fieldset标签
    $str=preg_replace("/<(input.*?)>/si"," ",$str);//过滤input标签
    $str=preg_replace("/<(script.*?)>(.*?)<(\/script.*?)>/si"," ",$str);//过滤script标签
    $str=preg_replace("/<(\/?script.*?)>/si"," ",$str);//过滤script标签
    $str=preg_replace("/javascript/si","Javascript",$str);//过滤script标签
    $str=preg_replace("/<(title.*?)>(.*?)<(\/title.*?)>/si"," ",$str);//过滤title标签
    $str=preg_replace("/<(\/?title.*?)>/si"," ",$str);//过滤title标签
//    $str=preg_replace("/<(applet.*?)>(.*?)<(\/applet.*?)>/si","",$str);//过滤applet标签
//    $str=preg_replace("/<(\/?applet.*?)>/si","",$str);//过滤applet标签
//    $str=preg_replace("/<(style.*?)>(.*?)<(\/style.*?)>/si","",$str);//过滤style标签
//    $str=preg_replace("/<(\/?style.*?)>/si","",$str);//过滤style标签
//    $str=preg_replace("/<(title.*?)>(.*?)<(\/title.*?)>/si","",$str);//过滤title标签
//    $str=preg_replace("/<(\/?title.*?)>/si","",$str);//过滤title标签
//    $str=preg_replace("/<(object.*?)>(.*?)<(\/object.*?)>/si","",$str);//过滤object标签
//    $str=preg_replace("/<(\/?objec.*?)>/si","",$str);//过滤object标签
//    $str=preg_replace("/<(noframes.*?)>(.*?)<(\/noframes.*?)>/si","",$str);//过滤noframes标签
//    $str=preg_replace("/<(\/?noframes.*?)>/si","",$str);//过滤noframes标签
//    $str=preg_replace("/<(i?frame.*?)>(.*?)<(\/i?frame.*?)>/si","",$str);//过滤frame标签
//    $str=preg_replace("/<(\/?i?frame.*?)>/si","",$str);//过滤frame标签
//    $str=preg_replace("/<(script.*?)>(.*?)<(\/script.*?)>/si","",$str);//过滤script标签
//    $str=preg_replace("/<(\/?script.*?)>/si","",$str);//过滤script标签
//    $str=preg_replace("/javascript/si","Javascript",$str);//过滤script标签
//    $str=preg_replace("/vbscript/si","Vbscript",$str);//过滤script标签
//    $str=preg_replace("/on([a-z]+)\s*=/si","On\\1=",$str);//过滤script标签
//    $str=preg_replace("/&#/si","&＃",$str);//过滤script标签，如javAsCript:alert
    return trim($str); //返回字符串
}

//修改客资表近三次追踪记录
function getSalesTracking($customer_id){

    $limit = db_config('tracking_num_'.session('brandclass_id'));
    $limit = $limit ? $limit : 3;
    $track=db('CSalestrackinginfo')
        ->where('customer_id',$customer_id)
        ->order('sales_day desc')
        ->limit($limit)
        ->field('sales_day, sales_remark')
        ->master()
        ->select();
    $str="";
    foreach($track as $k => $v){
        $day = date('m-d H:i', strtotime($v['sales_day']));//去掉时间
        // $day = '';
        $remark = preg_replace('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', '', $v['sales_remark']);
        $remark = strip_tags($remark);
        if(!$remark) $remark='未填写备注';
        if(strpos($remark,'驳回') !== false){//反驳回时标红
            $remark = '<font style="color: red">'.$remark.'</font>';
        }
        $str .='<font color="#ffffff" style="background-color:#8391a5;border-radius: 3px;padding: 2px 4px;width: 66px;display: inline-block;margin: 1px 0;text-align: center;">'.$day.'</font>&nbsp;'.$remark."<br/>";
        // $str .= $remark."<br/>";
    }
    db('c_customerinfo')->where('id',$customer_id)->update(array('track_record'=>$str));
}
//不跨月获取本周开始时间
function getWeekStartTimeNotFrontMonth(){
    $month = date('m');//当前月份
    $startTime = date('Y-m-d', strtotime("this week Monday", time()));//本周开始时间
    for($i=1;$i<=7;$i++){
        if ($month == date('m',strtotime($startTime))) {
            break;
        }
        $startTime = date('Y-m-d', strtotime($startTime)+$i*86400);
    }
    return $startTime;
}
//使用函数及数组来获取当月第一天及最后一天
function getthemonth($date)
{
    $firstday = date('Y-m-01', strtotime($date));
    $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
    return array($firstday,$lastday);
}
// 两个日期之间的所有日期
function getDates($start,$end){
    $dt_start = strtotime($start);
    $dt_end = strtotime($end);
    $arr = [];
    while ($dt_start<=$dt_end){
        array_push($arr,date('Y-m-d',$dt_start));
        $dt_start = strtotime('+1 day',$dt_start);
    }
    return $arr;
}

/**
 * 获取或控制后端服务状态，需要有缓存支持
 * 
 * {
 *     "last_active":"2018-01-20 10:14:26",
 *     "service_list":
 *     {
 *         "test1":
 *             {
 *                 "restart_count":102,
 *                 "last_restart":"2018-01-20 10:14:26"
 *              },
 *          "test2":
 *              {
 *                  "restart_count":11,
 *                  "last_restart":"2018-01-20 10:14:26"
 *              }
 *      }
 *  }
 * 
 * @param  string $serverName [要控制的服务名，如果只是获取，不需要传]
 * @param  [type] $status     [控制状态：start/restart]
 * @return [type]             [description]
 */
function service_status($serverName='',$status=null){
    $key = 'sxmonitor_serializelist';
    $service = cache($key);
    if(is_string($service)){
        $service = json_decode($service,true);
    }
    if(!$service){
        return false;
    }
    $serverArr = explode(',', $serverName);
    if(!is_null($status)){
        $sign = [];
        foreach ($serverArr as  $name) {
            # code...
            $serverInfo = $service['service_list'][$name];
            if(!$serverInfo){
                //无效的服务名
                continue;
            }
            switch ($status) {
                case 'restart':
                case 'stop':
                    $sign[$name] =['sign'=>$status,'status'=>0];
                    break;
                default:
                    # code...
                    break;
            }
        }
        if(!empty($sign)){
            cache('service_control_sign',json_encode($sign));
        }
        return true;
    }else{
        return $service;
    }
}
/*
 * unicode转中文
 * */
function decodeUnicode($str)
{
    return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
        create_function(
            '$matches',
            'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
        ),
        $str);
}
/*
 * 获取集团或事业部的电商、网销、全部shop_code
 * brandclass_id   0:全部（集团）  >0 当前事业部的
 * flag wx:网销  ds：电商  qd：渠道 ;null:全部
 * return : shop_code一维数组
 * */
function getShopCode($brandclass_id = 0,$flag=null){
    $brandInfo = controller('crm/Customer','lib')->companyInfo();
    if($brandclass_id){
        $arr = [];
        foreach($brandInfo[$brandclass_id]['shop'] as $key=>$val){
            if($flag == 'ds'){//电商
                if($val['is_marketing'] == 1){
                    array_push($arr,$key);
                }
            }elseif($flag == 'wx'){//网销
                if($val['is_marketing'] == 3){
                    array_push($arr,$key);
                }
            }elseif($flag == 'qd'){// 渠道
                if($val['is_marketing'] == 4){
                    array_push($arr,$key);
                }
            }else{//全部
                array_push($arr,$key);
            }
        }
    }else{
        $arr = [];
        foreach($brandInfo as $k=>$v){
            foreach($v['shop'] as $key=>$val){
                if($flag == 'ds'){//电商
                    if($val['is_marketing'] == 1){
                        array_push($arr,$key);
                    }
                }elseif($flag == 'wx'){//网销
                    if($val['is_marketing'] == 3){
                        array_push($arr,$key);
                    }
                }elseif($flag == 'qd'){//渠道
                    if($val['is_marketing'] == 4){
                        array_push($arr,$key);
                    }
                }else{//全部
                    array_push($arr,$key);
                }
            }
        }
    }
    return $arr;
}
//二维数组去重 $arr->传入数组   $key->判断的key值
function array_unset_tt($arr,$key){
    //建立一个目标数组
    $res = array();
    foreach ($arr as $value) {
        //查看有没有重复项

        if(isset($res[$value[$key]])){
            //有：销毁

            unset($value[$key]);

        }
        else{

            $res[$value[$key]] = $value;
        }
    }
    return $res;
}
/**
 * 记录分配日志
 * 
 * @param  String 
 * @param  String 
 * @param  String 
 * @return boolen  
 */
function fpLogs($fpData){
    
    db()->startTrans();
    try {
        db('l_fp_logs')->insert($fpData);
        db()->commit();
    } catch (Exception $e) {
        db()->rollback();
        \think\Log::error('日志保存错误:module:'.request()->module().';controller:'.request()->controller().';action:'.request()->action().';data:'.json_encode($fpData).';olddata:'.[].';customerid:'.$fpData['cid']);
    }
}
//计算店面目标
/*
 * param:$shop_code,$goal,$start,$end,$channel_id=0,$province_id=0,$city_id=0
 * 部门为空为店面目标
 * 岗位为空为部门部门,部门目标之和是店面目标
 * 人员为空位岗位目标,岗位目标之和是店面目标
 * 人员不为空是人员目标,之和是店面目标
 * */
function getShopGoal($param)
{
    if ($param['shop_code']) $where['shop_code'] = $param['shop_code'];
    if ($param['kpi_id']) $where['kpi_id'] = $param['kpi_id'];
    if ($param['channel_id']) $where['channel_id'] = $param['channel_id'];
    if ($param['province_id']) $where['province_id'] = $param['province_id'];
    if ($param['city_id']) $where['city_id'] = $param['city_id'];
    if($param['start']) $where['month'] = date('Y-m',strtotime($param['start']));
    $start = $param['start'] ? $param['start'] : date('Y-m-d');
    $end = $param['end'] ? $param['end'] : date('Y-m-d');
    $day_number = diffBetweenTwoDays($start,$end);
    $day_number = $day_number+1;
    $num = db('s_kpi_staffgoal')
        ->where($where)
        ->where('department_id',0)
        ->where('position_id',0)
        ->where('staff_id',0)
        ->value('avg_value');
    if(empty($num)){
        $num = db('s_kpi_staffgoal')
            ->where($where)
            ->where('department_id', '>',0)
            ->where('position_id',0)
            ->where('staff_id',0)
            ->value('avg_value');
    }
    $sum = round($num*$day_number);
    return $sum;
}
//根据店面类型获取消费类型
function get_consultation_type_id(){
    if(session('shop_type') == 1 || session('shop_type') == 3){
        return HS_TYPE;
    }elseif(session('shop_type') == 2){
        return ET_TYPE;
    }elseif(session('shop_type') == 4){
        return YS_TYPE;
    }
}
//获取同组人员id,包含自己
function getGroupStaffIds($staffId){
    $gid = db('c_staff_group_relation')->where('staff_id',$staffId)->value('group_id');
    $info = db('c_staff_group_relation')->where('group_id',$gid)->column('staff_id');
    return $info;
}
/*
 * 根据操作获取操作名,如 :customeradd,获取到录入客资
 * param action customeradd
 * returun 录入客资
 * */
function getLogsName($action){
    $arr = [
        'export' => '客资导出',
        'notrack' => '不再追踪',
        'customerRejectBack' => '反驳回',
        'fpCustomer' => '客资分配',
        'customeryjd' => '预约进店',
        'setjqgrid' => '设置列表页字段',
        'customerisexamine' => '客资审核通过',
        'customernoexamine' => '客资审核不通过',
        'customerrecove' => '客资回收站恢复',
        'editsalestracking' => '追踪',
        'addcustomermore' => '批量录入客资',
        'sales' => 'app追踪客资',
        'addfpset' => '添加分配规则',
        'delfpset' => '删除分配规则',
        'allotreceive' => '手动分配接收',
        'add' => '添加报表',
        'addmenu' => '添加菜单',
        'addgroup' => '添加编辑小组',
        'customermergesub' => '客资合并',
        'updategoal' => '添加修改目标',
        'homeshowedit' => '修改客资简析',
        'zhuanorder' => '转订单',
        'onlineOrder' => 'app网付订单',
        'addsource' => '添加订单来源',
        'editsource' => '编辑订单来源',
        'delsource' => '删除订单来源',
        'signvalid' => '标记有效',
        'addSalesTracking' => '客资追踪',
        'editcustomerinterface' => '编辑第三方接口',
        'crmprovinceset' => '设置省市县',
        'homeshowdel' => '删除客资简析',
        'authorise' => '授权',
        'homeshowadd' => '添加客资简析',
        'customermorevalid' => '批量有效',
        'customermoredd' => '批量待定',
        'addworkflow' => '添加沟通流程',
        'delcustomer' => '删除客资',
        'appDelCustomer' => '删除客资',
        'setnotonlineisfp' => '设置离线接收客资',
        'delmenu' => '删除菜单',
        'remindswitch' => '提醒快捷开关',
        'setrejectreason' => '驳回原因设定',
        'customermoreunvalid' => '批量无效',
        'signunvalid' => '标记无效',
        'customersign' => '客资标记',
        'setgoal' => '目标设置',
        'setreason' => '添加追踪失败原因',
        'addtrackingkmarker' => '添加客资标记',
        'editmark' => '修改客资标记',
        'stasetsub' => '报表设置',
        'send_message' => '发送信息',
        'editmmodal' => '修改短信模板',
        'addcustomer' => 'PC录入客资',
        'appaddcustomer' => '手机端录入客资',
        'addNewCustomer' => 'app录入客资',
        'editCustomerTel' => '修改客资手机号',
        'editCustomerWechat' => '修改客资微信号',
        'customerunvalidupdate' => '客资反驳回',
        'customervalidupdate' => '客资驳回',
        'addcallprefix' => '添加拨号前缀',
        'channelfee' => '添加修改渠道花费',
        'addqdtype' => '添加渠道花费',
        'editqdtype' => '修改渠道花费',
        'delqdtype' => '删除渠道花费',
        'addobtaincost' => '添加获取成本',
        'addqdreturn' => '添加渠道返点',
        'delqdreturn' => '删除渠道返点',
        'addmodal' => '增加短信模板',
        'erpEditCustomer' => 'erp修改客资',
        'addability' => '添加五维图',
        'addanothercost' => '添加其他花费',
        'customerAllotOne' => '客资手动分配',
        'appFP' => 'app分配追踪人',
        'customerInfo' => '客资编辑',
        'customerrevoke' => '客资撤销',
        'customerswapdel' => '客资爆破删除',
        'customerswapedit' => '客资爆破修改',
        'customerswapset' => '客资爆破设定',
        'deledittrackingkmarker' => '删除客资标记',
        'editorder' => '编辑订单',
        'editreason' => '编辑追踪失败原因',
        'editrejectreason' => '编辑驳回原因',
        'nottraking' => '不再追踪',
        'updateintroducer' => '修改介绍人信息',
        'customermove' => '客资转移',
        'customerHandover' => '离职交接',
        'delorder' => '退单',
        'erpset' => 'erp开关',
        'cityset' => '本地外地设置',
        'pswset' => '短信秘钥配置',
        'smsset' => '短信账号配置',
        'issendsmsset' => '录入(导入)时短信模板配置',
        'lrvaliddatenoticeset' => '客资过期录入是否提示配置',
        'lrvalidset' => '客资录入状态配置',
        'dfset' => '客资追踪必选项配置',
        'lrset' => '客资录入必选项配置',
        'yymodelset' => '预约短信模板配置',
        'erpzhandingdanset' => 'ERP转订单规则判定配置',
        'zhuanjieshaonumberset' => '每天转介绍次数配置',
        'mobileinputset' => '移动端介绍人是否可输入配置',
        'callcenteruserset' => '呼叫中心坐席设置',
        'callcenterchooseset' => '呼叫中心选择',
        'cusexamineset' => '客资重复审核配置',
        'shopset' => '客资提报归属店配置',
        'listjqgridset' => '列表页字段配置',
        'mobilenewcusset' => '移动端新客资录入开关配置',
        'customerchangesub' => '客资转移',
        // 进客接口里的方法
        'intostore'=>'erp标记进店',
        'allotReception'=>'erp分配接待人',
        'customerSign' => '门市标记',
        'customerEdit' => '进客编辑',
        'gift' => '领取礼品',
        'notIntostore' => '邀约未进店',
        'deleteInto' => '删除进店',
        'returnDoor' => '回门',
        'createCustomer' => '新增进客',
        'createNewOrder' => '进客转单',
        'addIntoTrackInfo' => '进客追踪',
        'setWxStatus' => '微信状态',
        'wxStatus' => '微信状态',
    ];
    return $arr[$action];
}
/*
 * 设定列表
 * */
function getSettingLogsName(){
    $arr = [
        'addfpset' => '添加分配规则',
        'delfpset' => '删除分配规则',
        'addmenu' => '添加菜单',
        'addgroup' => '添加编辑小组',
        'updategoal' => '添加修改目标',
        'homeshowedit' => '修改客资简析',
        'addsource' => '添加订单来源',
        'editsource' => '编辑订单来源',
        'delsource' => '删除订单来源',
        'editcustomerinterface' => '编辑第三方接口',
        'crmprovinceset' => '设置省市县',
        'homeshowdel' => '删除客资简析',
        'homeshowadd' => '添加客资简析',
        'addworkflow' => '添加沟通流程',
        'setnotonlineisfp' => '设置离线接收客资',
        'remindswitch' => '提醒快捷开关',
        'setrejectreason' => '驳回原因设定',
        'customersign' => '客资标记',
        'setgoal' => '目标设置',
        'setreason' => '添加追踪失败原因',
        'addtrackingkmarker' => '添加客资标记',
        'editmark' => '修改客资标记',
        'stasetsub' => '报表设置',
        'send_message' => '发送信息',
        'appSendMsg' => 'app发送信息',
        'editmmodal' => '修改短信模板',
        'addcallprefix' => '添加拨号前缀',
        'addqdtype' => '添加渠道花费',
        'editqdtype' => '修改渠道花费',
        'channelCostEdit' => 'app修改渠道花费',
        'delqdtype' => '删除渠道花费',
        'addobtaincost' => '添加获取成本',
        'addqdreturn' => '添加渠道返点',
        'delqdreturn' => '删除渠道返点',
        'addmodal' => '增加短信模板',
        'addability' => '添加五维图',
        'addanothercost' => '添加其他花费',
        'customerAllotOne' => '客资手动分配',
        'customerswapdel' => '客资爆破删除',
        'customerswapedit' => '客资爆破修改',
        'customerswapset' => '客资爆破设定',
        'authorise' => '授权',
        'deledittrackingkmarker' => '删除客资标记',
        'editorder' => '编辑订单',
        'editreason' => '编辑追踪失败原因',
        'editrejectreason' => '编辑驳回原因',
        'erpset' => 'erp开关',
        'cityset' => '本地外地设置',
        'pswset' => '短信秘钥配置',
        'smsset' => '短信账号配置',
        'issendsmsset' => '录入(导入)时短信模板配置',
        'lrvaliddatenoticeset' => '客资过期录入是否提示配置',
        'lrvalidset' => '客资录入状态配置',
        'dfset' => '客资追踪必选项配置',
        'lrset' => '客资录入必选项配置',
        'yymodelset' => '预约短信模板配置',
        'erpzhandingdanset' => 'ERP转订单规则判定配置',
        'zhuanjieshaonumberset' => '每天转介绍次数配置',
        'mobileinputset' => '移动端介绍人是否可输入配置',
        'callcenteruserset' => '呼叫中心坐席设置',
        'callcenterchooseset' => '呼叫中心选择',
        'cusexamineset' => '客资重复审核配置',
        'shopset' => '客资提报归属店配置',
        'listjqgridset' => '列表页字段配置',
        'mobilenewcusset' => '移动端新客资录入开关配置',
    ];
    return $arr;
}
//新版报表,判断有无权限
function getReportFormAuth($code){
    $info = db('s_position_menu')->where('position_code',session('main_position_code'))->field('id,menu_code')->find();
    $menu_code = explode(',',$info['menu_code']);
    if(in_array($code,$menu_code)){
        return true;
    }else{
        return false;
    }
}

/**
 * websocket回调方法，处理相应消息，后续优化
 * 
 * @param  [String] $type      类型，msg表示接收到一个消息，in表示连接，out表示断开
 * @param  [socket] $websocket [socket对像]
 * @param  [Array] $event     [事件内容]
 * @return [void]            
 */
function websocket_event($type,$websocket,$event){
    if($type == 'msg'){
        $websocket->log($event['k'].'收到消息:'.$event['msg']);
        $show = '';
        //$event['sign'],$event['msg']
        switch ($event['msg']){
            case 'hello':
                $show='hello';
            break;
            default:
                $show='hello';
        }
        $websocket->write($event['sign'],$show);
    }
    
}


//根据员工id获取本组成员
function getGroupStaffByStaffId($staffId){
    $gid = db('c_staff_group_relation')->where('staff_id',$staffId)->value('group_id');
    $info = db('c_staff_group_relation')->where('group_id',$gid)->select();
    return $info;
}

//时间段内按周分组
function getWeekByTime($start,$end)
{
    $end_date = diffBetweenTwoDays($start, $end);//计算天数
    $weekinfo = [];
    for ($i = 0; $i < $end_date; $i++) {   //循环天数
        $week = date('W', strtotime($start) + $i * 86400);
        $weekinfo[$week][$i] = date('Y-m-d', strtotime($start) + $i * 86400);
    }
    return $weekinfo;
}
/*
 * 根据shop_code 和 work_type 查询店下的人
 * param action customeradd
 * returun 录入客资
 * */
function getStaffsByWorkType($param){
    $url="5aafa4ac48058";
    $data['shop_code'] = $param['shop_code'];
    $data['get_leave'] = 2;
    $res=sx_call($url,$data);
    if($res['code']==200){
        $temp=$res['data'];
    }else{
        $temp = [];
    }
    $staffs = [];

    foreach ($temp as $key => $value) {
        $work_type_str = trim( trim($value['work_types']).','.trim($value['work_type']), ',' );
        $work_type = explode(',', $work_type_str);
        $is_in = in_array($param['work_type'], $work_type);
        if ($is_in) {
            array_push($staffs, $value);
        }
    }
    return $staffs;
}
//列表页字段配置
function listJQgrid(){
    $return = [];
    $return['customer_channel']='渠道名称';
    $return['sign_name']='客资标记';
    $return['is_valid']='是否有效';
    $return['op_signinfo']='追踪标记';
    $return['customer_number']='编号';
    if(session('shop_type') ==2){
        $return['baby_name'] = '宝宝姓名';
        $return['baby_sex'] = '宝宝性别';
        $return['baby_birthday'] = '宝宝生日';
        $return['ready_baby_day'] = '预产期';
        $return['customer_name']='妈妈姓名';
    }else{
        $return['customer_name']='姓名';
        $return['customer_sex']='性别';
    }
    $return['customer_tel']='手机号';
    $return['customer_wechat']='微信';
    $return['customer_weibo']='微博';
    $return['customer_qq']='QQ';
    if(session('shop_type') !=2){
        $return['mate_name']='配偶姓名';
        $return['mate_tel']='配偶手机';
        $return['mate_wechat']='配偶微信';
    }else{
        $return['mate_name']='爸爸姓名';
        $return['mate_tel']='爸爸手机';
        $return['mate_wechat']='爸爸微信';
    }
    $return['add_friend_time']   = '加好友时间';
    $return['city']='城市';
    $return['customer_address']='详细地址';
    $return['customer_key']='关键字';
    $return['channel_plan_number']='推广编号';
    if(session('shop_type') !=2){
        $return['marry_day']='婚期';
    }
    $return['budget']='预算';
    $return['consulation_shop']='意向店面';
    $return['reception_name']='接待人员';
    $return['next_time']='再约时间';
    $return['yjd_action_day']='预约操作时间';
    $return['yjd_day']='预约进店时间';
    $return['customer_remark']='客资备注';
    $return['step_name']='追踪阶段';
    $return['track_record']='追踪记录';
    $return['customer_label']='客资标签';
    $return['is_intostore']='是否进店';
    $return['is_urgent']='是否加急';
    $return['syjd_day']='进店时间';
    $return['is_success']='是否成交';
    $return['order_number']='订单号';
    $return['order_start_time']='订单开始时间';
    $return['order_day']='成交日期';
    $return['order_type']='订单类型';
    $return['totalpay_money']='订单金额';
    $return['order_fact']='一销实收';
    $return['order_amount']='一销套系';
    $return['fact_money']='实收金额';
    $return['loss_cause']='不再追踪原因';
    $return['erp_loss_reason']='流失原因';
    $return['customer_type']='客户类型';
    $return['dj_day']='登记日期';
    $return['create_time']='获取日期';
    $return['is_fp']='是否分配';
    $return['is_loss']='不再追踪';
    $return['erp_loss']='是否流失';
    $return['dj_staff']='登记人';
    $return['sales_staff']='追踪人';
    $return['sk_staff']='筛客人';
    $return['fp_staff']='分配人';
    $return['introduce_staff_name']='转介绍人';
    $return['introducer_name']='老顾客姓名';
    $return['introducer_tel']='老顾客电话';
    $return['introducer_ordernum']='老顾客单号';
    $return['introducer_type']='老顾客类型';
    $return['tel_visit_num']='电访量';
    $return['last_trackday']='最后追踪时间';
    $return['consultation_type']='消费类型';
    $return['customer_cource']='客户来源';
    $return['customer_intention']='客户意向';
    $return['access_model']='获取方式';
    $return['customer_orderaddress']='接单点';
    $return['customer_area']='客户分区';
    $return['bonus']='奖金';
    $return['brandclass']='品牌';
    $return['shop_name']='归属店';
    $return['add_shop_name']='提报店';
    $return['dj_department_name']='登记部门';
    $return['sales_department_name']='追踪部门';
    $return['dj_group_name']='登记小组';
    $return['sales_group_name']='追踪小组';
    $list = [];
    $i = 0;
    foreach($return as $k=>$v){
        $list[$i]['id'] = $k;
        $list[$i]['name'] = $v;
        $i++;
    }
    return $list;
}
//列表页字段对照表
function listGetColumName(){
    $return = [];
    $return['customer_channel']='渠道名称';
    $return['sign_name']='客资标记';
    $return['is_valid']='是否有效';
    $return['op_signinfo']='追踪标记';
    $return['customer_number']='编号';
    if(session('shop_type') ==2){
        $return['baby_name'] = '宝宝姓名';
        $return['baby_sex'] = '宝宝性别';
        $return['baby_birthday'] = '宝宝生日';
        $return['ready_baby_day'] = '预产期';
        $return['customer_name']='妈妈姓名';
    }else{
        $return['customer_name']='姓名';
        $return['customer_sex']='性别';
    }
    $return['customer_tel']='手机号';
    $return['customer_wechat']='微信';
    $return['customer_weibo']='微博';
    $return['customer_qq']='QQ';
    if(session('shop_type') !=2){
        $return['mate_name']='配偶姓名';
        $return['mate_tel']='配偶手机';
        $return['mate_tel']='配偶微信';
    }else{
        $return['mate_name']='爸爸姓名';
        $return['mate_tel']='爸爸手机';
        $return['mate_tel']='爸爸微信';
    }
    $return['add_friend_time']   = '加好友时间';
    $return['city']='城市';
    $return['customer_address']='详细地址';
    $return['customer_key']='关键字';
    $return['channel_plan_number']='推广编号';
    if(session('shop_type') ==2){
        $return['marry_day']='婚期';
    }
    $return['budget']='预算';
    $return['consulation_shop']='意向店面';
    $return['reception_name']='接待人员';
    $return['next_time']='再约时间';
    $return['yjd_action_day']='预约操作时间';
    $return['yjd_day']='预约进店时间';
    $return['customer_remark']='客资备注';
    $return['track_record']='追踪记录';
    $return['customer_label']='客资标签';
    $return['is_intostore']='是否进店';
    $return['is_urgent']='是否加急';
    $return['syjd_day']='进店时间';
    $return['is_success']='是否成交';
    $return['order_number']='订单号';
    $return['order_start_time']='订单开始时间';
    $return['order_day']='成交日期';
    $return['order_type']='订单类型';
    $return['totalpay_money']='订单金额';
    $return['order_fact']='一销实收';
    $return['order_amount']='一销套系';
    $return['fact_money']='实收金额';
    $return['loss_cause']='不再追踪原因';
    $return['erp_loss_reason']='流失原因';
    $return['customer_type']='客户类型';
    $return['dj_day']='登记日期';
    $return['create_time']='获取日期';
    $return['is_fp']='是否分配';
    $return['is_loss']='不再追踪';
    $return['erp_loss']='是否流失';
    $return['dj_staff']='登记人';
    $return['sales_staff']='追踪人';
    $return['sk_staff']='筛客人';
    $return['fp_staff']='分配人';
    $return['introduce_staff_name']='转介绍人';
    $return['introducer_name']='老顾客姓名';
    $return['introducer_tel']='老顾客电话';
    $return['introducer_ordernum']='老顾客单号';
    $return['introducer_type']='老顾客类型';
    $return['tel_visit_num']='电访量';
    $return['last_trackday']='最后追踪时间';
    $return['consultation_type']='消费类型';
    $return['customer_cource']='客户来源';
    $return['customer_intention']='客户意向';
    $return['access_model']='获取方式';
    $return['customer_orderaddress']='接单点';
    $return['customer_area']='客户分区';
    $return['bonus']='奖金';
    $return['brandclass']='品牌';
    $return['shop_name']='归属店';
    $return['add_shop_name']='提报店';
    $return['dj_department_name']='登记部门';
    $return['sales_department_name']='追踪部门';
    $return['dj_group_name']='登记小组';
    $return['sales_group_name']='追踪小组';
    return $return;
}
//根据员工id获取小组信息
function getGroupInfo($staffId){
    $info = db('c_staff_group_relation')->where('staff_id',$staffId)->find();
    if(empty($info)){
        return [];
    }
    $group = db('c_staff_group')->where('id',$info['group_id'])->find();
    return $group;
}
//判断是否是json
function is_json($str){
    $arr =  json_decode($str,true);
    if(is_array($arr) && !empty($arr)){
        return true;
    }else{
        return false;
    }
}

/*
 * 获取归属店
 * 
 * staff_id            员工id
 * brandclass_id       事业部id
 * shop_type           店面类型（儿童2；婚纱）
 * shop_code           当前店面code
 * belong_shop_code    归属店面code
 * belong_shop_name    归属店面名
 * 
 */
function getBelongShop($params){
    if ($data['staff_id']) {
        $return = cache('guishu_shop_'.$data['staff_id']);
    }
    if ($return) {
        return $return;
    }

    if (!(int)$params['staff_id']) {
        return array('code'=>100,'msg'=>'员工id不能为空');
    }
    if (!$params['shop_code']) {
        return array('code'=>101,'msg'=>'shop_code不能为空');
    }
    // 查看员工在某个事业部下的可操作店
    $mc = new \app\common\lib\mcInterface();
    $cz_data['staff_id'] = (int)$params['staff_id'];
    $cz_data['brandclass_id'] = $params['brandclass_id'];
    $cz_data['shop_type'] = (int)$params['shop_type'];
    $temp1 = $mc->getWorkShop($cz_data);



    // 查集团下所有的集团店
    $jt_url = '5a005e0038270';
    $jt_data['is_group'] = 1;


    // $jt_shop = sx_call($jt_url, $jt_data);
    // if ($jt_shop['code'] == 200) {
    //     $temp2 = $jt_shop['data'];
    // }else{
    //     $temp2 = [];
    // }

    $jt_shop = $mc->getShops($jt_data);
    if($jt_shop){
        $temp2 = $jt_shop;
    }else{
        $temp2 = [];
    }

    // mc配置归属店面不存在
    if (!$params['belong_shop_code']) {
        $gs_shop = db_config('dj_shops_'.$params['shop_code']);
        if (!$gs_shop) {
            $gs_shop = [];
        }
    }else{
        $gs_shop[0]['shop_code'] = $params['belong_shop_code'];
        $gs_shop[0]['shop_name'] = $params['belong_shop_name'];
    }
    
    $temp_shop = array_merge($temp2,$gs_shop,$temp1);    
    $shop_info = [];
    foreach ($temp_shop as $key => $value) {
        $shop_info[$value['shop_code']]['shop_code'] = $value['shop_code'];
        $shop_info[$value['shop_code']]['shop_name'] = $value['shop_name'];
    }
    if ($data['staff_id']) {
        cache('guishu_shop_'.$data['staff_id'], $shop_info);
    }
    return $shop_info;
}
//获取事业部下可操作店
function getShops($data){
    $mc = new \app\common\lib\mcInterface();
    return $mc->getWorkShop($data);
    //return [];
    /*
    if (!$return) {
        $url = '5b9cac8aa21c0';
        $info = sx_call($url,$data);
        if($info['code'] == 200){
            if ($data['staff_id']) {
                cache('caozuo_shop_'.$data['staff_id']);
            }
            $return = $info['data'];
        }else{
            $return = [];
        }
    }
    return $return;
    */
}
function getChannelJson($shop_code,$brandclass_id){
    $all = controller('crm/Customer','lib')->getChannel($shop_code,$brandclass_id);
    $result = [];
    foreach ($all as $value) {
        $find = array_search($value['channel_class_id'], array_column($result, 'value'));
        if($find === false){
            $result[] = [
                'title'=>$value['channel_class_name'],
                'value'=>$value['channel_class_id'],
                'data'=>[]
            ];
            $find = count($result) - 1;
        }
        $infoFind = array_search($value['channel_info_id'], array_column($result[$find]['data'], 'value'));
        if($infoFind === false){
            $result[$find]['data'][] = [
                'title'=>$value['channel_info_name'],
                'value'=>$value['channel_info_id'],
                'data'=>[]
            ];
            $infoFind = count($result[$find]['data']) - 1;
        }
        $result[$find]['data'][$infoFind]['data'][] = [
            'title'=>$value['channel_name'],
            'value'=>$value['id'],
            'data'  =>[]
        ];
    }
    return $result;
}
//获取多选下拉框的三级渠道 20201111--待删除20201222-sdm
function getChannelJson_del($shop_code,$brandclass_id){
    $mc = new \app\common\lib\mcInterface();
    $info1['data'] = $mc->getChannelClass();
    if ($info1['data']) {
        $info = $info1['data'];
        $info2 = $mc->getChannelInfo(['shop_code'=>$shop_code]);
        $info3 = controller('crm/Customer','lib')->getChannel($shop_code,$brandclass_id);
        $channel = [];
        foreach($info as $k=>$v){
            $arr = [];
            $arr['title'] = $v['channelclass'];
            $arr['value'] = $v['id'];
            $arr['data'] = [];
            foreach ($info2 as $kk=>$vv) {
                if($v['channelclass'] == $vv['channelclass']){
                    $arr1 = [];
                    $arr1['title'] = $vv['channel_name'];
                    $arr1['value'] = $vv['id'];
                    $arr1['data'] = [];
                    foreach($info3 as $kkk=>$vvv){
                        if($vv['id'] == $vvv['channel_info_id']){
                            $arr2 = [];
                            $arr2['title'] = $vvv['channel_name'];
                            $arr2['value'] = $vvv['id'];
                            $arr2['data'] = [];
                            $arr1['data'][] = $arr2;
                        }
                    }
                    $arr['data'][] = $arr1;
                }
            }
            $channel[] = $arr;
        }
        return $channel;
    }else{
        return [];
    }
}
//检测坐席登陆
function check_call(){
    //呼叫中心信息
    $call_id =  db_config('call_id');
    if($call_id){
        $call = db('SCallCenter')->where('id',$call_id)->find();
        session('ip',$call['ip']);
        session('port',$call['port']);
        //检测用户坐席信息
        $call_user = db('s_call_man')->where('staff_id',session('staff_id'))->find();
        session('user',$call_user['user']);
        session('pwd',$call_user['pwd']);
    }
}
/**
 * 根据shop_code 获取店下部门
 * 
 * @param  shop_code 
 *
 * @return array  
 */
function getDepartments($param){
    $url = '5a0aef152b750';
    $data['shop_code'] = $param['shop_code'];
    $res = sx_call($url, $data);
    if ($res['code'] == 200) {
        $return = $res['data'];
    }else{
        $return = [];
    }
    return $return;
}
/**
 * 根据department_id 获取部门下 小组信息
 * 
 * @param  deparment_id 
 *
 * @return array  
 */
function getGroups($param){
    $where = [
        'department_id' => $param['department_id'],
    ];
    $groups = db('c_staff_group')->where($where)->select();
    return $groups;
}
/**
 * 根据shop_code 和 work_type 获取店下的员工 包含工作类型
 * 
 * @param  shop_code 
 * @param  work_type 
 *
 * @return array  
 */
function getShopStaffs($param){
    /*$url = '5b75341456d18';
    $param['shop_code'] = $param['shop_code'];
    $param['work_type'] = $param['work_type'] ? $param['work_type'] : 0;

    $temp_data = sx_call($url, $param);
    if ($temp_data['code'] == 200) {
        $shopStaffs = $temp_data['data'];
    }else{
        $shopStaffs = [];
    }
    return $shopStaffs;*/

    //2021-06-21 优化
    $param['shop_code'] = $param['shop_code'];
    $param['work_type'] = $param['work_type'] ? $param['work_type'] : 0;
    $param['all'] = $param['all'] ? $param['all'] : 1;
    
    $mc = new \app\common\lib\mcInterface();
    $shopStaffs = $mc->getStaffsByWorkType($param);
    if ($shopStaffs===false) {
        $shopStaffs = [];
    }
    return $shopStaffs;
}

if(!function_exists('get_mathine_code')){
    function get_mathine_code(){
        //获取授权证信息，为空时，未授权用户。
        $code =  '';
        return $code;
    }
}
if(!function_exists('beast_encode_file')){
    function beast_encode_file($file1,$file2,$type,$entype){
        return true;
    }
}
function getProductId(){
    $productFile = ROOT_PATH.DS.'runtime'.DS.'Suxuan.php';
    if(file_exists($productFile)){
        $info = include($productFile);
        return $info['product_id'];
    }
    return false;
}
//追踪标记颜色数组
function salesSignColor(){
    $color = cache('sales_sign_color_'.session('shop_code'));
    if(empty($color)){
        $color = db('s_markset')->where('shop_code',session('shop_code'))->order('id desc')->column('mark_color','mark_name');
        cache('sales_sign_color_'.session('shop_code'),$color);
    }
    return $color;
}
//客资标记颜色数组
function signColor(){
    $color = cache('sign_color_'.session('shop_code'));
    if(empty($color)){
        $color = db('s_tracksign')->where('shop_code',session('shop_code'))->where('is_delete',1)->order('id desc')->column('sign_color','tracksign');
        cache('sign_color_'.session('shop_code'),$color);
    }
    return $color;
}
//查询客资是否有有效订单
function checkValidOrder($id,$order_sn){
    $res = db('c_customer_order')->where('customer_id',$id)->where('order_sn', '<>', $order_sn)->where('order_valid',2)->value('id');
    return $res;
}
/*
 * 参数为数字，查询所有事业部，组成已事业部id为键的数组
 * 参数为字符串，查询所有事业部，组成已事业部名为键的数组
 * */
function getAllbrand($data = 10000){
    if(is_numeric($data)){
        $arr = cache('brandclass_int');
    }else{
        $arr = cache('brandclass_string');
    }
    if(empty($info)){
        $url = '5a3bbb5d0988d';
        $info = sx_call($url,[]);
        if($info['code'] == 200){
            $detail = $info['data'];
            $arr = [];
            if(is_numeric($data)){
                foreach($detail as $k=>$v){
                    $arr[$v['id']] = $v;
                }
                cache('brandclass_int',$arr);
            }else{
                foreach($detail as $k=>$v){
                    $arr[$v['brandclass']] = $v;
                }
                cache('brandclass_string',$arr);
            }
        }else{
            $arr = [];
        }
    }
    return $arr;
}
/*
 * 查询所有店，组成以shop_code为键的数组
 * */
function getShopInfo(){
    $info = cache('theAllShops');
    if(empty($info)){
        $url="5a005e0038270";
        $res=sx_call($url,[]);
        if($res['code']==200){
            $info=$res['data'];
            cache('theAllShops',$info);
        }
    }
    $arr = [];
    foreach($info as $k=>$v){
        $arr[$v['shop_code']] = $v;
    }

    return $arr;
}
/*
    * 判断表是否存在
    */
function isTableExist($table){
    $sql = "show tables;";
    $res = db()->master()->query($sql);
    foreach($res as $value){
        if(array_search($table, $value)){
            return true;
        }
    }
    return false;
}
/**
 * 判断表中的某个字段是否存在
 *
 * @param  table       表名
 * @param  column      字段名
 *
 * @return boolen
 *
 * @author lilong<lilong@suxuantech.cn>
 */
function isColumnExist($param){
    $table = $param['table'];
    $column= $param['column'];

    $cSql = "SHOW FULL COLUMNS FROM $table;";
    $columns = db()->master()->query($cSql);

    foreach ($columns as $key => $value) {
        // var_dump($value['Field']);
        // var_dump($column);
        if ($value['Field']==$column) {
            return true;
        }
    }
    return false;
}
/*
 * 获取所以提醒，提醒名为键
 * */
function getRemind($bid){
    $info = cache('remind_'.$bid);
    if(empty($info)){
        $info = db('SReminditemset')->where('brandclass_id',$bid)->column('*','id');
        foreach($info as $k=>$v){
            if($v['send_method']){
                $info[$k]['send_method'] = explode(',',$v['send_method']);
            }
            if($v['send_receive']){
                $info[$k]['send_receive'] = explode(',',$v['send_receive']);
            }
        }
        cache('remind_'.$bid,$info);
    }
    return $info;
}
/*
 * 获取所以提醒，事业部id为键
 * */
function getAllRemind(){
    $temp = cache('remind');
    if(empty($info)){
        $info = db('SReminditemset')->select();
        foreach($info as $k=>$v){
            if($v['send_method']){
                $v['send_method'] = explode(',',$v['send_method']);
            }
            if($v['send_receive']){
                $v['send_receive'] = explode(',',$v['send_receive']);
            }
            $temp[$v['brandclass_id']][$v['id']] = $v;

        }
        cache('remind',$temp);
    }
    return $temp;
}
/**
 * @cc 获取函数的注释
 *
 * @param $module Home
 * @param $controller Auth
 * @param $action index
 *
 * @return string 注释
 *
 */
function get_cc_desc($module,$controller,$action){
    $desc='app\crm\controller\Customer';
    $func  = new \ReflectionMethod(new $desc(),$action);
    $tmp   = $func->getDocComment();
    $flag  = preg_match_all('/@cc(.*?)\n/',$tmp,$tmp);
    $tmp   = trim($tmp[1][0]);
    $tmp   = $tmp !='' ? $tmp:'';
    return $tmp;
}
//app验证token登录
function checkAppLogin($staff_id,$token){
    $mc = new \app\common\lib\mcInterface();
    $key = 'app_token_'.$token;
    $cacheToken = cache('?'.$key);
    if($token && $cacheToken){
        $info = cache($key);
    }
    /*$returnData = array('code' => 100,'msg'=>'测试', 'token' => $token,'staff_id'=>$staff_id,'info'=>$info);
    return json($returnData);*/
    if($info['staff_id'] == $staff_id){
        return $info;
    }else{
        $info = $mc->checkToken($staff_id,$token);
        if($info === false){
            return false;
        }else{
            cache($key,$info,300);
            return $info;
        }
    }
}
function changeMyPosition($positionCode){
    if(!$positionCode){
        return false;
    }
    $mc = new \app\common\lib\mcInterface();
    $info = $mc->getposition(['position_code'=>$positionCode]);

    if($info === false){
        return false;
    }
    session('accessModel',null);
    session('source',null);
    session('intention',null);
    session('areaSet',null);
    session('capacity',null);
    session('channel',null);
    cache('shopAllStaffs_'.session('belong_shop_code'),null);
    $b_id = session('brandclass_id');

    $position = $info[0];
    $shopInfo = $position['shop_code'] ? controller('crm/Customer','lib')->get_shop(['shop_code'=>$position['shop_code']]) : '';
    $cacheInfo = cache('staffInfo_'.session('staff_id'));
    // if(!empty($shopInfo)){
    $shopInfo = $shopInfo[0];

    session('shop_code',$shopInfo['shop_code'] ? $shopInfo['shop_code'] : null);
    session('shop_name',$shopInfo['shop_name'] ? $shopInfo['shop_name'] : null);
    session('belong_shop_code',$shopInfo['belong_shop_code'] ? $shopInfo['belong_shop_code'] : null);
    session('belong_shop_name',$shopInfo['belong_shop_name'] ? $shopInfo['belong_shop_name'] : null);
    session('shop_type',$shopInfo['shop_type'] ? $shopInfo['shop_type'] : null);
    session('is_sk',$shopInfo['is_sk'] ? $shopInfo['is_sk'] : null);
    session('is_marketing',$shopInfo['is_marketing'] ? $shopInfo['is_marketing'] : null);//是否是营销店
    // session('open_id', $shopInfo['open_id']);
    session('is_group', $shopInfo['is_group'] ? $shopInfo['is_group'] : null);//是不是集团店:1:是,2:否
    $cacheInfo['shop_type'] = $shopInfo['shop_type'] ? $shopInfo['shop_type'] : null;
    $cacheInfo['shop_code'] = $shopInfo['shop_code'] ? $shopInfo['shop_code'] : null;
    $cacheInfo['shop_name'] = $shopInfo['shop_name'] ? $shopInfo['shop_name'] : null;
    $cacheInfo['belong_shop_code'] = $shopInfo['belong_shop_code'] ? $shopInfo['belong_shop_code'] : null;
    $cacheInfo['belong_shop_name'] = $shopInfo['belong_shop_name'] ? $shopInfo['belong_shop_name'] : null;
    $cacheInfo['is_marketing'] = $shopInfo['is_marketing'] ? $shopInfo['is_marketing'] : null;
    $cacheInfo['is_sk'] = $shopInfo['is_sk'] ? $shopInfo['is_sk'] : null;
    $cacheInfo['is_group'] = $shopInfo['is_group'] ? $shopInfo['is_group'] : null;
    // }

    $positions = explode(',',session('position_code'));
    if(!in_array($position['position_code'], (array)$positions)){
        $positions[] = $position['position_code'];
    }
    session('position_code',implode(',',(array)$positions));
    session('main_position_code',$position['position_code']);
    session('main_position_name',$position['position_name']);
    session('department_id',$position['department_id']);
    session('department_name',$position['department_name']);
    session('brandclass_id',$position['brandclass_id']);
    session('brandclass',$position['brandclass']);
    session('main_work_type',$position['work_type']);
    session('is_belong',$position['grade_type']);
    //替换cache信息
    $cacheInfo = cache('staffInfo_'.session('staff_id'));
    $cacheInfo['brandclass_id'] = $position['brandclass_id'];
    $cacheInfo['brandclass'] = $position['brandclass'];
    $cacheInfo['department_name'] = $position['department_name'];
    $cacheInfo['department_id'] = $position['department_id'];
    $cacheInfo['main_position_name'] = $position['position_name'];
    $cacheInfo['main_position_code'] = $position['position_code'];
    $cacheInfo['position_code'] = $position['position_code'];
    $cacheInfo['main_work_type'] = $position['work_type'];
    $cacheInfo['active'] = time();
    cache('staffInfo_'.session('staff_id'),$cacheInfo);

    //替换为要切换的事业部的客资有效期
    if($b_id != $position['brandclass_id']){
        $url = '5a4216fe6b2b5';
        $info = sx_call($url,['id'=>$position['brandclass_id']]);
        if($info['code'] == 200){
            $brand = $info['data'][0];
            session('valid_date', (int)$brand['valid_date']);
        }
    }

    //权限
    // session('crm_auth', getAuth($type='auth'));
    // $menu = include(APP_PATH.'menu.php');
    // $menuCustomize = include(APP_PATH.'menu_customize.php');
    // $auth = getAuthMenu($menu,'auth',$menuCustomize);
    
    // $menu = getAuthMenu($menu,'menu',$menuCustomize);
    // session('crm_menu', $menu);
    // $newAuth = controller('crm/Setting','lib')->arrayDuoZhuanEr($auth['list']);
    // session('crm_auth', $newAuth);

    return true;
}
/*
 * 客资列表各种状态解析，只返回一种状态status
 * 参数：二维数组
 * */
function getCustomerStatus($info){
    foreach($info as $k=>$v) {
        if ($v['is_loss'] == '是') {
            $info[$k]['status'] = '不再追踪';
        } elseif ($v['is_success'] == '已订单') {
            $info[$k]['status'] = '已订单';
        } elseif ($v['is_success'] == '已订金') {
            $info[$k]['status'] = '已订金';
        } elseif ($v['is_intostore'] == '进店进客') {
            $info[$k]['status'] = '进店进客';
        } elseif ($v['is_intostore'] == '进店非进客') {
            $info[$k]['status'] = '进店非进客';
        } elseif ($v['is_intostore'] == '进店流失') {
            $info[$k]['status'] = '进店流失';
        } elseif ($v['yjd_day']) {
            $info[$k]['status'] = '预约进店';
        } elseif (!$v['last_trackday'] && $v['sales_staff']) {
            $info[$k]['status'] = '待追踪';
        } elseif ($v['is_fp'] == '未分配') {
            $info[$k]['status'] = '未分配';
        } elseif ($v['is_fp'] == '待接收') {
            $info[$k]['status'] = '待接收';
        } elseif ($v['is_fp'] == '分配失败') {
            $info[$k]['status'] = '分配失败';
        } elseif ($v['is_fp'] == 1) {
            if ($v['is_valid'] == '有效') {
                $info[$k]['status'] = '有效';
            } elseif ($v['is_valid'] == '无效') {
                $info[$k]['status'] = '无效';
            } elseif ($v['is_valid'] == '待定') {
                $info[$k]['status'] = '待定';
            } elseif ($v['is_valid'] == '驳回') {
                $info[$k]['status'] = '驳回';
            } elseif ($v['is_valid'] == '反驳回') {
                $info[$k]['status'] = '反驳回';
            } else {
                $info[$k]['status'] = '待定';
            }
        }
        $info[$k]['customer_channel'] = strip_tags($v['customer_channel']);
        $info[$k]['consultation_type'] = strip_tags($v['consultation_type']);
    }
    return $info;
}
// 手机地址  正则  0:中国大陆；1：中国香港；2：中国澳门；3：中国台湾
function grtTelAddressRegular(){
    $tel_address = array(
        '0'=>['name'=>'中国大陆','zc'=>'^1[3|4|5|6|7|8|9][0-9]{9}$'],
        '1'=>['name'=>'中国香港','zc'=>'^852[0-9]{8}$',],
        '2'=>['name'=>'中国澳门','zc'=>'^853[0-9]{8}$',],
        '3'=>['name'=>'中国台湾','zc'=>'^0[0-9]{10}$',],
    ); 
    return $tel_address;
    /*
     * 订单或进店有效标准判断
     *    fact   实收
     *    amount 套系
     *    $brandclass_id 事业部id
     *    标识  order:订单有效标准；into:进店有效标准
     * return boolean
     * ***/
}
function getPercent($fact,$amount,$brandclass_id,$flag='order'){
    if($fact == 0){
        return false;
    }else{
        if($flag == 'order'){
            $brandclassInfo= controller('index/Customer','lib')->getBrandClassInfo($brandclass_id);
            if($brandclassInfo['order_rule'] == 2){ //占比
                if($fact*100>=$amount*$brandclassInfo['proportion']){
                    return true;
                }else{
                    return false;
                }
            }elseif($brandclassInfo['order_rule'] == 1){ //实收
                if($fact>=$brandclassInfo['proportion']){
                    return true;
                }else{
                    return false;
                }
            }else{ //默认
                if($fact*100>=$amount*30){
                    return true;
                }else{
                    return false;
                }
            }
        }elseif($flag == 'into'){
            $onlinecash = db_config('onlinecash_'.$brandclass_id);
            if($onlinecash['onlinecash_id'] == 2){ //占比
                if($fact*100>=$amount*$onlinecash['onlinecash']){
                    return true;
                }else{
                    return false;
                }
            }elseif($onlinecash['onlinecash_id'] == 1){//实收
                if($fact>=$onlinecash['onlinecash']){
                    return true;
                }else{
                    return false;
                }
            }
        }
    }
}
/**
 * INI 配置快捷函数
 * 
 * @param  [type] $key   键
 * @param  [type] $value 值
 * @param  String $path  配置文件路径（绝对路径）
 * @return [type]        [description]
 */
function ini($key,$value = null , $path = null){
    $configPath = $path?$path:(APP_PATH.'config.ini');//定议ini文件配置
    list($first,$secend) = explode('.', $key);
    if($secend){
        if(is_null($value)){
            //读取
            $all = iniConfig($configPath,true);
            return $all[$first][$secend];
        }else{
            //写值
            iniConfig($configPath,[$first=>[$secend=>$value]]);
        }
    }else{
        if(is_null($value)){
            //读取
            $all = iniConfig($configPath,true);
            return $all[$first];
        }else{
            //写值
            iniConfig($configPath,[$first=>$value]);
        }
    }
}

/**
 * ini类型的配置文件操作函数
 * 
 * @param  [type]  $iniFile  配置文件名
 * @param  boolean $sections 读取方式：true加载成二维数组，如果是写函数，则直接传要更新的数组
 * @return [type]            [description]
 */
function iniConfig($iniFile,$sections=false){
     
    if(is_bool($sections)){
        if(!file_exists($iniFile)){
            return false;
        }
        $content = parse_ini_file($iniFile,$sections);
        return $content;
    }else{
        $content = parse_ini_file($iniFile,true);
    }
    if(is_array($sections)){
        $sections = $content?array_merge($content,$sections):$sections;
        $configStr = '';
        foreach ($sections as $key => $value) {
            if(is_array($value)){
                $configStr .= '['.$key.']'."\r\n";
                $substr = '';
                foreach ($value as $k=>$v) {
                    $substr .=$k.'='.$v."\r\n";
                }
                $configStr .= $substr;
            }else{
                $configStr .=$key.'='.$value."\r\n";
            }
        }
        $res = @file_put_contents($iniFile, $configStr);
        return $res;
    }
    return false;
}
/**
 * 在 erp收款，erp删除订单 erp作废订单时，调用此方法 
 * 
 * @param  cid            客资ID
 * @param  order_sn       订单编号
 * 
 * @return boolean
 * @author lilong<lilong@suxuantech.cn>
 */
function checkCustomerOrder($params){
    $insertPool['cid'] = $params['cid'];
    $insertPool['msg'] = $params['order_sn'];
    $insertPool['fp_time_out'] = time()+10;
    $insertPool['count'] = 0;
    $insertPool['create_time'] = date('Y-m-d H:i:s');
    $insertPool['pool_type'] = 11;
    $res = db('c_fp_pool')->insert($insertPool);
    return $res;
}
/**
 * 处理客资订单  当订单 发生变化时 处理客资
 * 
 * @param  cid            客资ID
 * 
 * @return boolean
 * @author lilong<lilong@suxuantech.cn>
 */
function dealCustomerOrder($params){
    $cid = (int)$params['cid'];
    if ($cid) {
        $where['customer_id'] = $cid;
        $where['refund'] = 1;
        $where['is_delete'] = 2;
        $oInfo = db('c_customer_order')->where($where)->field('order_sn,order_fact,order_amount,two_pin_fact,two_pin_amount,target_time,valid_time')->order('target_time desc')->find();
        $successOrder = db('c_customer_order')->where($where)->where('valid_time','not null')->count();
        $cInfo = db('c_customerinfo')->where('id',$cid)->field('is_success,order_number,order_start_time,order_day,fact_money,totalpay_money')->find();
        if ($cInfo) {
            // 如果没有订单，说明订单被删除
            if (!$oInfo) {
                // 单号
                if ($cInfo['order_number']) {
                    $cData['order_number'] = NULL;
                }
                // 订单状态
                if ($cInfo['is_success']!=2) {
                    $cData['is_success'] = 2;
                }
                // 开单时间
                if ($cInfo['order_start_time']) {
                    $cData['order_start_time'] = NULL;
                }
                // 成交时间
                if ($cInfo['order_day']) {
                    $cData['order_day'] = NULL;
                }
                // 实收
                if ($cInfo['fact_money']) {
                    $cData['fact_money'] = NULL;
                }
                // 营收
                if ($cInfo['totalpay_money']) {
                    $cData['totalpay_money'] = NULL;
                }
                if (!empty($cData)) {
                    db('c_customerinfo')->where('id',$cid)->update($cData);
                }
            }else{
                // 单号
                if ($oInfo['order_sn']!=$cInfo['order_number']) {
                    $cData['order_number'] = $oInfo['order_sn'];
                }
                // 开单时间
                if ( date('Ymd',strtotime($oInfo['target_time']))!=date('Ymd',strtotime($cInfo['order_start_time'])) ) {
                    $cData['order_start_time'] = date('Y-m-d H:i:s',strtotime($oInfo['target_time']));
                }
                // 成交时间
                if ( $oInfo['valid_time'] && date('Ymd',strtotime($oInfo['valid_time']))!=date('Ymd',strtotime($cInfo['order_day'])) ) {
                    $cData['order_day'] = date('Y-m-d H:i:s',strtotime($oInfo['valid_time']));
                }
                // 成交状态
                if ($successOrder>0) {
                    $cData['is_success'] = 1;
                }else{
                    $cData['is_success'] = 3;
                }
                // 营收
                $cData['totalpay_money'] = $oInfo['order_fact']+$oInfo['two_pin_fact'];
                // 实收
                $cData['fact_money'] = $oInfo['order_amount']+$oInfo['two_pin_amount'];
                if (!empty($cData)) {
                    db('c_customerinfo')->where('id',$cid)->update($cData);
                }
            }
        }
    }
    return true;
}
// 0.00和-100返回0
function dataFormate($params,$num = 2){
    $num = round($params,$num);
    if ($num == '0.00') {
        return '0';
    }else if ($num == '-1.00') {
        return '0';
    }else if ($num == '-100.00') {
        return '0';
    }
    else{
        return $num;
    }
}
//获取消费类型
function getSumptionType($param){
    $mc = new \app\common\lib\mcInterface();
    $info = $mc->getSumptionType($param);
    return $info;
}

/**
 * 记录日志
 * 
 * @param  str          要记录的字符串
 * @param  filename     要记录在哪个文件里
 * @param  pathe        相对路径 即 runtime下的相对路径
 * 
 * @return 
 * @author lilong<lilong@suxuantech.cn>
 */
function textlog($str,$filename='log.txt',$path){
    if(config('app_debug')){
        if (strtoupper(substr(php_uname(),0,3)) == 'WIN') {
            $str = iconv("UTF-8","GB2312//IGNORE",$str);
        }
        if ($path) {
            $realPath = ROOT_PATH.DS.'runtime'.DS.$path.DS;
        }else{
            $realPath = ROOT_PATH.DS.'runtime'.DS;
        }
        if(!file_exists($realPath)){
            mkdir($realPath,0777,true);
        }
        $realPath .= date('Ymd').$filename;
        file_put_contents($realPath,date('Y-m-d H:i:s')."\t".$str."\r\n",FILE_APPEND);
    }
}

//手机号格式验证
function check_phone($phone,$patrn){
    $res = preg_match("/".$patrn."/", $phone);
    if($res){
        return true;
    } else {
        return false;
    }
}
/**
 * 手机号处理
 * 
 * @param  String $mobile 手机号
 * @param  String $seed  种子，如果传了，则反处理也要传相同的种子。
 * @return String         处理后字符串
 */
function encodePhone($mobile,$seed=''){
    if(!$mobile) return '';
    $a = str_split($mobile);
    $z1 = 0;
    foreach ($a as $v) {
        $z1 += intval($v);
    }
    $s = $seed?md5(md5($z1).$seed):md5($z1);
    $m = array_unique(str_split($s));
    $p = [
        '0'=>'D',
        '1'=>'C',
        '2'=>'B',
        '3'=>'A',
        '4'=>'Q',
        '5'=>'P',
        '6'=>'N',
        '7'=>'M',
        '8'=>'X',
        '9'=>'W',
        'a'=>'Y',
        'b'=>'S',
        'c'=>'T',
        'd'=>'H',
        'e'=>'J',
        'f'=>'K',
    ];
    if(count($m) < 10){
        while ( count($m) < 10) {
            foreach ($p as $key => $value) {
                if(!in_array($key, $m)){
                    $m[] = (string)$key;
                    break;
                }
            }
        }
    }
    $m =  explode(',', implode(',', $m));
    $t = [];
    foreach ($a as $v) {
        $t[] = $p[$m[$v]];
    }
    foreach (str_split($z1) as $vv) {
        $t[] = $p[$vv];
    }
    return 'E'.strlen($mobile).implode('', $t);
}
/**
 * 手机号反处理
 * 
 * @param  String $str 手机号处理后字符串，由encodePhone处理的结果
 * @param  String $seed 种子字符串
 * @return String      手机号 ,如果处理失败，则返回false,如果种子不对，可能会返一个错误的结果
 * 如果传入未处理的手机号，则原样返回。兼容处理和未处理并行使用。
 * 
 */
function decodePhone($str,$seed=''){
    // $str = 'E11AQDHHHHHHHHCD';
    if(!$str){
        return '';
    }
    if(substr($str, 0,1) != 'E'){
        return $str;
    }
    $len = intval(substr($str, 1));
    if($len <= 0 ){
        return false;
    }
    $str = str_replace($len, '', substr($str, 1));
    $t = str_split($str);
    $p = [
        'D'=>'0',
        'C'=>'1',
        'B'=>'2',
        'A'=>'3',
        'Q'=>'4',
        'P'=>'5',
        'N'=>'6',
        'M'=>'7',
        'X'=>'8',
        'W'=>'9',
        'Y'=>'a',
        'S'=>'b',
        'T'=>'c',
        'H'=>'d',
        'J'=>'e',
        'K'=>'f',
    ];
    foreach ($t as $v) {
        $m[] = $p[$v];
    }
    $y = count($m) - $len;
    if($y<=0) return false;
    $z2 = array_slice($m, -$y);
    $z1 = intval(implode('', $z2));
    if(!$z1) return false;
    $s = $seed?md5(md5($z1).$seed):md5($z1);
    $n = array_unique(str_split($s));
    $n =  explode(',', implode(',', $n));
    if(count($n) < 10){
        while ( count($n) < 10) {
            foreach ($p as $key => $value) {
                if(!in_array($key, $n)){
                    $n[] = (string)$key;
                    break;
                }
            }
        }
    }
    $b = array_slice($m, 0,$len);
    $a = [];
    $c = 0;
    foreach ($b as $bb) {
        $a[] = $k = array_search($bb, $n);
        $c += $k;
    }
    $r = implode('', $a);
    if($c != $z1 || $len != strlen($r)){
        $r = false;
    }
    return  $r;
}
// 获取店下所有的渠道
function getChannels($param){
    $shop_code = $param['shop_code'] ? $param['shop_code'] : session('shop_code');
    $allChannel = cache('all_channel_'.$shop_code);
    // var_dump($allChannel);die;
    if (!$allChannel) {
        $allChannel = db('s_channel')->where('FIND_IN_SET("'.session('shop_code').'",share_shops)')->column();
        cache('all_channel_'.$shop_code,json_encode($allChannel));
    }
    return $allChannel;
}
// 获取小组下的员工 
function getGroupStaffs($param){
    $group_id = (int)$param['group_id'];

    $groupStaffs = db('c_staff_group')->alias('g')
        ->join('c_staff_group_relation r', 'g.id=r.group_id', 'left')
        ->where('g.id', $group_id)
        ->field('r.staff_id,r.staff_name')
        ->select();
    return $groupStaffs;
}

//判断字符串是否全是中文
function getChinese($value='')
{
    if(!eregi("[^\x80-\xff]","$value")){
        return true;
    }else{
        return false;
    }
}

//手机浏览器访问
function isMobile() {
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset($_SERVER['HTTP_VIA'])) {
    // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高。其中'MicroMessenger'是电脑微信
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile','MicroMessenger');
    // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}

//客资 客资列表 筛选 日期类型
function getCustomerDataType(){
    $DataType = [
        ['id'=>'dj_day','name'=>'登记日期'],
        ['id'=>'fp_day','name'=>'分配日期'],
        ['id'=>'yjd_day','name'=>'预约进店时间'],
        ['id'=>'syjd_day','name'=>'实际进店时间'],
    ];
    return $DataType;
}

//客资 客资列表 筛选 客资类型
function getCustomerKZType(){
    $DataType = [
        ['id'=>1,'name'=>'有效客资'],
        ['id'=>2,'name'=>'待定客资'],
        ['id'=>3,'name'=>'无效客资'],
        ['id'=>4,'name'=>'驳回客资'],
        ['id'=>5,'name'=>'反驳回'],
    ];
    return $DataType;
}

/**
 * 定制功能通过此函数判断，
 * 使用时直接使用此函数，并传入定制企业标识，如判断是否非常六加一的：
 * if(customize('xmfc6j1'))
 * {
 *     是定制六加1的逻辑。。。
 * }
 * @param  [type] $name [定制企业的标识]
 *                      xmfc6j1     厦门非常六加一
 *                      whxaf       武汉小阿福
 *                      cdtsyx      成都天使印像
 *                      babypastel  郑州babypastel
 *                      sqmhts      商丘梦幻天使
 *                      kmjsj       昆明晶视觉
 *                      whcy        武汉 楚韵
 *                      gyztf       贵阳醉唐风
 *                      hkbj        花开 北京
 *                      
 * @return [type]       true/false 是的，返回true不是的为false
 */
function customize($name,$productId=''){
    // return true;
    $mcproductId = $productId?$productId:session('mc_productid');
    if(!$mcproductId){
        $mc = new \app\common\lib\mcInterface();
        $data = $mc->cacheData('5ef1a04c80175');
        if($data){
            $mcproductId = $data['product_id'];
        }
    }
    switch ($mcproductId) {
        case '5903679116':
            if($name == 'xmfc6j1') return true;
            break;
        case '9657743504':
            if($name == 'whxaf') return true;
            break;
        case '9128787616':
            if($name == 'cdtsyx') return true;
            break;
        case '7921308917':
        case '7957528370':
            if($name == 'babypastel') return true;
            break;
        case '6315968332':
            if($name == 'sqmhts') return true;
            break;
        case '7663054564':
            if($name == 'bjggt') return true;
            break;
        case '3196407416':// 61mc 演示环境mc
            if($name == 'whxaf') return true;
            if($name == 'cdtsyx') return true;
            if($name == 'babypastel') return true;
            if($name == 'sqmhts') return true;
            break;
        case '6453079281':// 西安费思
            if($name == 'xianfeisi') return true;
            break;
        case '2227195365':// 西安绝对人气
            if($name == 'jueduirenqi') return true;
            break;
        case '5376269404'://哈尔宾摩西
            if($name == 'hebmx') return true;
            break;
        case '1365250534'://昆明晶视觉
            if($name == 'kmjsj') return true;
            break;
        // case '3201712315'://合肥匠古test
        case '4583370241'://合肥匠古
            if($name == 'hfjianggu') return true;
            break;
        // 武汉 楚韵
        case '1255219261':
            if ($name == 'whcy') return true;
            break; 
        case '1207591870'://贵阳醉唐风
            if($name == 'gyztf') return true;
            break;
        case '3390380586'://花开（北京）
            if($name == 'hkbj') return true;
            break;
        //以下为开发或测试环境，的MC的授权码，方便测试和开发时使用
        //加入了这里的授权码相当于是定制功能
        case '0428082539':
        case '7702959738':
        case '0470659185':// lilong
            return true;
            break;
        default:
            return false;
            break;
    }
    return false;
}

//测试速度
function testTime($file,$line)
{
    global $abc;
    $abc[] = [
            'page'=>$file,
            'time'=>microtime(true),
            'line'=>$line
        ];
}
