<?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) {
    $res = http_request($url, $method, $postfields, $headers, $debug);
    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('crm_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)){
        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('crm_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/CrmActionLog');
    $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;
    }
    $res  = httpRequest($addr, 'POST', $data, $header);

    // var_dump($res);
    // exit;
    return json_decode($res,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('crm_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_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'  => '-1',
        '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('crm_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('crm_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(){
    $info = cache('staffInfo_'.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();
        }

        $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;
}

// 获取起始时间 $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")));
            $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")));
            $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='crm_c_customerinfo', $key){
    $return = array(
        // 用户详情表
        'crm_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'         => '宝宝出生地',
            'baby_address'         => '宝宝出生医院',
            'marry_day'            => '结婚日期',
            'record_img'           => '聊天记录图片',
            'track_record'         => '最近三条追踪记录',
            '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'                => '邮箱',
            'baby_time'            => '获取次数',
            'record_day'           => '填写日期',
            'customer_names'       => '妈妈姓名',
            'customer_tels'        => '妈妈手机',
            'customer_wechats'     => '妈妈微信',
            'mate_names'           => '爸爸姓名',
            'mate_tels'            => '爸爸电话',
            'mate_wechats'         => '爸爸微信',
            'hospital_photo_time'  => '医拍时间',
            'hospital_photo_cameraman'=>'医拍摄影师',
            'hospital_photo_assistant'=>'医拍助理',
            'b_name'    =>'品牌',

        )
    );
    return $return[$table][$key];
}

//导入模板表头对应的表字段  儿童
function import_header_child(){
    $title=array(
        'baby_name'    =>'宝宝姓名',
        'baby_sex'     =>'宝宝性别',
        'baby_weight'     =>'宝宝体重',
        'baby_stature'     =>'宝宝身高',
        'baby_time'=>'获取次数',
        'baby_birthday'=>'宝宝生日(格式20180101)',
        'ready_baby_day'=>'预产期',
        'record_day'=>'填写日期',
        'customer_name'=>'妈妈姓名',
        'customer_tel'=>'妈妈手机号',
        'customer_wechat'=>'微信',
        'customer_qq'=>'QQ',
        'customer_weibo'=>'微博',
        'mate_name' =>'爸爸姓名',
        'mate_tel' =>'爸爸手机号',
        'province'=>'省',
        'city'=>'市',
        'county'=>'区',
        'customer_address'=>'详细地址',
        'customer_type'=>'客户类型',
        'introducer_name'=>'介绍人',
        'recommend_staff'=>'推广人',
        'sign_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'=>'关键字',
        'baby_address'=>'出生医院',
        'hospital_photo_cameraman'=>'医拍摄影师',
        'hospital_photo_assistant'=>'医拍助理',
        'hospital_photo_time'=>'医拍时间',
        'dj_day'=>'录入时间',
        'package_name'=>'意向套系',
    );
    return $title;
}
//导入模板表头对应的表字段 婚纱
function import_header(){
    $title=array(
        'customer_name'=>'客户姓名',
        'customer_sex'=>'性别',
        'customer_tel'=>'手机号',
        'customer_wechat'=>'微信',
        'customer_qq'=>'QQ',
        'customer_weibo'=>'微博',
        'baby_address'=>'出生医院',
        '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'=>'关键字',
        // 'dj_staff'     => '登记人',
        // 'dj_staff_id'  => '录入员工id',
        // 'dj_day'       => '登记日期',
        // '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','微博','省','市','区','详细地址','客户类型','介绍人','渠道名称','获取方式','消费类型','客户来源','推广编号','广告落地页','客户分区','客户意向','意向店面','接单点','追踪人','客资备注','转介绍人','关键字');
    return $title;
}
//下载导入excel模板 儿童
function template_header_child(){
    // $title=array('客户姓名','性别','手机号','微信','QQ','微博','省','市','区','详细地址','客户类型','客户渠道','获取方式','消费类型','客户来源','客户分区','客户意向','意向店面','接单点','追踪人','登记人','录入员工id','登记日期','分配人','分配人id','分配日期','接入日期','录入员工部门code','录入员工部门名','事业部名', '事业部ID','是否有效','标记有效时间','预约进店时间','是否进店','实际进店日期','开始追踪日期');
    $repeat_way = db_config('customer_repeat_method');
    $repeat_way = $repeat_way?$repeat_way:config('repeat_way');
    if ($repeat_way=='xaf') {
        $title=array('宝宝姓名','宝宝性别','宝宝体重','宝宝身高','获取次数','宝宝生日(格式20180101)','预产期','填写日期','录入时间','妈妈姓名','妈妈手机号','微信','QQ','微博','出生医院','医拍摄影师','医拍助理','医拍时间','爸爸姓名','爸爸手机号','省','市','区','详细地址','客户类型','介绍人','推广人','客资标记','渠道名称','获取方式','消费类型','客户来源','推广编号','广告落地页','客户分区','客户意向','意向店面','接单点','追踪人','客资备注','转介绍人','关键字','意向套系');
    }else{
        $title=array('宝宝姓名','宝宝性别','宝宝体重','宝宝身高','宝宝生日(格式20180101)','预产期','填写日期','录入时间','妈妈姓名','妈妈手机号','微信','QQ','微博','出生医院','医拍摄影师','医拍助理','医拍时间','爸爸姓名','爸爸手机号','省','市','区','详细地址','客户类型','介绍人','推广人','客资标记','渠道名称','获取方式','消费类型','客户来源','推广编号','广告落地页','客户分区','客户意向','意向店面','接单点','追踪人','客资备注','转介绍人','关键字','意向套系');
    }
    
    return $title;
}

//导出excel模板表头
function export_header(){
    $title=array('客资ID','渠道名称', '客资标记','是否有效','追踪标记','编号', '姓名', '性别', '手机号', '微信', '微博', 'QQ','城市','详细地址','关键字','婚期','预算','意向店面', '预约进店时间', '预约进店时间','推广编号','广告落地页','追踪记录','是否进店', '进店时间', '是否成交','订单开始时间','订单时间','订单类型','订单金额','实际收款','一销实收','一销套系','流失原因','客户类型','登记日期','获取日期','是否分配', '是否流失', '登记人','追踪人','筛客人','转介绍人','老顾客姓名','老顾客电话','老顾客单号','老顾客类型','电访量','最后追踪时间', '消费类型', '客户来源', '客户意向','获取方式', '接单点', '客户分区','品牌','归属店','提报店','单号','客资备注','加好友时间','登记小组','追踪小组',
    );
    return $title;
}
//导出excel模板表头
function export_header_child(){
    $title=array('客资ID','编号','是否有效','渠道名称','客资标记','追踪标记','宝宝姓名','宝宝性别','宝宝生日','预产期','妈妈姓名','妈妈手机','妈妈微信','妈妈微博','妈妈QQ','省','城市','详细地址','出生医院','医拍摄影师','医拍助理','医拍时间','推广人','关键字','婚期','预算','消费类型','客户来源','客户意向','获取方式','接单点','客户分区','渠道编号','广告落地页','意向店面','成交状态','订单编号','开单时间','成交时间','订单类型','一销应收','一销已付','二销应收','二销已付','流失原因','客户类型','转介绍人','老顾客姓名','老顾客电话','老顾客单号','电访量','追踪记录','最后追踪时间','客资备注','加好友时间','登记日期','登记人','登记小组','登记部门','提报店','是否分配','追踪人','追踪小组','追踪部门','归属店','品牌','渠道类型','二级渠道','爸爸姓名','爸爸手机');
    return $title;
}
//导出excel模板表头
function export_tohome_child(){
    $title=array('上门分组','摄影师','导师','预约日期','时间点','话务人员','上门备注','客资备注','所在省','所在市','所在地区','客资地址','妈妈姓名','妈妈手机','爸爸姓名','爸爸手机','出生医院','宝宝姓名','宝宝性别','宝宝生日','上门类型','消费类型','渠道名称','二级渠道','客资标记','上门状态','上门反馈','预约人员','套系名称','订单单号','订单应收','订单实收','服务店面','核销码','客资ID');
    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('crm_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('crm_c_sysconfig')->where('ckey',$key)->count();
            if($count>0){
                $res = db('crm_c_sysconfig')->where('ckey',$key)->delete();
            }
            cache($cacheKey,null);
            return true;
        }catch(\Exception $e){
            return false;
        }
    }else{
        try{
            db()->startTrans();
            $count = db('crm_c_sysconfig')->where('ckey',$key)->count();
            if($count>0){
                $res = db('crm_c_sysconfig')->where('ckey',$key)->update(array('cvalue'=>$value));
            }else{
                $res = db('crm_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){
    $mc = new \app\common\lib\mcInterface();
    $staff = $mc->getOneStaff(['staff_id'=>$staff_id]);
    return $staff;
}

// 根据时间获取对应的表明，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;
}

/*
 * 将数据递归处理
 *  @param array $list
 *  @param string $fid
 */
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;
}
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 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 getAuth($type){
    //$position_code=trim(session('main_position_code').','.session('position_code'),',');
    //$menuAll=db('crm_s_position_menu')->where('position_code','in',$position_code)->select();
    // 是否使用客户管理模块 1 不使用 其他值 使用
    $config = db_config('use_client_module');
    if ($config==1) {
        $where['id'] = ['<>',1000];
    }
    if($type=='menu'){
        // $menuList=cache('CRM_menuAll');
        if(!$menuList){
            $where['status'] = 1;
            $menuList=db('crm_s_menu')->where($where)->order('sort asc')->select();
            //$menuList=array_column($menus,'menu_code');
            cache('CRM_menuAll',$menuList);
        }
    }elseif($type=='auth'){
        // $menuList=cache('CRM_menuAllS');
        if(!$menuList){
            $where['status'] = ['<>',99];
            $menuList=db('crm_s_menu')->where($where)->select();
            //$menuList=array_column($menus,'menu_code');
            cache('CRM_menuAllS',$menuList);
        }
    }
    // echo db()->getLastSql();die;
    $work_type=explode(',',trim(session('main_work_type')));
    $work_type=explode(',',trim(session('main_work_type').','.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('crm_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;
    }
}

/**
 * 获取所有目录
 * 
 * @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('crm_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');
        }
    }
}
//功能菜单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;
}

// function check_right($code){
//     //判断是否有权限
//     $auth=getAuth($type='auth');
//     if(in_array($code,array_column($auth,'menu_code'))){
//         return true;
//     }else{
//         return false;
//     }
// }
///判断是PC还是微信登录
function is_weixin(){
    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('crm_action_log','db_logs')->insert($logData);
        db()->commit();
    } catch (\Exception $e) {
        db()->rollback();
        // echo $e->getMessage();
        \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
     * 
     **/
    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);
    $b = json_decode($a['response'], true);
    // print_r($b);
    // exit;
    if($b['Code'] != 200){
        api_log($content);
    }

    $resData = $a['response'];
    $len = strlen($resData);
    if ( ($len/1024) > 1024 ) {
        $resData = '';
    }

    $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,'crm_request_logs');
    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('crm_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('crm_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编码(不支持url)
 * @date 2017-02-20 19:41:22
 *
 * @param $img_file 传入本地图片地址
 *
 * @return string
 */
function imgToBase64($img_file) {

    $img_base64 = '';
    if (file_exists($img_file)) {
        $app_img_file = $img_file; // 图片路径
        $img_info = getimagesize($app_img_file); // 取得图片的大小，类型等

        //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
        $fp = fopen($app_img_file, "r"); // 图片是否可读权限

        if ($fp) {
            $filesize = filesize($app_img_file);
            $content = fread($fp, $filesize);
            $file_content = chunk_split(base64_encode($content)); // base64编码
            switch ($img_info[2]) {           //判读图片类型
                case 1: $img_type = "gif";
                    break;
                case 2: $img_type = "jpg";
                    break;
                case 3: $img_type = "png";
                    break;
            }

            $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码

        }
        fclose($fp);
    }

    return $img_base64; //返回图片的base64
}

/**
 * 将截图粘贴到文本编辑器内的带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){
    $into = [1=>'未进店',2=>'进店进客',3=>'进店非进客',4=>'邀约流失',5=>'进店流失'];
    return $into[$key] ? $into[$key] : '未进店';
}
//客资是否成交获取器
function getIsSuccess($key){
    $succ = [1=>'已成交',2=>'未成交',3=>'已订单',4=>'本单作废'];
    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 getIntroducerType($key){
    $fp = [1=>'新客',2=>'现客',3=>'老客'];
    return $fp[$key] ? $fp[$key] : '新客';
}
//电访结果获取器
function getTelResult($key){
    $tel = [1=>'接通',2=>'未接通',3=>'空号','4'=>'不是本人'];
    return $tel[$key] ? $tel[$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){

    $track=db('crm_c_salestrackinginfo')
        ->where('customer_id',$customer_id)
        ->order('sales_day desc')
        ->limit(3)
        ->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('crm_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('crm_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('crm_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('crm_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('crm_c_staff_group_relation')->where('staff_id',$staffId)->value('group_id');
//     $info = db('crm_c_staff_group_relation')->where('group_id',$gid)->column('staff_id');
//     return $info;
// }
/*
 * 根据操作获取操作名,如 :customeradd,获取到录入客资
 * param action customeradd
 * returun 录入客资
 * */
function getLogsName($action){
    $arr = [
        'export' => '客资导出',
        'fpCustomer' => '客资分配',
        'customeryjd' => '预约进店',
        'setjqgrid' => '设置列表页字段',
        'customerisexamine' => '客资审核通过',
        'customernoexamine' => '客资审核不通过',
        'customerrecove' => '客资回收站恢复',
        'editsalestracking' => '追踪',
        'addfpset' => '添加分配规则',
        'delfpset' => '删除分配规则',
        'allotreceive' => '手动分配接收',
        'add' => '添加报表',
        'addmenu' => '添加菜单',
        'addgroup' => '添加编辑小组',
        'customermergesub' => '客资合并',
        'updategoal' => '添加修改目标',
        'homeshowedit' => '修改客资简析',
        'zhuanorder' => '转订单',
        'addsource' => '添加订单来源',
        'editsource' => '编辑订单来源',
        'delsource' => '删除订单来源',
        'signvalid' => '标记有效',
        'addSalesTracking' => '客资追踪',
        'editcustomerinterface' => '编辑第三方接口',
        'crmprovinceset' => '设置省市县',
        'homeshowdel' => '删除客资简析',
        'authorise' => '授权',
        'addSMType' => '添加/修改上门类型',
        'delsmpaicheng' => '删除上门排程',
        'delSMType' => '删除上门类型',
        'homeshowadd' => '添加客资简析',
        'customermorevalid' => '批量有效',
        'customermoredd' => '批量待定',
        'addworkflow' => '添加沟通流程',
        'delcustomer' => '删除客资',
        'setnotonlineisfp' => '设置离线接收客资',
        'delmenu' => '删除菜单',
        'remindswitch' => '提醒快捷开关',
        'setrejectreason' => '驳回原因设定',
        'customermoreunvalid' => '批量无效',
        'signunvalid' => '标记无效',
        'customersign' => '客资标记',
        'setgoal' => '目标设置',
        'setreason' => '添加追踪失败原因',
        'addtrackingkmarker' => '添加客资标记',
        'editmark' => '修改客资标记',
        'stasetsub' => '报表设置',
        'send_message' => '发送信息',
        'editmmodal' => '修改短信模板',
        'addcustomer' => 'PC录入客资',
        'addCustomer' => 'PC录入客资',
        'appaddcustomer' => '手机端录入客资',
        'editCustomerTel' => '修改客资手机号',
        'editCustomerWechat' => '修改客资微信号',
        'customerunvalidupdate' => '客资反驳回',
        'customervalidupdate' => '客资驳回',
        'addcallprefix' => '添加拨号前缀',
        'channelfee' => '添加修改渠道花费',
        'addqdtype' => '添加渠道花费',
        'editqdtype' => '修改渠道花费',
        'delqdtype' => '删除渠道花费',
        'addobtaincost' => '添加获取成本',
        'addqdreturn' => '添加渠道返点',
        'delqdreturn' => '删除渠道返点',
        'addmodal' => '增加短信模板',
        'erpEditCustomer' => 'erp修改客资',
        'addability' => '添加五维图',
        'addanothercost' => '添加其他花费',
        'customerAllotOne' => '客资手动分配',
        'customerInfo' => '客资编辑',
        'customerrevoke' => '客资撤销',
        'customerswapdel' => '客资爆破删除',
        'customerswapedit' => '客资爆破修改',
        'customerswapset' => '客资爆破设定',
        'deledittrackingkmarker' => '删除客资标记',
        'editorder' => '编辑订单',
        'editreason' => '编辑追踪失败原因',
        'editrejectreason' => '编辑驳回原因',
        'nottraking' => '不再追踪',
        'updateintroducer' => '修改介绍人信息',
        'customermove' => '客资转移',
        'customerHandover' => '离职交接',
        'erpset' => 'erp开关',
        'cityset' => '本地外地设置',
        'pswset' => '短信秘钥配置',
        'smsset' => '短信账号配置',
        'issendsmsset' => '录入(导入)时短信模板配置',
        'lrvaliddatenoticeset' => '客资过期录入是否提示配置',
        'lrvalidset' => '客资录入状态配置',
        'dfset' => '客资追踪必选项配置',
        'lrset' => '客资录入必选项配置',
        'yymodelset' => '预约短信模板配置',
        'erpzhandingdanset' => 'ERP转订单规则判定配置',
        'zhuanjieshaonumberset' => '每天转介绍次数配置',
        'mobileinputset' => '移动端介绍人是否可输入配置',
        'callcenteruserset' => '呼叫中心坐席设置',
        'callcenterchooseset' => '呼叫中心选择',
        'cusexamineset' => '客资重复审核配置',
        'shopset' => '客资提报归属店配置',
        'listjqgridset' => '列表页字段配置',
        'mobilenewcusset' => '移动端新客资录入开关配置',
        'customerchangesub' => '客资转移',
        'setSmGroupAction' => '上门拍分组',
        'smpaichengsub'=>'安排上门拍',
        'fpCamera'=>'分配上门人员',
        'markHXHome'=>'取消上门',
        'markHX'=>'上门核销',
        'changeVisitInfo'=>'上门修改信息',
        'zuofeiunvalid'=>'自动作废无效订单客资还原无效状态',
        'RunExcelImport'=>'批量导入',
        'relieveorder'=>'解除订单',
        'customerRemoveActionx'=>'客资流转',
        
    ];
    $arr = array_change_key_case($arr, CASE_LOWER);
    return $arr[strtolower($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' => '发送信息',
        'editmmodal' => '修改短信模板',
        'addcallprefix' => '添加拨号前缀',
        'addqdtype' => '添加渠道花费',
        'editqdtype' => '修改渠道花费',
        '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('crm_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 = '';

        if (is_json($event['msg'])) {
            $mType = 'json';
        }else{
            $mType = 'text';            
        }
        if ($mType=="text") {
            switch ($event['msg']){
                case 'hello':
                    $show='back0';
                break;
                default:
                    $show='back1';
            }
        }else if ($mType == 'json') {
            $kf = json_decode($event['msg'],true);
            try {
                $showJson = cache('kfNewMsg_'.$kf['kf_id']);
                
            } catch (\Exception $e) {
                $show = $e->getMessage();
            }
            
            // try {
            //     $show = controller('weixin/weixin')->getNewWxMessage($kf);
            // } catch (\Exception $e) {
            //     $show = $e->getMessage();
            // }
        }
        
        $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";
    if($param['staff_id']){
        $data['staff_id'] = $param['staff_id'];
    }
    if($param['shop_code']){
        $data['shop_code'] = $param['shop_code'];
    }
    $data['get_leave'] = 2;
    // $res=sx_call($url,$data);

    $mc = new \app\common\lib\mcInterface();
    $temp = $mc->getAllStaffListByShopcode($data);
    if ($temp === false) {
        $temp = [];
    }
    // 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['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['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['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_id']='登记部门';
    $return['sales_department_id']='追踪部门';
    $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['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['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['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_id']='登记部门';
    $return['sales_department_id']='追踪部门';
    $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;
    }
}
/**
 * 根据指定店和客资提报类型，返回这个店的客资应该的归属店有哪些
 * 手动分配时，不用传客资类型
 * 如果这个返回为空，则调用的地方就取操作者当前店，或是提报店
 * @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;
}
/*
 * 获取归属店
 * 此方法逐步停用，改用getBelongShopList 方法，如再遇见，则整理后删除
 * staff_id            员工id
 * brandclass_id       事业部id
 * shop_type           店面类型（儿童2；婚纱）
 * shop_code           当前店面code
 * belong_shop_code    归属店面code
 * belong_shop_name    归属店面名
 * 
 */
function getBelongShop($params){
    if (!(int)$params['staff_id']) {
        return array('code'=>100,'msg'=>'员工id不能为空');
    }
    // if (!$params['shop_code']) {
    //     return array('code'=>101,'msg'=>'shop_code不能为空');
    // }
    // 查看员工在某个事业部下的可操作店
    // $cz_url = '5b9cac8aa21c0';
    // $cz_data['staff_id'] = (int)$params['staff_id'];
    // $cz_data['brandclass_id'] = $params['brandclass_id'];
    // $cz_data['shop_type'] = (int)$params['shop_type'];
    // $cz_shop = sx_call($cz_url, $cz_data);
    $mc = new \app\common\lib\mcInterface();
    $cz_shop = $mc->getWorkShop($params);
    if ($cz_shop===false) {
        $temp1 = [];
    }else{
        $temp1 = $cz_shop;
    }
    // if ($cz_shop['code'] == 200) {
    //     $temp1 = $cz_shop['data'];
    // }else{
    //     $temp1 = [];
    // }

    // 查集团下所有的集团店
    /* 
    $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 = [];
    }
    */
    $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'];
    }

    return $shop_info;
}
//获取事业部下可操作店
function getShops($data){
    // $url = '5b9cac8aa21c0';
    // $info = sx_call($url,$data);
    // if($info['code'] == 200){
    //     return $info['data'];
    // }else{
    //     return [];
    // }
    $mc = new \app\common\lib\mcInterface();
    $info = $mc->getWorkShop($data);
    if ($info===false) {
        return [];
    }else{
        return $info;
    }
}

function getChannelJson($shop_code){
    $all = controller('crm/Customer','lib')->getChannel($shop_code);
    $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;
}
//获取多选下拉框的三级渠道--即将删除--sdm 20201222
function getChannelJson_del($shop_code){
    // $url = '5a2757c0a9810';
    // $info1 = sx_call($url,['shop_code'=>$shop_code]);
    $mc = new \app\common\lib\mcInterface();
    $info1 = $mc->getChannelClass(['shop_code'=>$shop_code]);
    if($info1 !== false){
        // $info = $info1['data'];
        // $url = '59fd5e729e5a8';
        // $info2 = sx_call($url,['shop_code'=>$shop_code]);
        // $info2 = $info2['data'];
        $info2 = $mc->getChannelInfo(['shop_code'=>$shop_code]);
        $info3 = controller('crm/Customer','lib')->getChannel($shop_code);

        $channel = [];
        foreach($info1 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 getChannelJson1($shop_code){
    // $url = '5a2757c0a9810';
    // $info1 = sx_call($url,['shop_code'=>$shop_code]);
    $mc = new \app\common\lib\mcInterface();
    $info1 = $mc->getChannelClass(['shop_code'=>$shop_code]);
    if($info1 !== false){
        $channel = [];
        foreach($info1 as $k=>$v){
            $arr = [];
            $arr['title'] = $v['channelclass'];
            $arr['value'] = $v['id'];
            $arr['data'] = [];

            $channel[] = $arr;
        }
        return $channel;
    }else{
        return [];
    }
}

function getChannelJson12($shop_code){
    // $url = '5a2757c0a9810';
    // $info1 = sx_call($url,['shop_code'=>$shop_code]);
    $mc = new \app\common\lib\mcInterface();
    $info1 = $mc->getChannelClass(['shop_code'=>$shop_code]);
    if($info1 !== false){
        // $info = $info1['data'];
        // $url = '59fd5e729e5a8';
        // $info2 = sx_call($url,['shop_code'=>$shop_code]);
        // $info2 = $info2['data'];
        $info2 = $mc->getChannelInfo(['shop_code'=>$shop_code]);
        // $info3 = controller('crm/Customer','lib')->getChannel($shop_code);

        $channel = [];
        foreach($info1 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'] = [];
                    
                    $arr['data'][] = $arr1;
                }
            }
            $channel[] = $arr;
        }
        return $channel;
    }else{
        return [];
    }
}

//获取多选下拉框的三级渠道
function getChannelArray23($shop_code){
    // $url = '5a2757c0a9810';
    // $info1 = sx_call($url,['shop_code'=>$shop_code]);
    $mc = new \app\common\lib\mcInterface();

    $info2 = $mc->getChannelInfo(['shop_code'=>$shop_code]);
    $info3 = controller('crm/Customer','lib')->getChannel($shop_code);

    $channel = [];

    foreach ($info2 as $kk=>$vv) {

        $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;
            }
        }
        $channel[] = $arr1;
    }

    foreach($channel as $k => $v){
        if(count($v['data']) == 0){
            unset($channel[$k]);
        }
    }
    $channel = array_values($channel);

    return $channel;

}

/*
 * 获取小组 人员二级关系
 */
function getGroupStaff($params){

    $mc = new \app\common\lib\mcInterface();
    $group = $mc->getGroupInfo(['shop_code'=>$params['shop_code']]);
    $tree = [];

    foreach($group as $k => $v){

        $arr1 = [];
        $arr1['title'] = $v['group_name'];
        $arr1['value'] = $v['id'];
        $arr1['data'] = [];

        $staff = $mc->getStaffInfoByGid(['group_id'=>$v['id']]);

        foreach($staff as $kk => $vv){
            $arr2 = [];
            $arr2['title'] = $vv['staffname'];
            $arr2['value'] = $vv['id'];
            $arr2['data'] = [];
            $arr1['data'][] = $arr2;
        }
        $tree[] = $arr1;
    }

    foreach($tree as $k => $v){
        if(count($v['data']) == 0){
            unset($tree[$k]);
        }
    }

    $tree = array_values($tree);

    return $tree;

}

/*
 * 获取小组 里的人员
 */
function getGroupStaffs($params){
    if ($params['group_id']) {
        $where['group_id'] = $params['group_id'];
    }else{
        return array('code'=>100,'msg'=>'参数小组id不能为空');
    }

    $mc = new \app\common\lib\mcInterface();
    $group = $mc->getStaffInfoByGid($where);

    return $group;

}


//检测坐席登陆
function check_call(){
    //呼叫中心信息
    $call_id =  db_config('call_id');
    if($call_id){
        $call = db('crm_s_callCenter')->where('id',$call_id)->find();
        session('ip',$call['ip']);
        session('port',$call['port']);
        //检测用户坐席信息
        $call_user = db('crm_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 = [];
    // }

    $mc = new \app\common\lib\mcInterface();
    $return = $mc->getDepartments($data);
    if ($returun === false) {
        $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){
    // $shopStaffs = cache('_')
    // $url = '5b75341456d18';
    $param['shop_code'] = $param['shop_code'];
    $param['work_type'] = $param['work_type'] ? $param['work_type'] : 0;
    $param['all'] = $param['all'] ? $param['all'] : 1;
    
    // $temp_data = sx_call($url, $param);
    // if ($temp_data['code'] == 200) {
    //     $shopStaffs = $temp_data['data'];
    // }else{
    //     $shopStaffs = [];
    // }

    $mc = new \app\common\lib\mcInterface();
    $shopStaffs = $mc->getAllStaffListByShopcode($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('crm_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('crm_s_tracksign')->where('shop_code',session('shop_code'))->order('id desc')->column('sign_color','tracksign');
        cache('sign_color_'.session('shop_code'),$color);
    }
    return $color;
}
//查询客资是否有有效订单
function checkValidOrder($id,$order_sn){
    $res = db('crm_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,[]);
        
        $mc = new \app\common\lib\mcInterface();
        $info = $mc->getBrand();

        if($info !== false){
            // $detail = $info['data'];
            $arr = [];
            if(is_numeric($data)){
                foreach($info as $k=>$v){
                    $arr[$v['id']] = $v;
                }
                cache('brandclass_int',$arr);
            }else{
                foreach($info 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);
    //     }
    // }

    $mc = new \app\common\lib\mcInterface();
    $info = $mc->getShopInfo();
    $arr = [];
    if ($info) {
        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 isIndexExist($index,$table,$db=''){
    $sql = "SHOW INDEX FROM $table WHERE key_name='$index'";
    if($db){
        $index = db('',$db)->master()->query($sql);
    }else{
        $index = db()->master()->query($sql);
    }
    return !empty($index);
}
/*
 * 获取所以提醒，提醒名为键
 * */
function getRemind($bid){
//    $info = cache('remind_'.$bid);
    if(empty($info)){
        $info = db('crm_s_reminditemset')->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,60);
    }
    return $info;
}/*
 * 获取所以提醒，事业部id为键
 * */
function getAllRemind(){
    $temp = cache('remind');
    if(empty($info)){
        $info = db('crm_s_reminditemset')->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;
    }
    /*
    $url = '5a0b96b65c111';
    $info = sx_call($url,['position_code'=>$positionCode]);
    if(!$info || $info['code'] != 200){
        return false;
    }
    */
    $mc = new \app\common\lib\mcInterface();
    $info = $mc->getPosition(['position_code'=>$positionCode]);
    if (empty($info) || $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['data'][0];
    $position = $info[0];
    // 5a005e0038270
    // $shopInfo = $position['shop_code'] ? controller('crm/Customer','lib')->get_shop(['shop_code'=>$position['shop_code']]) : '';
    $shopInfo = $position['shop_code']?$mc->getShopInfo(['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;
    $cacheInfo['staff_sn'] = $shopInfo['staff_sn'] ? $shopInfo['staff_sn'] : 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']]);
        $info = $mc->getBrand(['id'=>$position['brandclass_id']]);
        if($info !== false){
            $brand = $info['data'][0];
            session('valid_date', (int)$brand['valid_date']);
        }
    }
    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']) {
            $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;
                }
            }
        }
    }
}
/**
 *   判断客户联系方式 是否符合 正则
 *
 * @param customer_tel      母亲手机
 * @param customer_wechat   母亲微信
 * @param mate_tel          父亲手机
 * @param mate_wechat       父亲微信
 *
 * @return  符合可以写入排重表的 联系方式
 */
function checkContact($params){
    // 参与排重的联系方式 设定
    $exclusion_field = config('exclusion_field');
    $contact = [];
    // 正则匹配父母手机号，微信（如果微信能通过正则匹配，且不等于父母手机号），存到排重表
    if ($params['customer_tel']) {
        $check_wtel = check_tel($params['customer_tel']);
        if (!$check_wtel) {
            return array('code'=> 100, 'msg'=>'母亲手机号不符合规则');
        }else{
            if (in_array('customer_tel',$exclusion_field)) {
                array_push($contact,$params['customer_tel']);
            }
        }
    }

    if ($params['mate_tel']) {
        $check_mtel = check_tel($params['mate_tel']);
        if (!$check_mtel) {
            return array('code'=> 100, 'msg'=>'父亲手机号不符合规则');
        }else{
            if (in_array('mate_tel',$exclusion_field)) {
                array_push($contact,$params['mate_tel']);
            }
        }
    }
    
    if ($params['customer_wechat']) {
        if (in_array('customer_wechat',$exclusion_field)) {
            array_push($contact,trim($params['customer_wechat']));
        }
    }
    if ($params['mate_wechat']) {
        if (in_array('mate_wechat',$exclusion_field)) {
            array_push($contact,trim($params['mate_wechat']));
        }
    }
    
    $returnData['code'] = 200;
    $returnData['msg']  = '';
    $returnData['data'] = array_unique($contact);
    return $returnData;
}
/**
 *  更新或者新增客户信息 记录客户信息修改日志
 *  
 * @param c_unique    主表唯一标识
 * @param data        客户信息，录入客资时数据
 *
 * @return  main表的唯一标识 c_unique
 */
function dealMain($c_unique,$data){

    $returnData['code'] = 200;
    $returnData['msg']  = '';
    $returnData['data'] = '';
    
    // var_dump($data);exit;
    $now = date('Y-m-d H:i:s');
    if ($data['customer_tel']) {
        $c_unique = db('crm_c_customer_main')->where('wphone',$data['customer_tel'])->value('c_unique');
        $uniqueSql= db()->getLastSql();
    }else{
        $returnData['c_unique'] = NULL;
        return $returnData;
    }

    // 有主表标识  将客户 信息更新到主表中
    if ($c_unique) {
        $mainInfo = db('crm_c_customer_main')->where('c_unique',$c_unique)->find();
        $mainData = [];
        $logStr = '';
        if ($mainInfo['wname'] != $data['customer_name'] && $data['customer_name']) {
            $mainData['wname'] = $data['customer_name'];
            $logStr .= '母亲姓名由"'.$mainInfo['wname'].'"，修改为：'.$data['customer_name'].'；';
        }
        if ($mainInfo['wphone'] != $data['customer_tel'] && $data['customer_tel']) {
            $mainData['wphone'] = $data['customer_tel'];
            $logStr .= '母亲手机由"'.$mainInfo['wphone'].'"，修改为：'.$data['customer_tel'].'；';
        }
        if ($mainInfo['wwechat'] != $data['customer_wechat'] && $data['customer_wechat']) {
            $mainData['wwechat'] = $data['customer_wechat'];
            $logStr .= '母亲微信由"'.$mainInfo['wwechat'].'"，修改为：'.$data['customer_wechat'].'；';
        }
        if ($mainInfo['wbirthday'] != date('Y-m-d',strtotime($data['customer_birthday'])) && $data['customer_birthday']) {
            $mainData['wbirthday'] = $data['customer_birthday'];
            $logStr .= '母亲生日由"'.$mainInfo['wbirthday'].'"，修改为：'.date('Y-m-d',strtotime($data['customer_birthday'])).'；';
        }
        if ($mainInfo['wcardnumber'] != $data['customer_idnumber'] && $data['customer_idnumber']) {
            $mainData['wcardnumber'] = $data['customer_idnumber'];
            $logStr .= '母亲证件号码由"'.$mainInfo['wcardnumber'].'"，修改为：'.$data['customer_idnumber'].'；';
        }
        if ($mainInfo['mname'] != $data['mate_name'] && $data['mate_name']) {
            $mainData['mname'] = $data['mate_name'];
            $logStr .= '父亲姓名由"'.$mainInfo['mname'].'"，修改为：'.$data['mate_name'].'；';
        }
        if ($mainInfo['mphone'] != $data['mate_tel'] && $data['mate_tel']) {
            $mainData['mphone'] = $data['mate_tel'];
            $logStr .= '父亲手机由"'.$mainInfo['mphone'].'"，修改为：'.$data['mate_tel'].'；';
        }
        if ($mainInfo['mwechat'] != $data['mate_wechat'] && $data['mate_wechat']) {
            $mainData['mwechat'] = $data['mate_wechat'];
            $logStr .= '父亲微信由"'.$mainInfo['mwechat'].'"，修改为：'.$data['mate_wechat'].'；';
        }
        if ($mainInfo['mbirthday'] != date('Y-m-d',strtotime($data['mate_birthday'])) && $data['mate_birthday']) {
            $mainData['mbirthday'] = $data['mate_birthday'];
            $logStr .= '父亲生日由"'.$mainInfo['mbirthday'].'"，修改为：'.date('Y-m-d',strtotime($data['mate_birthday'])).'；';
        }
        if ($mainInfo['mcardnumber'] != $data['mate_idnumber'] && $data['mate_idnumber']) {
            $mainData['mcardnumber'] = $data['mate_idnumber'];
            $logStr .= '父亲证件号码由"'.$mainInfo['mcardnumber'].'"，修改为：'.$data['mate_idnumber'].'；';
        }
        if ($mainInfo['homephone'] != $data['home_phone'] && $data['home_phone']) {
            $mainData['homephone'] = $data['home_phone'];
            $logStr .= '座机由"'.$mainInfo['homephone'].'"，修改为：'.$data['home_phone'].'；';
        }
        if ($mainInfo['email'] != $data['email'] && $data['email']) {
            $mainData['email'] = $data['email'];
            $logStr .= '邮箱由"'.$mainInfo['email'].'"，修改为：'.$data['email'].'；';
        }
        if ($mainInfo['marryday'] != date('Y-m-d',strtotime($data['marry_day'])) && $data['marry_day']) {
            $mainData['marryday'] = $data['marry_day'];
            $logStr .= '婚期由"'.$mainInfo['marryday'].'"，修改为：'.date('Y-m-d',strtotime($data['marry_day'])).'；';
        }
        if ($mainInfo['readybabyday'] != date('Y-m-d',strtotime($data['ready_baby_day'])) && $data['ready_baby_day']) {
            $mainData['readybabyday'] = $data['ready_baby_day'];
            $logStr .= '预产期由"'.$mainInfo['readybabyday'].'"，修改为：'.date('Y-m-d',strtotime($data['ready_baby_day'])).'；';
        }
        if ($mainInfo['babyname'] != $data['baby_name'] && $data['baby_name']) {
            $mainData['babyname'] = $data['baby_name'];
            $logStr .= '宝宝姓名由"'.$mainInfo['babyname'].'"，修改为：'.$data['baby_name'].'；';
        }
        if ($mainInfo['babybirthday'] != date('Y-m-d',strtotime($data['baby_birthday'])) && $data['baby_birthday']) {
            $mainData['babybirthday'] = $data['baby_birthday'];
            $logStr .= '宝宝生日由"'.$mainInfo['babybirthday'].'"，修改为：'.date('Y-m-d',strtotime($data['baby_birthday'])).'；';
        }
        if ($mainInfo['babysex'] != $data['baby_sex'] && $data['baby_sex']) {
            $mainData['babysex'] = $data['baby_sex'];
            $logStr .= '宝宝性别由"'.$mainInfo['babysex'].'"，修改为：'.$data['baby_sex'].'；';
        }
        if ($mainInfo['babyhospital'] != $data['baby_address'] && $data['baby_address']) {
            $mainData['babyhospital'] = $data['baby_address'];
            $logStr .= '宝宝出生医院由"'.$mainInfo['babyhospital'].'"，修改为：'.$data['baby_address'].'；';
        }
        if ($mainInfo['street'] != $data['street'] && $data['street']) {
            $mainData['street'] = $data['street'];
            $logStr .= '所属地由"'.$mainInfo['street'].'"，修改为：'.$data['street'].'；';
        }
        if ($mainInfo['street_id'] != $data['street_id'] && $data['street_id']) {
            $mainData['street_id'] = $data['street_id'];
        }
        if ($mainInfo['address'] != $data['customer_address'] && $data['customer_address']) {
            $mainData['address'] = $data['customer_address'];
            $logStr .= '详细地址由"'.$mainInfo['street'].'"，修改为：'.$data['street'].'；';
        }
        
        if (!empty($mainData)) {
            $mainData['update_time'] = $now;
            db()->startTrans();
            try {
                $res = db('crm_c_customer_main')->where('id', $mainInfo['id'])->update($mainData);
                history_log($logStr,$mainInfo,$c_unique,session('staff_id'),session('staff_name'),'crm','Customer','editCustomerMain');
                db()->commit();
                $returnData['c_unique'] = $c_unique;
                return $returnData;
            } catch (\Exception $e) {
                db()->rollback();
                $returnData['code'] = 100;
                $returnData['msg']  = '更新客户信息失败。';
                $returnData['uniqueSql'] = $uniqueSql;
                $returnData['data'] = db()->getLastSql();
                $returnData['err']  = $e->getMessage();
                return $returnData;
            }
        }else{
            $returnData['c_unique'] = $c_unique;
            return $returnData;
        }
    }
    // 没有主表标识  创建主表客户信息
    else{
        $logStr = '';
        $mainData['create_time']= $now;
        $mainData['c_unique']   = 'sx_'.str_shuffle(time().generate_code());
        $logStr = '新增客户信息。';
        if ($data['customer_name']) {
            $mainData['wname'] = $data['customer_name'];
            $logStr .= '母亲姓名为：'.$data['customer_name'].'；';
        }
        if ($data['customer_tel']) {
            $mainData['wphone'] = $data['customer_tel'];
            $logStr .= '母亲手机为：'.$data['customer_tel'].'；';
        }
        if ($data['customer_wechat']) {
            $mainData['wwechat'] = $data['customer_wechat'];
            $logStr .= '母亲微信为：'.$data['customer_wechat'].'；';
        }
        if ($data['customer_birthday']) {
            $mainData['wbirthday'] = $data['customer_birthday'];
            $logStr .= '母亲生日为：'.date('Y-m-d',strtotime($data['customer_birthday'])).'；';
        }
        if ($data['customer_idnumber']) {
            $mainData['wcardnumber'] = $data['customer_idnumber'];
            $logStr .= '母亲证件号码为：'.$data['customer_idnumber'].'；';
        }
        if ($data['mate_name']) {
            $mainData['mname'] = $data['mate_name'];
            $logStr .= '父亲姓名为：'.$data['mate_name'].'；';
        }
        if ($data['mate_tel']) {
            $mainData['mphone'] = $data['mate_tel'];
            $logStr .= '父亲手机为：'.$data['mate_tel'].'；';
        }
        if ($data['mate_wechat']) {
            $mainData['mwechat'] = $data['mate_wechat'];
            $logStr .= '父亲微信为：'.$data['mate_wechat'].'；';
        }
        if ($data['mate_birthday']) {
            $mainData['mbirthday'] = $data['mate_birthday'];
            $logStr .= '父亲生日为：'.date('Y-m-d',strtotime($data['mate_birthday'])).'；';
        }
        if ($data['mate_idnumber']) {
            $mainData['mcardnumber'] = $data['mate_idnumber'];
            $logStr .= '父亲证件号码为：'.$data['mate_idnumber'].'；';
        }
        if ($data['home_phone']) {
            $mainData['homephone'] = $data['home_phone'];
            $logStr .= '座机为：'.$data['home_phone'].'；';
        }
        if ($data['email']) {
            $mainData['email'] = $data['email'];
            $logStr .= '邮箱为：'.$data['email'].'；';
        }
        if ($data['marry_day']) {
            $mainData['marryday'] = $data['marry_day'];
            $logStr .= '婚期为：'.date('Y-m-d',strtotime($data['marry_day'])).'；';
        }
        if ($data['ready_baby_day']) {
            $mainData['readybabyday'] = $data['ready_baby_day'];
            $logStr .= '预产期为：'.date('Y-m-d',strtotime($data['ready_baby_day'])).'；';
        }
        if ($data['baby_name']) {
            $mainData['babyname'] = $data['baby_name'];
            $logStr .= '宝宝姓名为：'.$data['baby_name'].'；';
        }
        if ($data['baby_birthday']) {
            $mainData['babybirthday'] = $data['baby_birthday'];
            $logStr .= '宝宝生日为：'.date('Y-m-d',strtotime($data['baby_birthday'])).'；';
        }
        if ($data['baby_sex']) {
            $mainData['babysex'] = $data['baby_sex'];
            $logStr .= '宝宝性别为：'.$data['baby_sex'].'；';
        }
        if ($data['baby_address']) {
            $mainData['babyhospital'] = $data['baby_address'];
            $logStr .= '宝宝出生医院为：'.$data['baby_address'].'；';
        }
        if ($data['street']) {
            $mainData['street'] = $data['street'];
            $logStr .= '所属地为：'.$data['street'].'；';
        }
        if ($data['street_id']) {
            $mainData['street_id'] = $data['street_id'];
        }
        if ($data['customer_address']) {
            $mainData['address'] = $data['customer_address'];
            $logStr .= '详细地址为：'.$data['customer_address'].'；';
        }
        if ($data['brandclass_id']) {
            $mainData['brandclass_id'] = $data['brandclass_id'];
        }
        if ($data['brandclass']) {
            $mainData['brandclass'] = $data['brandclass'];
            $logStr .= '所属事业部：'.$data['brandclass'].'；';
        }

        db()->startTrans();
        try {
            $res = db('crm_c_customer_main')->insert($mainData);
            history_log($logStr,'',$mainData['c_unique'],session('staff_id'),session('staff_name'),'crm','Customer','insertCustomerMain');
            $c_unique = $mainData['c_unique'];
            db()->commit();
            $returnData['code'] = 200;
            $returnData['msg']  = '';
            $returnData['data'] = '';
            $returnData['c_unique'] = $c_unique;
            return $returnData;
        } catch (\Exception $e) {
            db()->rollback();
            $returnData['code'] = 100;
            $returnData['msg']  = '更新客户信息失败。';
            $returnData['uniqueSql'] = $uniqueSql;
            $returnData['data'] = db()->getLastSql();
            $returnData['err']  = $e->getMessage();
            return $returnData;
        }
    }

    return $returnData;
}
/**
 *  更新或者新增客户信息 记录客户信息修改日志
 *  
 * @param data    客资信息
 * @param rep     重复客资id
 *
 * @return  main表的唯一标识 c_unique
 */
function dealCus($data,$cid){
    // var_dump($data);exit;
    $now = date('Y-m-d H:i:s');
    $cusInfo = db('crm_c_customerinfo')->where('id',$cid)->field()->find();
    $cusData = [];
    $logStr = '';
    
    if ($cusInfo['baby_address'] != $data['baby_address'] && $data['baby_address']) {
        $cusData['baby_address'] = $data['baby_address'];
        $logStr .= '宝宝医院由"'.$cusInfo['baby_address'].'"，修改为：'.$data['baby_address'].'；';
    }
    if ($cusInfo['hospital_photo_time'] != $data['hospital_photo_time'] && $data['hospital_photo_time']) {
        $cusData['hospital_photo_time'] = $data['hospital_photo_time'];
        $logStr .= '医拍时间由"'.date('Y-m-d',strtotime($cusInfo['hospital_photo_time'])).'"，修改为：'.date('Y-m-d',strtotime($data['hospital_photo_time'])).'；';
    }
    if ($cusInfo['hospital_photo_cameraman'] != $data['hospital_photo_cameraman'] && $data['hospital_photo_cameraman']) {
        $cusData['hospital_photo_cameraman'] = $data['hospital_photo_cameraman'];
        $logStr .= '医拍摄影师由"'.$cusInfo['hospital_photo_cameraman'].'"，修改为：'.$data['hospital_photo_cameraman'].'；';
    }
    if ($cusInfo['hospital_photo_assistant'] != $data['hospital_photo_assistant'] && $data['hospital_photo_assistant']) {
        $cusData['hospital_photo_assistant'] = $data['hospital_photo_assistant'];
        $logStr .= '医拍摄影助理由"'.$cusInfo['hospital_photo_assistant'].'"，修改为：'.$data['hospital_photo_assistant'].'；';
    }
    
    if (!empty($cusData)) {
        $mainData['update_time'] = $now;
        $res = db('crm_c_customerinfo')->where('id',$cid)->update($cusData);
        history_log($logStr,$cusInfo,$cid,session('staff_id'),session('staff_name'),'crm','Customer','editCustomerInfo');
        if ($res === false) {
            $returnData['code'] = 100;
            $returnData['msg']  = '更新客户信息失败。';
            $returnData['data'] = '';
            $returnData['err']  = db()->getLastSql();
        }
    }else{
        $returnData['code'] = 200;
        $returnData['msg']  = '';
        $returnData['data'] = '';
    }

    return $returnData;
}
/**
 *  是否是有效新客（6+1）
 *  标准1：该手机从未录入客资或开单的，为有效新客；
 *  标准2：该手机录入后，并未订单（或有订单作废的），永远无效
 *  标准3：录入过客资，所有订单的总完成日超过一年，为有效新客
 *  标准4：录入过客资，只要有订单未完成的，全部为无效新客资
 *  标准5：未录入客资，但有订单信息，必须所有订单的总完成日超过一年，为有效新客资，只要有作废或未填总完成日的，全部为无效新客资
 *  标准6：全部订单总完成日超过一年的，在最近一次总完成日后，有录入客资的，算无效新客资
 *  
 * @param customer_tel    客资（妈妈）手机号
 *
 * @return boolean
 */
function isValidNew($param){
    // 根据手机号查，没有重复的，直接返回true
    $customer = db('crm_c_customerinfo')
        ->where('customer_tel',$param['customer_tel'])
        ->field('id,dj_day')
        ->order('dj_day desc')
        ->find();
    $order = db('c_customerinfo c')
        ->join('c_customerorder o','c.customerid=o.customerid','left')
        ->where('c.wphone', $param['customer_tel'])
        ->order('o.allfinishfate desc')
        ->field('c.id,o.create_time as dj_day,o.targetdate,o.allfinishfate')
       // ->where('o.blankoutannal',0)
        ->select();
    if(!$customer && !$order){
        return true;
    }
    if($customer && !$order){
        return false;
    }
    if($order){
        $orderFinish = '';
        foreach ($order as $info) {
            if(!$info['allfinishfate']){
                $orderFinish = time();
                break;
            }
            if($orderFinish){
                $orderFinish = strtotime($info['allfinishfate']) > $orderFinish?strtotime($info['allfinishfate']):$orderFinish;
            }else{
                $orderFinish = strtotime($info['allfinishfate']);
            }
        }
    }
    $ago = strtotime('-366 days');
    if($orderFinish > $ago){
        return false;
    }

    if(!$customer){
        return true;
    }else{
        $djDay = strtotime($customer['dj_day']);
        if($djDay > $orderFinish){
            return false;
        }else{
            return true;
        }
    }
    return false;
    //以下逻辑相当于永远不会走到
    $ago = date('Y-m-d 00:00:00',strtotime('-366 days'));
    if (!$res) {
        $res = db('c_customerinfo c')
            ->join('c_customerorder o','c.customerid=o.customerid','left')
            ->where('c.wphone', $param['customer_tel'])
            ->order('c.id desc')
            ->field('c.id,o.create_time as dj_day,o.targetdate')
            ->find();
        
        if (!$res) {
            return true;
        }else{
            if (!$res['dj_day']) {
                $res['dj_day'] = date('Y-m-d H:i:s',strtotime($res['targetdate']));
            }
        }
    }
    // 如果有，根据手机号，查erp数据库customerinfo关联order表，录入时间还是最后一次追踪时间
    $orderArr = db('c_customerinfo c')
        ->join('c_customerorder o','c.customerid=o.customerid','left')
        ->where('c.wphone',$param['customer_tel'])->where('o.blankoutannal',0)
        ->field('o.orderId')
        ->select();
    // echo db('c_customerinfo c','sx_erp')->getLastSql();
    if (count($orderArr)<1) {
        if(strtotime($res['dj_day'])>strtotime($ago)){
            return false;
        }else{
            return true;
        }
    }
    $orderStr = '';
    foreach ($orderArr as $key => $value) {
        $orderStr .= $value['orderId'].',';
    }
    $orderStr = trim($orderStr,',');
    // 如果有订单，根据订单号，查photo表（photostate，拍摄状态0未拍1未拍完2全拍完），（photooverdate，拍照完成日‘yyyy-mm-dd H:i:s’）
    // (photostate=0 or photostate=1) or (photooverdate>today-365) 返回false，else true
    $where = ' p.photostate in (0,1) or p.photooverdate > \''.$ago.'\'';
    $photo = db('c_customerorder o')
        ->join('c_customerphoto p','p.orderId=o.orderId','left')
        ->where('o.orderId','in',$orderStr)
        // ->where('photostate','in','0,1')
        ->where($where)
        ->count();
    unset($param,$res,$orderArr,$orderStr,$ago);
    if ($photo) {
        return false;
    }else{
        return true;
    }
}
// 生成guid
function getGuid(){
    if (function_exists('com_create_guid')){
        return com_create_guid();
    }else{
        mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = chr(123)// "{"
                .substr($charid, 0, 8).$hyphen
                .substr($charid, 8, 4).$hyphen
                .substr($charid,12, 4).$hyphen
                .substr($charid,16, 4).$hyphen
                .substr($charid,20,12)
                .chr(125);// "}"
        return $uuid;
    }
}
//根据员工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;
}
//查询人员权限,并返回权限内的人员id
function getStaffAuth(){
    if(check_right('menu1512637269')) {//查看所有客资权限
        $staff_id =  controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>session('shop_code')]);
        $staff_id = array_column($staff_id,'id');
        $staffId = implode(',',$staff_id);
    }elseif(check_right('menu1531471639')){//查看部门客资权限
        $staff_id = controller('crm/Customer')->getDepartmentStaffs(session('department_id'));
        $staff_id = array_column($staff_id,'id');
        $staffId = implode(',',$staff_id);
    }elseif(check_right('menu1529653231')) {//查看小组客资权限
        $staff_id = getGroupStaffByStaffId(session('staff_id'));
        $staff_id = array_column($staff_id,'staff_id');
        $staffId = implode(',',$staff_id);
    }else{
        $staffId = session('staff_id');
    }
    return $staffId;
}
/**
 * 获取微信access_token 调mc接口
 * @param  wx_appid   微信app_id
 * @param  wx_secret  微信secret
 * @param  force      是否强制获取(1：强制获取，默认0)
 * @return array      
 */
function getAccessToken($wx_appid,$wx_secret,$force){
    $mc = new \app\common\lib\mcInterface();
    $info = $mc->getAccessToken($wx_appid,$wx_secret,$force);
    return $info;
}

function textlog($str,$level=SX_LOG_LEVEL_INFO,$module='text'){
    $write = false;
    if($level < SX_LOG_LEVEL_INFO){
        $write = true;
    }else{
        $write = config('app_debug')?true:false;
    }
    if($write){
        if (strtoupper(substr(php_uname(),0,3)) == 'WIN') {
            $str = iconv("UTF-8","GB2312//IGNORE",$str);
        }
        $path = ROOT_PATH."runtime".DS.'log'.DS.date('Ym').DS;
        if(!file_exists($path) || !is_dir($path)){
            @mkdir($path,0777,true);
        }
        $module = date('d').'-'.$module;
        file_put_contents($path.$module.".log",date('Y-m-d H:i:s')."\t".$str."\r\n",FILE_APPEND);
        unset($str);
    }
}


/**
 * INI 配置快捷函数
 * 
 * @param  [type] $key   [description]
 * @param  [type] $value [description]
 * @return [type]        [description]
 */
function ini($key,$value){
    $configPath = 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;
}
/**
 * 获取当前域名  
 *
 * @return  string   返回格式为：http://crm.sx.com  最后的斜线去掉了
 * @author lilong<lilong@suxuantech.cn>
 */
function getAppHost(){
    $appHost = trim(config('app_host'));
    if ($appHost) {
        $appHost = trim($appHost,'/');
    }else{
        $appHost = trim('http://'.trim($_SERVER['HTTP_HOST']),'/');
    }
    return $appHost;
}
/**
 * 写入排重表 crm_c_customer_contact
 * @param  $id    要写入排重表的客资id
 * @param  $con   要写入排重表的联系方式
 *
 * @return boolen
 * @author lilong<lilong@suxuantech.cn>
 */
function updateContact($id,$con){
    $column = 'c_unique,customer_type,customer_channel,add_shop_code,shop_code,brandclass_id,brandclass';
    $baby_time = isColumnExist(array('table'=>'crm_c_customerinfo','column'=>'baby_time'));
    if ($baby_time) {
        $column .= ',baby_time';
    }
    $cInfo = db('crm_c_customerinfo')->where('id',$id)->field($column)->find();
    $repeat_way = db_config('customer_repeat_method');
    $repeat_way = $repeat_way?$repeat_way:config('repeat_way');
    if ($repeat_way == '6j1') {
        if ($cInfo['customer_type'] == 2) {
            $customer_channel = '';
        }else{
            $customer_channel = $cInfo['customer_channel'];
        }
    }else if ($repeat_way == 'xaf') {
        $customer_channel = $cInfo['baby_time'] ? $cInfo['baby_time'] : '一胎';
    }
    
    foreach ($con as $key => $value) {
        if ($value) {
            $inCon[$key]['c_id'] = $id;
            $inCon[$key]['c_unique'] = $cInfo['c_unique'];
            //2021-03-15 南宁qqbaby
            if (customize('nnqqbaby')) {
                $inCon[$key]['customer_channel'] = $cInfo['add_shop_code'];
            }else{
                $inCon[$key]['customer_channel'] = $customer_channel;
            }
            $inCon[$key]['brandclass'] = $cInfo['brandclass'];
            $inCon[$key]['contact'] = $value;
        }
    }
    db('crm_c_customer_contact')->where('c_id',$id)->delete();
    db('crm_c_customer_contact')->insertAll($inCon);
}
// 格式化数字 默认返回小数点后两位 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 getChannels($param){
    $shop_code = $param['shop_code'] ? $param['shop_code'] : 'all';
    $allChannel = cache('all_channel_'.$shop_code);
    // var_dump($allChannel);die;
    if (!$allChannel) {
        $sql = $shop_code=='all'?"":"FIND_IN_SET('$shop_code',share_shops)";
        $allChannel = db('crm_s_channel')->where($sql)->column();
        // echo db()->getLastSql();die;
        cache('all_channel_'.$shop_code,json_encode($allChannel));
    }
    return $allChannel;

}
/**
 * 定制功能通过此函数判断，
 * 使用时直接使用此函数，并传入定制企业标识，如判断是否非常六加一的：
 * if(customize('xmfc6j1'))
 * {
 *     是定制六加1的逻辑。。。
 * }
 * @param  [type] $name [定制企业的标识]
 *                      xmfc6j1     厦门非常六加一
 *                      whxaf       武汉小阿福
 *                      cdtsyx      成都天使印像
 *                      babypastel  郑州babypastel
 *                      sqmhts      商丘梦幻天使
 *                      nnqqbaby      南宁qqbaby
 *                      whbm          威海斑马
 *                      
 * @return [type]       true/false 是的，返回true不是的为false
 */
function customize($name,$productId=''){
	// return true;
    $cacheFile = RUNTIME_PATH.'customize.php';
    if(file_exists($cacheFile)){
        $nameList = include($cacheFile);
        if(in_array($name,$nameList) || in_array('all', $nameList)){
            return true;
        }else{
            return false;
        }
    }
    $mcproductId = $productId?$productId:session('mc_productid');
    if(!$mcproductId){
        $mc = new \app\common\lib\mcInterface();
        $data = $mc->cacheData('5ef1a04c80175');
        if($data){
            $mcproductId = $data['product_id'];
        }
    }
    if(!$mcproductId) return false;

    //新版只要修改这个数组即可，
    //如果已经执行过新版的定制判断，
    //需要把runtime下的customize.php删除掉才会生效
    $dist = [
        '5903679116'=>['xmfc6j1'],// 厦门非常六加一
        '9657743504'=>['whxaf'],// 武汉小阿福
        '9128787616'=>['cdtsyx'],// 成都天使印象
        '7921308917'=>['babypastel'],
        '7957528370'=>['babypastel'],
        '6315968332'=>['sqmhts'],// 商丘梦幻天使
        '7663054564'=>['bjggt'],// 北京乖乖兔
        '1439001586'=>['bjggt'],
        '3196407416'=>['whxaf','whxaf','cdtsyx','babypastel'],
        '0428082539'=>['all'],
        '7702959738'=>['all'],
        '0470659185'=>['all'],
        '4206678831'=>['shynk'],// 上海优尼克
        '3726894006'=>['nnqqbaby'],// 南宁qqbaby
        '6174330520'=>['nnqqbaby'],// 南宁qqbaby 新环境
        '9078737310'=>['whbm'],// 威海斑马
        '6381553896'=>['sjzsgbaby'],// 石家庄时光baby

    ];

    if(array_key_exists($mcproductId, $dist)){
        $nameList = $dist[$mcproductId];
        file_put_contents($cacheFile, arrayToString($nameList));
    }else{
        return false;
    }
    if(in_array($name,$nameList) || in_array('all', $nameList)){
        return true;
    }
    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 babyAge($today,$baby_birthday){
    $age = '';
    if (!$today) {
        $today = date('Y-m-d',time());
    }
    if ($baby_birthday) {
        $birthdayY = date('Y',strtotime($baby_birthday));
        $todayY = date('Y',strtotime($today) );
        if ( $todayY>$birthdayY ) {
            $age = $todayY-$birthdayY.'岁';
        }else{
            $birthdayM = date('m',strtotime($baby_birthday));
            $todayM = date('m',strtotime($today) );
            if ($todayM>$birthdayM) {
                $age = $todayM-$birthdayM.'个月';
            }else{
                $birthdayD = date('d',strtotime($baby_birthday));
                $todayD = date('d',strtotime($today) );
                $age = $todayD-$birthdayD.'天';
            }
        }
    }
    return $age;
}

/**
 * 二维数组根据某个字段排序
 * @param array $array 要排序的数组
 * @param string $keys   要排序的键字段
 * @param string $sort  排序类型  SORT_ASC     SORT_DESC 
 * @return array 排序后的数组
 */
function arraySort($array, $keys, $sort = SORT_DESC) {
    //根据字段last_name对数组$data进行降序排列
    $keysValue = array_column($array,$keys);
    array_multisort($keysValue,SORT_DESC,$data);
    return $array;
}
/**
 * 搜索介绍人信息
 * @param string $keys   姓名，手机，单号
 */
function getseachintroducer($key) {
    if ($key) {
        $introducer = db('c_customerorder')->alias('o')
            ->join("c_customerinfo c","c.customerid=o.customerid","left")
            ->where("o.orderId","like","%$key%")
            ->whereOr("c.wname","like","%$key%")
            ->whereOr("c.wphone","like","%$key%")
            ->field("c.mname,c.mphone,wname,wphone,o.orderId,o.crm_customer_number,c.shop_code,c.shop_name,o.storeconsuitant1")
            ->select();
        $sql = db()->getLastSql();
        // echo $sql;exit;
        $array['Data'] = $introducer;
        $array['Code'] = 200;
    }else{
        $array['Code'] = 100;
    }
    return $array;
}
// 微信会话 监听广播 回调方法
function wxGetMsgByOpenid($instance, $channelName, $message){
    if ($message) {
        $message = json_decode($message,true);
        $params = [
            'openid'=>$message['openid'],
            'tid'=>cache('new_wx_tid_'.$message['openid']),
        ];
        $message = controller('weixin/weixin','controller')->getTalkByOpenid($params);
        header("Content-Type:application/json;charset=utf-8");
        echo json_encode(
            ['code'=>200,'data'=>$message]
        );
        exit();
    }
}
function arrayToString($arr,$in=0,$sp="\t"){
    if(!is_array($arr)){
        return $arr;
    }
    if(empty($arr)){
        return '';
    }
    $res = $in?'':'<?php '."\n"."return [\n";
    foreach ($arr as $key => $value) {
        if(is_array($value)){
            $res .= $sp."'{$key}'=>[\n".arrayToString($value,1,$sp."\t").$sp.'],'."\n";
        }else{
            if(!is_numeric($key)){
                $key = "'".$key."'";
            }
            if(is_string($value)){
                $value = str_replace('\\', '\\\\', $value);
                $res .= $sp."{$key}=>'{$value}',\n";
            }elseif (is_int($value)) {
                $res .= $sp."{$key}=>{$value},\n";
            }elseif (is_bool($value)) {
                if($value === true){
                    $res .= $sp."{$key}=>true,\n";
                }else{
                    $res .= $sp."{$key}=>false,\n";
                }
            }else{
                $res .= $sp."{$key}=>'{$value}',\n";
            }
        }
    }
    $res .= $in?"":'];';
    return $res;
}
// 微信 状态
function getWxStatus($key){
    $wxStatus = [0=>'未标记',1=>'待通过',2=>'已加上',3=>'未加上'];
    return $wxStatus[$key] ? $wxStatus[$key] : '未标记';
}

// 获取客资录入 隐藏项
function getLrHidden($brandclassId){
    $hidden = db_config('lr_hidden_'.$brandclassId);
    $hidden = trim($hidden,',');
    $lrHidden = explode(',',$hidden);
    return $lrHidden;
}
function getLrMust($brandclassId,$shopCode){
    // 录入必选项配置
        $lrMust = db_config('lr_must_'.$brandclassId);
        $lrMust = trim($lrMust,',');
        $lrMust = explode(',',$lrMust);
        //成都网销中心录入客资 ‘获取方式’为必填项
        if($shopCode == 'TSYX13' && !in_array('access_model',$lrMust)){
            $lrMust[] = 'access_model';
        }
        return $lrMust;
}
function getLrValidList(){
    // 标记有效 客资状态 是否隐藏 应该根据当前 员工的权限
    $validArr = [];
    if(check_right('menu1546854995')){
        $temp['id']  = 1;
        $temp['name']= '有效';
        $temp['sele']= 0;
        $validArr[] = $temp;
    }
    // 标记待定
    $temp['id']  = 2;
    $temp['name']= '待定';
    $temp['sele']= 0;
    $validArr[] = $temp;
    // 标记无效
    if(check_right('menu1517129331')){
        $temp['id']  = 3;
        $temp['name']= '无效';
        $temp['sele']= 0;
        $validArr[] = $temp;
    }
    return $validArr;
}
function getExtCustomerField(){
    $shopCode = ini('lr_must.shop_code');
    if(strpos($shopCode, ',')){
        $shopCode = explode(',', $shopCode);
    }else{
        $shopCode = [$shopCode];
    }
    $field = [];
    if(in_array(session('shop_code'),$shopCode)){
        $column = isColumnExist(array('table'=>'crm_c_customerinfo','column'=>ini('lr_must.field')));
        if ($column) {
            $field['select'] = explode(',', ini('lr_must.select'));
            $field['field'] = ini('lr_must.field');
            $field['fieldname']  = ini('lr_must.fieldname');
        }
    }
    return $field;

}

function getLrType($shopCode){
     // 客资录入类型  查看设定
    $customer_type = explode(',', db_config('customer_type_'.$shopCode));
    $only = '';
    foreach ($customer_type as $key => $value) {
        if (!$value) { // 如果没有设定
            $mc = new \app\common\lib\mcInterface();
            $shopInfo = $mc->getShopInfo(array('shop_code' => $shopCode));
            if ($shopInfo[0]['is_dig'] == 1) { // 如果是转介绍客资接入店
                $only = '2';
            }else{ // 只有新客资，没有转介绍
                $only = '1'; 
            }
        }else{
            $only .= $value.',';
        }
    }
    $only = trim($only,',');
    if ($only == '1') {
        $only = 'new';
    }else if ($only == '2') {
        $only = 'zjs';
    }else{
        $only = 'all';
    }
   return $only;
}

// 2021-04-15 上海优尼可 获取订单所有服务信息
function getAllServiceInfo($params){
    if (empty($params['order_sn'])) {
        $res['code'] = 100;
        $res['msg'] = '缺少参数订单号order_sn';
        return $res;exit;
    }
    //订单信息
    $res['order'] = db('c_customerinfo')
                        ->alias('info')
                        ->field(['mname','wname','mphone','wphone','orderId','order_type','targetdate','mwechat','wwechat','mbirthdate','wbirthdate','mqq','wqq','email','shop_order_name','storeconsuitant2','storeconsuitant1','CONCAT(address_sheng,address_shi,address_qu,address)'=>'address'])
                        ->join('c_customerorder o','o.customerid = info.customerid',"left")
                        ->where('orderId',$params['order_sn'])
                        ->find();
    if (!$res['order']) {
        $res['code'] = 101;
        $res['msg'] = '没有查到订单信息';
        return $res;exit;
    }

    //产品信息
    $res['product'] = db('c_consumptioncontent')->field("consumption_name,amount,total,item_pagecount,item_sheetscount,remarks,servicenumber,sorting")->where("orderId",$params['order_sn'])->order("servicenumber asc,sorting asc")->select();

    //摄影信息
    $res['photography'] = db('c_customerphoto')->field("case photostate when '0' then '全未拍'  when '1' then '未拍完'  when '2' then '已拍完' else '' end as photostate,photodate,phototime,cameraman,mentor_a,dresser,yipaidress_count,locationcount,Interiorcount,currentfc")->where("orderId",$params['order_sn'])->order("id desc")->select();

    //选片信息
    $res['chip_select'] = db('c_customersp')->field("selectday,selectTime,selectman,spcount,spbook_photocount,currentfc")->where("orderId",$params['order_sn'])->order("id desc")->select();

    //收款信息
    $res['gathering'] = db('c_paymentcontent')->field("case payclass  when 0 then '门市收款' when 3 then 'VIP卡充值' when 4 then '商品销售' when 6 then '退款游泳次数'  end as payclass,paytype,paymentdate,fundname,payment_money,cashierman,remarks")->where("orderId",$params['order_sn'])->order("id desc")->select();

    return $res;
}

function help($hid){
    static $helpText;
    if(!$helpText){
        if(file_exists(APP_PATH.'helptext.php')){
            $helpText = include_once(APP_PATH.'helptext.php');
            $txt = empty($helpText[$hid])?'此处无提示内容':$helpText[$hid];
        }else{
            $txt = '缺少帮助字典文件，无法显示帮助内容。';
        }
    }else{
        $txt = empty($helpText[$hid])?'此处无提示内容':$helpText[$hid];
    }
    
    $content = '
        <span id="'.$hid.'" style="width:12px;height:12px;position: absolute;margin-top: -5px;cursor: pointer;border: 1px solid #ccc;border-radius: 15em;line-height: 13px;">
            <i class="layui-icon" style="font-size: 12px;">&#xe607;</i>
            <div style="display: none">'.$txt.'</div>
        </span>
        <script type="text/javascript">
         $("#'.$hid.'").click(function(){
            if(typeof layer === "undefined"){
                alert("没有layer无法加载帮助信息。");
                return;
            }
            tipindex = layer.tips($(this).children("div").html(),$(this),{
                    tips: 2,time:0
            });
            $(document).bind("click",function(e){
                var target  = $(e.target);
                if(target.closest("#'.$hid.'").length == 0){
                    layer.close(tipindex);
                    $(document).unbind("click");
                }
            });
         });
        </script>
    ';
    return $content;
}


//2021-05-27 呼叫中心(七陌) 
function huJiaoZXQiMo($params)
{
    if (!$params['url']) {
        return array('code'=>100,'msg'=>'没有传递url参数');exit;
    }
    if (!$params['data']) {
        return array('code'=>100,'msg'=>'没有传递data参数');exit;
    }

    // $accountid = "T00000021813";//云呼账号 
    // $secret = "1edb5cd0-bd2e-11eb-965b-5586b3519675";//云呼密码
    // $url = "https://openapis.7moor.com";//https://developer.7moor.com/dc/#/other/data 生成的地址

    if (db_config('call_id')) {
        $where['id'] = db_config('call_id');
    }else{
        $where['call_name'] = '呼叫中心(七陌)';
    }
    $res = db('crm_s_call_center')->where($where)->find();

    $accountid = $res['accountid'];//云呼账号 
    $secret = $res['secret'];//云呼密码
    $url = $res['ip'];

    $time = date("YmdHis");
    $sig = strtoupper(md5($accountid.$secret.$time));//sig的值为 32位大写MD5加密 （帐号Id + 帐号APISecret +时间戳）
    $authorization  =   base64_encode($accountid.":".$time);
    $url = $url.$params['url']."$accountid?sig=$sig";

    //Authorization : Base64编码(账户Id +冒号+时间戳) 时间戳是当前系统时间,格式"yyyyMMddHHmmss",需与sig参数中时间戳相同。
    $headers[] = "Accept: application/json";
    $headers[] = "Content-type: application/json;charset='utf-8'";
    $headers[] = "Authorization: ".$authorization;
    //print_r($accountid.$secret.$time."---".$sig);exit;

    $res = http_request($url, 'POST',json_encode($params['data']),$headers);
    if ($res['code'] == 200) {
        $log['hash'] = request()->module().'/'.request()->controller().'/'.request()->action();
        $log['api_url'] = $url;
        $log['result_code'] = $res['code'];
        $log['api_start_time'] = $res['request']['api_start_time'];
        $log['api_end_time'] = microtime(true);
        $log['data'] = json_encode($params);

        api_log($log);

        return $res['response'];
    }else{
        return array('code'=>300,'msg'=>'接口传递有误。'.$res['request']);
    }
    /*
    $accountid  =   "T00000021813";//云呼账号 
    $secret     =   "1edb5cd0-bd2e-11eb-965b-5586b3519675";//云呼密码
    $time       =   date("YmdHis");
    $url = "https://openapis.7moor.com";
    //echo $time;exit;
    $authorization  =   base64_encode($accountid.":".$time);
    $sig            =   strtoupper(md5($accountid.$secret.$time));
    //echo $authorization;
    //echo "<br>";


    $url    .=   $params['url']."$accountid?sig=".$sig;

    //print_r(  http_build_query($data) );exit;
    //echo $url;
    //exit;
    //echo strlen( http_build_query($data) );exit;
    //$header[] = 'Connection: Keep-Alive';
    $header[] = "Accept: application/json";
    $header[] = "Content-type: application/json;charset='utf-8'";
    $header[] = "Content-Length: ".strlen( json_encode($params['data']) );
    $header[] = "Authorization: ".$authorization;

    //print_r($header);

    $ch = curl_init ();
    curl_setopt($ch, CURLOPT_URL, ($url) );//地址
    curl_setopt($ch, CURLOPT_POST, 1);   //请求方式为post
    curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($params['data'])); //post传输的数据。
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);

    //print_r($message);exit;

    $return = curl_exec ( $ch );
    
    if($return === FALSE ){
        echo "CURL Error:".curl_error($ch);exit;
     }

    curl_close ( $ch );

    echo ($return);
    exit;*/
}

// 回调函数,这里写处理逻辑
function callCenterSevenStrangerRinging($instance, $channelName, $message) {
    if ($message) {
        $res = json_decode($message,true);
        if ($res['id']) {
            $tell = db('crm_c_call_temporary')->where('id',$res['id'])->value('time');
            response(array('code'=>200,'data'=>$tell),200,[],'json')->send();
            die;
        }

    }else{
        var_dump($channelName);die;
    }
    // file_put_contents("rNotice.txt", 'cName：'.$channelName.'；msg：'.$message.PHP_EOL, FILE_APPEND); 
}
//2021-07-20 时间 H:i:s 转 s
function HisToS($his)
{
    $str = explode(':', $his);

    $len = count($str);

    if ($len == 3) {
        $time = $str[0] * 3600 + $str[1] * 60 + $str[2];
    } elseif ($len == 2) {
        $time = $str[0] * 60 + $str[1];
    } elseif ($len == 1) {
        $time = $str[0];
    } else {
        $time = 0;
    }
    return $time;
}

//2021-07-20 时间 s 转 H:i:s
function SToHis($seconds)
{
    $seconds = (int)$seconds;
    $time = '';
    if ($seconds > 3600) {
        if ($seconds > 86400) {
            $days = (int)($seconds / 86400);
            $seconds = $seconds % 86400;//取余
            $time .= $days . " 天 ";
        }
        $hours = intval($seconds / 3600);
        $minutes = $seconds % 3600;//取余下秒数
        $time .= $hours . " 小时 " . gmstrftime('%M 分钟 %S 秒', $minutes);
    } elseif ($seconds > 60) {
        $time = gmstrftime('%M 分钟 %S 秒', $seconds);
    } else {
        $time = gmstrftime('%S 秒', $seconds);
    }
    return $time;
}