<?php
/**
 * CRM项目模块公共类，所有开发的模块要引用此模块，进行业务公共逻辑处理。
 * 主要处理运行初始化，用户认证，日志，
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 * 
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: songdemei<songdemei@suxuantech.cn> 2017-10-17 $
 */
namespace app\index\controller;
use think\Controller;
class Base  extends Controller{
    /**
     * API的hash值
     * 
     * @var type String
     */
    protected $apiHash = '';
    protected $apiUrl = '';
    protected $appSecret = '';
    protected $apiParams = array();
    protected $apiStartTime = 0;
    protected $apiEndTime = 0;
    protected $appId = '';
    function _initialize() {
        if(!request()->isAjax()){
            //获取后端服务监听状态。
            $service = service_status();
            $active = time() - intval(strtotime($service['last_active']));
            if( !$active || $active > 120 ){
                $this->assign('serviceStatus',3);
            }else{
                if(is_array($service['service_list']) && count($service['service_list']) >0){
                    $ServiceStatus = 1;
                    foreach ($service['service_list'] as  $v) {
                        if($v['restart_count'] > 10){
                            $ServiceStatus = 2;
                        }
                    }
                    $this->assign('serviceStatus',$ServiceStatus);
                }else{
                    $this->assign('serviceStatus',2);
                }
                
            }
            $this->assign('_empty','<option value="">请选择</option>');
            
        }

        if(\think\Request::instance()->isPost()){
            defined('IS_POST') or define('IS_POST', true);
        }
        $erp = is_install('sx_erp');
        $this->assign('erp',$erp);
        // 排重方式
        $repeat_way = db_config('customer_repeat_method');
        $repeat_way = $repeat_way?$repeat_way:config('repeat_way');
        // $repeat_way = config('repeat_way');
        // $repeat_way = $repeat_way ? $repeat_way : '6j1';
        $this->assign('repeat_way',$repeat_way);

        // 呼叫中心
        $call_id =  db_config('call_id');
        // var_dump($call_id);
        if($call_id){
            $call = db('crm_s_call_center')->where('id',$call_id)->value('call_name');
            $this->assign('callCenter',$call);
            if(SYSTEM_AUTH_ADMIN || check_right('menu1561718791')){
                $this->assign('callMan',1);
            }
        }
        //2020-08-06 menu表换成menu.php
        $menu = include_once(APP_PATH.'menu.php');
        $menuCustomize = include_once(APP_PATH.'menu_customize.php');
        $res = getAuthMenu($menu,'menu',$menuCustomize);

        // print_r($res['list']);die;
        $this->assign('menuList',$res['list']);
        // var_dump($res['list']);
        // $menuData=getAuth($type='menu');
        // if(empty(session('shop_code'))){
        //     foreach($menuData as $k=>$v){
        //         if($v['fid'] == 6 && $v['menu_code'] != 'menu1512029925'){
        //             unset($menuData[$k]);
        //         }
        //     }
        // }else{
        //     foreach($menuData as $k=>$v){
        //         if(session('shop_type') !=2 && ($v['menu_code'] == 'menu1542112060' || $v['menu_code'] == 'menu1542196943')){//非儿童店不显示排程设定和店务菜单
        //             unset($menuData[$k]);
        //         }
        //     }
        // }
        // $menuList=treeData($menuData,$fid=0);
        // var_dump($menuList);die;
        // echo '<pre>';
        // print_r($menuList);die;
        // $this->assign('menuList',$menuList);


        //多地登陆
        $more_login = db_config('more_login_'.session('staff_id'));
        $this->assign('more_login',$more_login);
        $info = cache('staffInfo_'.cookie('staff_id'));
        $this->assign('status',$info['status']);
        //录入必选项配置
        $lrMust = db_config('lr_must_'.session('brandclass_id'));
        $lrMust = trim($lrMust,',');

        //成都网销中心录入客资 ‘获取方式’为必填项
        if(session('shop_code') == 'TSYX13' && !in_array('access_model',explode(',',$lrMust))){

            $lrMust .= ',access_model';
        }

        $this->assign('jslrMust',json_encode(explode(',',$lrMust)));

        //手机配置地址
        $this->assign("patrn",check_tel_arr());
        //手机配置地址
        $this->assign("patrn",check_tel_arr());
        // 兼职岗位
        $positions = session('positions_'.session('staff_id'));
        if(empty($positions)){
            $positions = controller('crm/Customer','lib')->getPositions();
        }
        $this->assign('positions',$positions);

        if(defined('IS_API') && IS_API === true){
            $input = input();
            $this->apiHash = $input['action'];
            if(defined('IS_POST') && IS_POST === true){
                //验证接口加密规范 暂时只支持使用hash调用，后期再考虑可以支持url调用。--songdemei
                //if(!isset($input['method']) || empty($input['method'])){
                    //
                    return $this->checkAPI();
                //}else{
                    /*
                    $apiUrl = $input['action'].'/'.$input['method'];
                    $apiList = db('apilist')->find(array('apiUrl'=>$apiUrl));
                    */ 
                //}
            }
            //ECHO 'base init =-----<<<<<<br/>';
        }else{
            $login = check_login();
            check_call();
            // exit;
            if($login === false){
                if(\think\Request::instance()->isAjax()){
                    //返回未登录错误
                    exit(json_encode(array('code'=>ERR_LOGIN_UNLOGIN,'msg'=>'用户未登录','data'=>array())));
                    // $this->apiError('用户未登录', ERR_LOGIN_UNLOGIN);
                }else{
                    session('return_url',\think\Request::instance()->url(true));
                    // var_dump(session('return_url'));
                    // exit;
                    if(is_weixin() || is_mobile()){
                        $this->redirect('crm/Index/index');
                    }else{
                        //跳转到登录
                        // $module = \think\Request::instance()->module();
                        $this->redirect(url('/index/Index/login'));
                    }
                }
            }else{
                if(is_weixin() || session('login_type') == 'WX'){
                    //微信可访问的URL，非这里面的，直接跳微信首页
                    $module = strtolower(\think\Request::instance()->module());
                    $controller = strtolower(\think\Request::instance()->controller());
                    $action = strtolower(\think\Request::instance()->action());
                    $wxActions = [
                        'wx_index','logout','customertibao','kzdetails','kezitb','jieshaotb','searchcustomers','myqrcode','appaddcustomer','receivecustomer','customertbajax','customerdrop','customerreceive','setnotonlineisfp','basedata','mobile','rankdata','daychangerate','monthchangerate','monthcustomernumber','monthintonumber','monthnewordernumber','monthorderratenumber','brandmobile','update_status','makejdm','jdm','jindianma','wx_update_pwd','edit_pwd','experiencelist','experiencedetail','markhxhome','markresult','mobileorder','searchcity','zhuanorder','zhuanorderxaf','tibaonum','salesnum','markhx','getpackage','visitfeedback','getwxcopypage','wxstatus'
                    ];
                    $wxControllers = [
                        'wexin','report',
                    ];
                    $wxModule = [
                    ];
                    if(!in_array($module, $wxModule)&&
                        !in_array($controller, $wxControllers)&&
                        !in_array($action, $wxActions)){
                        $this->redirect('crm/customer/wx_index');
                    }
                }
                
                /**
                 * 客资录入公共数据
                 */
                if ( db_config('record_day_'.session('shop_code'))=='today' ) {
                    $this->assign('record_day', date('Y-m-d'));
                }else{
                    $this->assign('record_day', '');
                }
                $this->assign('ext_customer_field',getExtCustomerField());
                $this->assign('validArr',getLrValidList());
                $this->assign('only',getLrType(session('shop_code')));
                $this->assign('lrHidden',getLrHidden(session('brandclass_id')));
                // 录入客资必选项
                $this->assign('lrMust',getLrMust(session('brandclass_id'),session('shop_code')));
                $this->assign('sms',db_config('sms_'.session('shop_code')));// 短信账号
                $this->assign('is_send_sms',db_config('is_send_sms_'.session('shop_code'))); //录入时是否发送短信
                $this->assign('add_new_child_customer_page',$this->fetch('../../crm/view/customer/add_new_child_customer'));

                //左侧菜单是催派的话 隐藏客资录入
                $this->assign('controller',strtolower(\think\Request::instance()->controller()));

                //2021-04-25 在线状态 的 显示
                $this->assign('online_status',cookie('status'));
            }
        }
    }
    private function checkAPI() {
        $this->apiParams = input('post.');
        $apiInfo = db('crm_api_list',config('ext.db_api'))
                ->join('crm_api_app', 'crm_api_app.id = crm_api_list.app_id', 'left')
                ->field('crm_api_list.*,crm_api_app.app_name,crm_api_app.app_id,crm_api_app.app_secret,crm_api_app.app_status,crm_api_app.app_type')
                ->where('crm_api_list.hash',  $this->apiHash)
                // ->fetchSql(true)
                ->find();
        // var_dump($apiInfo);
        // exit;
        if(!$apiInfo){
            $this->apiError('接口不存在', -1001);
        }
        $this->apiUrl = $apiInfo['apiUrl'];
        $this->appSecret = $apiInfo['app_secret'];
        $this->appId = $apiInfo['app_id'];
        if($apiInfo['status'] != 1){
            $this->apiError('接口被禁用', -1002);
        }
        if($apiInfo['app_status'] != 1){
            $this->apiError('应用已禁用', -1003);
        }
        // if($apiInfo['accessToken'] == 1){ //强制token验证
            $accessToken = request()->header('ACCESS-TOKEN');
            $param = $this->apiParams;
            $param['accessToken'] = $accessToken;
            $this->apiParams = $param;
            if(!$accessToken){
                $this->apiError('当前接口需要token验证。', ERR_ACCESSTOKEN_EMPTY);
            }
            
            if(!checkAccessToken(config('ext.app_secret'),$accessToken)){
                $this->apiError('AccssToken check error。', ERR_ACCESSTOKEN_ERROR);
            }
        // }
        if($apiInfo['needLogin'] == 1){
            $sessionId = request()->header('SESSION-ID');
            if(!$sessionId){
                $this->apiError('当前接口需要登录才能使用。', ERR_LOGIN_UNLOGIN);
            }
            if(!api_check_login($sessionId)){
                $this->apiError('用户未登录，或登录信息已过期。', ERR_LOGIN_EXPIRED);
            }
        }
    }
    
