<?php
/**
 * 商品单位管理控制器
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
namespace Admin\Controller;
class GoodsPackageController extends BaseController
{
    public function _initialize(){
        parent::_initialize();
    }

    /**
    * 商品包装列表及搜索
    */
    public function index(){
        $name = CONTROLLER_NAME;
        $map=array();
        $list = $this->lists($name, $map);
        foreach($list as $k=>$v){
            if($v['pattr_key']){
                $pattr_key=explode('-', $v['pattr_key']);
                $list[$k]['pattr_name'] = attr_key2name($pattr_key[1],$v['pid']);
            }else{
                $list[$k]['pattr_name'] = '';
            }
            if($v['sattr_key']){
                $sattr_key=explode('-', $v['sattr_key']);
                $list[$k]['sattr_name'] = attr_key2name($sattr_key[1],$v['sid']);
            }else{
                $list[$k]['sattr_name'] = '';
            }
        }
        $this->assign('list', $list);
        $this->display();
    }

    public function _before_add()
    {
        $goods_list = "<option value=''>请选择商品</option>";
        $this->assign('goods_list', $goods_list);
        $this->getcateTree();
    }
    /**
     * 插入包装
     */
    public function insert(){
        $map=$data=$maps=array();
        $postdata = I('post.');
        $name = CONTROLLER_NAME;
        $data['pid']=$map['pid']=$postdata['pid'];
        $data['pattr_key']=$map['pattr_key']=$postdata['attr_key'][0];
        $countp = M($name)->where($map)->count();
        if($countp){
            $this->error('大单位商品已被绑定，请重新选择');exit;
        }

        $data['sid']=$maps['sid']=$postdata['sid'];
        $data['sattr_key']=$maps['sattr_key']=$postdata['attr_key'][1];
        $data['ratio']=$postdata['ratio'];
        $counts = M($name)->where($maps)->count();
        if($counts){
            $this->error('小单位商品已被绑定，请重新选择');exit;
        }
        $id = M($name)->add($data);
        if ($id !== false) {
            $this->success(L('ADD_OK'),U(CONTROLLER_NAME.'/index'));
        } else {
            $this->error(L('ADD_ERROR'));
        }
    }
    private function getcateTree($pid = '', $assign = '')
    {
        // $GoodsCategory = getcache('GoodsCategory');
        $GoodsCategory = getcache('PurchaseCategory');
        $Tree = new \Common\Vendor\Tree();
        $select_categorys = '';
        $treemini = $Tree->treemini($GoodsCategory);
        $select_categorys .= $Tree->treeminioption($treemini, $pid);
        if ($assign) return $select_categorys;
        else $this->assign('select_categorys', $select_categorys);
        $wh['status'] = 1;
        $brand = M('Brand')->where($wh)->field('id,brand_name')->select();
        $this->assign('brand_list', $brand);

    }
}