<?php

namespace app\api\controller;

use app\common\model\store_branch_product\StoreBranchProduct;
use app\common\model\store_category\StoreCategory;
use think\facade\Db;
class DataController  extends BaseApiController
{
    public $notNeedLogin = ['index', 'app_update', 'test','show'];

    public static function updateGoodsclass($cate_id, $store_id = 0, $type = 0)
    {
        $one = StoreCategory::where('id', $cate_id)->find();
        if ($one) {
            //查二级分类
            $two = StoreCategory::where('id', $one['pid'])->find();
            if ($two) {
                if ($two['pid'] != 0) {
                    self::cate_update($cate_id, $two['id'], $store_id, 3);
                    self::cate_update($two['id'], $two['pid'], $store_id, 2);
                    self::cate_update($two['pid'], 0, $store_id, 1);
                } else {
                    if ($one['pid'] == 0) {
                        self::cate_update($one['id'], 0, $store_id, 1);
                    } else {
                        self::cate_update($one['id'], $one['pid'], $store_id, 2);
                        self::cate_update($one['pid'], 0, $store_id, 1);
                    }
                }
            }
        }
    }

    public static function cate_update($cate_id = 0, $pid = 0, $store_id = 0, $level = 1)
    {
        $find = Db::name('store_product_cate')->where(['store_id' => $store_id, 'cate_id' => $cate_id, 'level' => $level])->find();
        if ($find) {
            Db::name('store_product_cate')->where('id', $find['id'])->inc('count', 1)->update();
        } else {
            Db::name('store_product_cate')->insert(['pid' => $pid, 'store_id' => $store_id, 'cate_id' => $cate_id, 'count' => 1, 'level' => $level, 'create_time' => time(), 'update_time' => time()]);
        }
    }


    public static function show()
    {
        //处理分类缺失
        $store_id = 23;
        $data = StoreBranchProduct::where('store_id', $store_id)
            ->field('cate_id,store_id')
            ->select()->toArray();
        foreach ($data as $value){
            self::updateGoodsclass($value['cate_id'], $value['store_id']);
        }

        d($data);


    }

}