<?php namespace Cate\Api;
use Dever;
class Goods
{
    # 导入数据
    public function import_commit(){}
    public function import()
    {
        $config = Dever::config('goods_cate')['json'];
        $config = Dever::json_decode($config);
        foreach ($config as $k => $v) {
            if ($v) {
                $v = array_values($v);
                $t = count($v);
                if ($t == 3) {
                    $level_2_sort = 0;
                    $level_3_sort = 0;
                    $level_1 = $this->create(1, $k, $v[0]);
                    $level_2 = $this->create(2, $level_2_sort, $v[1], $level_1);
                    $this->create(3, $level_3_sort, $v[2], $level_2, $level_1);
                } elseif ($t == 2) {
                    $level_2_sort += 1;
                    $level_2 = $this->create(2, $level_2_sort, $v[0], $level_1);
                    $this->create(3, $level_3_sort, $v[1], $level_2, $level_1);
                }
            }
        }
        return 'ok';
    }

    private function create($level, $sort, $name, $parent_id = false, $top_id = false)
    {
        $sort += 1;
        if ($level == 3 && strstr($name, '/')) {
            $name = explode('/', $name);
            foreach ($name as $k => $v) {
                $this->create($level, $k, $v, $parent_id, $top_id);
            }
            return;
        }
        $data['sort'] = $sort;
        if ($name == '其他') {
            $data['sort'] = 10000;
        }
        $data['name'] = $name;
        if ($parent_id) {
            $data['parent_id'] = $parent_id;
        }
        if ($top_id) {
            $data['top_id'] = $top_id;
            $data['parent'] = $data['top_id'] . ',' . $data['parent_id'];
        }
        $icon = Dever::load('icon', 'cate')->get($data['name']);
        if ($icon) {
            $data['icon_id'] = $icon['id'];
        }
        $db = Dever::db('goods_level_' . $level);
        $info = $db->find($data);
        if (!$info) {
            return $db->insert($data);
        }
        return $info['id'];
    }
}