<?php
/**
 * 订单管理
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author zhaoh <zhao@qq.com>
 */

namespace Shop\Controller;
use Think\Controller;
class PurOrderController extends BaseController {
	public function _initialize()
    {
        parent::_initialize();
        $shops_info=session('shops_info');
        if(empty($shops_info['id']))$this->error('请登录',U('Shop/Register/shop_login'));
		$this->mendian();
		$this->ship_status=array('1'=>'待发货','2'=>'待入库','3'=>'已完成');
		$this->assign('ship_status',$this->ship_status);
		$this->stocktaking_status=array('1'=>'盘盈','2'=>'盘亏');
		$this->assign('stocktaking_status',$this->stocktaking_status);
    }
    public function supindex(){
        if (!checksiteauth('CangKu')) {
            exit;
        }
		if($this->shops_info)$this->redirect('Home/PurIndex/index');//已登录
        $this->display();
    }
	/**
	 * 订单管理
	 */
    public function pur_index(){
		$postdata=I('param.');
		$tabid=$postdata['tabid'];
		if(empty($tabid)){
			$all_order=D('Common/OrderInfo')->all_order($postdata,'','',10,true,10);
		}elseif($tabid=='no_pay'){
			$all_order=D('Common/OrderInfo')->all_order($postdata,'no_pay','','','',10);
		}elseif($tabid=='no_ship'){
			$all_order=D('Common/OrderInfo')->all_order($postdata,'no_ship','','','',10);
		}elseif($tabid=='yes_ship'){
			$all_order=D('Common/OrderInfo')->all_order($postdata,'yes_ship','','','',10);
		}
		$tabid = $tabid ? $tabid : 'index';
		$this->assign($all_order);$this->assign($postdata);
        $this->display($tabid);
    }
	/**
	 * 发货弹窗
	 */
	public function ship_info(){
		$order_id=I('id');
		$order_info=M('OrderInfo')->where('id='.$order_id)->field('order_sn,id')->find();
		$this->assign($order_info);
		$shipping_list=M('Shipping')->where('status=1')->field('code,name')->select();
        foreach($shipping_list as $k=>$v){
            $shipping_info[$v['code']]=$v['name'];
        }
        $this->assign('shipping',$shipping_info);
		$this->display();
	}
	/**
	 * 店铺发货
	 */
	public function ship(){
		$postdata=I('param.');
		$postdata['admin_id']=MID;
		$postdata['type']='Shop';//店铺发货日志
		$return=D('Common/OrderInfo')->ship_goods($postdata);
		$this->ajaxReturn($return);
	}
	/**
	 * 修改运费
	 */
	public function change_ship_free(){
		$id=I('param.id');
		//订单信息
		$info=M('OrderInfo')->where('id='.$id)->field('id,order_sn,goods_amount,order_amount,delivery_fee')->find();
		//付款单信息
		$where['is_delete'] = 0;
		$where['order_id'] = array("like", "%," . $id . ",%");
		$need_pay = M("PayLog")->where($where)->getField('need_pay');
		$info['order_amount']=$info['order_amount']>$need_pay?$need_pay:$info['order_amount'];
		$this->assign($info);
		$this->display();
	}
	/**
	 * 修改运费
	 */
	public function change_ship(){
		$post=I('param.');
		$post['admin_id']=MID;
		$post['type']='Shop';//店铺修改运费日志
		$return=D('Common/OrderInfo')->change_ship_free($post);
		$this->ajaxReturn($return);
	}
	/**
	 * 退款退货
	 */
    public function back(){
		$postdata=I('param.');
		$tabid=$postdata['tabid'];
		if(empty($tabid)){
			$return=D('ReturnGoods')->return_list();$this->assign($return);
		}elseif($tabid=='refund'){
			$return=D('ReturnGoods')->refund_list();$this->assign($return);
		}
		$tabid=$tabid?$tabid:'back';
        $this->display($tabid);
    }
	/**
	 * 退货的确认收货
	 */
    public function confirm_goods(){
		$post['id']=I('id');
		$post['admin_id']=MID;//操作日志用
		$post['type']='Shop';//操作日志用
		$return=D('Common/OrderInfo')->confirm_goods($post);
        $this->ajaxReturn($return);
    }
    /**
     * 订单详情
     */
    public function info(){
        $id = I('param.id');
        $postdata=I('param.');
        $tabid=$postdata['tabid'];
        if(empty($id)){$this->redirect('Order/index');}
        $map['uid']=$this->shops_info['shop_id'];
        $map['id']=$id;
        $order_info = M('OrderInfo')->where($map)->field(true)->find();
        if($order_info) {
            //print_r($order_info);
            $order_info['end_time'] = $order_info['addtime'] + C('CANCEL_ORDER_TIME') * 86400;//取消订单倒计时
            $order_info['ship_time'] = M('ShipOrder')->where('order_id=' . $id)->getField('ship_time');//发货时间
            $order_info['get_time'] = M('ShipOrder')->where('order_id=' . $id)->getField('get_time');//收货时间
            $order_goods = M('OrderGoods')->where('order_id=' . $id)->field(true)->select();
			$ordershipping=M('ShipOrder')->where('order_id='.$id)->field(true)->select();
			$ordership=array();
			foreach($ordershipping as $v){
				$goodsid=explode(',',$v['goods_id']);
				foreach($goodsid as $val){
					$ordership[$val]=$v;
				}
			}
			foreach ($order_goods as $k => $v) {
				if(!empty($v['goods_attr'])){//获取属性和货号
					$attr = unserialize($v['goods_attr']);
					$order_goods[$k]['attr_name'] = $attr['name'];
					$attr_map['attr_key']=$attr['key'];
					$attr_map['goods_id']=$v['goods_id'];
					$attr_sn=M('goods_attr_stock')->where($attr_map)->getField('goods_attr_sn');
					$order_goods[$k]['attr_sn'] = $attr_sn;
				}
				$order_goods[$k]['goods_number'] =intval($order_goods[$k]['goods_number']);
				$order_goods[$k]['img'] = idtoname($v['goods_id'], 'Goods', 'img');
				$order_goods[$k]['goods_integral'] = $v['goods_integral'];
				$order_goods[$k]['shipping']=$ordership[$v['goods_id']];
			}
            $invoice = unserialize($order_info['invoice_info']);//print_r($invoice);
            $this->assign($invoice);
            $this->assign($order_info);
            $this->assign('order_goods', $order_goods);
        }else{
            $this->error('无此操作权限');
        }
        $this->assign('menu_action_current', 'index');
        $tabid=$tabid?$tabid:'info';
        $this->display($tabid);
    }
    /**
     * 缺货列表
     */
    public function qh_index(){
		$shops_info = checkshopauthtype();
        if($shops_info){
			$map['shop_id'] = $shops_info['shop_id'];
			$map['qh_count'] = array('neq',0);
			$map['_string'] = 'qh_count > goods_number';
			$goods_list = page_list('ShopsGoodsStock',$map,'','','15');
			if($goods_list){
				$this->assign($goods_list); 
			}   
        }
        $this->assign('title_ass','缺货商品');
        $this->display();
    }
    /**
     * 编辑缺货预警值
     */
    public function edit_qh(){
        $return['status'] = 0;$return['info'] = '修改失败';
        $goods_id = I('post.goods_id');
        $map['goods_id'] = $goods_id;
        $map['shop_id'] = MID;
        $goods = M('ShopsGoods')->where($map)->field(true)->find();
        $qh_num = I('post.qh_num');
        if($goods && $goods_id && $qh_num){
            $save['qh_count'] = $qh_num;
            $ret = M('ShopsGoods')->where($map)->save($save);
            $res = M('ShopsGoodsStock')->where($map)->save($save);
            if($ret && $res){
                $return['status'] = 1;
                $return['info'] = '修改成功';
            }
        }
        $this->ajaxReturn($return);
    }
	/**
	 * 确认收货
	 */
	public function confirm_order(){
		$postdata['order_id']=I('order_id');
		$postdata['admin_id']=MID;//操作日志用
		$postdata['type']='Shops';//操作日志用
		$postdata['og_id']=I('og_id');
		$postdata['number']=I('number');
		$result=D('Common/OrderInfo')->pconfirm_order($postdata);
		$this->ajaxReturn($result);
	}
	/**
	 * 退款审核页面
	 */
	public function refund_content(){
		$order_id=I("order_id");
		$order_goods=I("order_goods");
		$score=I("score");
		$this->assign("order_id",$order_id);
		$this->assign("order_goods",$order_goods);
		$this->assign("score",$score);
		if($score=='th'){
			$this->assign('types','退货');
			$this->assign('tplseo_title','退货审核'.'_'.C('WEB_SITE_TITLE'));
			$this->assign('page_title','退货审核');
		}elseif($score=='tk'){
			$this->assign('types','退款');
			$this->assign('tplseo_title','退款审核'.'_'.C('WEB_SITE_TITLE'));
			$this->assign('page_title','退款审核');
		}
		$this->display();
	}
	/**
	 * 退款
	 */
	public function refund_money(){
		$data=I("post.");
		$return=D('Common/OrderInfo')->refund_audit($data);
		$this->ajaxReturn($return);
	}
	/**
	 * 退货
	 */
	public function refund_goods(){
		$data=I("post.");
		$return=D('Common/OrderInfo')->apply_return($data);
		$this->ajaxReturn($return);
	}
	/**
	 * 退款审核操作
	 */
	public function sub_refund(){
		$data=I("post.");
		$order_info=$refund_data=array();
		$order_info[$data['data']['order_id']]=$data['data']['order_goods'];
		$refund_data['order_info']=$order_info;
		$refund_data['content']=$data['content'];
		$refund_data['type']=$data['type'];
		$refund_data['order_type']=10;
		$return=D('Common/OrderInfo')->check_refund_money($refund_data);
		$this->ajaxReturn($return);
	}
	/**
	 * 门店盘点
	 */
    public function stocktaking(){
		if(MID){
			$postdata=I('param.');
			$tabid=$postdata['tabid'];
			if(empty($tabid)){
				$map = array();
				$map['order_status'] = 6;
				$map['type_id'] = MID;//仓库id
				$map['type'] = 3;//仓库类型
				$map['is_delete'] = 0;
				if ($postdata['status'] == 1) {
					$map['profit_sum'] = array('gt',0);
				}elseif ($postdata['status'] == 2) {
					$map['loss_sum'] = array('lt',0);
				}
				if($postdata['time_form'] && $postdata['time_to']){
					$map['addtime'] = array(array('EGT',strtotime($postdata['time_form'])),array('ELT',strtotime($postdata['time_to'].' +1 days')));  
				}else if($postdata['time_form']){
					$map['addtime'] = array(array('GT',strtotime($postdata['time_form'])),array('LT',strtotime($postdata['time_form'].' +1 days'))); 
				}else if($postdata['time_to']){
					$map['addtime'] = array(array('GT',strtotime(I('time_to'))),array('LT',strtotime(I('time_to').' +1 days')));  
				}
				$list = $this->lists('StocktakingInfo', $map);
				$this->assign($postdata);
				$this->assign('list',$list);
			}elseif($tabid=='stocktaking_add'){
				$this->getcateTree();
			}elseif($tabid=='stocktaking_view'){
				$id = intval(I('get.id'));//订单id
				if(empty($id)){
					$this->error("参数错误");
				}
				$map = array();
				$map['stocktaking_id'] = $id;//订单id
				$list = $this->lists('StocktakingGoods', $map);
				$this->assign('list',$list);
				$this->assign('id',$id);
			}
		}
		$this->assign('menu_tab','');
		$tabid=$tabid?$tabid:'stocktaking';
        $this->display($tabid);
    }
	//搜索商品
	public function search_goods(){
		$return=array('status'=>0,'msg'=>'');
		$shop_id=intval(MID);//门店id
		$postdata=I('param.');
		$keyword=$postdata['keyword'];
		$g_map=$whereor=$cat_ids=$res=array();
		if($keyword){
			$whereor['goods_sn'] = array('like', '%' . $keyword . '%');
			$whereor['goods_name'] = array('like', '%' . $keyword . '%');
			$whereor['_logic'] = 'or';
			$g_map['_complex'] = $whereor;
		}
		
		if($postdata['catid']){
			GLOBAL $PurchaseCategory;
			if(empty($PurchaseCategory))$PurchaseCategory = getcache('PurchaseCategory');
			$cat_ids = $PurchaseCategory[$postdata['catid']]['allson'];
			if($cat_ids){
				$g_map['g.cat_id'] = array('in',$cat_ids);
			}
		}
		
		$g_map['g.goods_type'] = 5;
		$g_map['ss.shop_id'] = $shop_id;
		$g_map['ss.status'] = 1;
		$g_map['ss.goods_number'] = array('gt',0);
		$goods =M('ShopsGoodsStock ss')
				->JOIN('__GOODS__ g on ss.goods_id = g.id')
				->field('ss.id,ss.goods_id,ss.goods_number,ss.goods_stock,ss.suppliers_id,g.goods_name,g.goods_sn')
				->where($g_map)->select();
		
		if (empty($goods)) {//该门店没有商品
            $return['msg']='该门店没有符合搜索条件的商品！';
            $this->ajaxReturn($return);
        }
		
		$goods_list = array();
        foreach ($goods as $k => $v) {
            if ($v['goods_stock']) {//有货品的商品
                $attr_name=attr_key2name($v['goods_stock'],$v['goods_id']);
                $goods_list[]=array('attr_key' => $v['goods_stock'].'-1','goods_name' => $v['goods_name'], 'goods_sn' => $v['goods_sn'],'attr_name' => $attr_name,'goods_id' => $v['goods_id'],'stock' => $v['goods_number'],'supplier_id' =>$v['supplier_id']);
            }elseif (empty($v['goods_stock'])) {//没货品的商品
                $goods_list[]=array('attr_key' => $v['goods_id'].'-0','goods_name' => $v['goods_name'], 'goods_sn' => $v['goods_sn'],'goods_id' => $v['goods_id'],'stock' => $v['goods_number'],'supplier_id' =>$v['supplier_id']);
            }
        }
        $return['status']=1;
        $return['info']=$goods_list;
        $this->ajaxReturn($return);
		
	}
	//  创建商品表格（盘点单用）
    public function create_goods_table(){
        $shop_id=intval(MID);//门店id
        $goods_attr_sn = trim(I('post.goods_attr_sn'));//商品id_属性编号

        $return = array('status'=>0,'msg'=>'');
        if(empty($shop_id)  || empty($goods_attr_sn)){
            $return['msg'] = '参数错误';
            return $return;
        }
        $where = array();
        $where['shop_id'] = $shop_id;
		$attr = explode('-', $goods_attr_sn);
		if($attr[1] == 0){
			$where['goods_id'] = $attr[0];
		}else{
			$where['goods_stock'] = $attr[0];
		}
        $goods_info=M('ShopsGoodsStock')->where($where)->field(true)->find();

        if($goods_info === false){
            $return['msg'] = '参数错误';
            return $return;
        }
		$goods_info['goods_name'] = idtoname($goods_info['goods_id'],'Goods','goods_name');
		$goods_info['goods_sn'] = idtoname($goods_info['goods_id'],'Goods','goods_sn');
        $attr_name=attr_key2name($goods_info['goods_stock'],$goods_info['goods_id']);
        $goods_info['attr_name'] = $attr_name;
		$data['goods_info'] = $goods_info;
		if($goods_info['goods_stock'] == 0){
			$goods_info['goods_stock'] = $goods_info['goods_id'].'-0';
		}else{
			$goods_info['goods_stock'] = $goods_info['goods_stock'].'-1';
		}
        $data['tr'].="<tr>
            <td>".$goods_info['goods_id']."<input type='hidden' name='goods_type[goods_id][]' value='".$goods_info['goods_id']."' /><input type='hidden' name='goods_type[goods_attr_sn][]' value='".$goods_info['goods_stock']."' /><input type='hidden' name='goods_type[supplier_id][]' value='".$goods_info['suppliers_id']."' /><input type='hidden' name='goods_type[stock][]' value='".$goods_info['goods_number']."' />
            </td>            
            <td class='goodsn'>".$goods_info['goods_sn']."<input type='hidden' name='goods_type[goods_sn][]' value='".$goods_info['goods_sn']."' />
            </td>
            <td>".$goods_info['goods_name']."<input type='hidden' name='goods_type[goods_name][]' value='".$goods_info['goods_name']."' />
            </td>
            <td class='stock'>".$goods_info['goods_number']."</td>goods_type[stock]
            <td><input name='goods_type[reality][]' style='width:80px;' type='number' min='1'  onchange='change_loss(this)' value=".$goods_info['goods_number']."></td>
            <td><input name='goods_type[profit_loss][]' readonly='readonly' type='text' style='width:80px'  value='0' /></td>
            <td><a onclick='delCurrentRow(this);' style='cursor:pointer;'>删除</a></td>
            </tr>";
        $data['status']=1;
        $this->ajaxReturn($data);
    }
	//生成门店盘点单
    public function create_stocktaking(){
        $postdata = I('post.');
        if (empty($postdata)) {
            $this->error("参数错误");
        }
        $type_id = MID;//仓库id
        $name = 'Admin/Storage';
        $add = D($name)->create_stocktaking(3,$type_id,$postdata);//添加盘点订单
        $id = $add['data'];
        if ($add['status'] == 1) {
        	$add['msg'] = '保存成功';
            $add['url'] = U('Shop/PurOrder/print_template',array('id'=>$id,'type'=>'1'));
        }
        $this->ajaxReturn($add);
    }
	//删除盘点单
    public function stocktaking_delete(){
        $id=I('id');
        if(empty($id)){
            $this->error("参数错误");
        }
        $where=$map=array();
        if(isset($id)&&is_array($id)){
            $where = 'id in('.implode(',',$id).')';
        }else{
			$where = 'id='.$id;
        }
		$delete_save['is_delete'] = 1;
        $info = M('StocktakingInfo')->where($where)->save($delete_save);

        if($info!==false) {
            $this->success(L('DELETE_SUCCESS'), $url);
        }else{
            $this->error(L('DELETE_FAILED'), $url);
        }
        $this->id=$id;
    }
	/**
     * 得到节点树
     */
    private function getcateTree($pid = '', $assign = '', $brandid = '', $suppliersid = '',$shop_id=''){
        $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);
		
