<?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() {
        //判断如果配置完成生成过Suxuan.php就直接重定向
        /*
        if(!file_exists(APP_PATH.'../runtime'.DS.'Suxuan.php'))
        {
            $this->redirect('install/index/index');
            exit();
        }
        //
        //判断是否在有效期        
        $lib = new \app\index\lib\Lib();
        $res = $lib->check_auth_key();
        if ($res == 202) {
            $this->error("产品已过期");
        }else if ($res == 203) {
            $this->error("产品验证码失败");
        }
        //*/
        testTime(__FILE__,__LINE__);
        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(session('productid') == '3504328677'){//天长地久大屏
                $auth = controller('crm/Tcdj', 'lib')->checkBigScreenAuth();
                if($auth === true){
                    $this->assign('bgscreen','/crm/tcdj');
                }
            }
        }
        testTime(__FILE__,__LINE__);
        if(\think\Request::instance()->isPost()){
            defined('IS_POST') or define('IS_POST', true);
        }testTime(__FILE__,__LINE__);
        $erp = is_install('sx_erp');testTime(__FILE__,__LINE__);
        $this->assign('erp',$erp);
        $order_url = config('order_url');
        $this->assign('order_url',$order_url ? $order_url : 'orderManager');
        $call = db('s_call_center')->select();
        if($call){
            $call_id =  db_config('call_id');
            if($call_id){
                $call_name = db('s_call_center')->where('id',$call_id)->value('call_name');
                $this->assign('callCenter',$call_name);
            }
            $this->assign('call',$call);
            //坐席配置权限
            if(SYSTEM_AUTH_ADMIN || check_right('menu1561718791')){
                $this->assign('callMan',1);
            }
        }

        //2021-11-11 menu表换成menu.php
        // $res = session('crm_menu');
        $menu = include(APP_PATH.'menu.php');
        $menuCustomize = include(APP_PATH.'menu_customize.php');
        $newMenu = getAuthMenu($menu,'menu',$menuCustomize);

        // print_r($res['list']);die;
        $this->assign('menuList',$newMenu['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]);
        //         }
        //     }
        // }
        // // var_dump($menuData);
        // $menuList=treeData($menuData,$fid=0);
        // // var_dump($menuList);die;
        // // 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']);
        //手机配置地址
        $this->assign("patrn",check_tel_arr());
        //录入必选项配置
        $lrMust = db_config('lr_must_'.session('brandclass_id'));
        $lrMust = trim($lrMust,',');
        $this->assign('jslrMust',json_encode(explode(',',$lrMust)));
        // 兼职岗位
        $positions = session('positions_'.session('staff_id'));
        if(empty($positions)){
            $positions = controller('crm/Customer','lib')->getPositions();
        }
        $this->assign('positions',$positions);
        //查看一年内客资
        if(check_right('menu1546854888') && session('main_work_type') != SYSTEM_AUTH_ADMIN){
            $this->assign('yearCus',1);
        }else{
            $this->assign('yearCus',0);
        }
        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{
                    $action = strtolower(\think\Request::instance()->action());
                    if ($action != "getWxCopyPageEwm") {
                        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($module.'/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','receivecustomerdetail','getwxcopypage','wxstatus','index','data'
                    ];
                    $wxControllers = [
                        'wexin','bigscreen'
                    ];
                    $wxModule = [
                        'mobile'
                    ];
                    if(!in_array($module, $wxModule)&&
                        !in_array($controller, $wxControllers)&&
                        !in_array($action, $wxActions)){
                        $this->redirect('crm/customer/wx_index');
                    }
                }
            }
        }
        
        if($this->request->module() == 'crm') {
            //客户地址
            $data['type'] = 1;
            $address = controller("\app\crm\lib\Customer")->address($data);
            $this->assign("address", $address);
            
            // 新版新增客资页面 开始 20200928
            // 录入客资必选项
            $this->assign('lrMust', $this->getLrMust());
            // 录入必选项定制 录入时显示 20200106
            if (ini('lr_must.shop_code') == session('shop_code')) {
                // 判断字段是否存在
                $column = isColumnExist(array('table' => 'c_customerinfo', 'column' => ini('lr_must.field')));
                if ($column) {
                    $select = explode(',', ini('lr_must.select'));
                }
            }
            // 录入客资隐藏项
            $lrHidden = $this->getLrHidden();
            $this->assign('lrHidden', $lrHidden);
            // 先暂时这样 后面想想有没有其他的办法
            $allLrSelect = [
                'channel_info',// 来源渠道
                'customer_channel',// 渠道名称
                'access_model',// 获取方式
                'consultation_type',// 消费类型
                'customer_intention',// 客户意向
                'customer_cource',// 客户来源
                'tracksign',// 客资标记
                'consulation_shop',// 意向店面
                'is_valid',// 客资状态
            ];
            foreach ($allLrSelect as $key => $value) {
                if (in_array($value, $lrHidden)) {
                    unset($allLrSelect[$key]);
                }
            }
            $allLrSelect = implode(',', $allLrSelect);
            $this->assign('all_lr_select', $allLrSelect);
            // 标记有效 客资状态 是否隐藏 应该根据当前 员工的权限
            $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;
            }
            $this->assign('validArr', $validArr);
            // 客资录入类型  查看设定
            $customer_type = explode(',', db_config('customer_type_' . session('shop_code')));
            $only = '';
            foreach ($customer_type as $key => $value) {
                if (!$value) { // 如果没有设定
                    $mc = new \app\common\lib\mcInterface();
                    $shopInfo = $mc->getShopInfo(array('shop_code' => session('shop_code')));
                    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';
            }
            $this->assign('only', $only);
            // 介绍人是否可输入
            $mobile_input = db_config('mobile_input_' . session('shop_code'));
            $this->assign("mobile_input", $mobile_input);
            $this->assign('sms',db_config('sms_'.session('shop_code')));//短信账号
            $this->assign('is_send_sms',db_config('is_send_sms_'.session('shop_code')));//录入时是否发送短信
            
            // 输出页面
            $ready_marry_day = controller("crm/Customer", "lib")->ready_marry_day(array('brandclass_id' => session('brandclass_id')));
            $this->assign('ready_marry_day', $ready_marry_day);
            $this->assign('add_new_customer_page', $this->fetch('../../crm/view/customer/add_new_customer'));
            // 新版新增客资页面 结束
            testTime(__FILE__,__LINE__);
        }

        testTime(__FILE__,__LINE__);
    }
    // 获取客资录入 必选项
    public function getLrMust(){
        // 录入必选项配置
        $lrMust = db_config('lr_must_'.session('brandclass_id'));
        $lrMust = trim($lrMust,',');
        $lrMust = explode(',',$lrMust);
        return $lrMust;
    }
    // 获取客资录入 隐藏项
    public function getLrHidden(){
        $hidden = db_config('lr_hidden_'.session('brandclass_id'));
        $hidden = trim($hidden,',');
        $lrHidden = explode(',',$hidden);
        return $lrHidden;
    }
    private function checkAPI() {
        $this->apiParams = input('post.');
        $apiInfo = db('apiList',config('ext.db_api'))
                ->join('api_app', 'api_app.id = api_list.app_id', 'left')
                ->field('api_list.*,api_app.app_name,api_app.app_id,api_app.app_secret,api_app.app_status,api_app.app_type')
                ->where('api_list.hash',  $this->apiHash)
                ->find();
        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验证
        if ($apiInfo['app_type'] == 1){
            $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);
            }
        }else{
            $accessToken = request()->header('ACCESS-TOKEN');
            $param = $this->apiParams;
            $param['accessToken'] = $accessToken;
            $this->apiParams = $param;
            if (!$accessToken) {
                $this->apiError('当前接口需要token验证。', ERR_ACCESSTOKEN_EMPTY);
            }

            if (!checkAccessToken($apiInfo['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(){


    }
    
}