class BaseController extends Controller { //当前用户 protected $customer_id = 0; protected $country_code = 'US'; protected $customer_info = []; protected $categoryList = []; protected $country_list = []; protected $productCategory = []; protected $nav_header = []; protected $nav_footer = []; public function __construct() { parent::__construct(); } // 初始化 protected function _initialize() { parent::_initialize(); if ($this->check_true_login()) { $customer_info = json_decode(Cookie::get('c'), true); $this->view->assign('customer_info', $customer_info); $this->customer_id = $customer_info['id']; $this->customer_info = $customer_info; } else { $this->_logout(); } $website_email = (string) Config::get('website_email'); $this->view->assign('website_email', $website_email); $website_phone = (string) Config::get('website_phone'); $this->view->assign('website_phone', $website_phone); $business_email = (string) Config::get('business_email'); $this->view->assign('business_email', $business_email); $this->view->assign('seo_title', (string) Config::get('website_seo_title_us')); $this->view->assign('seo_keyword', (string) Config::get('website_seo_keyword')); $this->view->assign('seo_description', (string) Config::get('website_seo_description')); //$this->categoryList = $this->cacheGet('productCategoryList'); if (empty($this->productCategory)) { // $this->categoryList = Loader::model('ProductCategory')->getList(['stat' => 0, 'siteid' => $this->siteid,'isshow'=>1, 'country_code' => $this->country_code], ['sort' => 'asc', 'id' => 'asc'], ['id', 'pid', 'haschild', 'name', 'shortname', 'sort', 'description', 'isshow', 'recommend', 'picture', 'icon', 'image', 'm_icon', 'unique_id']); $this->categoryList = \think\Db::name('product_category')->alias('pc') ->field([ 'pc.id', 'pc.pid', 'pc.haschild', 'pc.name', 'pc.shortname', 'pc.sort', 'pc.description', 'pc.isshow', 'pc.recommend', 'pc.picture', 'pc.icon', 'pc.image', 'pc.m_icon', 'pc.unique_id' ]) ->where('pc.stat', '=', 0) ->where('pc.siteid', '=', $this->siteid) ->where('pc.isshow', '=', 1) ->where('pc.haschild', '=', 0) ->where('pc.country_code', '=', $this->country_code) ->whereExists(function ($query) { $query->name('product')->alias('p') ->where('p.stat', '=', 0) ->where('p.is_show', '=', 0) ->where('p.country_code', '=', $this->country_code) ->where('p.cid=pc.id'); }) ->union(function ($query) { $query->name('product_category')->alias('uni_pc') ->field([ 'uni_pc.id', 'uni_pc.pid', 'uni_pc.haschild', 'uni_pc.name', 'uni_pc.shortname', 'uni_pc.sort', 'uni_pc.description', 'uni_pc.isshow', 'uni_pc.recommend', 'uni_pc.picture', 'uni_pc.icon', 'uni_pc.image', 'uni_pc.m_icon', 'uni_pc.unique_id' ]) ->where('uni_pc.stat', '=', 0) ->where('uni_pc.siteid', '=', $this->siteid) ->where('uni_pc.isshow', '=', 1) ->where('uni_pc.haschild', '=', 1) ->where('uni_pc.country_code', '=', $this->country_code); }) ->order(['sort' => 'asc', 'id' => 'asc']) ->select(); $this->cacheTag('ProductCategoryTag')->set('productCategoryList', $this->categoryList); } $this->productCategory = $this->buildTreeForCategory($this->categoryList, 0); if ($this->cacheHas('country_list')) { $this->country_list = $this->cacheGet('country_list'); } else { $this->country_list = model('country')->where(['stat' => 0])->order(['sort' => 'asc'])->select(); $this->cacheSet('country_list', $this->country_list, 3600); } $this->view->assign('country_list', $this->country_list); //搜索推荐产品 $search_views = Loader::model('Product')->where(['stat' => 0, 'siteid' => $this->siteid,'is_show'=>0, 'country_code' => $this->country_code])->limit(3)->order(['sort' => 'asc'])->select(); $this->view->assign('popular_list', $search_views); //$historyList = getBannerList(79, 5); $historyList = Loader::model('banner')->getList(['typeid'=>79,'stat' => 0, 'country_code' => COUNTRY_CODE], ['sort' => 'asc', 'id' => 'desc'], array('*'), 3); $this->view->assign('historyList', $historyList); //echo "
=="; print_r($historyList);
        //导航
        $navigation =self::navInit();
        $this->nav_header = $navigation['header'];
        $this->nav_footer = $navigation['footer'];
        $this->assign('nav_header', $this->nav_header);
        $this->assign('nav_footer', $this->nav_footer);       
        
        $product_country_code = "products_".strtolower($this->country_code)."_color";
        $productColor = config($product_country_code);
        $this->view->assign('productColor', $productColor);
        //echo $product_country_code."
=="; print_r($this->nav_header);die;
        
