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

namespace activity;

use algorithm;
use Log;
use StatesHelper;


class recommend_goods
{
    static private $stInstance = null;
    const STORE_ID = 6;
    private $goods_ids;
    const cache_name = 'all_recommend_goods';


    static public function instance()
    {
        if(self::$stInstance == null) {
            self::$stInstance = new recommend_goods();
        }

        if(StatesHelper::fetch_state('recommend_goods')) {
            Log::record("recommend_goods reinit data.",Log::DEBUG);
            self::$stInstance->init();
        }

        return self::$stInstance;
    }

    public function isTakepart($goods_id)
    {
        $goods_id = intval($goods_id);
        if(algorithm::binary_search($this->goods_ids,$goods_id)) {
            return true;
        } else {
            return false;
        }
    }

    public function goods_ids() {
        return $this->goods_ids;
    }

    private function __construct()
    {
    }

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

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

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

        $goods_ids = [];
        $mod = Model('p_booth');
        $list = $mod->getBoothGoodsList(array('store_id' => self::STORE_ID), 'goods_id');
        foreach ($list as $val) {
            $goods_id = intval($val['goods_id']);
            $goods_ids[] = $goods_id;
        }
        sort($goods_ids);

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

        return $data;
    }
}