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

namespace activity;

use Log;
use StatesHelper;

class gift_item
{
    public $goods_id;
    public $amount;
}

class goods_gift
{
    static private $stInstance = null;
    private $contents;
    const cache_name = 'all_goods_gift';

    private function __construct()
    {
    }

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

        return self::$stInstance;
    }

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

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

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

        $mod = Model('goods_gift');
        $list = $mod->getGoodsGiftList(array());

        $contents = [];
        foreach ($list as $val)
        {
            $goods_id = intval($val['goods_id']);
            $giftid = intval($val['gift_goodsid']);
            $amount = intval($val['gift_amount']);

            if(isset($contents[$goods_id]) == false) {
                $contents[$goods_id] = [];
            }
            $item = array('gift_goods_id' => $giftid,'amount' => $amount);
            $contents[$goods_id][] = $item;
        }

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

        return $data;
    }

    public function gifts($goods_id)
    {
        $goods_id = intval($goods_id);
        if(isset($this->contents[$goods_id])) {
            return $this->contents[$goods_id];
        } else {
            return false;
        }
    }
    public function goods_giftids($goods_id)
    {
        $goods_id = intval($goods_id);
        if(isset($this->contents[$goods_id]))
        {
            $gids = [];
            $content = $this->contents[$goods_id];
            foreach ($content as $gift) {
                $gids[] = $gift['gift_goods_id'];
            }
            return $gids;
        } else {
            return false;
        }
    }

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