        //echo Loader::model('banner')->getlastsql();
        $this->view->assign('productCategory', $this->productCategory);
        $this->view->assign('allCategoryList', $this->categoryList);
    }

    // 组装分类树状结构
    private function buildTreeForCategory($data, $pid = 0)
    {
        $tree = [];
        foreach ($data as $val) {
            if ($val['pid'] == $pid) {
                $children = $this->buildTreeForCategory($data, $val['id']);
                if (!empty($children)) {
                    $val['child'] = $children;
                }
                if (empty($children) && $val['haschild'] == 1) {
                    continue;
                }
                $tree[] = $val;
            }
        }

        return $tree;
    }

    //导航初始化
    private function navInit(){
        // 读取缓存数据
        //$header = $this->cacheGet('cache_common_nav_header_key');
        //$footer = $this->cacheGet('cache_common_nav_footer_key');
        
        // 导航模型
        $field = array('id', 'pid', 'name', 'url', 'value', 'data_type', 'is_new_window_open');
        
        // 缓存没数据则从数据库重新读取,顶部菜单
        //if(empty($header))
        //{
            $headerData = Loader::model('Navigation')->field($field)->where(array('nav_type'=>'header', 'stat'=>0, 'pid'=>0, 'country_code' => COUNTRY_CODE))->order('sort')->select();
            $header = self::navDataDealWith($headerData);
            if(!empty($header))
            {
                foreach($header as &$v)
                {
                    $childData = Loader::model('Navigation')->field($field)->where(array('nav_type'=>'header', 'stat'=>0, 'pid'=>$v['id'], 'country_code' => COUNTRY_CODE))->order('sort')->select();    
                    $v['items'] = self::navDataDealWith($childData);
                }
            }
            //$this->cacheSet('cache_common_nav_header_key', $header, 3600);    
           
       // }  
        
        // 底部导航
        //if(empty($footer))
       // {
            $footerdata = Loader::model('Navigation')->field($field)->where(array('nav_type'=>'footer', 'stat'=>0, 'pid'=>0, 'country_code' => COUNTRY_CODE))->order('sort')->select();
            $footer = self::navDataDealWith($footerdata);
            if(!empty($footer))
            {
                foreach($footer as &$v)
                {
                    $childData = Loader::model('Navigation')->field($field)->where(array('nav_type'=>'footer', 'stat'=>0, 'pid'=>$v['id'], 'country_code' => COUNTRY_CODE))->order('sort')->select();    
                    $v['items'] = self::navDataDealWith($childData);
                }
            }            
            //$this->cacheSet('cache_common_nav_footer_key', $footer, 3600);    
        //}

        return [
            'header' => $header,
            'footer' => $footer,
        ];        
    }
    /**
     * [NavDataDealWith 导航数据处理]
     * @author   martin
     * @version  0.0.1
     * @datetime 2023-11-23T21:36:46+0800
     * @param    [array]      $data [需要处理的数据]
     * @return   [array]            [处理好的数据]
     */
    public function NavDataDealWith($data)
    {
        if(!empty($data) && is_array($data))
        {
            foreach($data as $k=>&$v)
            {
                // url处理
                switch($v['data_type'])
                {
                    // 文章分类
                    case 'article':
                        $v['url'] = 'article/detail/'.$v['value'].'.html';
                        break;

                    // 博客
                    case 'blog':
                        $v['url'] = 'blog/detail/id/'.$v['value'].'.html';
                        break;

                    // 商品分类
                    case 'goods_category':
                        $category = Loader::model('ProductCategory')->getRow(['stat' => 0, 'id' => $v['value'], 'country_code' => $this->country_code], null, ['id' => 'asc']);
                        if (empty($category)) {
                            continue;
                        }
                        if($category['pid'] == 0) {
                            $v['url'] = '/product/catelists/'.$v['value'].'.html';
                        }
                        else{
                            $v['url'] = '/product/subcategory/'.$v['value'].'.html';
                        }                        

                        break;
                }
                
               $data[$k] = $v;
            }
            unset($v);
        }
        
        return $data;
    }

    /**
     * 节点遍历
     * @param $list
     * @param string $pk
     * @param string $pid
     * @param string $child
     * @param int $root
     * return array
     */
    protected function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'child', $root = 0) {
        //dump($root);die;
        //header('content-type:text/html;charset=utf-8;');
        // 创建Tree
        $tree = [];
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = [];
            foreach ($list as $key => $data) {
                $list[$key] = is_array($data) ? $data : $data->toArray();
                $refer[$data[$pk]] = & $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] = & $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent = & $refer[$parentId];
                        $parent[$child][] = & $list[$key];
                    }
                }
            }
        }
        return $tree;
    }

    private function check_login_token($customer_id, $curr_time, $p)
    {
        $expire = 86400 * 30;
        if (time() - $curr_time > $expire)
            return false;

        $temp_p = $this->make_pwd($customer_id, $curr_time);
        if ($temp_p !== $p)
        {
            return false;
        }

        return true;
    }

    protected function set_login_token($customer_info)
    {
        $curr_time = time();
        $p = $this->make_pwd($customer_info['id'], $curr_time);

        $customer_info['telephone'] = $customer_info['telephone'] != '' ? substr_replace($customer_info['telephone'], '****', 3, 4) : '';
        $customer_info['email'] = $customer_info['email'] != '' ? substr_replace($customer_info['email'], '****', 2, 6) : '';
        $customer_info['have_pwd'] = $customer_info['password'] != '' ? 1 : 0;
        unset($customer_info['password']);

        $customer_info['ct'] = $curr_time;
        $customer_info['p'] = $p;

        $expire = 86400 * 30;
        Cookie::init(['expire' => $expire]);
        Cookie::set('c', $customer_info);
    }

    private function make_pwd($customer_id, $curr_time)
    {
        $salt = 'Orico2019.';
        $p = md5(md5($customer_id . $curr_time . $salt));

        return $p;
    }

    private function check_login()
    {
        return Cookie::has('c');
    }

    protected function check_true_login()
    {
        //  校验用户是否登录,且校验cookie合法性
        if (!$this->check_login())
        {
            return false;
        }

        $customer_info = json_decode(Cookie::get('c'), true);
        
        $ct = isset($customer_info['ct']) ? $customer_info['ct'] : '';
        $p = isset($customer_info['p']) ? $customer_info['p'] : '';
        return $this->check_login_token($customer_info['id'], $ct, $p);
    }

    protected function _logout()
    {
        if (Cookie::has('c'))
            Cookie::delete('c');

        $this->customer_id = 0;
    }

}