<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 16/8/16
 * Time: 下午4:33
 */

namespace activity;
use Log;
use StatesHelper;


class recommend_combo
{
    static private $stInstance = null;
    //goods_id 可能包含多个商品形成一个组合
    private $goods_combos;
    const cache_name = 'all_recommend_combo';

    private function __construct() {
    }
    static public function instance()
    {
        if(self::$stInstance == null) {
            self::$stInstance = new recommend_combo();
        }
        if(StatesHelper::fetch_state('recommend_combo')) {
            Log::record("recommend_combo reinit data.",Log::DEBUG);
            self::$stInstance->init();
        }

        return self::$stInstance;
    }

    private function init()
    {
       $data = $this->read_cache();
        $this->goods_combos = $data['goods_combos'];
    }

    private function read_cache()
    {
        $prefix = 'mb_activity';
        $items = rcache(self::cache_name, $prefix);

        if (!empty($items)) {
            return unserialize($items['data']);
        }

        $goods_combos = [];

        $mod = Model('goods_combo');
        $list = $mod->getGoodsComboList(array());
        foreach ($list as $val)
        {
            $gid = intval($val['goods_id']);
            $cgid   = intval($val['combo_goodsid']);

            if(isset($goods_combos[$gid])) {
                $goods_combos[$gid][] = $cgid;
            } else {
                $goods_combos[$gid] = [];
                $goods_combos[$gid][] = $cgid;
            }
        }

        $data = array('goods_combos' => $goods_combos);
        wcache(self::cache_name, array('data' => serialize($data)), $prefix);

        return $data;
    }

    public function have_combo($goods_id)
    {
        $goods_id = intval($goods_id);
        if(isset($this->goods_combos[$goods_id])) {
            return true;
        } else {
            return false;
        }
    }

    public function combo_goods($goods_id)
    {
        $goods_id = intval($goods_id);
        if(isset($this->goods_combos[$goods_id])) {
            return $this->goods_combos[$goods_id];
        } else {
            return false;
        }
    }
}