<?php namespace Place\Lib;
use Dever;
class Cate
{
    public function __construct($app = 'content')
    {
        $this->db = Dever::db('cate', $app);
    }

    # 获取所有分类信息
    public function getData()
    {
        $data['cate_parent'] = $this->getList();
        $data['cate_child'] = array();
        $data['cate_id'] = Dever::input('cate_id');
        if ($data['cate_id']) {
            $cate = $this->getInfo($data['cate_id']);
            $data['cate'] = $cate;
            if ($cate) {
                $cate['name'] = '全部';
                if ($cate['parent_id'] <= 0) {
                    $parent_id = $cate['id'];
                } else {
                    $parent_id = $cate['parent_id'];
                }
                if ($data['cate_parent']) {
                    foreach ($data['cate_parent'] as &$v) {
                        $v['selected'] = 2;
                        if ($v['id'] == $parent_id) {
                            $v['selected'] = 1;
                        }
                    }
                }
                $data['cate_child'][] = array('id' => $parent_id, 'name' => '全部');
                $data['cate_child'] = array_merge($data['cate_child'], $this->getList($parent_id, 10));
                if ($data['cate_child']) {
                    foreach ($data['cate_child'] as &$v) {
                        $v['selected'] = 2;
                        if ($v['id'] == $cate['id']) {
                            $v['selected'] = 1;
                        }
                    }
                }
            }
        } else {
            $data['cate_child'] = $this->getList(array('>', 0), 10);
            if ($data['cate_child']) {
                foreach ($data['cate_child'] as &$v) {
                    $v['selected'] = 2;
                }
            }
        }
        return $data;
    }

    # 获取分类列表
    public function getList($parent_id = 0, $num = false)
    {
        $set = array();
        if ($num) {
            $set['limit'] = '0, ' . $num;
        }
        return $this->db->select(array('parent_id' => $parent_id, 'status' => 1), array('col' => 'id,name,icon,cdate,parent_id,`desc`'), $set);
    }

    # 获取分类信息
    public function getInfo($id)
    {
        return $this->db->find($id);
    }
}