    function actionLog() {
        
        
        
    }
    public function apiReturn ($data) {
        // $nologUrl = ['Intostore/customerList'];
        if (!in_array($this->apiUrl, $nologUrl)){
            $inData['param'] = $this->apiParams;
            // if (mb_strlen($data) >= 2048) {
            //     $data = '';
            // }
            $inData['return']= $data;
            apiLog(array(
                'api_url'=>  $this->apiUrl,
                'hash'=>  $this->apiHash,
                'data'=> json_encode($inData),
                'api_start_time'=> $this->apiStartTime,//number_format($this->apiStartTime, 4,'.',''),
                'api_end_time'=>  $this->apiEndTime,//number_format($this->apiEndTime,4,'.',''),
                'result_code'=>'200',
            ));
        }
        $ret = array('code'=>200,'msg'=>'','data'=>$data);
        exit(json_encode($ret));
        //return json($data,200);
    }
    public function apiError($msg,$code,$data = []) {
        $ret = array('code'=>$code,'msg'=>$msg,'data'=>$data);
        $nologUrl = ['Intostore/customerList'];
        if (!in_array($this->apiUrl, $nologUrl)){
            $inData['param'] = $this->apiParams;
            $inData['return']['msg'] = $msg;
            $inData['return']['code']= $code;
            $inData['return']['data']= $data;
            apiLog(array(
                'api_url'=>  $this->apiUrl,
                'hash'=>  $this->apiHash,
                'data'=> json_encode($inData),
                'api_start_time'=>  $this->apiStartTime,//number_format($this->apiStartTime,4,'.',''),
                'api_end_time'=>  $this->apiEndTime,//number_format($this->apiEndTime,4,'.',''),
                'result_code'=>$code,
            ));
        }
        send_http_status(500);
        exit(json_encode($ret));
    }
    //侧边栏menu显示
    public function menuList(){


    }
    
}