<?php
/**
 * 商品管理控制器
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
namespace Admin\Controller;
class GoodsController extends BaseController
{
    public function _initialize(){
        parent::_initialize();
        $this->admin_info=session('admin_info');
        $map=array();
        $map['uid']=$this->admin_info['id'];
        $this->auth_group_id=M("AuthGroupAccess")->where($map)->getField('group_id');
       /* if($this->auth_group_id==2 && ACTION_NAME!="index"){
            $this->redirect('Admin/Member/index');
        }*/
    }

    /**
     * 商品管理列表及搜索
     */
    public function index(){
        $name = CONTROLLER_NAME;
        $where=array();
        $where['status'] = 1;
        $postdata=I('param.');
        if($postdata['keyword']){
            $where['name']=array('like','%'.$postdata['keyword'].'%');
        }
        $service_info = $this->lists($name,$where);
        $this->assign('list',$service_info);
        $this->display();
    }

    /**
     * 添加商品
     */
    public function _before_add(){
        $this->getNodeTree();
        $basedefault = array('moreimg' => '', 'moreimgstr' => '', 'morecatarr' => '', 'morecatid' => '', 'configstr' => '');
        $this->assign($basedefault);
        $this->get_goods_label();
        $this->get_member_price();//会员价
    }

    /**
     * 插入商品
     */
    public function insert(){
        $name = CONTROLLER_NAME;
        $model = D($name);
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        $id = $model->add();
        if ($id !== false) {
            $postdata = I('post.');
            if($postdata['is_integral']!=1){
                $postdata['is_integral']=0;
            }
            $postdata['id'] = $id;
            $model->update_goodsattr($postdata, 1);//更新扩增分类
            $model->update_goodsimg($postdata, 1);//更新商品相册
            $model->update_goodstype($postdata, 1);//更新商品属性
            $model->update_user_price($postdata, 1);//更新会员价
            $model->update_goods_sn($postdata, 1);//更新货号
            $model->update_goods_content($postdata, 1);//更新商品详情和seo
            $model->update_goods_label($postdata, 1);//更新商品标签
            unset($postdata);
            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 insert_pur(){
        $model = D(CONTROLLER_NAME);
		$data = $model->create();
		$this->check_goods_sn($data);
		if($data['goods_code']){
			$map_sn = array();
			if($data['id']){
				$map_sn['id'] = array('neq',$data['id']);
			}
			$map_sn['goods_code'] = $data['goods_code'];
			$map_sn['goods_type'] = 5;
			$g_count = $model->where($map_sn)->count();
			if($g_count){
				$this->error('货码不能重复，不填可以自动生成');exit;
			}
		}
		if($data['is_type'] == 1){
			if($data['goods_plu']){
				$map_sn = array();
				if($data['id']){
					$map_sn['id'] = array('neq',$data['id']);
				}
				$map_sn['goods_plu'] = $data['goods_plu'];
				$plu_count = $model->where($map_sn)->count();
				if($plu_count){
					$this->error('商品PLU不能重复');exit;
				}
			}
		}else{
			$data['goods_plu'] = 0;
			if($data['limit_count']) $data['limit_count'] = intval($data['limit_count']);
			if($data['lower_count']) $data['lower_count'] = intval($data['lower_count']);
		}
		
		if($data['sale_type'] == 1){
			$data['limit_count'] = $data['lower_count'] = 0;
		}
		// echo "<pre>";print_r($data);exit;
        if (false === $data) {
            $this->error($model->getError());
        }
        $id = $model->add();
        if ($id !== false) {
            $postdata = I('post.');
            // echo "<pre>";print_r($postdata);exit;
            if($postdata['is_integral']!=1){
                $postdata['is_integral']=0;
            }
            $postdata['id'] = $id;
            if($postdata['label_ids']){
                $postdata['label_ids']  = array_filter($postdata['label_ids']);
                $postdata['label_ids'] = implode(',',$postdata['label_ids']);
            }
        
			
            $model->update_goodsattr($postdata, 1);//更新扩增分类
            $model->update_goodsimg($postdata, 1);//更新商品相册
            $model->update_goodstype($postdata, 1);//更新商品属性
            $model->update_user_price($postdata, 1);//更新会员价
            $model->update_review_price($postdata,1);//更新团长佣金
            // $model->update_goods_sn($postdata, 1);//更新货号
            $model->update_goods_code($postdata, 1);//更新货码
            $model->update_goods_content($postdata, 1);//更新商品详情和seo
            $model->update_goodsmatter($postdata, 1);//更新商品素材库 jxr 2019.1.14

            $model->update_goods_label($postdata,1); //更新商品标签
            // 有添加属性，不添加初始库存
            if(!$postdata['config'] && !empty($postdata['goods_num']) && $postdata['sale_type'] != 1){
                $model->save_shops_stock($postdata);//仓库初始库存
            }

            if($postdata['sale_type']==1){
                $res = $model->update_goods_package($postdata);//添加商品包装
                if($res['status']==0){
                    $this->error('组合包装商品数量必须大于0');exit;
                }
            }
            unset($postdata);
            if ($_POST['isajax']) $this->assign('dialog', '1');
            $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(CONTROLLER_NAME . '/index_purchase');
            $this->assign('jumpUrl', $jumpUrl);
            $this->success(L('ADD_OK'));
        } else {
            $this->error(L('ADD_ERROR') . ': ' . $model->getDbError());
        }
    }
	/**
     * 获得计重商品编码
     */
	public function jz_sn(){
		$return = array();
		$return['status'] = 1;
		$sn = weight_goods_sn();
		if($sn){
			$return['sn'] = $sn;
		}else{
			$return['status'] = 0;
		}
		$this->ajaxReturn($return);
	}
	/**
     * 检查商品编号是否正确
     */
	private function check_goods_sn($data){
		if(empty($data['goods_sn'])){
			$this->error('商品编码不能为空！');exit;
		}else{
			if(strlen(intval($data['goods_sn'])) < 5){
				$this->error('商品编码最少为5位，可以重新生成！');exit;
			}
			$map_sn = array();
			if($data['id']){
				$map_sn['id'] = array('neq',$data['id']);
			}
			$map_sn['goods_sn'] = $data['goods_sn'];
			$map_sn['goods_type'] = 5;
			$g_count = M('Goods')->where($map_sn)->count();
			if($g_count){
				$this->error('商品编码不能重复，可以重新生成！');exit;
			}else{
				if($data['is_type'] == 1 && strlen(intval($data['goods_sn'])) != 5){
					$this->error('商品编码不正确，可以重新生成！');exit;
				}
				if($data['is_type'] != 1 && strlen(intval($data['goods_sn'])) == 5){
					$this->error('商品编码不正确，可以重新生成！');exit;
				}
			}
		}
	}
    /**
     * 编辑服务
     */
    public function edit()
    {
        $id = I('get.id');

        $info = M('GoodsService')->where('id='.$id)->field(true)->find();
        $this->assign($info);
        $this->assign('info', $info);
        $this->display();
    }

    /*
    * 商品标签
     */
    public function label_list($id){
        $map = array();
        if($id){
            $map['id'] = $id;
            $label_ids = M('Goods')->where($map)->getField('label_ids');
            $label_ids_arr = array_filter(explode(',',$label_ids));
            $this->assign('label_ids_arr',$label_ids_arr);
            unset($map['id']);
            //end
        }
        
        $map['pid'] = 48;
        $label_list = M('Type')->where($map)->field('id,name')->select();
        $this->assign('label_list',$label_list);
    }
    //修改标签
    public function save_labels(){
        $return = array();
        $post = I('param.');
        $map = array();
        $map['id'] = $post['goods_id'];
        $label_ids = M('Goods')->where($map)->getField('label_ids');
        $new_label_ids = ',';
        
        $new_ids = $post['label_id'].',';
        
        if($label_ids){
            if(strpos($label_ids,','.$new_ids) !== false){
                $label_ids = str_replace(','.$new_ids,',',$label_ids);
            }else{
                $label_ids .= $new_ids;
            }
            $new_label_ids = $label_ids;
        }else{
            $new_label_ids .= $new_ids;
        }
        if($new_label_ids){
            $save_label_ids = array();$save_label_ids['label_ids'] = $new_label_ids;
            $ret = M('Goods')->where($map)->save($save_label_ids);
            if($ret){
                $return['status'] = 1;
            }else{
                $return['status'] = 0;
            }
        }
        $this->ajaxReturn($return);
    }
    public function add_label(){
        $return = array();
        $post = I('param.');
        $new_label = $post['new_label'];
        $new_label_arr = array_filter(explode(' ',$new_label));
        if($new_label_arr){
            $save_data = array();
            $ret = 1;$html = '';
            foreach($new_label_arr as $v){
                $save_data['pid'] = 48;
                $save_data['sort'] = 0;
                $save_data['status'] = 1;
                $save_data['name'] = $save_data['temp'] = $v;
                $id = M('Type')->add($save_data);
                if(!$id){$ret = 0;}
                else{
                    $html .= '<li onclick="add_member(this,'.$id.')">'.$v.'</li>';
                }
            }
            if($ret){
                $return['status'] = 1;
                $return['html'] = $html;
            }else{
                $return['status'] = 0;
            }
        }
        $this->ajaxReturn($return);
    }
    /**
     * 编辑商品
     */
    public function edit_purchase()
    {
        $id = I('get.id');
        $info = '';
        if (!$id) $this->error(L('PARAM_ERR'));
        $info = M('goods')->field(true)->find($id);
        $this->attr_arr();
        $this->get_goods_label($id);
        $this->pattr_html($id);//获取属性
		$this->imgs_cate_list();
        $this->label_list($id);
        //获取关联分类
        $morecatarr = $morecatidarr = array();
        $where1['goods_id'] = $id;
        $morecat = M('GoodsCat')->where($where1)->field(true)->select();
        if (!empty($morecat)) {
            foreach ($morecat as $v) {
                $morecatidarr[] = $v['catid'];
                $morecatarr[] = $this->getcateTree($v['catid'], 1,'','','',5);
            }
        }
        $this->assign('morecatarr', $morecatarr);
        $this->assign('morecatid', implode(',', $morecatidarr));
        //获取商品相册
        $moreimg = M('GoodsGallery')->where('goods_id=' . $id)->field('id,goods_img,img_desc,img_sort')->order('id')->select();
        $moreimgarr = array();
        $moreimgstr = '';
        if (!empty($moreimg)) {
            foreach ($moreimg as $v) {
                $moreimgarr['goods_img'][] = $v['goods_img'];
                $moreimgarr['img_desc'][] = $v['img_desc'];
                $moreimgarr['img_sort'][] = $v['img_sort'];
            }
            $moreimgstr = implode('', $moreimgarr['goods_img']) . implode('', $moreimgarr['img_desc']) . implode('', $moreimgarr['img_sort']);

        }
        $this->assign('moreimg', $moreimg);
        $this->assign('moreimgstr', md5($moreimgstr));

        //获取素材库 jxr start 2019.1.14
        $gmmap['goods_id']=$id;
        $goods_matter = $this->lists('GoodsMatter', $gmmap);
        $this->assign('goods_matter', $goods_matter);
        //获取素材库 jxr end 2019.1.1

        //获取分类 类型 品牌 店铺
        $this->getNodeTree($info['cat_id'], '', $info['brand_id'], $info['suppliers_id'],$id,5);
        //获取商品的长字段
        $goodscontent = M('GoodsContent')->where('goods_id = ' . $id)->find();
        $info['content'] = $goodscontent['content'];
        $info['seotitle'] = $goodscontent['seotitle'];
        $info['seokeywords'] = $goodscontent['seokeywords'];
        $info['seodescription'] = $goodscontent['seodescription'];
        $this->get_member_price($id);//会员价

        //团长等级
        $this->get_review_rank($id);
        // $this->assign('info', $info);
        $this->assign($info);
        $umap['status']=1;
        $unitlist = M('GoodsUnit')->where($umap)->select();
        $select_unit = '';
        if (!empty($unitlist)) {
            foreach ($unitlist as $k => $v) {
                if ($info['unit_id'] == $v['id']) {
                    $select_unit .= "<option selected='selected' value='" . $v['id'] . "'>" . $v['name'] . "</option>";
                } else {
                    $select_unit .= "<option value='" . $v['id'] . "'>" . $v['name'] . "</option>";
                }
            }
        }
        $this->assign('select_unit', $select_unit);
        $this->group_goods($id);
        unset($info, $morecatarr, $morecatidarr, $moreimg, $moreimgarr, $moreimgstr);
        
        $this->display();
    }
	public function choose_shops(){
		$postdata=I('post.');
		$goods_id = $postdata['goods_id'];
		$map = array();
		$map['status'] = 1;
		$map['id'] = array('gt',0);
		$total=M('Shops')->where($map)->count();
        if(empty($total)){
            $return['status']=2;
            $return['info']='没有查询到仓库';
            $this->ajaxReturn($return);//返回查询商品为空
        }
		// $listRows=!empty($postdata['pagesize'])?$postdata['pagesize']:8;
        // $page = new \Common\Vendor\Page($total, $listRows);
        // $pageconfig='%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%';
        // $page->setConfig('theme',$pageconfig);
        // $page->rollPage=6;
        // $pagehtml = $page->show();
        $pagehtml = '<span class="sum_shop">共有'.$total.'个仓库</span>';
        $list=array();
        $list=M('Shops')->where($map)->field('id,name')->select();

        $html='<table class="table_shops">';
		$html.='<thead><tr><th width="220">仓库名称</th><th width="180">当前库存</th><th width="120">增减</th><th width="140">变更数量</th></tr></thead><tbody>';
		if($list){
			foreach($list as $k=>$v){
				if($goods_id){
					$where = array();
					$where['shop_id'] = $v['id'];
					$where['goods_id'] = $goods_id;
					if($postdata['is_edit'] != 1){
						$where['goods_stock'] = $postdata['attr_key'];
					}else{
						$where['goods_stock'] = 0;
					}
					$v['shop_num'] = M('ShopsGoodsStock')->where($where)->getField('goods_number');
					if(!$v['shop_num']){
						$v['shop_num'] = 0;
					}
				}else{
					$v['shop_num'] = 0;
				}
				$html.='<tr><td>'.$v['name'].'</td><td>'.floatval($v['shop_num']).'</td>';
				$html.='<td class="t_c"><select name="type_num[]" class="shops_control">';
				$html.='<option value="0">增加</option><option value="1">减少</option></select></td>';
				$html.='<td><input type="hidden" value="'.$v['id'].'" name="shop_ids[]" />';
				$html.='<input type="text" value="" name="goods_num[]" /></td></tr>';
			}
		}else{
			$html.='<tr><td colspan="4" class="t_c">暂无仓库</td></tr>';
		}
		$html.='</tbody></table>';
        $return['status']=1;
        $return['data']=$html;
        $return['page']=$pagehtml;
        // $return['totalpages']=$page->totalPages;
        $this->ajaxReturn($return);
	}
	public function choose_shops_stock(){
		$postdata=I('post.');
		$goods_id = $postdata['goods_id'];
		$attr_key = $postdata['attr_key'];
		$map = array();
		$map['status'] = 1;
		$map['id'] = array('gt',0);
		$total=M('Shops')->where($map)->count();
        if(empty($total)){
            $return['status']=2;
            $return['info']='没有查询到仓库';
            $this->ajaxReturn($return);//返回查询商品为空
        }
		$listRows=!empty($postdata['pagesize'])?$postdata['pagesize']:8;
        $page = new \Common\Vendor\Page($total, $listRows);
        $pageconfig='%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%';
        $page->setConfig('theme',$pageconfig);
        $page->rollPage=6;
        $pagehtml = $page->show();
        $list=array();
        $list=M('Shops')->where($map)->field('id,name')->limit($page->firstRow.','.$listRows)->select();

        $html='<table class="table_shops">';
		$html.='<thead><tr><th width="220">仓库名称</th><th width="180">当前库存</th><th width="120">增减</th><th width="140">变更数量</th></tr></thead><tbody>';
		if($list){
			foreach($list as $k=>$v){
				if($goods_id){
					$where = array();
					$where['shop_id'] = $v['id'];
					$where['goods_id'] = $goods_id;
					$where['goods_stock'] = $attr_key;
					$v['shop_num'] = M('ShopsGoodsStock')->where($where)->getField('goods_number');
					if(!$v['shop_num']){
						$v['shop_num'] = 0;
					}
				}else{
					$v['shop_num'] = 0;
				}
				$html.='<tr><td>'.$v['name'].'</td><td>'.floatval($v['shop_num']).'</td>';
				$html.='<td class="t_c"><select name="type_num[]" id="type_num" class="shops_control">';
				$html.='<option value="0">增加</option><option value="1">减少</option></select></td>';
				$html.='<td><input type="hidden" value="'.$v['id'].'" name="shop_ids[]" />';
				$html.='<input type="text" value="" name="goods_num[]" /></td></tr>';
			}
		}else{
			$html.='<tr><td colspan="4" class="t_c">暂无仓库</td></tr>';
		}
		$html.='</tbody></table>';
        $return['status']=1;
        $return['data']=$html;
        $return['page']=$pagehtml;
        $return['totalpages']=$page->totalPages;
        $this->ajaxReturn($return);
	}
    /**
     * 修改商品
     * @param string $model
     * @param string $data
     * @param string $where
     * @param string $msg
     */
    public function update($model = '', $data = '', $where = '1', $msg = '')
    {
        $model = D(CONTROLLER_NAME);
        $postdata = I('post.');
        
        
        $data = $model->create($postdata);
        $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/index');
        $id = array_unique((array)I('id', 0));
        $id = is_array($id) ? implode(',', $id) : $id;
        $where = array_merge(array('id' => array('in', $id)), (array)$where);
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        if ($model->where($where)->save($data) !== false) {
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
    }
    /**
     * 修改订货商品
     * @param string $model
     * @param string $data
     * @param string $where
     * @param string $msg
     */
    public function update_pur($model = '', $data = '', $where = '1', $msg = '')
    {
        $model = D(CONTROLLER_NAME);
        $postdata = I('post.');
        // if(empty($postdata['limit_off']) || $postdata['limit_off']==0){
        //     $postdata['limit_off']=0;
        //     $postdata['limit_starttime']='';
        //     $postdata['limit_endtime']='';
        // }
        if($postdata['status'] != 2){
            $postdata['limit_starttime']='';
            $postdata['limit_endtime']='';
        }
        if($postdata['status']==2){
            if(empty($postdata['limit_starttime']) || empty($postdata['limit_endtime'])) $this->error('请填写限时上架时间');
            $postdata['limit_starttime'] = $postdata['limit_starttime'];
            $postdata['limit_endtime'] = $postdata['limit_endtime'];
        }
        if($postdata['deil_time']!=4){
            $postdata['custom_dtime'] = '';
        }
        if(empty($postdata['is_recom']) || $postdata['is_recom']==0){
            $postdata['is_recom'] = 0;
        }
        if($postdata['is_integral']!=1){
            $postdata['is_integral']=0;
        }
        $checkcheckbox = array('is_best', 'is_new', 'is_hot', 'is_shipping');
        foreach ($checkcheckbox as $v) {
            if (empty($postdata[$v])) $postdata[$v] = '0';
        }
		if($postdata['sale_type'] == 1){
			$postdata['limit_count'] = $postdata['lower_count'] = 0;
		}
		$this->check_goods_sn($postdata);
		
		if($postdata['goods_code']){
			$map_sn = array();
			if($postdata['id']){
				$map_sn['id'] = array('neq',$postdata['id']);
			}
			$map_sn['goods_code'] = $postdata['goods_code'];
			$map_sn['goods_type'] = 5;
			$g_count = $model->where($map_sn)->count();
			if($g_count){
				$this->error('货码不能重复，不填可以自动生成');exit;
			}
		}
		if($postdata['is_type'] == 1){
			if($postdata['goods_plu']){
				$map_sn = array();
				if($postdata['id']){
					$map_sn['id'] = array('neq',$postdata['id']);
				}
				$map_sn['goods_plu'] = $postdata['goods_plu'];
				$plu_count = $model->where($map_sn)->count();
				if($plu_count){
					$this->error('商品PLU不能重复');exit;
				}
			}
		}else{
			$postdata['goods_plu'] = 0;
			if($postdata['limit_count']) $postdata['limit_count'] = intval($postdata['limit_count']);
			if($postdata['lower_count']) $postdata['lower_count'] = intval($postdata['lower_count']);
		}
		
        $data = $model->create($postdata);
        $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/index_purchase');
        $id = array_unique((array)I('id', 0));
        $id = is_array($id) ? implode(',', $id) : $id;
        $where = array_merge(array('id' => array('in', $id)), (array)$where);
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        if ($model->where($where)->save($data) !== false) {
            $postdata['id'] = $id;
            $model->update_goodsattr($postdata);//更新扩增分类
            $model->update_goodsimg($postdata);//更新商品相册
            $model->update_goodstype($postdata);//更新商品属性
            $model->update_user_price($postdata);//更新会员价
            $model->update_review_price($postdata);//更新会员价

            // $model->update_goods_sn($postdata);//更新货号
            $model->update_goods_code($postdata);//更新货码
            $model->update_goods_content($postdata);//更新商品详情和seo
            $model->update_goods_package($postdata);//更新商品包装
			$model->update_goodsmatter($postdata);//更新商品素材库 jxr 2019.1.14
            clearhomehtml($id);//更新静态缓存
            unset($data, $postdata, $newgoodscat, $newgoodsimg, $goodstype, $goodstypearr, $newgoodsattr);
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
    }
	
    /**
     * 得到会员价
     * @param int $id
     */
    public function get_member_price($id=0){
        //会员
        $morerank = M('MemberRank')->field('id,name')->cache(true)->select();
		//会员价
        $user_price_list = M('MemberPrice')->where('goods_id = ' . $id)->field('user_price,user_rank')->select();
        $member_price = array();
        if($user_price_list){
            $user_price=format_array2select($user_price_list,'user_price','user_rank');
        }
        if($morerank){
            foreach ($morerank as $key => $v) {
                $k=$v['id'];
                $member_price[$k]['id'] = $v['id'];
                $member_price[$k]['name'] = $v['name'];
                if(!empty($user_price[$k]))$member_price[$k]['user_price'] = $user_price[$k];
            }
        }
        $this->assign('member_price', $member_price);
        $this->assign('morerank', $morerank);
    }


    //得到团长等级
    public function get_review_rank($id=0){
        //团长等级
        $reviewrank = M('ReviewRank')->field('id,name')->cache(true)->select();
        //团长价
        $user_price_list = M('ReviewPrice')->where('goods_id = ' . $id)->field('review_price,review_rank')->select();
        $review_price = array();
        if($user_price_list){
            $user_price=format_array2select($user_price_list,'review_price','review_rank');
        }
        if($reviewrank){
            foreach ($reviewrank as $key => $v) {
                $k=$v['id'];
                $review_price[$k]['id'] = $v['id'];
                $review_price[$k]['name'] = $v['name'];
                if(!empty($review_price[$k]))$review_price[$k]['review_price'] = $user_price[$k];
            }
        }
        $this->assign('review_price', $review_price);
        $this->assign('reviewrank', $reviewrank);
        

    }
    //end

    /**
     * 商品标签
     * @param string $goods_id
     */
    public function get_goods_label($goods_id = ''){
        $selectstr =$select_str = $label_arr =  array();
        $this->assign('selectstr', $selectstr);
        $this->assign('label_arr', $label_arr);
        $this->assign('select_str', $select_str);
    }
	public function attr_arr(){
		$ga_map = array();
        $ga_map['status'] = 1;
        $attr_arr=M('GoodsAttribute')->where($ga_map)->field(true)->select();
        $this->assign('attr_arr', $attr_arr);
	}
    /**
     * 得到树节点
     * @param string $pid
     * @param string $goods_type 商品类型
     */
    private function getNodeTree($pid = '', $assign = '', $brandid = '', $suppliersid = '',$shop_id='',$goods_type=1)
    {
        if (empty($pid)) $pid = I('pid');
        $this->getcateTree($pid, $assign, $brandid, $suppliersid,$shop_id,$goods_type);
        //获取所有供货商
        $suppliersattr = M('Suppliers')->where('status>0')->field('id,name')->cache(true)->order('convert(name using gb2312) ASC')->select();
        $supplierattr = array();
        if (!empty($suppliersattr)) {
            foreach ($suppliersattr as $v) {
                $supplierattr[$v['id']] = $v['name'];
            }
        }
        $this->assign('suppliers', $supplierattr);
        unset($suppliersattr, $supplierattr);
    }

    /**
     * 得到节点树
     */
    private function getcateTree($pid = '', $assign = '', $brandid = '', $suppliersid = '',$shop_id='',$goods_type)
    {
        if($goods_type==5){
            $GoodsCategory = getcache('PurchaseCategory');
        }else{
            $GoodsCategory = getcache('GoodsCategory');
        }

        $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);
        $brand = M('Brand')->where('status=1')->order('convert(brand_name using gb2312) ASC')->field('id,brand_name')->select();
        $brand_op = "<option value=''>" . L('PLEASE_SELECT_BRAND') . "</option>";
        foreach ($brand as $k => $v) {

	  //if(intval($shopid)>0&&!in_array($v['id'],$use_BrandCategory)){unset($brand[$k]);continue;}
            if ($brandid == $v['id']) {
                $brand_op .= "<option selected='selected' value='" . $v['id'] . "'>" . $v['brand_name'] . "</option>";
            } else {
                $brand_op .= "<option value='" . $v['id'] . "'>" . $v['brand_name'] . "</option>";
            }
        }
        $this->assign('select_brands', $brand_op);
        $where_s=array();
        $where_s['status']=1;
        if($goods_type==5){
            $where_s['is_purchase']=1;
        }else{
            $where_s['is_direct']=1;
        }
        $suppliers_info = M('Suppliers')->where($where_s)->order('convert(name using gb2312) ASC')->field('id,name')->select();
        $suppliers_op = '';
        if (!empty($suppliers_info)) {
            foreach ($suppliers_info as $k => $v) {
                if ($suppliersid == $v['id']) {
                    $suppliers_op .= "<option selected='selected' value='" . $v['id'] . "'>" . $v['name'] . "</option>";
                } else {
                    $suppliers_op .= "<option value='" . $v['id'] . "'>" . $v['name'] . "</option>";
                }
            }
        }
        $this->assign('select_suppliers', $suppliers_op);
        unset($GoodsCategory, $select_categorys, $brand, $brand_op, $suppliers_info, $suppliers_op);
    }
	/**
     * 获取商品属性
     */
	public function attr_html(){
        $goods_catid = intval($_REQUEST['catid']);//商品分类id
        $goodsid = intval($_REQUEST['goodsid']);//商品id
        $join = '';
        if ($goods_catid > 0) {
            $getallson = getallson($goods_catid, 'GoodsCategory');//获取所有子分类
            $getallparent = getallparent($goods_catid, '', 'GoodsCategory');//获取所有父级分类
            $new_catid_array = array_unique(array_merge($getallson, explode(',', $getallparent)));
            if ($new_catid_array) {
                //添加商家自定义属性
                $shop_id = idtoname($goodsid,'Goods','shop_id','id');
                if(intval($shop_id)>0){//判断是店铺商品
                    $join = ' or ga.shop_id='.$shop_id;
                }
                //end
                $allattr = M('GoodsCategory')->alias('gc')->where('gc.id in(' . implode(',', $new_catid_array) . ')')->JOIN('LEFT JOIN __GOODS_ATTRIBUTE__ ga ON gc.type_id=ga.type_id'.$join)->select();
            }
        }
        foreach ($allattr as $k => $v) {
            if (empty($v['id'])) continue;
            $all_attr[$v['id']] = $v['type'];
            if ($allattr[$k]['options']) {
                $v['options'] = strtoarray($v['options']);
            }
            $all_attr_format[$v['id']] = $v;
        }
        if ($goodsid > 0) {//获取商品属性值
            $goodsval = $goodsattrarr = array();
            $goodsattr = M('GoodsAttr')->where('goods_id=' . $goodsid)->field('attr_id,attr_value,attr_price,supplier_price,attr_img')->order('id')->select();
            foreach ($goodsattr as $k => $v) {
                $goodsattrarr[] = $v['attr_value'] . floatval($v['attr_price']) . $v['attr_img'];
                $goodsval[$v['attr_id']]['attr_id'] = $v['attr_id'];
                if ($all_attr[$v['attr_id']] == 'text') {
                    $goodsval[$v['attr_id']]['attr_text'] = $v['attr_value'];
                } else {
                    $goodsval[$v['attr_id']]['attr_select'][] = $v['attr_value'];
                    $goodsval[$v['attr_id']]['attr_price'][] = $v['attr_price'];
                    $goodsval[$v['attr_id']]['attr_balance_price'][] = $v['supplier_price'];
                    $goodsval[$v['attr_id']]['attr_img'][] = $v['attr_img'];
                    $goodsval[$v['attr_id']]['attr_count'] = count($goodsval[$v['attr_id']]['attr_select']);//循环总数
                }
            }
            $this->assign('configstr', md5(implode('', $goodsattrarr)));
            $this->assign('goodsattr', $goodsval);
        }
        $this->assign('allattr', $all_attr_format);
        unset($allattr, $goodsattr, $goodsattrarr, $goodsval);
        $this->display();
    }
    /**
     * 获取订货商品属性
     */
    public function pattr_html($goodsid){
        // $goodsid = intval($_REQUEST['goodsid']);//商品id
		
		$ga_map = array();
        $ga_map['status'] = 1;
        $allattr=M('GoodsAttribute')->where($ga_map)->select();
        
		$all_attr_format = array();
        foreach ($allattr as $k => $v) {
            if ($allattr[$k]['options']) {
                $v['options'] = strtoarray($v['options']);
            }
            $all_attr_format[$v['id']] = $v;
        }
		
        if ($goodsid > 0) {
            //获取商品属性值
            $attr_ids = $goodsval = $goodsattrarr = array();
            $goodsattr = M('GoodsAttr')->where('goods_id=' . $goodsid)->field(true)->select();
            foreach ($goodsattr as $k => $v) {
                $goodsattrarr[] = $v['attr_value'] . floatval($v['attr_price']) . $v['attr_img'];
                $goodsval[$v['attr_id']]['attr_id'] = $v['attr_id'];
				
				$attr_ids[] = $v['attr_id'];
                if ($all_attr[$v['attr_id']] == 'text') {
                    $goodsval[$v['attr_id']]['attr_text'] = $v['attr_value'];
                } else {
                    $goodsval[$v['attr_id']]['attr_select'][] = $v['attr_value'];
                    $goodsval[$v['attr_id']]['attr_img'][$v['attr_value']] = $v['attr_img'];
                }
				$map = array();
				$map['id'] = $v['attr_id'];
				$map['status'] = 1;
				$attr_all = M('GoodsAttribute')->where($map)->getField('options');
                $goodsval[$v['attr_id']]['attr_all'] = explode(',',$attr_all);
            }
			$attr_idstr = ','.implode(',',array_unique(array_filter($attr_ids))).',';
			// echo "<pre>";
			// print_r($goodsval);exit;
            $this->assign('configstr', md5(implode('', $goodsattrarr)));
            $this->assign('goodsattr', $goodsval);
            $this->assign('attr_ids', $attr_idstr);
        }
        $this->assign('allattr', $all_attr_format);
        unset($allattr, $goodsattr, $goodsattrarr, $goodsval);
    }
    /**
     * 货品管理
     */
    public function stock()
    {
        $postdata = I('param.');
        $goods_id = intval($postdata['id']);
        if ($goods_id > 0) {
            $goodsdata = M('Goods')->where('id=' . $goods_id)->field('goods_name,goods_sn')->find();
            $this->assign('goodsdata', $goodsdata);
            $this->assign('id', $goods_id);
            $goodsattr = M('GoodsAttr')->alias('ga')->where("gatt.type='checkbox' and ga.goods_id = " . $goods_id)->JOIN("LEFT JOIN __GOODS_ATTRIBUTE__ gatt ON ga.attr_id=gatt.id")->select();
            foreach ($goodsattr as $k => $v) {
                if (empty($v['id'])) continue;
                $v['options'] = strtoarray($v['options']);
                $check_option[$v['id']][] = $v['attr_value'];
                $goodsattr_format[$v['id']] = $v;
            }
            foreach ($check_option as $k => $v) {
                $check[$k] = array_values($v);
                foreach ($goodsattr_format[$k]['options'] as $key => $val) {
                    if (in_array($key, $check[$k])) {
                        $goodsattr_format[$k]['options_format'][$key] = $val;
                    }
                }
            }
            $goodsattrstock = M('GoodsAttrStock')->where('goods_id=' . $goods_id)->order('id')->select();
            foreach ($goodsattrstock as $k => $v) {
                $attr_key_array[$k]['attr_key'] = explode('_', $v['attr_key']);
                $attr_key_array[$k]['stock_cfg'] = $v['stock_cfg'];
                $attr_key_array[$k]['goods_attr_sn'] = $v['goods_attr_sn'];
                $attr_key_array[$k]['sell_count'] = $v['sell_count'];
            }
            foreach ($attr_key_array as $k => $v) {
                foreach ($v['attr_key'] as $val) {
                    if (empty($val)) continue;
                    $goods_attr_info = M('GoodsAttr')->where('id=' . $val)->field('id,attr_id,attr_value')->find();
                    $attr_key_array_format[$k]['attr_val'][$goods_attr_info['attr_id']]['id'] = $goods_attr_info['attr_id'];
                    $attr_key_array_format[$k]['attr_val'][$goods_attr_info['attr_id']]['val'] = $goods_attr_info['attr_value'];
                    $attr_key_array_format[$k]['stock_cfg'] = $v['stock_cfg'];
                    $attr_key_array_format[$k]['goods_attr_sn'] = $v['goods_attr_sn'];
                    $attr_key_array_format[$k]['sell_count'] = $v['sell_count'];
                }
            }
            if (empty($attr_key_array_format)) {//构造空数组循环
                foreach ($goodsattr_format as $k => $v) {
                    $where[$k]['goods_id'] = $goods_id;
                    $where[$k]['attr_id'] = $k;
                    $goods_attr_info = M('GoodsAttr')->where($where[$k])->field('id,attr_id,attr_value')->order('id asc')->find();
                    $attr_key_array_format[0]['attr_val'][$k]['id'] = $goods_attr_info['attr_id'];
                    $attr_key_array_format[0]['attr_val'][$k]['val'] = $goods_attr_info['attr_value'];
                }
            }
            $this->assign('attr_count', count(array_keys($attr_key_array_format)));//循环总数
            $this->assign('goodsattr_format', $goodsattr_format);
            $this->assign('attr_key_array_format', $attr_key_array_format);
        }
        $this->display();
    }
    /**
     * 订货货品管理
     */
    public function stock_purchase()
    {
        $postdata = I('param.');
        $goods_id = intval($postdata['id']);
        if ($goods_id > 0) {
            $goodsdata = M('Goods')->where('id=' . $goods_id)->field('goods_name,goods_sn')->find();
            $this->assign('goodsdata', $goodsdata);
            $this->assign('id', $goods_id);
            $goodsattr = M('GoodsAttr')->alias('ga')->where("gatt.type='checkbox' and ga.goods_id = " . $goods_id)->JOIN("LEFT JOIN __GOODS_ATTRIBUTE__ gatt ON ga.attr_id=gatt.id")->select();
            foreach ($goodsattr as $k => $v) {
                if (empty($v['id'])) continue;
                $v['options'] = strtoarray($v['options']);
                $check_option[$v['id']][] = $v['attr_value'];
                $goodsattr_format[$v['id']] = $v;
            }
            foreach ($check_option as $k => $v) {
                $check[$k] = array_values($v);
                foreach ($goodsattr_format[$k]['options'] as $key => $val) {
                    if (in_array($key, $check[$k])) {
                        $goodsattr_format[$k]['options_format'][$key] = $val;
                    }
                }
            }
            $goodsattrstock = M('GoodsAttrStock')->where('goods_id=' . $goods_id)->order('id')->field(true)->select();
            foreach ($goodsattrstock as $k => $v) {
                $attr_key_array[$k]['attr_key_arr'] = $v['attr_key'];
                $attr_key_array[$k]['attr_key'] = explode('_', $v['attr_key']);
                // $attr_key_array[$k]['stock_cfg'] = $v['stock_cfg'];
                $attr_key_array[$k]['goods_attr_sn'] = $v['goods_attr_sn'];
                $attr_key_array[$k]['sell_count'] = $v['sell_count'];
                $attr_key_array[$k]['attr_price'] = $v['attr_price'];
            }
            foreach ($attr_key_array as $k => $v) {
                foreach ($v['attr_key'] as $val) {
                    if (empty($val)) continue;
                    $goods_attr_info = M('GoodsAttr')->where('id=' . $val)->field('id,attr_id,attr_value')->find();
                    $attr_key_array_format[$k]['attr_val'][$goods_attr_info['attr_id']]['id'] = $goods_attr_info['attr_id'];
                    $attr_key_array_format[$k]['attr_val'][$goods_attr_info['attr_id']]['val'] = $goods_attr_info['attr_value'];
                    // $attr_key_array_format[$k]['stock_cfg'] = $v['stock_cfg'];
                    $attr_key_array_format[$k]['goods_attr_sn'] = $v['goods_attr_sn'];
                    $attr_key_array_format[$k]['sell_count'] = $v['sell_count'];
                    $attr_key_array_format[$k]['attr_price'] = $v['attr_price'];
                    $attr_key_array_format[$k]['attr_key'] = $v['attr_key_arr'];
                }
            }
            if (empty($attr_key_array_format)) {//构造空数组循环
                foreach ($goodsattr_format as $k => $v) {
                    $where[$k]['goods_id'] = $goods_id;
                    $where[$k]['attr_id'] = $k;
                    $goods_attr_info = M('GoodsAttr')->where($where[$k])->field('id,attr_id,attr_value')->order('id asc')->find();
                    $attr_key_array_format[0]['attr_val'][$k]['id'] = $goods_attr_info['attr_id'];
                    $attr_key_array_format[0]['attr_val'][$k]['val'] = $goods_attr_info['attr_value'];
                }
            }
			// echo "<pre>";
			// print_r($attr_key_array_format);exit;
            $this->assign('attr_count', count(array_keys($attr_key_array_format)));//循环总数
            $this->assign('goodsattr_format', $goodsattr_format);
            $this->assign('attr_key_array_format', $attr_key_array_format);
        }
        $this->display();
    }

    public function delete(){
        $id=I('param.id');
        $del_id  = M('GoodsService')->where('id='.$id)->delete();
        if($del_id) $this->success('删除成功');
        else $this->error('删除失败');
    }
    /**
     * 导出商品
     */
    public function export()
    {
        $name = CONTROLLER_NAME;
        $postdata = I('param.');
        $postdata['is_delete'] = 0;
        $postdata['publish_wait'] = 1;
        $map = D($name)->index_condition($postdata);
        $map['goods_type']=1;
        $list = M('Goods')->where($map)->field(true)->select();
        $title = array('序号', '商品编号', '商品名称','价格', '分类', '品牌', '供货商', '库存', '销量');
        $data = array();
        foreach ($list as $k => $v) {
            $data[$k][] = $v['id'];
            $data[$k][] = $v['goods_sn'];
            $data[$k][] = $v['goods_name'];
            $data[$k][] = $v['shop_price'];
            $data[$k][] = idtoname($v['cat_id'], 'GoodsCategory');
            $data[$k][] = idtoname($v['brand_id'], 'Brand', 'brand_name');
            $data[$k][] = idtoname($v['suppliers_id'], 'Suppliers');
            $data[$k][] = $v['goods_number'];
            $data[$k][] = $v['sell_count'];
        }
        export_xls($title, $data, 'utf8');
        unset($title, $data);
        exit;
    }
    /**
     * 导出批发商品
     */
    public function export_pur()
    {
        $name = CONTROLLER_NAME;
        $postdata = I('param.');
        $postdata['is_delete'] = 0;
        $postdata['publish_wait'] = 1;
		$map = array();
        $map = D($name)->index_condition($postdata);
		if (isset($postdata['internetid'])) {
            if($postdata['internetid'] == 1){
				$map['is_internet'] = 1;
			}else if($postdata['internetid'] == 2){
				$map['is_internet'] = 0;
			}else{
				$map['is_internet'] = array('in','1,0');
			}
        }
		if (isset($postdata['typeid'])) {
			if($postdata['typeid'] == 1){
				$map['is_type'] = 1;
			}else if($postdata['typeid'] == 2){
				$map['is_type'] = 0;
			}else{
				$map['is_type'] = array('in','1,0');
			}
        }
        $map['goods_type'] = 5;
        $list = M('Goods')->where($map)->field(true)->select();
        // $title = array('序号', '商品编号', '商品名称','价格', '分类', '品牌', '供货商', '库存', '销量');
        $title = array('序号', '商品条码', '商品名称','价格', '分类', '供货商', '是否网上销售', '销量');
		// echo "<pre>";
		// print_r($postdata);exit;
        $data = array();
        foreach ($list as $k => $v) {
            $data[$k][] = $v['id'];
            $data[$k][] = $v['goods_sn'];
            $data[$k][] = $v['goods_name'];
            $data[$k][] = $v['shop_price'];
            $data[$k][] = idtoname($v['cat_id'], 'PurchaseCategory');
            $data[$k][] = idtoname($v['suppliers_id'], 'Suppliers');
            $data[$k][] = $v['is_internet'] ? '是' : '否';
            $data[$k][] = $v['sell_count'];
        }
        export_xls($title, $data, 'utf8');
        unset($title, $data);
        exit;
    }
    /**
     * 搜索品牌
     */
    public function search_brand()
    {
        $return = array();
        $postdata = I('param.');
        $keyword = $postdata['keyword'];
		$map=array();
        if (is_numeric($keyword)) {
            $map['id|brand_name'] = array(intval($keyword), array('like', '%' . $keyword . '%'), '_multi' => true);
        } else if (!empty($keyword)) {
            $map['brand_name'] = array('like', '%' . (string)$keyword . '%');
        }
        $brands = M('Brand')->where($map)->field('id,brand_name')->order('id asc')->select();
        $options = "<option value=''>" . L('PLEASE_SELECT_BRAND') . "</option>";
        foreach ($brands as $k => $v) {
            $options .= "<option value='" . $v['id'] . "'>" . $v['brand_name'] . "</option>";
        }
        $return['status'] = 1;
        $return['options'] = $options;
        $this->ajaxReturn($return);
    }

    /**
     * 搜索供货商
     */
    public function search_suppliers()
    {
        $return = array();
        $postdata = I('param.');
        $keyword = $postdata['keyword'];
        if (is_numeric($keyword)) {
            $map['id|name'] = array(intval($keyword), array('like', '%' . $keyword . '%'), '_multi' => true);
        } else if (!empty($keyword)) {
            $map['name'] = array('like', '%' . (string)$keyword . '%');
        }
        $brands = M('Suppliers')->where($map)->field('id,name')->order('id asc')->select();
        $options = "<option value=''>" . L('PLEASE_SELECT_SUPPLIER') . "</option>";
        foreach ($brands as $k => $v) {
            $options .= "<option value='" . $v['id'] . "'>" . $v['name'] . "</option>";
        }
        $return['status'] = 1;
        $return['options'] = $options;
        $this->ajaxReturn($return);
    }

    /**
     * 删除，回收站
     * @param $is_delete 0恢复,1删除
     */
    public function recycling()
    {
        $name = 'Goods';
        $postdata = I('post.');
        $id = I('get.id');
        if (empty($postdata['id']) && !empty($id)) $postdata['id'][] = $id;
        $is_delete = I('is_delete');
        if (empty($postdata['id'])) {
            if ($is_delete == 1) $this->error(L('PLEASE_SELECT_DELETE_GOODS'));
            else $this->error('请选择要恢复的商品！');
        }
        $where['is_delete'] = $is_delete;
        foreach ($postdata['id'] as $key => $value) {
            $map['id'] = $value;
            $g_info = M($name)->where($map)->save($where);
        }
        if ($is_delete == 1) {
            if (isset($g_info)) {
                $this->success(L('HAVE_PUT_IN_RECYCLE'));
            } else {
                $this->error(L('DELETE_FAILED'));
            }
        } else {
            if (isset($g_info)) {
                $this->success(L('RECOVER_SUCCESS'));
            } else {
                $this->error(L('RECOVER_FAILED'));
            }
        }
    }

    /**
     * 回收站的商品
     */
    public function recycle()
    {
        $name = CONTROLLER_NAME;
        $postdata = I('param.');
        $postdata['is_delete'] = 1;
        $map = D($name)->index_condition($postdata);
        $map['goods_type'] = 1;
        if (!isset($postdata['catid'])) {
            $postdata['catid'] = 0;
        }
        if (!isset($postdata['brandid'])) {
            $postdata['brandid'] = 0;
        }
        if (!isset($postdata['suppliersid'])) {
            $postdata['suppliersid'] = 0;
        }
        $this->getcateTree($postdata['catid'], '', $postdata['brandid'], $postdata['suppliersid']);
        $list = $this->lists($name, $map);
        $this->assign('list', $list);
        $this->assign($postdata);
        $this->display();
    }
   /**
     * 订货回收站的商品
     */
    public function recycle_purchase()
    {
        $name = CONTROLLER_NAME;
        $postdata = I('param.');
        $postdata['is_delete'] = 1;
        $map = D($name)->index_condition($postdata);
        $map['goods_type'] = 5;
        if (!isset($postdata['catid'])) {
            $postdata['catid'] = 0;
        }
        if (!isset($postdata['brandid'])) {
            $postdata['brandid'] = 0;
        }
        if (!isset($postdata['suppliersid'])) {
            $postdata['suppliersid'] = 0;
        }
        $this->getcateTree($postdata['catid'], '', $postdata['brandid'], $postdata['suppliersid'],'',5);
        $list = $this->lists($name, $map);
        $this->assign('list', $list);
        $this->assign($postdata);
        $this->display();
    }

    public function stock_update()
    {
        $model = D(CONTROLLER_NAME);
        $postdata = I('post.');
		
		
        $data = $model->create($postdata);
        $goods_type=idtoname($postdata['id'],'Goods','goods_type');
        if($goods_type != 5){
            $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/index');
        }else{
            // $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/index_purchase');
            $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/stock_purchase',array('id'=>$postdata['id']));
        }
		if($postdata['attr_key']){
			$success_msg = '编辑成功';
		}else{
			$success_msg = '添加成功，编辑货品的初始库存！';
		}
        $msg = array_merge(array('success' => $success_msg, 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        
        if (!$model->update_goodsattr_stock($postdata)) {//更新商品属性库存，货品
            $this->error('货品编号不能为空或者有重复，请重新输入');
        }
        clearhomehtml($postdata['id']);//更新静态缓存
        unset($data, $postdata);
        $this->success($msg['success'], $msg['url'], $msg['ajax']);
    }
	
	/**
     * 修改订货商品初始库存
     */
    public function sub_shops_stock(){
		$return = array();$return['status'] = 1;
		$postdata = I('param.');
		if ($postdata['id'] && $postdata['goods_num']) {
			$ret = D('Goods')->save_shops_stock($postdata);//仓库初始库存
			if ($ret['status'] == 0) {
				$return['status'] = 0;$return['msg'] = $ret['msg'];
			}
		}else{
			$return['status'] = 0;$return['msg'] = '参数错误！';
		}
		$this->ajaxReturn($return);
    }

    public function check_goods_attr_sn()
    {
        $postdata = I('post.');
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => '', 'ajax' => IS_AJAX), (array)$msg);
        $map['goods_attr_sn'] = $postdata['goods_attr_sn'];
        $goodsattrstock = M('GoodsAttrStock')->where($map)->count();
        $status = 0;
        if ($goodsattrstock > 0) $status = 1;
        unset($data, $postdata);
        $this->success($status, '', $msg['ajax']);
    }

    /**
     * 店铺商品管理列表及搜索
     */
    public function index_shops()
    {
        $name = CONTROLLER_NAME;
        $postdata = I('param.');
        if (!isset($postdata['shops_keyword'])) {
            $postdata['shops_keyword'] = '';
        }
        $postdata['is_delete'] = 0;
        $postdata['publish_wait'] = 1;
        $map = D($name)->index_condition($postdata);
        $this->getcateTree(!empty($postdata['catid']) ? $postdata['catid'] : 0, '', !empty($postdata['brandid']) ? $postdata['brandid'] : 0);
        $list = $this->lists($name, $map);
        $this->assign('list', $list);
        $this->assign($postdata);
        $this->display();
    }

    /**
     * 店铺回收站的商品
     */
    public function recycle_shops()
    {
        $name = CONTROLLER_NAME;
        $postdata = I('param.');
        if (!isset($postdata['shops_keyword'])) {
            $postdata['shops_keyword'] = '';
        }
        $postdata['is_delete'] = 1;
        $map = D($name)->index_condition($postdata);
        $this->getcateTree(!empty($postdata['catid'])?$postdata['catid']:0, '', !empty($postdata['brandid'])?$postdata['brandid']:0);
        $list = $this->lists($name, $map);
        $this->assign('list', $list);
        $this->assign($postdata);
        $this->display();
    }
	public function _before_delete(){
		$id=I('id');
		if(isset($id)&&is_array($id)){
			foreach($id as $k=>$v){
				$result=check_delete($v,4);
				if(!$result['status'])unset($id[$k]);
			}
			if(empty($id)){$this->error($result['info']);exit;}
		}else{
			$result=check_delete($id,4);
			if(!$result['status']){$this->error($result['info']);exit;}
		}
		$this->id=$id;
	} 
    /**
     * 商品管理列表及搜索
     */
    public function collect_goods()
    {
        $name="GoodsCollect";
        $map['status']=1;
        $map['shop_id']=0;
        $map['type']=0;
        $list = $this->lists($name, $map);
        $this->assign('list', $list);
        $this->display();
    }
    /**
     * 订货商品列表及搜索
     */
    public function index_purchase()
    {
        $name = CONTROLLER_NAME;
        $postdata = I('param.');
        $postdata['is_delete'] = 0;
        $postdata['publish_wait'] = 1;
        $map = D($name)->index_condition($postdata,5);
        $map['goods_type'] = array('eq','5,2');
        if (!isset($postdata['catid'])) {
            $postdata['catid'] = 0;
        }
        if (!isset($postdata['brandid'])) {
            $postdata['brandid'] = 0;
        }
        if (!isset($postdata['suppliersid'])) {
            $postdata['suppliersid'] = 0;
        }
		if (isset($postdata['internetid'])) {
            if($postdata['internetid'] == 1){
				$map['is_internet'] = 1;
			}else if($postdata['internetid'] == 2){
				$map['is_internet'] = 0;
			}else{
				$map['is_internet'] = array('in','1,0');
			}
        }
		if (isset($postdata['typeid'])) {
			if($postdata['typeid'] == 1){
				$map['is_type'] = 1;
			}else if($postdata['typeid'] == 2){
				$map['is_type'] = 0;
			}else{
				$map['is_type'] = array('in','1,0');
			}
        }
        $this->getcateTree($postdata['catid'], '', $postdata['brandid'], $postdata['suppliersid'],'',5);
		unset($map['shop_id']);
		$list = $this->lists($name, $map);
        $this->label_list();
        $this->assign('list', $list);
        $this->assign($postdata);
        $this->display('index_purchase');
    }

    /*
    *删除商品标签
     */
    public function sub_delete(){
        $return = array();$return['status'] = 0;
        $post = I('param.');
        $label_id = $post['label_id'];
        if($label_id){
            $str_label = ','.$label_id.',';
            $ret = M('Goods')->execute("update __GOODS__ set label_ids = replace (`label_ids`,'".$str_label."',',') where label_ids like '%".$str_label."%'");
            $map = array();$map['id'] = $label_id;$map['pid'] = 48;
            $res = M('Type')->where($map)->delete();
            if($res){
                $return['status'] = 1;
            }else{
                $return['msg'] = '删除失败！';
            }
        }else{
            $return['msg'] = '参数错误！';
        }
        $this->ajaxReturn($return);
    }
     /**
     * 添加订货商品
     */
    public function add_purchase()
    {
		$umap = array();
		$umap['status']=1;
        $unitlist = M('GoodsUnit')->where($umap)->select();
        $select_unit = '';
        if (!empty($unitlist)) {
            foreach ($unitlist as $k => $v) {
				$select_unit .= "<option value='" . $v['id'] . "'>" . $v['name'] . "</option>";
            }
        }
        $this->assign('select_unit', $select_unit);
		
        $this->getNodeTree('','','','','',5);
        $basedefault = array('moreimg' => '', 'moreimgstr' => '', 'morecatarr' => '', 'morecatid' => '', 'configstr' => '');
        $this->assign($basedefault);
        $this->attr_arr();
        $this->get_goods_label();
        $this->get_member_price();//会员价
        $this->get_review_rank();//会员价

		$this->imgs_cate_list();
        $this->label_list();
        $this->display('edit_purchase');
    }
	public function imgs_cate_list(){
		$list = json_decode(curlget('http://www.hanchao9999.com/barcode/img.php?keyword=catlist'),true);
		$imgs_cate_html = '';
		if($list['info']){
			foreach($list['info'] as $k => $v){
				$imgs_cate_html.='<option value="'.$k.'">'.$v.'</option>';
			}
		}
        $this->assign('imgs_cate_html', $imgs_cate_html);
	}
	public function service(){
		$servicetypes = array('1'=>'到店服务','2'=>'上门服务','3'=>'会员自选');
		$this->assign('servicetypes',$servicetypes);
		$name = CONTROLLER_NAME;
		$map=array();
        $postdata = I('param.');
        $map['is_delete'] = 0;
        $map['publish_wait'] = 1;
        $map['goods_type'] = 4;
		if($postdata['catid'])$map['cat_id'] = $postdata['catid'];
		if($postdata['service_types']==1){$map['service_tostore']=1;$map['service_tohome']=0;}elseif($postdata['service_types']==2){$map['service_tostore']=0;$map['service_tohome']=1;}elseif($postdata['service_types']==3){$map['service_tostore']=1;$map['service_tohome']=1;}
			
		
		$keyword = I('keyword');
        if(!empty($keyword)){
			$whereor['id']=array('like','%'.$keyword.'%');
            $whereor['goods_sn']=array('like','%'.$keyword.'%');
            $whereor['goods_name']=array('like','%'.$keyword.'%');
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
            $seotitle=$keyword.'_';
		}
		
		$this->getShops(1);
        //仓库管理员
        if($this->auth_group_id==2){
            $map['shop_id']=$this->admin_info['shop_id'];
        }
        $list = $this->lists($name, $map);
        $this->assign('list', $list);
        $this->assign($postdata);
		$this->display();
	}
	 /**
     * 添加服务
     */
    public function service_add()
    {
		if (IS_POST) {
			$name = CONTROLLER_NAME;
			$map = array();
			$postdata = I('post.');
			
			$map['status'] = 1;
			if($postdata['is_integral']!=1){
                $postdata['is_integral']=0;
            }
			
			if($postdata['spec_spec'] && $postdata['spec_price']){
				$service_spec_info = array();
				foreach($postdata['spec_spec'] as $k => $v){
					if($v && $postdata['spec_price'][$k]){
						$service_spec_info[$v] = $postdata['spec_price'][$k];
					}
				}unset($k,$v,$postdata['spec_spec'],$postdata['spec_price']);
				$postdata['service_spec'] = json_encode($service_spec_info);
			}
			// echo "<pre>";print_r($postdata);exit;
			
			$model = D($name);
			if (false === $model->create($postdata)) {
				$this->error($model->getError());
			}
			$id = $model->add($postdata);
			if ($id !== false) {
				$postdata['id'] = $id;
				$model->update_user_price($postdata, 1);//更新会员价
				// $model->update_goods_sn($postdata, 1);//更新货号
                $model->update_service_sn($postdata, 1);//更新货号
				$model->update_goods_content($postdata, 1);//更新商品详情和seo
				unset($postdata);
				
				$jumpUrl = U(CONTROLLER_NAME. '/service');
				$this->assign('jumpUrl', $jumpUrl);
				$this->success(L('ADD_OK'));
			} else {
				$this->error(L('ADD_ERROR') . ': ' . $model->getDbError());
			}
		}else{
			$this->getShops(1);
			$this->assign('shop_id', 0);
			$this->display('service_edit');
		}
        
    }
	public function service_edit(){
		$id = I('get.id');
        $info = '';
        if (!$id) $this->error(L('PARAM_ERR'));
		$info = M('Goods')->field(true)->find($id);
		$info['content'] = idtoname($id,'GoodsContent','content','goods_id',false);
		
		if($info['service_spec']){
			$info['service_spec_info'] = json_decode($info['service_spec'],true);
			unset($info['service_spec']);
		}
		$info['speac_count'] = count($info['service_spec_info']);
		// echo "<pre>";print_r($info);exit;
		
		$this->assign($info);
		$this->assign($id);
		$this->getShops(1);
		$this->display();
	}
	public function service_update(){
			$model = D(CONTROLLER_NAME);
			$postdata = I('post.');
			
            if($postdata['is_integral']!=1){
                $postdata['is_integral']=0;
            }
			if($postdata['spec_spec'] && $postdata['spec_price']){
				$service_spec_info = array();
				foreach($postdata['spec_spec'] as $k => $v){
					if($v && $postdata['spec_price'][$k]){
						$service_spec_info[$v] = $postdata['spec_price'][$k];
					}
				}unset($k,$v,$postdata['spec_spec'],$postdata['spec_price']);
				$postdata['service_spec'] = json_encode($service_spec_info);
			}
			// echo "<pre>";print_r($postdata);exit;
			
			if(!$postdata['service_tostore'] && !$postdata['service_tohome']){
				$this->error('服务类型至少选择一种');
			}
            if(!$postdata['service_tostore']){
                $postdata['service_tostore'] = 0;
            }
            if(!$postdata['service_tohome']){
                $postdata['service_tohome'] = 0;
            }
			$data = $model->create($postdata);
			$jumpUrl = U(CONTROLLER_NAME . '/service');
			$id = array_unique((array)I('id', 0));
			$id = is_array($id) ? implode(',', $id) : $id;
			$where = array_merge(array('id' => array('in', $id)), (array)$where);
			$msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
			if ($model->where($where)->save($data) !== false) {
				$postdata['id'] = $id;
				$model->update_user_price($postdata);//更新会员价
				// $model->update_goods_sn($postdata);//更新货号
                $model->update_service_sn($postdata);//更新货号
				$model->update_goods_content($postdata);//更新商品详情和seo
				clearhomehtml($id);//更新静态缓存
				unset($data, $postdata, $newgoodscat, $newgoodsimg, $goodstype, $goodstypearr, $newgoodsattr);
				$this->success($msg['success'], $msg['url'], $msg['ajax']);
			} else {
				$this->error($msg['error'], $msg['url'], $msg['ajax']);
			}
	}
	/**
     * 回收站的商品
     */
    public function service_recycle(){
        $name = CONTROLLER_NAME;
        $postdata = I('param.');
        $map['is_delete'] = 1;
        $map['goods_type'] = 4;
        if($postdata['catid'])$map['cat_id'] = $postdata['catid'];
		$keyword = I('keyword');
        if(!empty($keyword)){
			$whereor['id']=array('like','%'.$keyword.'%');
            $whereor['goods_sn']=array('like','%'.$keyword.'%');
            $whereor['goods_name']=array('like','%'.$keyword.'%');
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
            $seotitle=$keyword.'_';
		}
        $list = $this->lists($name, $map);
        $this->assign('list', $list);
		$this->getShops(1);
        $this->assign($postdata);
        $this->display();
    }
	
	/* 得到所有仓库和服务分类 */
    private function getShops($type = ''){
		$map = array();
		$map['status'] = 1;
		$map['shop_type'] = 1;
        $shopsData = M('Shops')->where($map)->field('id,name')->select();
		$serviceCat = M('ServiceCategory')->where('status=1')->field('id,name')->select();
		if ($type == 1) {
			// $shopsData = format_array2select($shopsData); 
			$serviceCat = format_array2select($serviceCat); 
		}
		
        $this->assign('shopsData', $shopsData);
        $this->assign('serviceCat', $serviceCat);
    }
	/**
     * 积分商品
     */
    public function points(){
		$name = CONTROLLER_NAME;
        $map['status'] = 1;
        $map['is_delete'] = 0;
        $map['goods_type'] = 3;
		$keyword = I('keyword');
        if(!empty($keyword)){
			$whereor['id']=array('like','%'.$keyword.'%');
            $whereor['goods_sn']=array('like','%'.$keyword.'%');
            $whereor['goods_name']=array('like','%'.$keyword.'%');
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
            $seotitle=$keyword.'_';
		}
        $list = $this->lists($name, $map);
        $this->assign('list', $list);
        $this->display();
	}
	 /**
     * 
     */
    public function points_add(){
		if (IS_POST) {
			$name = CONTROLLER_NAME;
			$model = D($name);
			if (false === $model->create()) {
				$this->error($model->getError());
			}
			$id = $model->add();
			if ($id !== false) {
				$postdata = I('post.');
				$postdata['id'] = $id;
				$model->update_user_price($postdata, 1);//更新会员价
				$model->update_goods_sn($postdata, 1);//更新货号
				$model->update_goods_content($postdata, 1);//更新商品详情和seo
				unset($postdata);
				
				$jumpUrl = U(CONTROLLER_NAME. '/points');
				$this->assign('jumpUrl', $jumpUrl);
				$this->success(L('ADD_OK'));
			} else {
				$this->error(L('ADD_ERROR') . ': ' . $model->getDbError());
			}
		}else{
			$this->display('points_edit');
		}
        
    }
	public function points_edit(){
		$id = I('get.id');
        $info = '';
        if (!$id) $this->error(L('PARAM_ERR'));
		$info = M('Goods')->field(true)->find($id);
		$info['content'] = idtoname($id,'GoodsContent','content','goods_id',false);
		$this->assign($info);
		$this->assign($id);
		$this->display();
	}
    public function points_update(){
            $model = D(CONTROLLER_NAME);
            $postdata = I('post.');
            $data = $model->create($postdata);
            $jumpUrl = U(CONTROLLER_NAME . '/points');
            $id = array_unique((array)I('id', 0));
            $id = is_array($id) ? implode(',', $id) : $id;
            $where = array_merge(array('id' => array('in', $id)), (array)$where);
            $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
            if ($model->where($where)->save($data) !== false) {
                $postdata['id'] = $id;
                $model->update_user_price($postdata, 1);//更新会员价
                $model->update_goods_sn($postdata, 1);//更新货号
                $model->update_goods_content($postdata, 1);//更新商品详情和seo
                clearhomehtml($id);//更新静态缓存
                unset($data, $postdata);
                $this->success($msg['success'], $msg['url'], $msg['ajax']);
            } else {
                $this->error($msg['error'], $msg['url'], $msg['ajax']);
            }
    }
	public function search_attrinfo(){
		$return = array();
		$return['status'] = 0;
		$goodsid = intval($_REQUEST['goodsid']);//商品id
		$postdata = I('post.');
		
		$attr_id = $postdata['attrid'];
		
		if($attr_id){
			$ga_map = array();
			$ga_map['status'] = 1;
			$ga_map['id'] = $attr_id;
			$allattr=M('GoodsAttribute')->where($ga_map)->field(true)->find();
			
			$allattr['options'] = strtoarray($allattr['options']);
			if($allattr){
				$return['status'] = 1;
				$this->assign($allattr);
				$return['html'] = $this->fetch("pattr_html");
			}else{
				$return['msg'] = '没有找到相关信息！';
			}
		}else{
			$return['msg'] = '请选择属性！';
		}
		$this->ajaxReturn($return);
	}
    /**
     * 获取商品信息
     */
	public function get_goods()
    {
        $return=$where=$map = array();
        $postdata = I('param.');
        $id= intval($postdata['id']);
        $html='';
        if($id){
            $map['id'] = $id;
            $map['goods_type']=5;
            $info = M('Goods')->where($map)->field('id,shop_price,supply_price,goods_sn,unit_id,is_type,goods_name')->find();
            $where['goods_id'] =$id;
            $attr_key = M('GoodsAttrStock')->where($where)->field('attr_key,attr_price,goods_attr_sn')->select();
            if($attr_key){

                $html='<select class=\'form-control\' name=\'attr_key[]\' onchange=\'shopprice('.this.')\'>';
                foreach($attr_key as $k=>$v){
                    $attr = attr_key2name($v['attr_key'],$id);
                    $html.='<option value='.$v['attr_key'].' attrprice='.$v['attr_price'].' goodssn='.$v['goods_attr_sn'].'>'.$attr.'</option>';
                }
                $html.='</select>';
                $info['shop_price']=$attr_key[0]['attr_price'];
                $info['goods_sn']=$attr_key[0]['goods_attr_sn'];
                $info['attr_keys']=$html;
            }else{
                $info['attr_keys']='';
            }
            $info['unit_name']=idtoname($info['unit_id'],'GoodsUnit','name','id',false);
            $return['status'] = 1;
            $return['info'] = $info;
        }else{
            $return['status'] = 0;
            $return['info'] = '数据获取错误';
        }

        $this->ajaxReturn($return);
   }
    public function group_goods($id){
        $map=array();
        $map['goodsid'] = $id;
        $list = M('GroupGoods')->where($map)->select();
        foreach($list as $k=>$v){

            if($v['attr_key']){
                $attr_key = explode('-',$v['attr_key']);
                $list[$k]['attr']=attr_key2name($attr_key[1],$v['linkid']);
                $list[$k]['shop_price']=idtoname($attr_key[1],'GoodsAttrStock','attr_price','attr_key',false);
                $list[$k]['goods_sn']=idtoname($attr_key[1],'GoodsAttrStock','goods_attr_sn','attr_key',false);
            }else{
                $list[$k]['shop_price']=idtoname($v['linkid'],'Goods','shop_price','id',false);
                $list[$k]['goods_sn']=idtoname($v['linkid'],'Goods','goods_sn','id',false);
            }

        }
        $this->assign('groupnum',count($list));
        $this->assign('groupgoods',$list);
    }
	public function file_down(){
		file_down(ROOT_PATH."/uploads/file/goods.csv",'Goods导入格式文档.csv');
	}
	
	public function do_import(){
		$filename = $_FILES['file']['tmp_name'];
		$result = input_csv($filename);
		$len = count($result);$py = new \Common\Vendor\Py();
		for ($i = 1; $i < $len; $i++) { //循环获取各字段值 
			$data = array();
            $data['goods_sn'] = $result[$i][0];
            $data['goods_name'] = iconv('gb2312', 'utf-8', $result[$i][1]); //中文转码
            $data['supply_price'] = $result[$i][2];
            $data['shop_price'] = $result[$i][3];
            $data['market_price'] = $result[$i][4];
            $data['cat_id'] = $result[$i][5];
            $data['suppliers_id'] = $result[$i][6];
            $data['is_internet'] = $result[$i][7];
			$data['is_type'] = $result[$i][8];
            $data['unit_id'] = $result[$i][9];
			// 0:普通商品，1:计重商品
			if($data['goods_sn']){
				$map = array();$map['goods_sn'] = $data['goods_sn'];
				$count = M('Goods')->where($map)->count();
				if($count) continue;
			}else{
				if($data['is_type'] == 1){
					$data['goods_sn'] = weight_goods_sn();
					$data['goods_weight'] = 1;
				}else{
					continue;
				}
			}
			
            $data['goods_zhuji']= $py->getFirstLetter($data['goods_name']);
			$data['addtime'] = NOW_TIME;
			$data['updatetime'] = NOW_TIME;
			$data['goods_type'] = 5;
			$data['is_hot'] = 1;
			$data['is_new'] = 1;
			$data['is_delete'] = 0;
			$data['publish_wait'] = 1;
			$data['status'] = 1;
			$query = M('Goods')->add($data);
			$postdata = array();$postdata['id'] = $query;$postdata['goods_zhuji']=$data['goods_zhuji'];
			D('Goods')->update_goods_code($postdata, 1);//更新货码
		} 
		if($query){ 
			$this->success('导入成功！'); 
		}else{ 
			$this->error('导入失败！'); 
		} 
	}
	public function goods_moresn(){
		if (IS_POST) {
			$postdata = I('post.');
            $res = D('Goods')->update_goods_moresn($postdata);//更新商品一品多码
			if($res['status'] == 1){
				$this->success('编辑成功！');
			}else{
				$this->error($res['msg']);
			}
		}else{
			$goods_id = I('id');
			if(!$goods_id){$this->error("参数错误！");}
			$map = array();$map['goods_id'] =  $goods_id;
			$goods_code = M('GoodsMorecode')->where($map)->getField('goods_sn',true);
			$goods_sns = implode(',',$goods_code);
			$this->assign('goods_sns',$goods_sns);
			$this->assign('goods_id',$goods_id);
			$this->display();
		}
	}
    public function all_edit(){
        $return=array('status'=>3,'msg'=>'');
        $postdata=I('param.');
        $postdata['datas']= str_replace('&amp;', '&', $postdata['datas']);
        parse_str($postdata['datas'], $data);
        $ids=$data['id'];
        if(empty($ids)){$return['msg']='请选择要编辑的商品';$this->ajaxReturn($return);}
        $return['status']=1;
        $return['ids']=$ids;
        $tr_td='';
        foreach ($ids as $key => $value) {
            $tr_td.='<tr><td>'.idtoname($value,'Goods','goods_name').'</td></tr>';
        }
        $goods_num= count($ids);
        $return['goods_num']=$goods_num;
        $return['tr_td']=$tr_td;
        $return['ids']=implode(',', $ids);
        $this->ajaxReturn($return);
    }
    public function all_change(){
        $return=array('status'=>3,'msg'=>'');
        $postdata=I('param.');
        if(empty($postdata['change_type'])){$return['msg']='请选择修改类别';$this->ajaxReturn($return);}
        $select_option='';
        $input='';
        switch ($postdata['change_type']) {
            // case 'is_offline':
            //     $select_option='<span>是否线下销售</span>';
            //     $select_option.='<div id="edit_sb_commission" class="swicth" onclick="huainput(\''.$postdata['change_type'].'\')"><div class="sLeft">是</div><div class="sRight">否</div><div class="sBotton"></div></div>';
            //     $input='<input type="hidden" name="is_offline" id="is_offline" value="1" />';
            //     break;
            case 'is_internet':
                $select_option='<span>是否网上销售</span>';
                $select_option.='<div id="edit_sb_commission" class="swicth" onclick="huainput(\''.$postdata['change_type'].'\')"><div class="sLeft">是</div><div class="sRight">否</div><div class="sBotton"></div></div>';
                $input='<input type="hidden" name="is_internet" id="is_internet" value="1" />';
                break;
            case 'is_dinghuo':
                $select_option='<span>是否订货</span>';
                $select_option.='<div id="edit_sb_commission" class="swicth" onclick="huainput(\''.$postdata['change_type'].'\')"><div class="sLeft">是</div><div class="sRight">否</div><div class="sBotton"></div></div>';
                $input='<input type="hidden" name="is_dinghuo" id="is_dinghuo" value="1" />';
                break;
            case 'cat_id':
                $goods_type=$postdata['goods_type'];
                if($goods_type==5){
                    $GoodsCategory = getcache('PurchaseCategory');
                }else{
                    $GoodsCategory = getcache('GoodsCategory');
                }

                $Tree = new \Common\Vendor\Tree();
                $select_option = '<span>商品分类</span>';
                $select_option.='<select name="cat_id" id="cat_id">';
                $select_option.= "<option value='0'>请选择分类</option>";
                $treemini = $Tree->treemini($GoodsCategory);
                $select_option .= $Tree->treeminioption($treemini, 0);
                $select_option.='</select>';
                break;
            case 'brand_id':
                $select_option = '<span>商品品牌</span>';
                $brand = M('Brand')->where('status=1')->order('convert(brand_name using gb2312) ASC')->field('id,brand_name')->select();
                $select_option.='<select name="brand_id" id="brand_id">';
                    $select_option.= "<option value=''>" . L('PLEASE_SELECT_BRAND') . "</option>";
                    foreach ($brand as $k => $v) {
                        $select_option .= "<option value='" . $v['id'] . "'>" . $v['brand_name'] . "</option>";
                    }
                $select_option.='</select>';
                break;
            case 'staff_comm':
                $onclick="$('#money')";
                $select_option='<span>是否提成</span>';
                $select_option.='<div id="edit_sb_commission" class="swicth" onclick="huainput(\''.$postdata['change_type'].'\')"><div class="sLeft">是</div><div class="sRight">否</div><div class="sBotton"></div></div>';
                $input='<input type="hidden" name="staff_comm" value="1" />';
                $input.='<div class="item top"><div class="radioBox14"><input type="radio" name="staffcomm" value="1" id="staff_comm_2"></div><div class="project"><b>按系统设定</b></div></div>';
                $input.='<div class="item top"><div class="radioBox14"><input type="radio" name="staffcomm" value="2" id="staff_comm_3"></div><div class="project"><b>按固定金额</b><input class="textInput quantity" onblur="staff_comm_onblur(this)" onclick="staff_comm_click(this)" onmouseover="staff_comm_onmouseover(this)" onmouseout="staff_comm_onmouseout(this)" type="text" name="money" id="money" value="0.00" maxlength="6"><span>元 </span></div></div>';
                break;
            case 'suppliers_id':
                $goods_type=$postdata['goods_type'];
                $select_option = '<span>选择供货商</span>';
                $where_s=array();
                $where_s['status']=1;
                if($goods_type==5){
                    $where_s['is_purchase']=1;
                }else{
                    $where_s['is_direct']=1;
                }
                $suppliers_info = M('Suppliers')->where($where_s)->order('convert(name using gb2312) ASC')->field('id,name')->select();
                $select_option.='<select name="suppliers_id" id="suppliers_id">';
                $select_option.= "<option value='0'>请选择供货商</option>";
                if (!empty($suppliers_info)) {
                    foreach ($suppliers_info as $k => $v) {
                        $select_option .= "<option value='" . $v['id'] . "'>" . $v['name'] . "</option>";
                    }
                }
                $select_option.='</select>';
                break;
            case 'is_delete':
                $select_option = '<span>商品回收站</span>';
                $input='<input type="hidden" name="is_delete" id="is_delete" value="1" />';
                break;
            
        }
        $return['status']=1;
        $return['select_option']=$select_option;
        $return['input']=$input;
        $this->ajaxReturn($return);
    }
    public function all_update(){
        $return=array('status'=>3,'msg'=>'');
        $model = M(CONTROLLER_NAME);
        $postdata=I('param.');
        if (empty($postdata['ids'])){$return['msg']='请选择要编辑的商品！';$this->ajaxReturn($return);}
        $ids=explode(',', $postdata['ids']);
        $save=array();
        if($postdata['staff_comm']>0)$postdata['staff_comm']=$postdata['staffcomm'];
        unset($postdata['ids'],$postdata['staffcomm'],$postdata['__hash__']);
        $save=$postdata;
        $save['updatetime']=NOW_TIME;
        foreach ($ids as $key => $value) { 
            $save['id']=$value;
            $result=$model->save($save);
        }
        if ($result != false) {
            $return['status']=1;
            $return['msg']='编辑成功！';
        } else {
            $return['msg']='编辑失败！';
        }
        $this->ajaxReturn($return);
    }
}