<?php
/**仓库
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
namespace Admin\Model;
use Think\Model;
class StorageModel extends Model
{
    
     /** 
     * 查找供应商
     * @param  string $name   供应商名字 
     * @param  int $storage_id   仓库id（该参数存在就到该仓库去查供货商）仓库给供货商退货时用 
     * @return array  $data   响应数据 
     */ 
      public function search_chu($name,$chu_id='')
    {
        $return=array('status'=>0,'msg'=>'');
        if(empty($name)){$return['msg']='关键字为空';return $return;}
        $map=array();
        $map['name']=array('like', '%'.$name.'%');

        if (!empty($chu_id)) {
            $where['storage_id'] = $chu_id;
            $Suppliers_id=M('StorageStock')->where($where)->getField('supplier_id');  
            if (!$Suppliers_id) {
                $return['msg']='该供货商没有查询到';
                return $return;
            }
            $map['id']=array('in',$Suppliers_id);
        }
        $Suppliers=M('Suppliers')->where($map)->field('id,name')->select();  
        if(empty($Suppliers)){
            $return['msg']='没有查询到';return $return;
        }
        $return['status']=1;
        $return['info']=$Suppliers;
        return $return;

    }    

    
    /** 
     * 查找平台仓库
     * @param  string $name   平台仓库名字 
     * @param  int $order_type   订单类型 
     * @param  int $storage_type   仓库类型 ： 1 出库   2入库
     * @return array  $data   响应数据 
     */ 
    // 1订货单 2发货单 3配货单 4调拨单 5退货单 6入库单
    public function search_ru($name,$order_type,$storage_type)
    {
        $return = array('status'=>0,'msg'=>'');
        if(empty($name)){$return['msg']='关键字为空';return $return;}
        $map = array();
        if ($order_type == 1 || $order_type == 6 || ($order_type == 4 && $storage_type == 1) || ($order_type == 5 && $storage_type == 1)) {
            $storage_ids = $this -> get_storage_ids(UID);//当前管理员的仓库ids
            if ($storage_ids['status'] == 0) {
                $return['msg'] = $storage_ids['msg'];
                return $return;
            }
            if ($storage_ids['data'] != 'all') {//不是超级管理员
                $map['id']=array('in',$storage_ids['data']);
            }
        }

        $map['name']=array('like', '%'.$name.'%');
        $Storage=$this->where($map)->field('id,name')->select(); 
        if (empty($Storage)) {
            $return['msg'] = '没有查询到';
            return $return;
        } 
        $return['status']=1;
        $return['info']=$Storage;           
        return $return;
    }   


    /** 
     * 从供应商或仓库查找商品
     * @param  string $name   商品编号或名字 
     * @param  int $chu_id    要查询的供应商或仓库id
     * @param  int $chu_type   出库类型  1个人  2供货商  3仓库
     * @param  int $ru_id   仓库给供货商退货时的供货商id（只能添加退货单搜索时用）
     * @return array  $data   响应数据 
     */ 

     public function search_goods($goods_sn,$chu_id,$chu_type,$ru_id = 0)
    {
            $return = array('status'=>0,'msg'=>'');
            if(empty($goods_sn)  || empty($chu_id) || empty($chu_type)){
                $return['msg'] = '参数错误';
                return $return;
            }

            if ($chu_type == 2) { // 查找的商品是从供货商商品库里查
                $whereor = array();
                $map = array();
                $whereor['suppliers_id']=$chu_id;//供货商id
                $whereor['status']=1;//并且是上架状态
                $whereor['is_delete']=0;//并且是未删除
                $whereor['publish_wait']=1;//并且是已审核
                $whereor['goods_sn|goods_name']=array('like', '%'.$goods_sn.'%');//模糊查询
                $whereor['_logic'] = 'and';
                $map['_complex'] = $whereor;

                $count = 0;
                $count=M('Goods')->where($map)->count();//判断用户输入的是否是商品编号或商品名称

                if ($count > 0) { //有就在商品表中查找
                    $goods = array();
                    $goods=M('Goods')
                            ->field(true)
                            ->where($map)
                            ->select();
                    $ids = M('Goods')->where($map)->getField('id',true);
                    $map = array();
                    $map['goods_id']=array('in',$ids);
                    $count=0;
                    $count=M('GoodsAttrStock')
                            ->field('goods_id,attr_key')
                            ->where($map)
                            ->count();
                    $goods_attrs = array();//当前供应商的属性组合的商品
                    if ($count > 0) {
                        $attrs=M('GoodsAttrStock')
                                ->field('goods_id,attr_key,stock_cfg')
                                ->where($map)
                                ->select();
                        foreach ($attrs as $v) {
                            $goods_attrs[$v['goods_id']][] = $v;
                        }
                    }
                    $goods_list=array();
                    foreach($goods as $v){
                        if(!empty($goods_attrs[$v['id']])){//如果存在货品
                            foreach($goods_attrs[$v['id']] as $vo){
                                $attr_name=attr_key2name($vo['attr_key'],$v['id']);
                                $attr_key = $v['id'].'-'.$vo['attr_key'];
                                $goods_list[]=array('attr_key' => $attr_key,'goods_name' => $v['goods_name'], 'goods_sn' => $v['goods_sn'],'attr_name' => $attr_name,'shop_price' => $v['supply_price'],'cat_id' => $v['cat_id'],'stock' => $vo['stock_cfg'],'unit_name'=>$v['unit_name']);
                            }
                        }else{  
                            $attr_key = $v['id'].'-';
                            $goods_list[]=array('attr_key' => $attr_key,'goods_name' => $v['goods_name'], 'goods_sn' => $v['goods_sn'],'shop_price' => $v['supply_price'],'cat_id' => $v['cat_id'],'stock' => $v['goods_number'],'unit_name'=>$v['unit_name']);
                        }
                    }
                    $return['status'] = 1;
                    $return['info'] = $goods_list;
                    return $return;

                }else{//否则就到货品表里去查

                    $map = array();
                    $whereor = array();
                    $whereor['g.suppliers_id']=$chu_id;//供货商id
                    $whereor['g.status']=1;//并且是上架状态
                    $whereor['g.is_delete']=0;//并且是未删除
                    $whereor['g.publish_wait']=1;//并且是已审核
                    $map['gas.goods_attr_sn']=array('like', '%'.$goods_sn.'%');//模糊查询
                    $whereor['_logic'] = 'and';
                    $map['_complex'] = $whereor;
                    $count = 0;
                    $count=M('GoodsAttrStock')
                                ->alias('gas')
                                ->join('LEFT JOIN __GOODS__ g  on gas.goods_id = g.id')
                                ->where($map)
                                ->count();
                    if(empty($count)){
                        $return['msg'] = '没有查询到';
                        return $return;
                    }else{
                        $attrs = array();
                        $attrs=M('GoodsAttrStock')
                                ->alias('gas')
                                ->field('gas.goods_id,gas.attr_key,gas.stock_cfg,g.goods_name,g.goods_sn,g.supply_price,g.cat_id,g.goods_number')
                                ->join('LEFT JOIN __GOODS__ g  on gas.goods_id = g.id')
                                ->where($map)
                                ->select();
                        $goods_list=array();
                        foreach ($attrs as $v) {
                            $attr_name = attr_key2name($v['attr_key'],$v['goods_id']);
                            // echo $attr_name;die;
                            $attr_key = $v['goods_id'].'-'.$v['attr_key'];
                            $goods_list[] = array('attr_key' => $attr_key,'goods_name' => $v['goods_name'],'goods_sn' => $v['goods_sn'],'attr_name' => $attr_name,'shop_price' => $v['supply_price'],'cat_id' => $v['cat_id'],'stock' => $v['stock_cfg']);

                        }
                        $return['status'] = 1;
                        $return['info'] = $goods_list;
                        return $return;
                    }
                }
            }else if($chu_type == 3){ //查找的商品是从仓库里查
                $map = array();
                $map['s.storage_id']=$chu_id;//仓库id
                if (!empty($ru_id)) {//仓库给供货商退货时的供货商id
                    $map['s.supplier_id']=$ru_id;
                }
                $map['s.goods_sn|s.goods_name']=array('like', '%'.$goods_sn.'%');//模糊查询
                $map['_logic'] = 'and';  
                $count = 0;
                $count=M('StorageStock')//判断用户输入的是否是商品编号或商品名称
                        ->alias('s')
                        ->where($map)
                        ->count();
                if ($count > 0) { //有就在商品表中查找
                    $goods = array();
                    $goods=M('StorageStock')
                            ->alias('s')
                            ->field('s.*,g.cat_id')
                            ->join('LEFT JOIN __GOODS__ g  on s.goods_id = g.id')
                            ->where($map)
                            ->select(); 
                    $goods_list = array();
                    foreach ($goods as $k => $v) {
                        $attr = explode('-', $v['goods_attr_sn']);
                        if (!empty($attr[1])) {//有货品的商品
                            $attr_name=attr_key2name($attr[1],$attr[0]);
                            $goods_list[]=array('attr_key' => $v['goods_attr_sn'],'goods_name' => $v['goods_name'], 'goods_sn' => $v['goods_sn'],'attr_name' => $attr_name,'shop_price' => $v['buy_price'],'goods_id' => $v['goods_id'],'stock' => $v['stock'],'cat_id' => $v['cat_id'],'supplier_id' =>$v['supplier_id']);
                        }elseif (empty($attr[1])) {//没货品的商品
                            $goods_list[]=array('attr_key' => $v['goods_attr_sn'],'goods_name' => $v['goods_name'], 'goods_sn' => $v['goods_sn'],'shop_price' => $v['buy_price'],'goods_id' => $v['goods_id'],'stock' => $v['stock'],'cat_id' => $v['cat_id'],'supplier_id' =>$v['supplier_id']);
                        }
                    }
                    $return['status'] = 1;
                    $return['info'] = $goods_list;
                    return $return;
                }else{//否则就到货品表里去查货品号
                    $map = array();
                    $whereor = array();
                    $map['goods_attr_sn']=array('like', '%'.$goods_sn.'%');//模糊查询
                    $count = 0;
                    $count=M('GoodsAttrStock')
                                ->where($map)
                                ->count();
                    if(empty($count)){
                        $return['msg'] = '没有查询到';
                        return $return;
                    }

                    if (empty($ru_id)) {
                        $attr_key=M('GoodsAttrStock')
                            ->field('goods_id,attr_key')
                            ->where($map)
                            ->select();
                    }else{//仓库给供货商退货时的供货商id
                        $attr_goods_ids=M('GoodsAttrStock')->where($map)->getField('goods_id',true); //获取货品表商品id
                        $map = array();
                        $map['suppliers_id'] =  $ru_id;  
                        if($attr_goods_ids){
                            $map['goods_id'] =  array('in',$attr_goods_ids); 
                        }               
                        $count=M('StorageStock')//获取货品表商品id仓库供货商所有商品id
                                ->where($map)
                                ->count();
                        if (empty($count)) {
                            $return['msg'] = '没有查询到该供货商的商品';
                            return $return;
                        }

                        $goods_ids=M('StorageStock')->where($map)->getField('goods_id',true);//获取货品表商品id仓库供货商所有商品id
                        $map = array();
                        if($goods_ids){
                            $map['goods_id'] =  array('in',$goods_ids);
                        }
                        $attr_key=M('GoodsAttrStock')
                            ->field('goods_id,attr_key')
                            ->where($map)
                            ->select();
                    }

                    $keys = array();        
                    foreach ($attr_key as $k => $v) {
                        $keys[]=$v['goods_id'].'-'.$v['attr_key'];
                    }

                    $map = array();
                    $whereor = array();
                    $whereor['s.goods_attr_sn']=array('in',$keys);
                    $whereor['s.storage_id']=$chu_id;//仓库id
                    $whereor['_logic'] = 'and';
                    $map['_complex'] = $whereor;

                    $goods=M('StorageStock')
                            ->alias('s')
                            ->field('s.*,g.cat_id')
                            ->join('LEFT JOIN __GOODS__ g  on s.goods_id = g.id')
                            ->where($map)
                            ->select(); 
                    // echo M('StorageStock')->_sql();die;
                    $goods_list = array();
                    foreach ($goods as $k => $v) {
                        $attr = explode('-', $v['goods_attr_sn']);
                        if (!empty($attr[1])) {//有货品的商品
                            $attr_name=attr_key2name($attr[1],$attr[0]);
                            $goods_list[]=array('attr_key' => $v['goods_attr_sn'],'goods_name' => $v['goods_name'], 'goods_sn' => $v['goods_sn'],'attr_name' => $attr_name,'shop_price' => $v['buy_price'],'goods_id' => $v['goods_id'],'stock' => $v['stock'],'cat_id' => $v['cat_id'],'supplier_id' =>$v['supplier_id']);
                        }elseif (empty($attr[1])) {//没货品的商品
                            $goods_list[]=array('attr_key' => $v['goods_attr_sn'],'goods_name' => $v['goods_name'], 'goods_sn' => $v['goods_sn'],'shop_price' => $v['buy_price'],'goods_id' => $v['goods_id'],'stock' => $v['stock'],'cat_id' => $v['cat_id'],'supplier_id' =>$v['supplier_id']);
                        }
                    }
                    
                    $return['status'] = 1;
                    $return['info'] = $goods_list;
                    return $return;
                    
                }
               
            }
    }


    /** 
     * 从供应商或仓库检查库存
     * @param  string $c_type       要查询的出库单位类型 1：供应商, 2：平台仓库
     * @param  string $chu_id       供应商或仓库id
     * @param  attry $attr_keys     要查询的商品id加attr_key(id-attr_key)
     * @param  array  $nums          比较的库存
     * @return array  $data         响应数据 
     */ 
    public function check_stock($c_type,$chu_id,$attr_keys,$nums)
    {
        // var_dump($nums);die;
        // echo 'aaaaaa';die;
        $return = array('status' => 0,'msg' => '');
        if(empty($c_type)  || empty($chu_id) || empty($attr_keys) || empty($nums)){
            $return['msg'] = '缺少参数';
            return $return;
        }        
        $c_type = intval($c_type);
        $chu_id = intval($chu_id);
        if(empty($c_type)  || empty($chu_id) || !is_array($attr_keys) || !is_array($nums)){
            $return['msg'] = '参数错误';
            return $return;
        }

        if ($c_type == 2) {//出库类型  1个人  2供货商  3仓库'

            $stock = array();//库存数据
            $goods_id = array();//没有属性的商品id
            $attr_key = array();//有属性的商品attr_key

            foreach ($attr_keys as $k => $v) {
                $key = explode('-',$v);
                // return var_dump($key);die;
                // $count = count($key);
                if (empty($key[1])) {
                    $stock[$key[0]] = $nums[$k];
                    $goods_id[] = $key[0];
                } else if(!empty($key[1])){
                    $stock[$key[1]] = $nums[$k];
                    $attr_key[] = $key[1];
                }
            }
            if (!empty($attr_key)) {//有属性的商品
                $map = array();
                $whereor = array();
                $whereor['suppliers_id']=$chu_id;//供货商id
                $whereor['g.status']=1;//并且是上架状态
                $whereor['g.is_delete']=0;//并且是未删除
                $whereor['g.publish_wait']=1;//并且是已审核
                $whereor['attr_key']=array('in',$attr_key);
                $whereor['_logic'] = 'and';
                $map['_complex'] = $whereor;
                $attr_stock=M('GoodsAttrStock')
                        ->alias('s')
                        ->join('LEFT JOIN __GOODS__ g on g.id=s.goods_id')
                        ->where($map)
                        ->getField('s.attr_key,s.stock_cfg,g.id,g.goods_name');
                // return $attr_stock;die;
                if(empty($attr_stock)){
                    $return['msg'] = '没有查询到';
                    return $return;
                } 
                foreach ($attr_stock as $k => $v) {
                    if ($attr_stock[$k]['stock_cfg'] < $stock[$k] || $attr_stock[$k]['stock_cfg']<= 0) {
                        $attr = attr_key2name($k,$attr_stock[$k]['id']);
                        $attr_name = $attr_stock[$k]['goods_name'].'('.$attr.')';
                        $return['msg'] = $attr_name.'库存不足';
                        return $return;
                    }elseif($stock[$k] <= 0){
                        $attr = attr_key2name($k,$attr_stock[$k]['id']);
                        $attr_name = $attr_stock[$k]['goods_name'].'('.$attr.')';
                        $return['msg'] = $attr_name.'商品数量不能小于1';
                        return $return;
                    }              
                }
            }

            if (!empty($goods_id)) { //没有属性的商品id
                $map = array();
                $whereor = array();
                $whereor['suppliers_id']=$chu_id;//供货商id
                $whereor['status']=1;//并且是上架状态
                $whereor['is_delete']=0;//并且是未删除
                $whereor['publish_wait']=1;//并且是已审核
                $whereor['id']=array('in',$goods_id);
                $whereor['_logic'] = 'and';
                $map['_complex'] = $whereor;
                $goods=M('Goods')
                        ->where($map)
                        ->getField('id,goods_name,goods_number');
                if(empty($goods)){
                    $return['msg'] = '没有查询到';
                    return $return;
                }
                foreach ($goods as $k => $v) {
                    if ($goods[$k]['goods_number'] < $stock[$k] || $goods[$k]['goods_number'] <= 0) {
                        $return['msg'] = $goods[$k]['goods_name'].'库存不足';
                        return $return;
                    }elseif ($stock[$k] <= 0) {
                        $return['msg'] = $goods[$k]['goods_name'].'商品数量不能小于1';
                        return $return;
                    }               
                } 
            } 
            $return['status'] = 1;
            return $return;
        } else if ($c_type == 3){ //出库类型  1个人  2供货商  3仓库'
            $where = array();
            $where['storage_id']=$chu_id;
            $where['goods_attr_sn']=array('in',$attr_keys);
            $attr_stock=M('StorageStock')
                    ->alias('s')
                    ->where($where)
                    ->getField('goods_attr_sn,goods_name,stock');

            $stocks= array();
            foreach ($attr_keys as $k => $v) {
                $stocks[$v]['num'] = $nums[$k]; 
            }

            foreach ($attr_stock as $k => $v) {
                if ($v['stock'] < $stocks[$k]['num'] || $v['stock'] <= 0) {
                    $attr_key = explode('-', $k);
                    if (empty($attr_key[1])) {
                        $return['msg'] = $v['goods_name'].'库存不足';
                        return $return;
                    } elseif(!empty($attr_key[1])) {
                        $attr_name = attr_key2name($attr_key[1],$attr_key[0]);
                        $return['msg'] = $v['goods_name'].'('.$attr_name.')库存不足';
                        return $return;
                    }
                }elseif ($stocks[$k]['num'] <= 0) {
                    $return['msg'] = $nums[$k]['num'];
                    return $return;
                    $attr_key = explode('-', $k);
                    if (empty($attr_key[1])) {
                        $return['msg'] = $v['goods_name'].'商品数量不能小于1';
                        return $return;
                    } elseif(!empty($attr_key[1])) {
                        $attr_name = attr_key2name($attr_key[1],$attr_key[0]);
                        $return['msg'] = $v['goods_name'].'('.$attr_name.')商品数量不能小于1';
                        return $return;
                    }
                }                   
            }

            $return['status'] = 1;
            return $return;
        }
    }


      /** 
     * 列表查询
     * @param  int $order_type   订单类型 
     * @return int  $status   订单状态$status = 0
     * @return string  $map   搜索数据
     */ 

      public function orderlist($order_type = '',$map ){//订单记录
        //搜索
        /*if (empty($order_type)) {
            $data['error'] = 0;
            $data['msg'] = "参数错误！";
        }else{
            $data = array();
            $where = array();
            if(!empty($map['keyword'])){
                $keyword_fields=I('keyword_fields','name');
                $field_arr=explode(',',$keyword_fields);
                $arr = implode('|',$field_arr);
                $where[$arr] = array('like', '%'.$map['keyword'].'%');
            }
            if($map['time_form'] && $map['time_to']){
                $where['addtime'] = array(array('EGT',strtotime($map['time_form'])),array('ELT',strtotime($map['time_to'].' +1 days')));  
            }else if($map['time_form']){
                $where['addtime'] = array(array('GT',strtotime($map['time_form'])),array('LT',strtotime($map['time_form'].' +1 days'))); 
            }else if($map['time_to']){
                $where['addtime'] = array(array('GT',strtotime(I('time_to'))),array('LT',strtotime(I('time_to').' +1 days')));  
            }
            if ($map['status'] != '') {
                $where['status'] = $map['status'];
            }else{
                $where['status'] = array('neq',3);
            }


            $storage_ids = $this -> get_storage_ids(UID);//当前管理员的仓库ids
            if ($storage_ids['status'] == 0) {
                $data['error'] = 0;
                $data['msg'] = $storage_ids['msg'];
                return $data;
            }
            if ($order_type == 4 && empty($map['chu_id']) && empty($map['ru_id']) && $storage_ids['data'] != 'all') {
                $where['ru_id | chu_id'] = array('in',$storage_ids['data']);
            }elseif ($order_type == 5 && $storage_ids['data'] != 'all') {
                if ($map['chu_type'] == 1) {//个人
                    $where['chu_type'] = $map['chu_type'];
                    $where['ru_id'] = array('in',$storage_ids['data']);
                    
                }elseif ($map['chu_type'] == 3) {//仓库
                    $where['chu_type'] = $map['chu_type'];
                    if (empty($map['chu_id'])) {
                        $where['chu_id'] = array('in',$storage_ids['data']);
                    }
                }else{
                    $ids=implode(',',$storage_ids['data']);
                    $where['_complex'] = ' ( chu_type=1 AND ru_id in ('.$ids.') ) OR ( `chu_type` = 3 AND chu_id in ('.$ids.') )';
                }

                if ($map['ru_type'] == 2) {//供货商
                    $where['ru_type'] = $map['ru_type'];
                    $where['chu_id'] = array('in',$storage_ids['data']);
                }elseif ($map['ru_type'] == 3) {//仓库
                    $where['ru_type'] = $map['ru_type'];
                    if (empty($map['ru_id'])){
                        $where['ru_id'] = array('in',$storage_ids['data']);
                    }                    
                }
            }else{//否则是订货单或入库单
                if ($storage_ids['data'] != 'all' && empty($map['ru_id'])) {
                    $where['ru_id'] = array('in',$storage_ids['data']);
                } 
            }
            
            if (!empty($map['chu_id'])) {
                $where['chu_id'] = $map['chu_id'];
            }
            if (!empty($map['ru_id'])) {
                $where['ru_id'] = $map['ru_id'];
            }    
			$where['ru_type'] = array('neq',4);
            $where['order_status'] = $order_type;
            $where['is_delete'] = 0;
            $allmoney = M('LibraryInfo')->Field('goods_allmoney')->where($where)->select();
            $map['count'] = count($allmoney);
            $map['allmoney'] = 0;
            foreach ($allmoney as $key => $value) {
                $map['allmoney'] += $value['goods_allmoney'];
            }
            $field=true;
            $pagesize=20;
            $order = 'status asc,id desc';
            $list = page_list('LibraryInfo',$where,$order,$field,$pagesize,'',1);
            $map['list'] = $list;
            $map['error'] = 1;
        }
        return $map;*/
    }



    /** 
     * 出入库记录列表(商城平台和供货商平台用)
     * @param  int $pt_type  平台类型 (1.商城平台。2.供货商)
     * @param int  $id    商城平台是管理员的id，供货商平台是供货商的id，
     * @return array  $map   搜索数据
     */ 
     public function stock_records($pt_type,$id,$map){//出入库记录
        /*$return = array('status' => 0,'msg' =>'');
        $pt_type = intval($pt_type);
        $id = intval($id);

        if ( $pt_type < 1 || $pt_type > 2 ) {
            $return['msg'] = '参数错误！';
            return $return;
        }
        if (empty($id)) {
            $return['msg'] = "参数为空！";
            return $return;
        }
     
        $where = array();
        $where['status'] = 2;
		$where['ru_type'] = array('neq',4);
        if ($pt_type == 1) {//1.商城平台
            $storage_ids = $this -> get_storage_ids($id);//当前管理员的仓库ids
            if ($storage_ids['status'] == 0) {
                $return['msg'] = $storage_ids['msg'];
                return $return;
            }  
            $storage_ids = $storage_ids['data'];//当前管理员的仓库ids
            if ($storage_ids != 'all') {
                $storage_ids  =  implode ( "," ,  $storage_ids );
                $where['_string'] = '((chu_type=2 AND ru_type=3) AND ru_id in ('.$storage_ids.')) 
                                    OR 
                                    (order_status=4 AND ru_id in ('.$storage_ids.'))                              
                                    OR 
                                    (order_status=2 AND chu_id in ('.$storage_ids.'))                               
                                    OR 
                                    (chu_type=1 AND chu_id in ('.$storage_ids.'))
                                    OR
                                    ((chu_type=3 AND ru_type=2) AND chu_id in ('.$storage_ids.')
                                    )';
                $order_ids = M('LibraryInfo')->where($where)->getField('id',true);
               
                if(!$order_ids){
                    $return['status'] = 1;
                    $return['msg'] = "没有与您仓库相关的记录！";
                    return $return;
                }
                $where = array();
                $where['a.id']=array('in',$order_ids);
            }


        }else{//2.供货商
            $count = M('Suppliers')->field('id')->where('id='.$id)->count();
            if (empty($count)) {
                $return['msg'] = '您输入供货商id不存在';
                return $return;
            }
            $count = 0;
            $count = M('Goods')->where('suppliers_id='.$id)->count();
            if (empty($count)) {
                $return['msg'] = '该供货商不存在商品';
                return $return;
            }
            $goods_ids = M('Goods')->where('suppliers_id='.$id)->getField('id',true);//该供货商所有商品id

            $where['goods_id'] = array('in',$goods_ids);
            $count = 0;
            $count = M('LibraryGoods')->where($where)->count();
            if (empty($count)) {
                $return['status'] = 1;
                $return['msg'] = '订单表不存在该供货商的商品';
                return $return;
            }
            $lgoods_ids = M('LibraryGoods')->where($where)->getField('goods_id',true);//包含该供货商商品的订单id
            $where = array();
            $where['g.goods_id']=array('in',$lgoods_ids);

        }
        

        if (!empty($map)) {//有搜索参数
           
            if(!empty($map['keyword'])){
                $keyword=I('keyword');
                $where['a.order_sn|g.goods_name']=array('like', '%'.$keyword.'%');
            }
            if(!empty($map['time_form']) && !empty($map['time_to'])){
                $time_form=I('time_form');
                $time_to=I('time_to').' +1 days';
                $where['a.updatetime'] = array(array('EGT',strtotime($time_form)),array('ELT',strtotime($time_to)));  
            }else if(!empty($map['time_form'])){
                $time_form=I('time_form').' +1 days';
                $where['a.updatetime'] = array(array('GT',strtotime(I('time_form'))),array('LT',strtotime($time_form))); 
            }else if(!empty($map['time_to'])){
                $time_to=I('time_to').' +1 days';
                $where['a.updatetime'] = array(array('GT',strtotime(I('time_to'))),array('LT',strtotime($time_to)));   
            }
            if (!empty($map['order_status'])) {
                $status=I('order_status');
                $where['a.order_status'] = $status;
            }            
            if (!empty($map['chu_id'])) {
                $chu_id=I('chu_id');
                $chu_type=I('chu_type');
                $where['chu_type'] = $chu_type;
                $where['chu_id'] = $chu_id;
            }          
            if (!empty($map['ru_id'])) {
                $ru_id=I('ru_id');
                $ru_type=I('ru_type');
                $where['ru_type'] = $ru_type;
                $where['ru_id'] = $ru_id;
            }
        }
        $where['is_delete'] = 0;
        $join = 'LEFT JOIN __LIBRARY_GOODS__ g on g.libinfo_id = a.id';
        $field='g.goods_id,g.goods_name,g.goods_attr_sn,a.order_sn,a.order_status,a.chu_type,a.chu_id,a.ru_type,a.ru_id,g.num,g.chu_end_num,g.ru_end_num,a.updatetime';
        $pagesize=20;
        $order = 'updatetime desc';
        $list = page_list('LibraryInfo',$where,$order,$field,$pagesize,$join,1);
        foreach ($list['list'] as $k => $v) {
            $attr_sn = explode('-', $v['goods_attr_sn']);
            if(!empty($attr_sn[1])){
                $list['list'][$k]['goods_attr_sn'] = attr_key2name($attr_sn[1],$attr_sn[0],true);
            }else{
                $list['list'][$k]['goods_attr_sn'] = '';
            }
            // '1订货单 2发货单 3配货单 4调拨单 5退货单 6入库单',
            $order_status = '';
            switch ( $v['order_status'] ) {
                case  1 :
                    $order_status = '订货单';
                    break;                    
                case  2 :
                    $order_status = '发货单';
                    break;
                case  3 :
                    $order_status = '配货单';
                    break;
                case  4 :
                    $order_status = '调拨单';
                    break;
                case  5 :
                    $order_status = '退货单';
                    break;                    
                case  6 :
                    $order_status = '入库单';
                    break;
                default:
                    $order_status = '---';
            }
            $list['list'][$k]['order_status'] = $order_status;

            $chu_unit = $this -> unit_name($v['chu_type'],$v['chu_id']);
            if ($chu_unit['status'] == 0) {
                // return $chu_unit;
                $list['list'][$k]['chu_id'] = '---';
            }else{
                $list['list'][$k]['chu_id'] = $chu_unit['data'];
            }
            $ru_unit = $this -> unit_name($v['ru_type'],$v['ru_id']);
            if ($ru_unit['status'] == 0) {
                // return $ru_unit; 
                $list['list'][$k]['ru_id'] = '---';
            }else{
                $list['list'][$k]['ru_id'] = $ru_unit['data'];
            }
        }
        $map['status'] = 1;
        $map['list'] = $list;
        return $map;*/
    }

    /** 
     * 单位名称
     * @param int  $unit_type  单位类型 1个人  2供货商  3仓库
     * @param string  $unit_id   单位ID
     * @return string   $data   单位名称
    */ 
    public function unit_name($unit_type,$unit_id)
    {
        $unit_type = intval($unit_type);
        $unit_id = intval($unit_id);
        $return = array('status' => 0,'msg' => '');

        if ( $unit_type < 1 || $unit_type > 3 ) {
            $return['msg'] = '参数错误！';
            return $return;
        }
        if (empty($unit_id)) {
            $return['msg'] = '参数为空！';
            return $return;
        }
        $where = array();
        $where['id'] = $unit_id;
        if ($unit_type == 1) {//库类型  1个人
                $count = 0;
                $count = M('Member')
                        ->where($where)
                        ->count(); 
                if (empty($count)) {
                    $return['msg'] = '没有查询到！';
                    return $return; 
                }               
                $unit = M('Member')
                        ->field('username')
                        ->where($where)->cache(true)
                        ->select();
                $data = $unit[0]['username'];
        }elseif ($unit_type == 2) {// 2供货商
            $count = 0;
            $count = M('Suppliers')
                    ->where($where)
                    ->count(); 
            if (empty($count)) {
                $return['msg'] = '没有查询到！';
                return $return; 
            }               
            $unit = M('Suppliers')
                    ->field('name')
                    ->where($where)->cache(true)
                    ->select();
            $data = $unit[0]['name'];
        }else{//3仓库
            $count = 0;
            $count = M('Storage')
                    ->where($where)
                    ->count(); 
            if (empty($count)) {
                $return['msg'] = '没有查询到！';
                return $return; 
            }               
            $unit = M('Storage')
                    ->field('name')
                    ->where($where)->cache(true)
                    ->select();
            $data = $unit[0]['name'];
        }
        $return['status'] =1;
        $return['data'] =$data;
        return $return;
    }


        /** 
     * 搜索出入库记录中出入库单位(商城平台和供货商平台用)
     * @param int  $pt_type    平台类型 1：商城平台 2：供货商平台， 
     * @param int  $id    商城平台是管理员的id，供货商平台是供货商的id
     * @param int  $type   出入库类型 1：出库单位，2：入库单位
     * @param int  $unit_type  单位类型 1个人  2供货商  3仓库
     * @param string  $unit_name   单位名称
     * @return array   $data   单位数组
    */ 
    public function search_records_unit($pt_type,$id,$type,$unit_type,$unit_name)
    {/*
        $pt_type = intval($pt_type);
        $id = intval($id);
        $type = intval($type);
        $unit_type = intval($unit_type);

        $return = array('status' => 0,'msg' => '');

        if ( $pt_type < 1 || $pt_type > 2 || $type < 1 || $type > 2 || $unit_type < 1 || $unit_type > 3 ) {
            $return['msg'] = '参数错误！';
            return $return;
        }
        if (empty($id) || empty($unit_name)) {
            $return['msg'] = '参数为空！';
            return $return;
        }

        if ($pt_type == 1) {//1：商城平台
            $storage_ids = $this->get_storage_ids($id);//当前管理员的仓库ids 
            if ($storage_ids['status'] == 0) {
                $return['msg'] = $storage_ids['msg'];
                return $return;
            }  
            $storage_ids = $storage_ids['data'];
            $where = array();
            $where['is_delete']  = 0;
            $where['status']  = array('neq',3);
            if ($type == 1) {//1：出库单位
                $where['chu_type']  = $unit_type;//出库类型
                if ($storage_ids != 'all') {//仓库管理员
                    if ($unit_type == 1 || $unit_type == 2) {//出库类型1个人或 2供货商
                            $where['ru_id']  = array('in', $storage_ids);
                    }elseif ($unit_type == 3) {//出库类型3仓库
                            $where['chu_id']  = array('in', $storage_ids);
                    }
                }
                $count = 0;
                $count = M('LibraryInfo')
                        ->where($where)
                        ->count();
                if (empty($count)) {
                    $return['msg'] = '没有查询到！';
                    return $return; 
                }            
                $unit_ids = M('LibraryInfo')->where($where)->getField('chu_id',true);//出库单位ids
            }else{//2：入库单位
                $where['ru_type']  = $unit_type;//入库类型
                if ($storage_ids != 'all') {//仓库管理员
                    if ($unit_type == 1 || $unit_type == 2) {//入库类型1个人或 2供货商
                            $where['chu_id']  = array('in', $storage_ids);
                    }elseif ($unit_type == 3) {//入库类型3仓库
                            $where['ru_id']  = array('in', $storage_ids);
                    }
                }
                $count = M('LibraryInfo')
                        ->where($where)
                        ->count();
                if (empty($count)) {
                    $return['msg'] = '没有查询到！';
                    return $return; 
                }            
                $unit_ids = M('LibraryInfo')->where($where)->distinct(true)->getField('ru_id',true);//入库单位ids
            }
        }elseif ($pt_type == 2) {//供货商平台
            $count = M('Suppliers')->where('id='.$id)->count();
            if (empty($count)) {
                $return['msg'] = '您输入供货商id不存在';
                return $return;
            }
            $count = 0;
            $count = M('Goods')->where('suppliers_id='.$id)->count();
            if (empty($count)) {
                $return['msg'] = '该供货商不存在商品';
                return $return;
            }
            $goods_ids = M('Goods')->field('id')->where('suppliers_id='.$id)->select();//该供货商所有商品id

            $where = array();
            $where['goods_id'] = array('in',$goods_ids);
            $count = 0;
            $count = M('LibraryGoods')->where($where)->count();
            if (empty($count)) {
                $return['msg'] = '订单表不存在该供货商的商品';
                return $return;
            }
            $order_ids = M('LibraryGoods')->field('libinfo_id')->group('libinfo_id')->where($where)->select;//包含该供货商商品的订单id

            $where = array();
            $where['chu_type']  = $unit_type;//出库类型
            $where['id']  = array('in', $order_ids);
            $where['is_delete']  = 0;
            $where['status']  = array('neq',3);    
            $count = M('LibraryInfo')
                        ->where($where)
                        ->count();
            if (empty($count)) {
                $return['msg'] = '没有查询到！';
                return $return; 
            } 
            if ($type == 1) {//1：出库单位           
                $unit_ids = M('LibraryInfo')->where($where)->getField('chu_id',true);//出库单位ids 
            }else{//1：入库单位
                $unit_ids = M('LibraryInfo')->where($where)->getField('ru_id',true);//出库单位ids
            } 
        }
        $where = array();
        $where['id'] = array('in',$unit_ids);
        if ($unit_type == 1) {//库类型  1个人
            $where['username'] = array('like','%'.$unit_name.'%');
            $where['_logic'] = 'and';
            $count = 0;
            $count = M('Member')
                    ->where($where)
                    ->count(); 
            if (empty($count)) {
                $return['msg'] = '没有查询到！';
                return $return; 
            }               
            $units = M('Member')
                    ->field('id,username')
                    ->where($where)
                    ->select();
        }elseif ($unit_type == 2) {// 2供货商
            // $where['id'] = array('in',$unit_ids);
            $where['name'] = array('like','%'.$unit_name.'%');
            $where['_logic'] = 'and';
            $count = 0;
            $count = M('Suppliers')
                    ->where($where)
                    ->count(); 
            if (empty($count)) {
                $return['msg'] = '没有查询到！';
                return $return; 
            }               
            $units = M('Suppliers')
                    ->field('id,name')
                    ->where($where)
                    ->select();
        }else{//3仓库
            $where['name'] = array('like','%'.$unit_name.'%');
            $where['_logic'] = 'and';
            $count = 0;
            $count = M('Storage')
                    ->where($where)
                    ->count(); 
            if (empty($count)) {
                $return['msg'] = '没有查询到！';
                return $return; 
            }               
            $units = M('Storage')
                    ->field('id,name')
                    ->where($where)
                    ->select();
        }
        $return['status'] = 1;
        $return['unit_type'] = $unit_type;
        $return['data'] = $units;
        return $return;*/
    }


    /** 
     * 获取管理员能管理仓库的id
     * @param int  $admin_id   管理员id
     * @return array或string   $storage_ids   如果是仓库管理员就返回仓库id数组，如果是超级管理员或其他管理员就返回字符串all
     */ 
     public function get_storage_ids($admin_id)
     {
        $return = array('status' => 0,'msg' => '');
        $admin_id = intval($admin_id);
        if (empty($admin_id)) {
            $return['msg'] = '参数为空！';
            return $return;
        }
        $is_admin = is_administrator($admin_id);
        if (!empty($is_admin)) {//超级管理员
            $return['status'] = 1;
            $return['data'] = 'all';//超级管理员可以查看所有仓库
            return $return;
        }
        $admin = M('Admin')->where('id='.$admin_id)->count();  
        if (empty($admin)) {
            $return['msg'] = '您输入的id不为管理员';
            return $return;
        }        
        
        $storage_admin = M('StorageAdmin');
        $where = array();
        $where['admin_id'] = $admin_id;
        $count = $storage_admin -> where($where) ->count();
        if (empty($count)) {
            $return['status'] = 1;
            $return['data'] = 'all';//没有分配仓库id就可以查看所有仓库
            return $return;
        }else{
            $storage_ids = $storage_admin -> where($where)->getField('storage_id',true);
            $return['status'] = 1; 
            $return['data'] = $storage_ids; 
            return $return;
        }
     }   
  
    /** 
     * 入库
     * @param int  $order_id   订单id
     * @return string  $chuli_temp   备注
     */    
    public function all_add_stock($order_id,$chuli_temp = '')
    {/*
        $return = array('status' => 0,'msg' => '');
        if (empty($order_id)) {
            $return['msg'] = '参数错误';
            return  $return;
        }

        $where=array();
        $data = array();
        $where['id'] = $order_id;//订单id
        $where['is_delete'] = 0;
        $where['status'] = array('neq',3);
        $data['status'] = 2;//订单改成已完成
        $data['updatetime'] = NOW_TIME;
        $data['chuli_temp'] = $chuli_temp;
        $library_info = M('LibraryInfo');

        // order_status`'1订货单 2发货单 3配货单 4调拨单 5退货单 6入库单',
        $list = $library_info
                    ->Field('ru_id,chu_id,chu_type,ru_type,order_status,goods_allnum')
                    ->where($where)
                    ->find();
        if (empty($list)) {
            $return['msg'] = '订单没有查询到';
            return  $return;
        }
        if ($list['order_status'] == 2 || $list['order_status'] == 3) {//不为 2发货单 3配货单
            $return['msg'] = '订单类型错误';
            return  $return;
        }
        $result = $library_info->where($where)->save($data);//修改订单
        $LibraryGoods = M('LibraryGoods');
        $library_goods = $LibraryGoods
                        ->Field('goods_id,goods_name,libinfo_id,goods_sn,goods_attr_sn,num,attr_price,supplier_id')
                        ->where('libinfo_id='.$order_id)
                        ->select();
        $StorageStock = M('StorageStock');
        if ($list['ru_type'] != 2) {//入库类型不为 2供货商（退货单）
            foreach ($library_goods as $key => $value) {
                //改库存详细 单商品库存
                $where = array();
                $where['storage_id'] = $list['ru_id'];
                $where['supplier_id'] = $value['supplier_id'];
                $where['goods_id'] = $value['goods_id'];
                $where['goods_attr_sn'] = $value['goods_attr_sn'];
                $storage_stock = $StorageStock->where($where)->count();
                $data = array();
                if ($storage_stock < 1) {
                    //添加
                    $data['goods_id'] = $value['goods_id'];
                    $data['goods_name'] = $value['goods_name'];
                    $data['goods_sn'] = $value['goods_sn'];
                    $data['goods_attr_sn'] = $value['goods_attr_sn'];
                    $data['stock'] = $value['num'];//库存量
                    $data['storage_id'] = $list['ru_id'];
                    $data['supplier_id'] = $value['supplier_id'];
                    $data['buy_price'] = $value['attr_price'];
                    $data['add_time'] = NOW_TIME;
                    $data['in_time'] = NOW_TIME;
                    $stock = $StorageStock ->add($data);

                    //入库单位变更后数量
                    $ru_end_num = $StorageStock->where('id='.$stock)->getField('stock');
                }else{
                    //修改库存
                    $data['in_time'] = NOW_TIME;
                    $data['stock'] = array('exp','stock+'.$value['num']);//库存量
                    $stock = $StorageStock->where($where)->save($data);
                    $ru_end_num = $StorageStock->where($where)->getField('stock');//入库单位变更后数量
                }  

                //修改商品表：出库单位变更后数量和入库单位变更后数量 
                if ($list['chu_type'] != 1) {//出库类型不为 1个人时（用户给仓库的退货单）
                    $attr_sn = explode('-',$value['goods_attr_sn']);
                    if ( $list['order_status'] == 1 || $list['order_status'] == 6 ) {//（订货单、入库单）
                        if (!empty($attr_sn[1])) {//存在属性就到属性表找
                            $where = array();
                            $where['goods_id'] = $value['goods_id'];
                            $where['attr_key'] = $attr_sn[1];
                            $chu_end_num = M('GoodsAttrStock')
                                                ->where($where)
                                                ->getField('stock_cfg');//出库单位变更后数量
                        }else{//不存在属性就到goods表找
                            $where = array();
                            $where['id'] = $value['goods_id'];
                            $chu_end_num = M('Goods')
                                                ->where($where)
                                                ->getField('goods_number');//出库单位变更后数量
                        }   
                    }elseif ($list['order_status'] == 4) {//（调拨单）
                            $where = array();
                            $where['storage_id'] = $list['chu_id'];
                            $where['goods_attr_sn'] = $value['goods_attr_sn'];
                            $chu_end_num = $StorageStock->where($where)->getField('stock');//出库单位变更后数量
                    }
                }
                $where = array();
                $data = array();
                $where['libinfo_id'] = $value['libinfo_id'];
                $where['goods_attr_sn'] = $value['goods_attr_sn'];
                $data['ru_end_num'] = $ru_end_num;
                $data['chu_end_num'] = $chu_end_num;
                $end_num = $LibraryGoods -> where($where) -> save($data);
            }
            // 改总库存
            $data = array();
            $data['update_time'] = NOW_TIME;
            $data['allstock'] = array('exp','allstock+'.$list['goods_allnum']);
            $all_stock = M('Storage')->where('id='.$list['ru_id'])->save($data);

            if ($result !== false && $stock !== false && $all_stock !== false) {
                $return['status'] = 1;
                $return['msg'] = '入库成功';
            }else{
                $return['msg'] = '入库失败';
            }
            return  $return;
        }else{//入库类型为 2供货商（仓库给供货商的退货单）给供货商加库存
            $GoodsAttrStock = M('GoodsAttrStock');
            $Goods = M('Goods');
            foreach ($library_goods as $key => $value) {//检查商品是否存在
                $attr_sn = explode('-', $value['goods_attr_sn']);
                $flag = 0;
                if (!empty($attr_sn[1])) {//存在属性就到属性表找
                    $where = array();
                    $where['goods_id'] = $value['goods_id'];
                    $where['attr_key'] = $attr_sn[1];
                    $count = $GoodsAttrStock->where($where)->count();
                    if (!empty($count)) {
                        $flag = 1;
                    }
                }else{//不存在属性就到goods表找
                    $where = array();
                    $data = array();
                    $where['id'] = $value['goods_id'];
                    $count = $Goods->where($where)->count();
                    if (!empty($count)) {
                        $flag = 1;
                    }
                } 
                if (empty($flag)) {
                    $where=array();
                    $data = array();
                    $where['id'] = $order_id;//订单id
                    $data['status'] = 1;//订单改为未入库
                    $result = $library_info->where($where)->save($data);//修改订单
                    $return['msg'] = '供货商不存在该商品';
                    return  $return;
                }
            }

            foreach ($library_goods as $key => $value) {//增加供货商库存
                $attr_sn = explode('-', $value['goods_attr_sn']);
                if (!empty($attr_sn[1])) {//存在属性就到属性表找
                    $where = array();
                    $data = array();
                    $where['goods_id'] = $value['goods_id'];
                    $where['attr_key'] = $attr_sn[1];
                    $data['stock_cfg'] = array('exp','stock_cfg+'.$value['num']);//库存量
                    $stock = $GoodsAttrStock->where($where)->save($data);
                    $ru_end_num = $GoodsAttrStock
                                        ->where($where)
                                        ->getField('stock_cfg');//入库单位变更后数量                      
                }else{//不存在属性就到goods表找
                    $where = array();
                    $data = array();
                    $where['id'] = $value['goods_id'];
                    $data['goods_number'] = array('exp','goods_number+'.$value['num']);
                    $stock = $Goods->where($where)->save($data);
                    $ru_end_num = $Goods
                                    ->where($where)
                                    ->getField('goods_number');//入库单位变更后数量
                }  
                $where = array();
                $where['storage_id'] = $list['chu_id'];
                $where['supplier_id'] = $value['supplier_id'];
                $where['goods_id'] = $value['goods_id'];
                $where['goods_attr_sn'] = $value['goods_attr_sn'];
                $chu_end_num = $StorageStock->where($where)->getField('stock');//出库单位变更后数量 

                 //修改商品表：出库单位变更后数量和入库单位变更后数量
                $where = array();
                $data = array();
                $where['libinfo_id'] = $value['libinfo_id'];
                $where['goods_attr_sn'] = $value['goods_attr_sn'];
                $data['ru_end_num'] = $ru_end_num;
                $data['chu_end_num'] = $chu_end_num;
                $end_num = $LibraryGoods -> where($where) -> save($data);
            }
        }

        $return['status'] = 1;
        $return['msg'] = '入库成功';
        return  $return;*/
    }    

  
    /** 
     * 出库
     * @param int  $order_id   订单id
     * @return string  $chuli_temp   备注
     */ 
    public function all_out_stock($order_id)
    {   /*
        $return = array('status' => 0,'msg' => '');

        $order_id = intval($order_id);
        if(empty($order_id)){
            $return['msg'] = '参数错误';
            return $return;
        }

        $where=array();
        $data = array();
        $where['id'] = $order_id;//订单id
        $where['is_delete'] = 0;
        $where['status'] = array('neq',3);
        $library_info = M('LibraryInfo');
        $count = $library_info->where($where)->count();  
        if(empty($count)){
                $return['msg'] = '订单没有查询到';
                return $return;
        } 

        // order_status`'1订货单 2发货单 3配货单 4调拨单 5退货单 6入库单',
        $list = $library_info
                    ->Field('ru_id,chu_id,chu_type,ru_type,order_status,goods_allnum')
                    ->where($where)
                    ->find();
        if ($list['chu_type'] == 1 || $list['order_status'] == 3) {//不为（3配货单）和（会员退货单）
            $return['msg'] = '订单类型错误';
            return  $return;
        }

        if ($list['order_status'] == 2) {//2发货单(仓库给会员发货 一发货就算完成)
            $data['status'] = 2;//2已入库、已完成
        }else{
            $data['status'] = 1;//订单改为 1待入库、待收货
        }

        $data['shipping_time'] = NOW_TIME;
        $data['updatetime'] = NOW_TIME;
        $result = $library_info->where($where)->save($data);//修改订单状态
        $LibraryGoods = M('LibraryGoods');
        $library_goods = $LibraryGoods
                        ->Field('goods_id,goods_name,libinfo_id,goods_sn,goods_attr_sn,num,attr_price,supplier_id')
                        ->where('libinfo_id='.$order_id)
                        ->select();
        $StorageStock = M('StorageStock');

        if ($list['order_status'] != 1 && $list['order_status'] != 6) {  //不为订货单和入库单

            foreach ($library_goods as $k => $v) {//查看商品是否存在
                $where = array();
                $where['storage_id'] = $list['chu_id'];
                $where['goods_id'] = $v['goods_id'];
                $where['goods_attr_sn'] = $v['goods_attr_sn'];
                $count = 0;
                $count = $StorageStock ->where($where)->count();
                if (empty($count)) {
                    $where=array();
                    $data = array();
                    $where['id'] = $order_id;//订单id
                    $data['status'] = 0;//订单改成未发货
                    $result = $library_info->where($where)->save($data);//修改订单
                    $return['msg'] = '订单商品没有查询到';
                    return $return;
                }
            }            

            foreach ($library_goods as $k => $v) {
                $where = array();
                $where['storage_id'] = $list['chu_id'];
                $where['goods_id'] = $v['goods_id'];
                $where['goods_attr_sn'] = $v['goods_attr_sn'];
                //改库存详细 单商品库存
                $storage_stock = $StorageStock ->where($where)->find();
                $data = array();
                $data['out_time'] = NOW_TIME;
                //修改库存
                $data['stock'] =array('exp','stock-'.$v['num']);
                $stock = $StorageStock->where($where)->save($data);
                if ($v['order_status'] == 2) {//发货单（修改出库单位变更后数量和入库单位变更后数量）
                    $chu_end_num = $StorageStock->where($where)->getField('stock');//出库单位变更后数量 
                    $where = array();
                    $data = array();
                    $where['libinfo_id'] = $v['libinfo_id'];
                    $where['goods_attr_sn'] = $v['goods_attr_sn'];
                    $data['chu_end_num'] = $chu_end_num;
                    $end_num = $LibraryGoods -> where($where) -> save($data);
                }
            }

            $where = array();
            $data = array();
            $where['id'] = $list['chu_id'];
            $data['update_time'] = NOW_TIME;
            $data['allstock'] =array('exp','allstock-'.$list['goods_allnum']);
            $all_stock = M('Storage')->where($where)->save($data);
            if ($all_stock === false) {
                    $return['msg'] = '总库存修改失败';
                    return $return;
            }

        }else{//订货单 入库单（供货商减库存）

            $GoodsAttrStock = M('GoodsAttrStock');
            $Goods = M('Goods');
            foreach ($library_goods as $key => $value) {//检查供货商商品是否存在
                $attr_sn = explode('-', $value['goods_attr_sn']);
                $flag = 0;
                if (!empty($attr_sn[1])) {//存在属性就到属性表找
                    $where = array();
                    $where['goods_id'] = $value['goods_id'];
                    $where['attr_key'] = $attr_sn[1];
                    $count = $GoodsAttrStock->where($where)->count();
                    if (!empty($count)) {
                        $flag = 1;
                    }
                }else{//不存在属性就到goods表找
                    $where = array();
                    $data = array();
                    $where['id'] = $value['goods_id'];
                    $count = $Goods->where($where)->count();
                    if (!empty($count)) {
                        $flag = 1;
                    }
                } 
                if (empty($flag)) {
                    $where=array();
                    $data = array();
                    $where['id'] = $order_id;//订单id
                    $data['status'] = 0;//订单改成未发货
                    $result = $library_info->where($where)->save($data);//修改订单
                    $return['msg'] = '供货商商品没有查询到';
                    return $return;
                }
            }


            foreach ($library_goods as $key => $value) {//减少供货商库存
                $attr_sn = explode('-', $value['goods_attr_sn']);
                if (!empty($attr_sn[1])) {//存在属性就到属性表找
                    $where = array();
                    $data = array();
                    $where['goods_id'] = $value['goods_id'];
                    $where['attr_key'] = $attr_sn[1];
                    $data['stock_cfg'] = array('exp','stock_cfg-'.$value['num']);//库存量
                    $stock = $GoodsAttrStock->where($where)->save($data);
                }else{//不存在属性就到goods表找
                    $where = array();
                    $data = array();
                    $where['id'] = $value['goods_id'];
                    $data['goods_number'] = array('exp','goods_number-'.$value['num']);
                    $stock = $Goods->where($where)->save($data);
                } 
            }
        }

        $return['status'] = 1;
        $return['msg'] = '出库成功';
        return $return;    */
    }

    /** 
     * 生成仓库盘点单
     * @param  int   $type  盘点类型（1：仓库 2：供货商 3：店铺
     * @param  int  $type_id   仓库或供货商或店铺id
     * @param  array $postdata   订单数据
     * @return array  $data  返回订单id
    */ 
    public function create_stocktaking($type,$type_id,$postdata){
        $return=array('status'=>0,'msg'=>'');
        $type_id=intval($type_id);
        $type=intval($type);
        if (empty($type_id) || empty($postdata) || empty($type)) {
            $return['msg'] = '参数错误';
            return $return;
        }
        $unique = array_unique($postdata['goods_type']["goods_attr_sn"]);
        $count = count($postdata['goods_type']["goods_attr_sn"]);
        $count2 = count($unique);
        if ($count != $count2) {
            $return['msg'] = '商品不能重复!';
            return $return;
        }
        $data = array();
        $data['all_stock'] = array_sum($postdata['goods_type']["stock"]);//库存总数
        $data['reality_sum'] = array_sum($postdata['goods_type']["reality"]);//实际盘点总数
        $data['profit_sum'] = 0;//盘盈总数
        $data['loss_sum'] = 0;//盘亏总数
        $data['addtime'] = NOW_TIME;
		if($type == 3){
			$data['admin_id'] = $type_id;//仓库id
		}else{
			$data['admin_id'] = UID;//添加人
		}
        $data['type_id'] = $type_id;//仓库或供货商或仓库id
        $data['type'] = $type;//类型id
        // 区分盈利盈亏
        foreach ($postdata['goods_type']["profit_loss"] as  $v) {
            if ($v > 0) {
                $data['profit_sum'] += $v;
            }else{
                $data['loss_sum'] += $v;
            }
        }
        $save_info = M('StocktakingInfo')->add($data);
        if($save_info === false){
            $return['msg'] = '添加订单失败!';
            return $return;
        }

        $data = array();
        for ($i=0; $i < $count; $i++) { 
            $data['stocktaking_id'] = $save_info;
            $data['goods_id'] = $postdata['goods_type']['goods_id'][$i];
            $data['supplier_id'] = $postdata['goods_type']['supplier_id'][$i];
            $data['goods_name'] = $postdata['goods_type']['goods_name'][$i];
            $data['goods_sn'] = $postdata['goods_type']['goods_sn'][$i];
            $data['goods_attr_sn'] = $postdata['goods_type']['goods_attr_sn'][$i];
            $data['stock'] = $postdata['goods_type']['stock'][$i];
            $data['reality'] = $postdata['goods_type']['reality'][$i];
            $data['profit_loss'] = $postdata['goods_type']['profit_loss'][$i];
            $data['remark'] = $postdata['goods_type']['remark'][$i];
            $save_goods = M('StocktakingGoods')->add($data);
            if($save_goods === false){
                $return['msg'] = '添加订单商品失败!';
                return $return;
            }
        }

        $return['status'] = 1;
        $return['msg'] = '添加成功';
        $return['data'] = $save_info;
        return $return;
    }


    /** 
     * 打印盘点单
     * @param  int   $id  盘点单id
     * @return array  $data  响应数据
    */
    public function stocktaking_print($id){
        $return=array('status'=>0,'msg'=>'');
        $id = intval($id);
        if (empty($id)) {
            $return['msg'] = '参数错误！';
            return $return;
        }
        $map = array();
        $map['id'] = $id;
        $info = M('StocktakingInfo')->where($map)->field(true)->find();
        if (empty($info)) {
            $return['msg'] = '没有查询到订单！';
            return $return;
        }
        $map = array();
        switch ( $info['type'] ) {//盘点类型
            case  1 :
                $map['id'] = $info['type_id'];
                $unit_name = M('Storage')->where($map)->getField('name');
                $order_status = '仓库';
                break;                    
            case  2 :
                $map['id'] = $info['type_id'];
                $unit_name = M('Suppliers')->where($map)->getField('name');
                $order_status = '供货商';
                break;
            case  3 :
                $map['id'] = $info['type_id'];
                $unit_name = M('Shops')->where($map)->getField('name');
                $order_status = '店铺';
                break;
            default:
                $unit_name = '';
                $order_status = '';
        }
        $info['order_status'] = $order_status;
        $info['unit_name'] = $unit_name;

        $where = array();
        $where['stocktaking_id']=$id;
        $goods = M('StocktakingGoods')->field(true)->where($where)->select();
        if (empty($goods)) {
            $return['msg'] = '没有查询到订单商品！';
            return $return;
        }
		foreach ($goods as $k => $v) {
			$attr_key = explode('-', $v['goods_attr_sn']);
			if(!empty($attr_key[1])) {
				if($info['type'] == 3){
					$attr_name = attr_key2name($attr_key[0],$v['goods_id']);
				}else{
					$attr_name = attr_key2name($attr_key[1],$attr_key[0]);
				}
				$goods[$k]['attr_name'] = $attr_name;
			}else{
				$goods[$k]['attr_name'] = '';
			}
		}

        $return['status'] = 1;
        $return['info'] = $info;
        $return['goods'] = $goods;
        return $return;
    }
	/** 
     * 打印入库单
     * @param  int   $id  盘点单id
     * @return array  $data  响应数据
    */
    public function stock_index_print($id){
        /*$return=array('status'=>0,'msg'=>'');
        $id = intval($id);
        if (empty($id)) {
            $return['msg'] = '参数错误！';
            return $return;
        }
        $map = array();
        $map['id'] = $id;
        $info = M('LibraryInfo')->where($map)->field(true)->find();
        if (empty($info)) {
            $return['msg'] = '没有查询到订单！';
            return $return;
        }
		// 出库类型 1个人 2供货商 3仓库
		// 入库类型 1个人 2供货商 3仓库 4仓库
        $map = array();
        switch ( $info['ru_type'] ) {//入库类型
            case  1 :
                $map['id'] = $info['ru_id'];
                $unit_name = M('Member')->where($map)->getField('username');
                $order_status = '个人';
                break;                    
            case  2 :
                $map['id'] = $info['type_id'];
                $unit_name = M('Suppliers')->where($map)->getField('name');
                $order_status = '供货商';
                break;
			case  3 :
                $map['id'] = $info['type_id'];
                $unit_name = M('Storage')->where($map)->getField('name');
                $order_status = '仓库';
                break;
            case  4 :
                $map['id'] = $info['type_id'];
                $unit_name = M('Shops')->where($map)->getField('name');
                $order_status = '店铺';
                break;
            default:
                $unit_name = '';
                $order_status = '';
        }
        $info['order_status'] = $order_status;
        $info['unit_name'] = $unit_name;

        $where = array();
        $where['libinfo_id']=$id;
        $goods = M('LibraryGoods')->field(true)->where($where)->select();
        if (empty($goods)) {
            $return['msg'] = '没有查询到该单商品！';
            return $return;
        }
		foreach ($goods as $k => $v) {
			$attr_key = explode('-', $v['goods_attr_sn']);
			if(!empty($attr_key[1])) {
				if($info['ru_type'] == 4){
					$attr_name = '';
				}else{
					$attr_name = attr_key2name($attr_key[1],$attr_key[0]);
				}
				$goods[$k]['attr_name'] = $attr_name;
			}else{
				$goods[$k]['attr_name'] = '';
			}
		}

        $return['status'] = 1;
        $return['info'] = $info;
        $return['goods'] = $goods;
        return $return;*/
    }
}

