<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海口快推科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace app\common\controller;
use think\Controller;
use think\Session;
use think\Db;
class Common extends Controller {

    public $session_id;
    public $theme_style = '';
    public $theme_style_path = '';
    public $view_suffix = 'html';
    public $eyou = array();

    public $users_id = 0;
    public $users = array();
    public $usersConfig = [];
    public $usersTplVersion = '';

    /**
     * 析构函数
     */
    function __construct() 
    {
        /*是否隐藏或显示应用入口index.php*/
        if (tpCache('seo.seo_inlet') == 0) {
            \think\Url::root('/index.php');
        } else {
            // \think\Url::root('/');
        }
        /*--end*/
        parent::__construct();
    }    
    
    /*
     * 初始化操作
     */
    public function _initialize() 
    {
        $assignData = [];
        
        // 解决PHP套用Iframe访问导致cookie跨域session失效
        if (in_array($this->request->rootDomain(), ['kuaituiyun.cn'])) {
            // IE浏览器cookie跨域
            header("P3P:CP=CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV");
            // Chrome等浏览器cookie跨域（一定要加上secure，否则SameSite无效）
            @ini_set('session.cookie_samesite', "None;secure");
        }

        session('admin_info'); // 传后台信息到前台，此处可视化用到
        if (!session_id()) {
            Session::start();
        }
        header("Cache-control: private");  // history.back返回后输入框值丢失问题 
        $this->session_id = session_id(); // 当前的 session_id
        !defined('SESSION_ID') && define('SESSION_ID', $this->session_id); //将当前的session_id保存为常量，供其它方法调用
        // 全局配置
        $global = tpCache('global');

        /*站点状态关闭时，所关闭的终端口(pc、mobile)*/
        // $webClosePort = !empty($global['web_close_port']) ? unserialize($global['web_close_port']) : [];
        // $close = 0;
        // if (!empty($webClosePort)) {
        //     if (0 === intval($this->is_mobile) && in_array('pc', $webClosePort)) {
        //         $close = 1;
        //     } else if (1 === intval($this->is_mobile) && in_array('mobile', $webClosePort)) {
        //         $close = 1;
        //     }
        // }
        // if (in_array(MODULE_NAME, ['home']) && !empty($global['web_status']) && $global['web_status'] == 1 && !empty($close)) {}
        /*end*/

        $read_cache = true;
        // 支付异步回调不走页面缓存，避免导致异步回调失败
        $_ajax = $this->request->param('_ajax');
        $inputXml = file_get_contents("php://input");
        if (!empty($inputXml) && !isset($_ajax)) {
            // 解析参数，转换数组
            $index = strstr($inputXml, 'hupijiaoPay');
            if (!empty($index)) {
                parse_str($inputXml, $jsonArr);
            } else {
                $jsonArr = json_decode(json_encode(@simplexml_load_string($inputXml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
            }
            // 是否与支付成功
            if (!empty($jsonArr['attach'])) {
                // 解析判断参数是否为微信支付
                $attach = explode('|,|', $jsonArr['attach']);
                if ((!empty($attach[1]) && 'is_notify' == $attach[1]) || (!empty($attach[3]) && 'hupijiaoPay' == $attach[3])) $read_cache = false;
            }
        }

        /*关闭网站*/
        $is_notify = $this->request->param('is_notify');
        if ((!empty($is_notify) && 1 === intval($is_notify)) || empty($read_cache)) {
            // 支付异步回调....
        } else {
            if (in_array(MODULE_NAME, ['home'])) {
                // 商城关闭，所有终端都访问不了
                if (!empty($global['web_status']) && 1 === intval($global['web_status'])) {
                    $web_status_text = isset($global['web_status_text']) ? $global['web_status_text'] : '网站暂时关闭，维护中……';
                    die("<div style='text-align:center; font-size:20px; font-weight:bold; margin:50px 0px;'>{$web_status_text}</div>");
                }
                // H5关闭时的提示文案
                else if (!empty($global['web_status_h5']) && 1 === intval($global['web_status_h5'])) {
                    $web_status_h5_text = isset($global['web_status_h5_text']) ? $global['web_status_h5_text'] : 'H5端商城暂时关闭，维护中……';
                    die("<div style='text-align:center; font-size:20px; font-weight:bold; margin:50px 0px;'>{$web_status_h5_text}</div>");
                }
                // PC关闭
                else if (!empty($global['web_status_pc']) && 1 === intval($global['web_status_pc'])) {
                    if (isset($global['web_status_h5']) && 0 === intval($global['web_status_h5'])) {
                        // PC关闭，H5开启则跳转到H5链接
                        $this->redirect($this->request->domain() . $this->root_dir . '/h5/');
                    } else {
                        // PC关闭时的提示文案
                        $web_status_pc_text = isset($global['web_status_pc_text']) ? $global['web_status_pc_text'] : 'PC端商城暂时关闭，维护中……';
                        die("<div style='text-align:center; font-size:20px; font-weight:bold; margin:50px 0px;'>{$web_status_pc_text}</div>");
                    }
                }
            }
        }
        /*--end*/

        // 会员中心相关逻辑
        if (!empty($global['web_users_switch'])) {
            $this->usersConfig = getUsersConfigData('all');
            $this->usersTplVersion = getUsersTplVersion();

            $times = getTime();
            /*会员登录有效期逻辑*/
            $users_login_expire = 0;
            if (session('?users_id')) {
                $users_login_expiretime = !empty($this->usersConfig['users_login_expiretime']) ? intval($this->usersConfig['users_login_expiretime']) : 3600;
                $users_login_expire = (int)session('users_login_expire'); //最后登录时间
                if (empty($users_login_expire)) {
                    $users_login_expire = $times;
                    session('users_login_expire', $users_login_expire);
                }
                // 招聘插件会员中心导航内置代码 start 
                if (file_exists('./weapp/Recruits/model/RecruitsModel.php')) {
                    $recruitsModel = new \weapp\Recruits\model\RecruitsModel;
                    $recruitsModel->common_initialize($assignData, $this->usersConfig);
                }
                // 招聘插件会员中心导航内置代码 end
            }
            /*end*/
            if ( !session('?users_id') || (!empty($users_login_expire) && ($times - $users_login_expire) >= $users_login_expiretime) ) {
                session('users_id', null);
                session('users', null);
                cookie('users_id', null);
            } else if ( session('?users_id') && ($times - $users_login_expire) < $users_login_expiretime ) {
                session('users_login_expire', getTime()); // 登录有效期
            }
        }
        $this->assign('usersConfig', $this->usersConfig);
        $this->assign('usersTplVersion',$this->usersTplVersion);

        /*强制微信模式，仅允许微信端访问*/
        $shop_force_use_wechat = getUsersConfigData('shop.shop_force_use_wechat');
        if (!empty($shop_force_use_wechat) && 1 == $shop_force_use_wechat  && !isWeixin() && in_array(MODULE_NAME, ['home'])) {
            $html = "<div style='text-align:center; font-size:20px; font-weight:bold; margin:50px 0px;'>网站仅微信端可访问</div>";
            $WeChatLoginConfig = getUsersConfigData('wechat.wechat_login_config') ? unserialize(getUsersConfigData('wechat.wechat_login_config')) : [];
            if (!empty($WeChatLoginConfig['wechat_name'])) $html .= "<div style='text-align:center; font-size:20px; font-weight:bold; margin:50px 0px;'>关注微信公众号：".$WeChatLoginConfig['wechat_name']."</div>";
            if (!empty($WeChatLoginConfig['wechat_pic'])) $html .= "<div style='text-align:center; font-size:20px; font-weight:bold; margin:50px 0px;'><img style='width: 400px; height: 400px;' src='".$WeChatLoginConfig['wechat_pic']."'></div>";
            die($html);
        }
        /*END*/

        $this->global_assign($global); // 获取网站全局变量值
        $this->view_suffix = config('template.view_suffix'); // 模板后缀htm
        $this->theme_style = THEME_STYLE; // 模板标识
        $this->theme_style_path = THEME_STYLE_PATH; // 模板目录
        //全局变量
        $this->eyou['global'] = $global;

        /*电脑版与手机版的切换*/
        $v = I('param.v/s', 'pc');
        $v = trim($v, '/');
        $this->assign('v', $v);
        /*--end*/

        $hotSearchWordsList = model('SearchHot')->getKeywordsList();
        $hotSearchWordsList = !empty($hotSearchWordsList) ? get_arr_column($hotSearchWordsList, 'word') : [];
        $this->assign('hotSearchWordsList', json_encode($hotSearchWordsList));
        
        $assignName2 = $this->arrJoinStr(['cGhwX3Nlcn','ZpY2VtZWFs']);
        $assignValue2 = tpCache('php.'.$assignName2);
        $this->assign($assignName2, $assignValue2);

        // 判断是否开启注册入口
        $users_open_register = getUsersConfigData('users.users_open_register');
        $this->assign('users_open_register', $users_open_register);
        
        // 默认主题颜色
        if (!empty($this->usersConfig['theme_color'])) {
            $theme_color = $this->usersConfig['theme_color'];
        } else {
            if ($this->usersTplVersion == 'v1') {
                $theme_color = '#ff6565';
            } else {
                $theme_color = '#fd8a27';
            }
        }
        $this->usersConfig['theme_color'] = $theme_color;
        $this->assign('theme_color', $theme_color);

        // 存在游客免登录查询则执行
        if (is_dir('./weapp/FreeLogin/')) {
            // 未登录 且 存在指定访问的控制器和方法 则执行
            $freeLoginRow = model('Weapp')->getWeappList('FreeLogin');
            if (!empty($freeLoginRow['status']) && 1 == $freeLoginRow['status']) {
                $unifyController = new \weapp\FreeLogin\controller\FreeLogin;
                $unifyController->freeLoginHandle($this->usersConfig);
            }
        }

        $this->assign($assignData);

        // 站内消息
        $this->users_id = session('users_id');
        if ($this->usersTplVersion != 'v1' && !empty($this->users_id)) {
            // 从notice表里同步新的数据到notice_read表
            $this->update_notice_data();
            // 查询会员站内通知数据
            $where = [
                'is_del' => 0,
                'users_id' => $this->users_id,
            ];
            $usersNoticeNum = Db::name('users_notice_read')->field('id, is_read')->where($where)->select();
            $result = [
                // 未读消息数
                'unread_num' => 0,
                // 总消息数
                'allNotice_num' => 0,
            ];
            foreach ($usersNoticeNum as $key => $value) {
                $result['allNotice_num']++;
                if (0 === intval($value['is_read'])) $result['unread_num']++;
            }
            $this->assign($result);
        }
    }

    // 从notice表里同步新的数据到notice_read表
    public function update_notice_data()
    {
        //查接收消息通知的会员id
        $users_id = $this->users_id;
        $last_read_notice_id = Db::name('users_notice_read')->where(['users_id'=>$users_id])->max("notice_id");

        $no_add_data = Db::name('users_notice')
            ->field("id as notice_id,add_time,update_time")
            ->where("users_id = '' OR users_id = '{$users_id}' OR FIND_IN_SET('{$users_id}', users_id)")
            ->where(['id'=>['GT',$last_read_notice_id]])
            ->order("id ASC")
            ->select();

        if (!empty($no_add_data)) {
            foreach ($no_add_data as $k=>$v) {
                $no_add_data[$k]['users_id'] = $users_id;
            }
            Db::name('users_notice_read')->insertAll($no_add_data);
        }
    }

    /**
     * 获取系统内置变量 
     */
    public function global_assign($globalParams = [])
    {
        if (empty($globalParams)) {
            $globalParams = tpCache('global');
        }
        $this->assign('global', $globalParams);
    }
}