        $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,$suppliers_info, $suppliers_op);
    }
	//搜索入库商品
	public function search_stock_goods(){
		$postdata=I('param.');
		$keyword=$postdata['keyword'];
		$g_map['goods_type'] = 5;
		if($keyword){
			$whereor['goods_sn'] = array('like', '%' . $keyword . '%');
			$whereor['goods_name'] = array('like', '%' . $keyword . '%');
			$whereor['_logic'] = 'or';
			$g_map['_complex'] = $whereor;
		}
		if($postdata['catid']){
			GLOBAL $PurchaseCategory;
			if(empty($PurchaseCategory))$PurchaseCategory = getcache('PurchaseCategory');
			$cat_ids = $PurchaseCategory[$postdata['catid']]['allson'];
			if($cat_ids){
				$g_map['cat_id'] = array('in',$cat_ids);
			}
		}
		$goods = M('Goods')->where($g_map)->field('id,goods_sn,goods_name,goods_number')->select();
		if(!$goods){
			$return['msg']='没有该商品';
			$this->ajaxReturn($return);
		}
        foreach ($goods as $k => $v) {
			$g_ids[$k] = $v['id'];
        }
		$map['goods_id'] = array('in',$g_ids);
        $attr = M('GoodsAttrStock')->where($map)->field('goods_id,attr_key,stock_cfg')->select();
		$attr_goods=array();
		foreach($attr as $key => $val){
			$attr_goods[$val['goods_id']][]=$val;
		}
		foreach ($goods as $k => $v) {
			if($attr_goods[$v['id']]){
				foreach($attr_goods[$v['id']] as $val){
					$attr_name=attr_key2name($val['attr_key'],$val['goods_id']);
					$goods_list[]=array('attr_key' => $val['attr_key'].'-1','goods_name' => $v['goods_name'], 'goods_sn' => $v['goods_sn'],'attr_name' => $attr_name,'goods_id' => $v['id']);
				}
			}else{
				$goods_list[]=array('attr_key' => $v['id'].'-0','goods_name' => $v['goods_name'], 'goods_sn' => $v['goods_sn'],'goods_id' => $v['id']);
			}
		}
		
        $return['status']=1;
        $return['info']=$goods_list;
        $this->ajaxReturn($return);
	}
	//  创建商品表格（入库单用）
    public function stock_goods_table(){
        $goods_attr_sn = trim(I('post.goods_attr_sn'));//商品id_属性编号
		$shop_id = MID;
        $return = array('status'=>0,'msg'=>'');
        if(empty($shop_id)  || empty($goods_attr_sn)){
            $return['msg'] = '参数错误';
            return $return;
        }
        $where = array();
		$attr = explode('-', $goods_attr_sn);
		if($attr[1] == 0){
			$where['goods_type'] = 5;
			$where['id'] = $attr[0];
			$goods_info=M('Goods')->where($where)->field('id as goods_id,goods_name,goods_sn,shop_price')->find();
			$goods_info['goods_stock'] = $goods_info['goods_id'].'-0';
		}else{
			$where['attr_key'] = $attr[0];
			$goods_info=M('GoodsAttrStock')->where($where)->field(true)->find();
			$goods_info['goods_sn'] = idtoname($goods_info['goods_id'],'Goods','goods_sn');
			$goods_info['shop_price'] = idtoname($goods_info['goods_id'],'Goods','shop_price');
			$attr_name=attr_key2name($goods_info['attr_key'],$goods_info['goods_id']);
			$goods_info['goods_name'] = idtoname($goods_info['goods_id'],'Goods','goods_name').'('.$attr_name.')';
			$goods_info['goods_stock'] = $goods_info['attr_key'].'-1';
		}
		$goods_info['sum_price'] = floatval($goods_info['shop_price'])*1;
        
        if($goods_info === false){
            $return['msg'] = '参数错误';
            return $return;
        }
		$data['goods_info'] = $goods_info;
        $data['tr'].="<tr>
            <td>".$goods_info['goods_id']."<input type='hidden' name='infos[goods_id][]' value='".$goods_info['goods_id']."' /><input type='hidden' name='infos[goods_attr_sn][]' value='".$goods_info['goods_stock']."' /></td>            
            <td class='goodsn'>".$goods_info['goods_sn']."<input type='hidden' name='infos[goods_sn][]' value='".$goods_info['goods_sn']."' /></td>
            <td>".$goods_info['goods_name']."<input type='hidden' name='infos[goods_name][]' value='".$goods_info['goods_name']."' /></td>
			<td><input name='infos[reality][]' style='width:80px;' type='number' min='1'  onchange='change_loss(this)' value='1'></td>
            <td><input name='infos[shop_price][]' value='".floatval($goods_info['shop_price'])."' readonly='readonly' style='border:none;' /></td>
			<td class='sun_money'>".floatval($goods_info['sum_price'])."</td>
            <td><a onclick='delCurrentRow(this);' style='cursor:pointer;'>删除</a></td>
            </tr>";
        $data['status']=1;
        $this->ajaxReturn($data);
    }
	//  创建商品表格（调拨单用）
    public function allocation_table(){
        $shop_id=intval(MID);//门店id
        $goods_attr_sn = trim(I('post.goods_attr_sn'));//商品id_属性编号

        $return = array('status'=>0,'msg'=>'');
        if(empty($shop_id)  || empty($goods_attr_sn)){
            $return['msg'] = '参数错误';
            return $return;
        }
        $where = array();
        $where['shop_id'] = $shop_id;
		$attr = explode('-', $goods_attr_sn);
		if($attr[1] == 0){
			$where['goods_id'] = $attr[0];
		}else{
			$where['goods_stock'] = $attr[0];
		}
        $goods_info=M('ShopsGoodsStock')->where($where)->field(true)->find();

        if($goods_info === false){
            $return['msg'] = '参数错误';
            return $return;
        }
		$goods_info['goods_name'] = idtoname($goods_info['goods_id'],'Goods','goods_name');
		$goods_info['goods_sn'] = idtoname($goods_info['goods_id'],'Goods','goods_sn');
		$goods_info['shop_price'] = idtoname($goods_info['goods_id'],'Goods','shop_price');
		$goods_attr_name='';
		if($attr[1]){
			$attr_name=attr_key2name($goods_info['goods_stock'],$goods_info['goods_id']);
			$goods_attr_name = '('.$attr_name.')';
		}
		$data['goods_info'] = $goods_info;
		if($goods_info['goods_stock'] == 0){
			$goods_info['goods_stock'] = $goods_info['goods_id'].'-0';
		}else{
			$goods_info['goods_stock'] = $goods_info['goods_stock'].'-1';
		}
		$goods_info['unit_name'] = idtoname($goods_info['goods_id'],'Goods','unit_name');
        $data['tr'].="<tr>
            <td>".$goods_info['goods_id']."<input type='hidden' name='infos[goods_id][]' value='".$goods_info['goods_id']."' /><input type='hidden' name='infos[goods_attr_sn][]' value='".$goods_info['goods_stock']."' /><input type='hidden' name='infos[supplier_id][]' value='".$goods_info['suppliers_id']."' /><input type='hidden' name='infos[stock][]' value='".$goods_info['goods_number']."' /><input type='hidden' name='infos[shop_price][]' value='".floatval($goods_info['shop_price'])."' />
            </td>            
            <td class='goodsn'>".$goods_info['goods_sn']."<input type='hidden' name='infos[goods_sn][]' value='".$goods_info['goods_sn']."' />
            </td>
            <td>".$goods_info['goods_name'].$goods_attr_name."<input type='hidden' name='infos[goods_name][]' value='".$goods_info['goods_name']."' />
            </td>
			<td>".$goods_info['goods_number']."</td>
            <td><input name='infos[reality][]' style='width:80px;' type='number' min='1'  max=".$goods_info['goods_number']."  onchange='change_loss(this)' value='1'></td>
			<td>".$goods_info['unit_name']."</td>
            <td><a onclick='delCurrentRow(this);' style='cursor:pointer;'>删除</a></td>
            </tr>";
        $data['status']=1;
        $this->ajaxReturn($data);
    }
	//搜索入库商品
	public function search_dinghuo_goods(){
		$postdata=I('param.');
		
		$keyword=$postdata['keyword'];
		$chu_type=intval($postdata['chu_type']);//出货单位类型 1：供应商, 2：平台仓库
		
		$name = 'Admin/Storage';
		$goods_sn=trim($keyword);// 商品编号或名字
		$chu_id=intval($postdata['chu_id']);//出货单位id
		$return = array('status'=>0,'msg'=>'');
		if(empty($goods_sn)  || empty($chu_id) || empty($chu_type)){
			$return['msg'] = '参数错误';
			return $return;
		}
   
		$data = D($name)->search_goods($goods_sn,$chu_id,$chu_type);//查找对应商品
		$this->ajaxReturn($data);
	}
	//  创建商品表格（配货单用）
    public function dinghuo_table(){
		$chu_type = intval(I('post.chu_type'));
		$chu_id = intval(I('post.chu_id'));
        $goods_attr_sn = trim(I('post.goods_attr_sn'));//商品id_属性编号
		$shop_id = MID;
        $return = array('status'=>0,'msg'=>'');
        if(empty($shop_id)  || empty($goods_attr_sn)){
            $return['msg'] = '参数错误';
            return $return;
        }
        $where = array();
		$attr = explode('-', $goods_attr_sn);
		if($chu_type == 3){
			$where['goods_id'] = $attr[0];
			$where['storage_id'] = $chu_id;
			$goods_info=M('StorageStock')->where($where)->field('goods_id,goods_name,goods_sn,buy_price,stock,goods_attr_sn')->find();
			$goods_info['goods_stock'] = $goods_info['stock'];
		}else{
			$where['id'] = $attr[0];
			$where['goods_type'] = 5;
			$where['suppliers_id'] = $chu_id;
			$goods_info=M('Goods')->where($where)->field('id as goods_id,goods_name,goods_sn,goods_number')->find();
			if(!empty($attr[1])){
				$map['attr_key'] = $attr[1];
				$goods_stock=M('GoodsAttrStock')->where($map)->getField('stock_cfg');
				$goods_info['goods_stock'] = $goods_stock;
			}else{
				$goods_info['goods_stock'] = $goods_info['goods_number'];
			}
		}
		
		$moq = getmoq($goods_info['goods_id']);
		$goods_info['moq'] = $moq['moq'];
		$goods_info['shop_price'] = $moq['shop_price'];
		$goods_info['unit_name'] = $moq['unit_name'];
		$goods_info['sum_price'] = floatval($goods_info['shop_price'])*$goods_info['moq'];
		
		$goods_info['goods_attr_sn'] = $goods_attr_sn;
		if(!empty($attr[1])){
			$attr_name = '';
			$attr_name = '('.attr_key2name($attr[1],$attr[0]).')';
		}
        
        if($goods_info === false){
            $return['msg'] = '参数错误';
            return $return;
        }
		$data['goods_info'] = $goods_info;
        $data['tr'].="<tr>
            <td>".$goods_info['goods_id']."<input type='hidden' name='infos[goods_id][]' value='".$goods_info['goods_id']."' /><input type='hidden' name='infos[goods_attr_sn][]' value='".$goods_info['goods_attr_sn']."' /></td>            
            <td class='goodsn'>".$goods_info['goods_sn']."<input type='hidden' name='infos[goods_sn][]' value='".$goods_info['goods_sn']."' /></td>
            <td>".$goods_info['goods_name'].$attr_name."<input type='hidden' name='infos[goods_name][]' value='".$goods_info['goods_name']."' /></td>
			<td>".$goods_info['goods_stock']."</td>
			<td><input name='infos[reality][]' style='width:80px;' type='number' min='".$goods_info['moq']."' max='".$goods_info['goods_stock']."' onchange='change_loss(this)' value='".$goods_info['moq']."'></td>
            <td><input name='infos[shop_price][]' value='".floatval($goods_info['shop_price'])."' readonly='readonly' style='border:none;' /></td>
			<td class='sun_money'>".floatval($goods_info['sum_price'])."</td>
			<td>".$goods_info['unit_name']."</td>
            <td><a onclick='delCurrentRow(this);' style='cursor:pointer;'>删除</a></td>
            </tr>";
        $data['status']=1;
        $this->ajaxReturn($data);
    }
	private function get_suppliers(){
		$suppliers = M('Suppliers')->field('id,name')->select();
		$this->assign('suppliers',$suppliers);
	}
}
?>