<?php
/**
 * 商品分类管理
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
 
namespace Admin\Controller;
class PurchaseCategoryController extends BaseController
{
    public function _initialize()
    {
        parent::_initialize();
        $this->PurchaseCategory = getcache('PurchaseCategory');
    }

    public function index()
    {
        $pid = I('pid') ? I('pid') : 1;
        $PurchaseCategory = M('PurchaseCategory')->where(1)->field(true)->select();
        $Tree = new \Common\Vendor\Tree();
        $Tree->icon = array('&nbsp;&nbsp;&nbsp;   ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $Tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($PurchaseCategory as &$values) {
            $values['goodstype'] = "<a href='" . U('GoodsAttribute/index', array('type_id' => $values['type_id'])) . "'>" . idtoname($values['type_id'], 'GoodsType') . "</a>";
            $values['str_manage'] = '<a href="' . U('add', array('pid' => $values['id'])) . '" class="operate">' . L('ADD_CHILD_CAT') . '</a>&nbsp;&nbsp;<a class="operate" href="' . U('edit', array('id' => $values['id'])) . '">' . L('EDIT') . '</a>&nbsp;&nbsp;<a class="operate" href="javascript:;" onclick="$.showConfirm(\'' . L('SURE_DELETE') . '\',function(){window.location.href=\'' . U('delete', array('id' => $values['id'])) . '\'},\'hc\')">' . L('DELETE') . '</a>';
            $values['status'] = '<td onclick="status(' . $values['id'] . ',' . "'status'" . ')" id="status_' . $values['id'] . '" style="text-align:left;"><img src="' . __ROOT__ . '/Application/Admin/View/' . get_default_theme() . '/common/images/status_' . $values['status'] . '.gif" /></td>';
        }
        $Tree->init($PurchaseCategory);
        $str = "<tr>
	    <td style='text-align:left;'>\$id</td>
		<td ondblclick=editeTable(this,'sort','\$id','sort')>\$sort</td>
		<td style='text-align:left;padding-left:10px;' title='\$name'>\$spacer\$name</td>
        \$status
		<td style='text-align:left;'>\$str_manage</td>
		</tr>";

        // <td style='text-align:left;'>\$goodstype</td>
        $cateString = $Tree->get_tree(0, $str);
        $this->assign('cateString', $cateString);
        $this->display();
    }

    //插入
    public function insert()
    {
        $model = D(CONTROLLER_NAME);
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        $id = $model->add();
        $data = I('post.');
		$map['price'] = $data['price'];
        $map['pid'] = $data['pid'] ? $data['pid'] : '';
        $map['name'] = $data['name'] ? $data['name'] : '';
        //$map['icon'] = $data['icon'] ? $data['icon'] : '';
        $map['img'] = $data['img'] ? $data['img'] : '';
        //$map['class'] = $data['class'] ? $data['class'] : '';
        //$map['measure_unit'] = $data['measure_unit'] ? $data['measure_unit'] : '';
        $map['type_id'] = $data['type_id'] ? $data['type_id'] : '';
        $map['is_home'] = $data['is_home'] ? $data['is_home'] : '';
        $map['grade'] = $data['grade'] ? $data['grade'] : '';
        $map['sort'] = $data['sort'] ? $data['sort'] : '';
        $map['seotitle'] = $data['seotitle'] ? $data['seotitle'] : '';
        $map['seokeywords'] = $data['seokeywords'] ? $data['seokeywords'] : '';
        $map['seodescription'] = $data['seodescription'] ? $data['seodescription'] : '';
        $map['status'] = $data['status'] ? $data['status'] : '';
        $map['show_in_nav'] = $data['show_in_nav'] ? $data['show_in_nav'] : '';
        if ($map['show_in_nav'] == 1) {
            $map['show_in_nav'] = 1;
            $nav = M('nav')->where('cid=' . $id)->find();
            if ($nav) {
                $status['show_status'] = 1;
                M('nav')->where('cid=' . $id)->save($status);
            } else {
                $map_nav['cid'] = $id;
                $map_nav['name'] = $map['name'];
                $map_nav['navtype'] = 0;
                $map_nav['url'] = 'Home/cate/index?catid=' . $id;
                $map_nav['status'] = 1;
                $map_nav['show_status'] = 1;
                $map_nav['pid'] = 0;
                $map_nav['sort'] = 100;
                M('nav')->add($map_nav);
            }
        } elseif ($map['show_in_nav'] == 0) {
            $map['show_in_nav'] == 0;
            $nav = M('nav')->where('cid=' . $id)->find();
            if ($nav) {
                $show['show_status'] = 0;
                M('nav')->where('cid=' . $id)->save($show);
            }
        }
        $res = M('PurchaseCategory')->where('id=' . $id)->data($map)->save();
        if ($res !== false) {
            if (in_array(CONTROLLER_NAME, $this->cache_model)) {
                savecache(CONTROLLER_NAME);
            }
            if ($_POST['isajax']) $this->assign('dialog', '1');
            $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(CONTROLLER_NAME . '/index');
            $this->assign('jumpUrl', $jumpUrl);
            $this->success(L('ADD_OK'));
        } else {
            $this->error(L('ADD_ERROR') . ': ' . $model->getDbError());
        }
    }

    //编辑 更新
    public function update()
    {
        $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/index');
        $id = array_unique((array)I('id', 0));
        $id = is_array($id) ? implode(',', $id) : $id;
        $data = I('post.');
//		$map['price'] = $data['price'];
        $map['pid'] = $data['pid'] ? $data['pid'] : '';
        $map['name'] = $data['name'] ? $data['name'] : '';
        $map['icon'] = $data['icon'] ? $data['icon'] : '';
        $map['img'] = $data['img'] ? $data['img'] : '';
        $map['class'] = $data['class'] ? $data['class'] : '';
        $map['measure_unit'] = $data['measure_unit'] ? $data['measure_unit'] : '';
        $map['type_id'] = $data['type_id'] ? $data['type_id'] : '';
        $map['is_home'] = $data['is_home'] ? $data['is_home'] : '';
        $map['grade'] = $data['grade'] ? $data['grade'] : '';
        $map['sort'] = $data['sort'] ? $data['sort'] : '';
        $map['seotitle'] = $data['seotitle'] ? $data['seotitle'] : '';
        $map['seokeywords'] = $data['seokeywords'] ? $data['seokeywords'] : '';
        $map['seodescription'] = $data['seodescription'] ? $data['seodescription'] : '';
        $map['status'] = $data['status'] ? $data['status'] : '';
        $map['show_in_nav'] = $data['show_in_nav'] ? $data['show_in_nav'] : '';
        if ($data['pid'] == $data['id']) {//自己不能绑定自己为父级
            $this->error('父级不能为自己');
        }
        if ($map['show_in_nav'] == 1) {
            $map['show_in_nav'] = 1;
            $nav = M('nav')->where('cid=' . $id)->find();
            if ($nav) {
                $status['show_status'] = 1;
                M('nav')->where('cid=' . $id)->save($status);
            } else {
                $map_nav['cid'] = $id;
                $map_nav['name'] = idtoname($id, 'PurchaseCategory');
                $map_nav['navtype'] = 0;
                $map_nav['url'] = 'Home/cate/index?catid=' . $id;
                $map_nav['status'] = 1;
                $map_nav['show_status'] = 1;
                $map_nav['pid'] = 0;
                $map_nav['sort'] = 100;
                M('nav')->add($map_nav);
            }
        } elseif ($map['show_in_nav'] == 0) {
            $map['show_in_nav'] == 0;
            $nav = M('nav')->where('cid=' . $id)->find();
            if ($nav) {
                $show['show_status'] = 0;
                M('nav')->where('cid=' . $id)->save($show);
            }
        }
        $res = M('PurchaseCategory')->where('id=' . $id)->data($map)->save();
        $msg = array_merge(array('success' => L('EDIT_OK'), 'error' => L('EDIT_ERROR'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        if ($res !== false) {
            if (in_array(CONTROLLER_NAME, $this->cache_model)) {
                savecache(CONTROLLER_NAME);
            }
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
    }

    public function _before_add()
    {
        $this->getNodeTree();
    }

    public function _before_edit()
    {
        $id = I('get.id');
        if (!$id) $this->error(L('PARAM_ERR'));
        $pid =$this->PurchaseCategory[$id]['pid'];
        $this->getNodeTree($pid);
    }
	public function _before_delete(){
		$id=I('id');
		if(isset($id)&&is_array($id)){
			foreach($id as $k=>$v){
				$result=check_delete($v,4,'cate');
				if(!$result['status'])unset($id[$k]);
			}
			if(empty($id)){$this->error($result['info']);exit;}
		}else{
			$result=check_delete($id,4,'cate');
			if(!$result['status']){$this->error($result['info']);exit;}
		}
		$this->id=$id;
	} 
    /* 得到节点树 */
    private function getNodeTree($pid = '')
    {
        $select_categorys = '';
        $PurchaseCategory = $this->PurchaseCategory;
        if (empty($pid)) $pid = I('pid');
        $Tree = new \Common\Vendor\Tree();
        $treemini = $Tree->treemini($PurchaseCategory);
        $select_categorys .= $Tree->treeminioption($treemini, $pid);
        $this->assign('select_categorys', $select_categorys);
        //获取所有商品类型
        $allgoodstype = M('GoodsType')->where('status>0')->field('id,name')->cache(true)->order('sort,id desc')->select();
        foreach ($allgoodstype as $k => $v) {
            $goodstype[$v['id']] = $v['name'];
        }
        $this->assign('goodstype', $goodstype);
    }

    /**
     * 店铺结算设置
     * 按一级分类分配结算率
     */
    public function balance_shops()
    {
        $GoodsCategory = $this->GoodsCategory;
        foreach ($GoodsCategory as $k => $v) {
            if ($v['pid'] == 0) {
                $goods_cats[$k]['id'] = $v['id'];
                $goods_cats[$k]['name'] = $v['name'];
                $map['id'] = $v['id'];
                $goods_cats[$k]['balance_rate'] = M('GoodsCategory')->where($map)->getField('balance_rate');
            }
        }
        $this->assign('goods_cats', $goods_cats);
        unset($GoodsCategory, $goods_cats);
        $this->display();
    }
    public function update_balance(){
        $id=I('id');
        $map['id']=$id;
        $data['balance_rate']=I('balance_rate');
        $res=M('GoodsCategory')->where($map)->save($data);
        if(!$res){
            $this->error('编辑失败！');
        }
    }


    /**
     * 审核通过店铺经营类目
     */
    public function check_shopcate(){
        /*$id=I('id');
        $map['id']=$id;
        $data['creat_time']=time();
        $data['status']=1;
        $model= M("AuditLog");
        $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/shops_cateadd',array('type'=>4));
        //修改临时表的状态为通过
        $result = $model->where($map)->save($data);
        if($result){
            //获取经营类目id

            $remark=array();
            $remark = $model->where($map)->field('pro_id,param')->find();
//print_r($remark);exit;
            //修改店铺的经营类目
            $cateids=$remark['param'];
            $shop_map['id']=$remark['pro_id'];
            $shop_cateids= M('Shops')->where($shop_map)->getField("catids");

            if($shop_cateids){
                $shop_cate=array();
                $shop_cate = explode(',',$shop_cateids);
                $shop_cate[]=$cateids;
                //插入分类数组并去重
                $shop_cates=array_unique($shop_cate);
                $data['catids']=implode(',',$shop_cates);
            }else{
                $data['catids']=$cateids.',';
            }
           // print_r($data);exit;
            $info = M('Shops')->where($shop_map)->save($data);
            $this->success('审核成功',$jumpUrl);
        }else{
            $this->success('审核失败',$jumpUrl);
        }*/
    }

    /**
     * 审核拒绝
     */
    public function check_cate_exit(){
        /*$id=I('id');
        $type = I('type');
        $content=I("remark");
        //print_r($type);exit;
        $map['id']=$id;
        $data['remark']=$content;
        $data['status']=2;
        $data['creat_time']=time();
        $model= M("AuditLog");
        $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/shops_cateadd',array("type"=>$type));
        //修改临时表的状态为不通过
        $result = $model->where($map)->save($data);
        if($result){
            $this->success('审核拒绝成功',$jumpUrl);
        }else{
            $this->success('审核拒绝失败',$jumpUrl);
        }*/
    }
    /**
     * 审核通过店铺类目退出
     */
    public function check_shopcate_exit(){
       /* $id=I('id');
        $map['id']=$id;
        $data['status']=1;
        $data['creat_time']=time();
        $model= M("AuditLog");
        $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/shops_cateadd',array('type'=>5));
        //修改临时表的状态为通过
        $result = $model->where($map)->save($data);
        if($result){
            //获取经营类目id
            $ids['id'] = $id;
            $remark=array();
            $remark = $model->where($ids)->field('pro_id,param')->find();
//print_r($remark);exit;
            //修改店铺的经营类目
            $cateids=$remark['param'];
            $shop_map['id']=$remark['pro_id'];
            $shop_cateids= M('Shops')->where($shop_map)->getField("catids");
            if($shop_cateids){
                if(strstr(',',$shop_cateids)){
                    $shop_cate = explode(',',$shop_cateids);
                    if(in_array($cateids,$shop_cate)){
                        foreach($shop_cate as $k=>$val){
                            if($val==$cateids){
                                unset($val);
                            }
                        }
                        $shop_cates = array_filter($shop_cate);
                        $data['catids']=implode(',',$shop_cates);
                    }
                }else{
                    $data['catids']='';
                }
            }else{
                $this->error('该店铺没有要退出的经营类目',$jumpUrl);
            }
            $info = M('Shops')->where($shop_map)->save($data);
            $this->success('审核成功',$jumpUrl);
        }else{
            $this->error('审核失败',$jumpUrl);
        }*/
    }

    /**
     * 批量修改
     */
    public function total_update()
    {
        $data = I('post.');
        $model = M('GoodsCategory');
        for ($i = 0; $i < count($data['id']); $i++) {
            $id = $data['id'][$i];
            $value = $data['balance_rate'][$id];
            $updata['id'] = $id;
            $updata['balance_rate'] = $value;
            $map['id'] = $updata['id'];
            $result = $model->where($map)->save($updata);
        }
        if (false !== $result) {
            $this->success(L('DO_OK'), '', '', 'edit');
        } else {
            $this->error(L('DO_ERROR'));
        }
    }
    public function check_cate(){
        $id=I('id');
        $type=I('type');
        $this->assign("id",$id);
        $this->assign("type",$type);
        $this->display();
    }
    /**
     * 批量审核
     */
    public function check_data(){
        /*$data = I('post.');
        $model=M("AuditLog");
        for($i=0; $i<count($data['id']);$i++){

        }*/
    }
}