<?php
/**
 * Copy Right IJH.CC
 * Each engineer has a duty to keep the code elegant
 * $Id$
 */
if(!defined('__CORE_DIR')){
    exit("Access Denied");
}
class Ctl_Biz_Cate extends Ctl_Biz
{    

    public function items($params)
    {
        $limit = 50;
        $page = max((int)$params['page'], 1);
        if($items = K::M('product/cate')->items(array('shop_id'=>$this->shop_id), null, $page, $limit, $count)){
            foreach($items as $k=>$v){
                $v = $this->filter_fields('cate_id,title,orderby', $v);
                $items[$k] = $v;
            }
        }else{
            $items = array();
        }
        $this->msgbox->set_data('data', array('items'=>array_values($items)));
    }

    public function create($params)
    {
        if(!$data = $this->check_fields($params, 'title,orderby')){
            $this->msgbox->add('非法的数据提交', 211);
        }else{
            $data['shop_id'] = $this->shop_id;
            if($cate_id = K::M('product/cate')->create($data)){
                $this->msgbox->set_data('data', array('cate_id'=>$cate_id));
            }
        }
    }

    public function update($params)
    {
        if(!$cate_id = (int)$params['cate_id']){
            $this->msgbox->add('非法的数据提交', 211);
        }else if(!$data = $this->check_fields($params, 'title,orderby')){
            $this->msgbox->add('非法的数据提交', 212);
        }else if(!$cate = K::M('product/cate')->detail($cate_id)){
            $this->msgbox->add('非法的数据提交', 213);
        }else if($cate['shop_id'] != $this->shop_id){
            $this->msgbox->add('您无权修改该分类', 214);
        }else if(K::M('product/cate')->update($cate_id, $data)){
            $this->msgbox->set_data('data', array('cate_id'=>$cate_id));
        }
    }

    public function delete($params)
    {
        if($ids = K::M('verify/check')->ids($params['cate_id'])){
            $this->msgbox->add('未指删除的分类', 211);
        }else if(!$items = K::M('product/cate')->items_by_ids($ids)){
            $this->msgbox->add('未指删除的分类', 212);
        }else{
            $del_ids = array();
            foreach($items as $k=>$v){
                if($v['shop_id'] == $this->shop_id){
                    $del_ids[$v['cate_id']] = $v['cate_id'];
                } 
            }
            if($del_ids){
                K::M('product/cate')->delete($del_ids);
            }
            $this->msgbox->add('success');
        }
    }
}