<?php
/**
 * Copyright: Shanghai NuLang Network Technology Co., Ltd.
 * Faith: Some things do not need others to understand.
 * Project: CoverCMS <Your world, your ambition>
 * License: http://www.svipplus.cn/license/
 * Author: The Rain° <rain@svipplus.cn>
 * File: CategoryItemsListener.php
 * Time: 14:59
 */

namespace app\common\listener;


use app\common\toolKit\CacheKit;
use think\Db;

class CategoryItemsListener
{
    public function run(&$param)
    {
        if (isset($param['action']) && method_exists(new static(), $param['action']) && isset($param['category_id']) && intval($param['category_id']) !== 0) {
            $action = $param['action'];
            $num = 1;
            if (isset($param['num']) && intval($param['num']) !== 0) {
                $num = intval($param['num']);
            }
            $this->$action(intval($param['category_id']), $num);
            CacheKit::updateCategoryCache();
        }
    }

    private function add($categoryId, $num)
    {
        $currentCategory = $this->currentData($categoryId);
        Db::name('category')->where('id', $categoryId)->setInc('items', $num);
        if (intval($currentCategory['parent_id']) !== 0) {
            $this->add($currentCategory['parent_id'], $num);
        }
    }

    private function remove($categoryId, $num)
    {
        $currentCategory = $this->currentData($categoryId);
        Db::name('category')->where('id', $categoryId)->setDec('items', $num);
        if (intval($currentCategory['parent_id']) !== 0) {
            $this->remove($currentCategory['parent_id'], $num);
        }
    }

    private function currentData($categoryId)
    {
        return Db::name('category')->where('id', $categoryId)->find();
    }
}