<?php
/**
 * @Copyright (C) 2017 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */

namespace Admin\Controller;
class StorageController extends BaseController
{	
    public function _initialize(){

        parent::_initialize ();
        $this->order_type=strtoarray(C('ORDER_TYPE'));$this->assign('order_type',$this->order_type);
        $wm_order_type=strtoarray(array('13'=>'收银','14'=>'商品'));$this->assign('wm_order_type',$wm_order_type);
        $this->order_status=strtoarray(C('ORDER_STATUS'));$this->assign('order_status',$this->order_status);
        $this->order_pay=strtoarray(C('ORDER_PAY'));$this->assign('order_pay',$this->order_pay);
        $this->order_shipping=strtoarray(C('ORDER_SHIPPING'));$this->assign('order_shipping',$this->order_shipping);
        $this->zy_shipping=array('1'=>'未发货','2'=>'已发货');
		$this->assign('zy_shipping',$this->zy_shipping);
    }

    private function getadminlist(){
            $map=array();
            $map['a.status']=1;
            $map['a.id']=array('neq',C('USER_ADMINISTRATOR'));
            $admin = M('AuthGroupAccess')->alias('ag')->Field('a.id,a.username')->join('left join hanchao_admin as a on a.id = ag.uid')->where($map)->select();
            $this->assign('admin',format_array2select($admin,'username'));
    }

    public function _before_add(){        
        $this->getadminlist();
    }    
    // 仓储中心首页
    public function index(){ 
        $name = CONTROLLER_NAME;
        $keyword = I('post.keyword');
        $map = array();
        if(!empty($keyword)){
            $map['name']  = array('like', '%'.$keyword.'%');
            $map['id'] = $keyword;//仓库id
            $map['_logic'] = 'or';
        }
        $storage_ids = D($name) -> get_storage_ids(UID);//当前管理员的仓库ids
        if ($storage_ids['data'] != 'all') {//不是超级管理员
            $where= array();
            $ids = $storage_ids['data'];
            if(!empty($keyword)){
                $is_exists = in_array($keyword,$ids);
                if ($is_exists) {
                    $ids = $keyword;
                }
                $where['_complex'] = $map;
            }
            $where['id'] = array('in',$ids);
            $map = $where;
            $this->assign('admin_id', 1);
        }
        $list = $this->lists(CONTROLLER_NAME, $map);
        $this->assign('list',$list);
        $this->assign('keyword',$keyword);
        $this->display();
    }

    //仓库盘点列表
    public function stocktaking_list(){
        $postdata = I('param.');
        // var_dump($postdata);die;
        if(empty($postdata['storage_id'])){
            $this->error("参数错误");
        }
        $map = array();
        $map['type_id'] = $postdata['storage_id'];//仓库id
        $map['type'] = 1;//仓库类型
        
        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);
        $username = M('Admin')->cache(true)->getField('id,username');
        $list = $this->lists('StocktakingInfo', $map);
        foreach ($list as $k => $v) {
            $list[$k]['username'] = $username[$v['admin_id']];
        }
        $this->assign('map',$postdata);
        $this->assign('storage_id',$postdata['storage_id']);
        $this->assign('list',$list);
        $this->display();
    } 

    //仓库盘点单查看
    public function 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->display();
    }
    //删除盘点单
    public function stocktaking_delete(){
        $id=I('id');
        if(empty($id)){
            $this->error("参数错误");
        }
        $where=array();
        $map=array();
        if(isset($id)&&is_array($id)){
            $where = 'id in('.implode(',',$id).')';
            $map = 'stocktaking_id in('.implode(',',$id).')';
        }else{
              $where = 'id='.$id;
              $map = 'stocktaking_id='.$id;
        }
        $info = M('StocktakingInfo')->where($where)->delete(); 
        $goods = M('StocktakingGoods')->where($map)->delete(); 

        if($info!==false && $goods!==false) {
            $this->success(L('DELETE_SUCCESS'), $url);
        }else{
            $this->error(L('DELETE_FAILED'), $url);
        }
        $this->id=$id;
    } 

  //添加仓库盘点
    public function add_stocktaking(){
        $id=intval(I('get.storage_id'));//仓库id
        if(empty($id)){
            $this->error("参数错误");
        }
        $this->assign('storage_id',$id);
        $this->display();
    }

    //生成仓库盘点单
    public function create_stocktaking(){
        $postdata = I('post.');
        if (empty($postdata)) {
            $this->error("参数错误");
        }
        $type_id = $postdata['storage_id'];//仓库id
        $name = CONTROLLER_NAME;
        $add = D($name) -> create_stocktaking(1,$type_id,$postdata);//添加盘点订单
        $id = $add['data'];
        if ($add['status'] == 1) {
            $add['url'] = U('stocktaking_print',array('id'=>$id));
        }
        $this->ajaxReturn($add);
    }

    //打印盘点单
    public function stocktaking_print(){
        $id = I('get.id');//盘点单id
        if (empty($id)) {
            $this->error('参数错误！');
        }
        $name = CONTROLLER_NAME;
        $print = D($name) -> stocktaking_print($id);
        if ($print['status'] == 0) {
            $msg = $print['msg'];
            $this->error($msg);
        }
        $admin = idtoname(UID,'admin','username');
        $time = date('Y-m-d H:i:s',NOW_TIME);
        $this->assign('info',$print['info']);
        $this->assign('goods',$print['goods']);
        $this->assign('admin',$admin);
        $this->assign('time',$time);
        $this->display('stocktaking_print');
    }

    /**
     * 配货单
     */
    public function distribution(){

        $storage_ids = D('Storage') -> get_storage_ids(UID);//当前管理员的仓库ids

        $postdata=I('param.');
        if($postdata['order_sn'])$map['order_sn']=$postdata['order_sn'];
        if($postdata['status'])$map['status']=$postdata['status'];
        if($postdata['pay_status'])$map['pay_status']=$postdata['pay_status'];
        if($postdata['shipping_status'])$map['shipping_status']=$postdata['shipping_status'];
        if($postdata['keyword']){
            $whereor['uid']=$postdata['keyword'];
            $whereor['consignee']=array('like','%'.$postdata['keyword'].'%');
            $whereor['address']=array('like','%'.$postdata['keyword'].'%');
            $whereor['mobile']=array('like','%'.$postdata['keyword'].'%');
            $whereor['email']=array('like','%'.$postdata['keyword'].'%');
            $whereor['sign_building']=array('like','%'.$postdata['keyword'].'%');
            $whereor['temp']=array('like','%'.$postdata['keyword'].'%');
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
        }
        $map['storage_id']=array('gt',0);
        if($storage_ids['status']==1&&$storage_ids['data']!='all' ){
            if($postdata['storage']){
                if(!in_array($postdata['storage'],$storage_ids['data']))$storage_ids['data']=0;
                else $storage_ids['data']=$postdata['storage'];
            }
            $map['storage_id']=is_array($storage_ids['data']) || strpos($storage_ids['data'],',')?array('in',$storage_ids['data']):$storage_ids['data'];
        }elseif($postdata['storage']){
            $map['storage_id']=$postdata['storage'];
        }
        $list=$this->lists("OrderInfo",$map);
        
        $this->storage_list($storage_ids);
        $this->assign($postdata);
        $this->assign('list',$list);
        $this->display();
    }
    /**
     * 仓库处理发货
     */
    public function deliver_goods(){
        $data['order_id']=I('order_id');
        $data['notice_sn']=I('notice_sn');
        $data['send_type']=I('send_type');
        if(I('get_type')==1) {
            $location_id=I('locaion_id');
            if(empty($location_id)){
                $this->error('请选择附近仓库');
            }
            $data['take_location_id'] = I('locaion_id');
        }
        $data['type']='store';
        $data['admin_id']=UID;
        $result=D("Common/OrderInfo")->ship_goods($data);
        if($result['status']){
            $this->success($result['info'],geturl('Admin/OrderInfo/ship_print',array('id'=>$result['id'])));
        }else{
            $this->error($result['info']);
        }
    }
    public function _before_view(){
        $id=I('id');
        if(empty($id))$this->error('参数不正确');
        $order=M('OrderInfo')->field('true')->find();
        $ordergoods=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($ordergoods as $k=>$v){
            $attr=unserialize($v['goods_attr']);
            $ordergoods[$k]['attr_name']=$attr['name'];
            $ordergoods[$k]['org_parce']=$v['attr_price']*$v['goods_number'];
            $ordergoods[$k]['org_integral']=$v['goods_integral']*$v['goods_number'];
            $ordergoods[$k]['shipping']=$ordership[$v['goods_id']];
            $goods_ids[]=$v['goods_id'];
        }
        $this->assign('ordergoods',$ordergoods);
        $actionlog=M('ActionLog')->where('action_id in (9,10) and record_id='.$id)->order('id desc')->select();
        $this->assign('actionlog',$actionlog);
    }
    public function dis_view(){
        $id=I('id');if(empty($id))$this->error('参数不正确');
        $ordergoods=M('OrderGoods')->where('order_id='.$id)->select();
        foreach($ordergoods as $k=>$v){
            $attr=unserialize($v['goods_attr']);
            $ordergoods[$k]['attr_name']=$attr['name'];
            $ordergoods[$k]['org_parce']=$v['goods_price']*$v['goods_number'];
        }
        $this->assign('ordergoods',$ordergoods);
        $order_info=M('OrderInfo')->where('id='.$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);

        if($order_info['type']==10){
            $operable_list=R('Admin/OrderInfo/operable_list',array('id'=>$id));
            $this->assign('operable_list',$operable_list);
            $this->display ('dis_mview');
        }else{
            //店铺
            $shop_info=D("Shops")->get_shops_info($order_info['uid']);
            foreach($shop_info as $k=>$v){
                $shop_infos[$v['id']]=$v['name'];
            }
            $this->assign('shop_info',$shop_infos);
            $this->display ();
        }
    }

     /** 
     * 查找指定仓库商品或查找仓库指定供应商的商品
    * @param  string $name   商品编号或名字 
     *@param  int $storage_id    仓库id
     *@param  int $supplier_id   供货商id
     *@return array  $data   响应数据 
     */ 
    public function storage_goods(){

        $return=array('status'=>0,'msg'=>'');
        $postdata = I('post.');
        $storage_id = $postdata['storage_id'];//仓库id
        $supplier_id = $postdata['supplier_id'];//供货商id
        $goods_sn = $postdata['goods_sn'];//商品名或编号
        if (empty($storage_id)) {
            $data = '参数错误';
            $this->ajaxReturn($data);
        }
        $where = array();
        if (!empty($storage_id) && !empty($supplier_id) && empty($goods_sn)) {
            $where['storage_id'] = $storage_id;
            $where['supplier_id'] = $supplier_id;
        }elseif(!empty($storage_id) && !empty($supplier_id) && !empty($goods_sn)){
            $where['storage_id'] = $storage_id;
            $where['supplier_id'] = $supplier_id;
            $where['goods_sn|goods_name']=array('like', '%'.$goods_sn.'%');//模糊查询
        }elseif(!empty($storage_id) && empty($supplier_id) && !empty($goods_sn)){
            $where['storage_id'] = $storage_id;
            $where['goods_sn|goods_name']=array('like', '%'.$goods_sn.'%');//模糊查询
        }
        $goods=M('StorageStock')->field(true)->where($where)->order('goods_id')->limit(50)->select(); 

        if (empty($goods)) {//该供货商没有商品
            $return['msg']='该供货商没有商品！';
            $this->ajaxReturn($return);
        }
        $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;
        $this->ajaxReturn($return);
    }


    //  创建商品表格（盘点单用）
    public function create_goods_table(){
        $storage_id=intval(I('post.storage_id'));//仓库id
        $goods_attr_sn = trim(I('post.goods_attr_sn'));//商品id_属性编号

        $return = array('status'=>0,'msg'=>'');
        if(empty($storage_id)  || empty($goods_attr_sn)){
            $return['msg'] = '参数错误';
            return $return;
        }
        $where = array();
        $where['storage_id'] = $storage_id;
        $where['goods_attr_sn'] = $goods_attr_sn;
        $goods_info=M('StorageStock')->field(true)->where($where)->find();

        if($goods_info === false){
            $return['msg'] = '参数错误';
            return $return;
        }
        $attr = explode('-', $goods_info['goods_attr_sn']);
        $attr_name=attr_key2name($attr[1],$attr[0]);
        $goods_info['attr_name'] = $attr_name;
        // var_dump($goods_info);
        $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_attr_sn']."' /><input type='hidden' name='goods_type[supplier_id][]' value='".$goods_info['supplier_id']."' /><input type='hidden' name='goods_type[stock][]' value='".$goods_info['stock']."' />
            </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['stock']."</td>
            <td><input name='goods_type[reality][]' style='width:80px;' type='number' min='1'  onchange='change_loss(this)' value=".$goods_info['stock']."></td>
            <td><input name='goods_type[profit_loss][]' readonly='readonly' type='text' style='width:80px'  value='0' /></td>
            <td colspan='1'><textarea class='form-control w120' name='goods_type[remark][]' rows='1'>{$temp}</textarea></td>
            <td><a onclick='delCurrentRow(this);' style='cursor:pointer;'>删除</a></td>
            </tr>";
        // var_dump($data);
        // profit_loss
        $data['status']=1;
        $this->ajaxReturn($data);
    }





    public function delete(){
        $id=I('id');
        if(empty($id)){
            $this->error("参数错误");
        }
        $where=array();
        $map=array();
        if(isset($id)&&is_array($id)){
            $where = 'id in('.implode(',',$id).')';
            $map = 'storage_id in('.implode(',',$id).')';
        }else{
              $where = 'id='.$id;
              $map = 'storage_id='.$id;
        }
        $list = M(CONTROLLER_NAME)->where($where)->delete(); 
        $admin = M('StorageAdmin')->where($map)->delete(); //删除绑定管理员

        if($list!==false && $admin!==false) {
            $url = U(CONTROLLER_NAME . '/index');
            $this->success(L('DELETE_SUCCESS'), $url);
        }else{
            $this->error(L('DELETE_FAILED'));
        }
        $this->id=$id;
    }
//删除配货单
    public function delete_dis(){
        $mod=D('OrderInfo');
        $id=$this->id?$this->id:I('id');
        if (isset($id) && is_array($id)) {
            $ids = implode(',', $id);
            $result=$mod->delete($ids);
        } else {
            $id = intval($id);
            $result=$mod->delete($id);
        }
        if($result!==false){
            if(in_array('OrderInfo',$this->cache_model)){savecache('OrderInfo');}
            $this->success(L('DO_OK'));
        }else{$this->error(L('DO_ERROR'));}

    }
    public function insert()
    {
        $postdata = I('post.');
        if(empty($postdata['admin_id'])){
            $this->error("管理员不得为空");
        }
        $arr['is_country'] = isset($postdata['is_country']) ? $postdata['is_country'] : 0;
        $regions = implode(',', $postdata['regions']);
        $arr['area_id'] = $regions;
        if ($arr['is_country'] < 1) {
            if(empty($postdata['regions'])){
            $this->error("配送区域不得为空");
            }
        }else{
            $arr['area_id'] = '';
        }
        $model = D(CONTROLLER_NAME);
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        $storage_id = $model->add();
        $arr['name'] = isset($postdata['name']) ? $postdata['name'] : '';
        $arr['allocation_num'] = isset($postdata['allocation_num']) ? $postdata['allocation_num'] : '';
        $arr['storage_desc'] = isset($postdata['storage_desc']) ? $postdata['storage_desc'] : '';
        $arr['contact_name'] = isset($postdata['contact_name']) ? $postdata['contact_name'] : '';
        $arr['phone'] = isset($postdata['phone']) ? $postdata['phone'] : '';
        $arr['address'] = isset($postdata['address']) ? $postdata['address'] : '';
        $arr['province'] = isset($postdata['areas_province']) ? $postdata['areas_province'] : '';
        $arr['city_id'] = isset($postdata['areas_city_id']) ? $postdata['areas_city_id'] : '';
        $arr['district'] = isset($postdata['areas_district']) ? $postdata['areas_district'] : '';

        $arr['add_time'] = time();
        $admin_id = $postdata['admin_id'];
        for ($i=0; $i < count($admin_id) ; $i++) { 
            $data['storage_id'] = $storage_id;
            $data['admin_id'] = $admin_id[$i];
            M('storage_admin')->add($data);
        }
        $map['id'] = $storage_id;
        M('storage')->where($map)->save($arr);
        if ($storage_id !== false) {
            $url = U(CONTROLLER_NAME . '/index');
            $this->success(L('ADD_OK'), $url);
        } else {
            $this->error(L('ADD_ERROR'));
        }
    }

    
    public function update()
    {
        $postdata = I('post.');
        if(empty($postdata['admin_id'])){
            $this->error("管理员不得为空");
        }
        $arr['is_country'] = 0;
        $regions = implode(',', $postdata['regions']);
        $arr['area_id'] = $regions;
        if ($arr['is_country'] < 1) {
            if(empty($postdata['regions'])){
            $this->error("配送区域不得为空");
            }
        }else{
            $arr['area_id'] = '';
        }
        $id = I('post.id');
        $arr['name'] = $postdata['name'];
        $arr['allocation_num'] = $postdata['allocation_num'];
        $arr['storage_desc'] = $postdata['storage_desc'];
        $arr['contact_name'] = $postdata['contact_name'];
        $arr['phone'] = $postdata['phone'];
        $arr['address'] = $postdata['address'];
        $arr['province'] = $postdata['areas_province'];
        $arr['city_id'] = isset($postdata['areas_city_id']) ? $postdata['areas_city_id'] : '';
        $arr['district'] = isset($postdata['areas_district']) ? $postdata['areas_district'] : '';
        $arr['update_time'] = time();
        $admin_id = $postdata['admin_id'];

        $data['storage_id'] = $id;
        M('storage_admin')->where($data)->delete();
        for ($i=0; $i < count($admin_id) ; $i++) { 
            $data['admin_id'] = $admin_id[$i];
            M('storage_admin')->add($data);
        }
        $where_s['id'] = $id;
        $info = M('storage')->where($where_s)->save($arr);
        if ($info !== false) {
            $url = U(CONTROLLER_NAME . '/index');
            $this->success(L('EDIT_OK'), $url);
        } else {
            $this->error(L('EDIT_ERROR'), $url);
        }
    }

    
     //仓库查看
    public function check(){
        $id = $_REQUEST['id'];
        if (!$id) $this->error(L('PARAM_ERR'));
        $map = array();
        $param=I('param.');
        if($param['supplier']){
            $map['name'] = array('like', '%'.(string)$param['supplier'].'%');
            $id_ar = M('Suppliers')->where($map)->getField('id',true);
            $ids = implode(',', $id_ar);
        }
        if(!empty($param['keyword'])){
            $keyword_fields=I('keyword_fields','name');
            $field_arr=explode(',',$keyword_fields);
            $arr = implode('|',$field_arr);
            $map[$arr] = array('like', '%'.$param['keyword'].'%');
            $keyword = $param['keyword'];
        }
        if(!empty($ids) && !empty($param['supplier'])){
            $map['supplier_id']=array('in',$ids);
        }
        if(!empty($param['supplier']) && empty($ids)){
            $map['supplier_id']=array('eq',-5);
        }
        $data = M('storage')->Field('name,allstock')->where('id='.$id)->find();
        $map['storage_id'] = $id;
        $price = M('StorageStock')->Field('stock,buy_price')->where($map)->select();
        foreach ($price as $key => $value) {
            $data['price'] += $value['stock'] * $value['buy_price'];
        }
        $field = 'id,goods_id,goods_name,goods_sn,goods_attr_sn,stock,buy_price,in_time,supplier_id';
        $pagesize = 0;
        $list = page_list('StorageStock',$map,'id desc',$field,$pagesize,'',1);
        foreach ($list['list'] as $k => $v) {
            $attr_key = explode('-', $v['goods_attr_sn']);
            if(!empty($attr_key[1])) {
                $attr_name = attr_key2name($attr_key[1],$attr_key[0]);
                $list['list'][$k]['goods_attr_sn'] = $attr_name;
            }else{
                $list['list'][$k]['goods_attr_sn'] = '';
            }
        }
        $supplier = $param['supplier'];
        $this->assign('id', $id);
        $this->assign('data', $data);
        $this->assign('keyword', $keyword);
        $this->assign('supplier', $supplier);
        $this->assign('list', $list);
        $this->display();

    }

    public function edit()
    {
        $id = I('get.id');
        if (!$id) $this->error(L('PARAM_ERR'));
        $edit = M('storage');
        $edits = $edit->field(true)->find($id);
        $where['storage_id'] = $id;
        $where['admin_id'] = array('neq',0);
        $admin_id = M('storage_admin as s')->join('left join hanchao_admin as a on a.id = s.admin_id')->field('s.admin_id,a.username')->where($where)->select();
        // var_dump($admin_id);
        if (!empty($edits['area_id'])) {
            $region = explode(',', $edits['area_id']);
            $this->assign('region', $region);
        }
        $this->assign('admin_id', $admin_id);
        $this->assign('id', $id);
        $this->assign($edits);
        $this->assign('edit', $edits);
        $this->getadminlist();
        $this->display();
    }

     /** 
     * 判断新加的配送区域是否其他的仓库已经加过 
     * @param  string $area   所有区域id 
     * @param  int  $id     仓库id 修改时用，除当前仓库，其他仓库有没有加过此区域 
     */

      public function queryarea(){
        $return = array('status' => 0, 'msg'=>'' );
        $area = I('post.area');
        $id = I('post.id');
        
        $map=array();
        if(!empty($id)){$map['id']=array('neq',$id);}
        if(!empty($area)){
            $area = explode(',', ltrim($area,','));
            
            $areas=M(CONTROLLER_NAME)->where($map)->getField('area_id',true);
            $area_str=implode(',',$areas);
            $area_arr=explode(',',$area_str);
            
            $where=array();
            foreach($area as $v){
                if(in_array($v,$area_arr)){
                    $return['msg']='地区：'.idtoname($v,'Area').' 已存在';
                    $this->ajaxReturn($return);
                }
            }
        }else{
            $return['msg']='配送区域不得为空';
            $this->ajaxReturn($return);

        }
        $return['msg'] = 1;
        $this->ajaxReturn($return);
    }



    //查找供应商
    public function searchu(){
        $name = CONTROLLER_NAME;
        $chu_name=trim(I('post.chu_name'));// 供应商名字
        $chu_id=trim(I('post.chu_id'));// 仓库ID 退货单需要查仓库下的供货商
        // var_dump(I('post.'));die;
        $return = array('status'=>0,'msg'=>'');
        if(empty($chu_name)){
            $return['msg'] = '参数错误';
            return $return;
        } 
        $data = D($name)->search_chu($chu_name,$chu_id);//查找供应商
        $this->ajaxReturn($data);
    }    

    /** 
     * 退货单下拉框用查找供应商方法
     */ 
    public function search_supplier(){
        $return=array('status'=>0,'msg'=>'');
        $id = intval(I('post.id'));//仓库id
        if (empty($id)) {
            $data = '';
            $this->ajaxReturn($data);
        }
        $where = array();
        $where['storage_id'] = $id;
        $Suppliers_id=M('StorageStock')->where($where)->getField('supplier_id',true);  
        if (!$Suppliers_id) {//该供货商没有查询到
            $return['msg']='该仓库没有供货商！';
            $this->ajaxReturn($return);
        }

        $map = array();
        $map['id']=array('in',$Suppliers_id);
        $Suppliers=M('Suppliers')->where($map)->field('id,name')->order('name')->limit(20)->select();  
        if(empty($Suppliers)){
            $return['msg'] = '该供货商没有查询到！';
            $this->ajaxReturn($return);
        }
        $return['status']=1;
        $return['info']=$Suppliers;
        $this->ajaxReturn($return);
    }


     //查找入库单位
    public function search_shops(){
        $name = CONTROLLER_NAME;
        $ru_name=trim(I('post.ru_name'));// 平台仓库名
        $order_type=trim(I('post.order_type'));// 订单类型
        $storage_type=trim(I('post.storage_type'));// 仓库类型 ： 1 出库   2入库
        $return = array('status'=>0,'msg'=>'');
        if(empty($ru_name)){
            $return['msg'] = '参数错误';
            return $return;
        }   
        $data = D($name)->search_ru($ru_name,$order_type,$storage_type);//查找平台仓库
        $this->ajaxReturn($data);
    }     

   // 查询商品 //带属性的
    public function search_goods(){
        $name = CONTROLLER_NAME;
        $goods_sn=trim(I('post.goods_sn'));// 商品编号或名字
        $chu_id=intval(I('post.chu_id'));//出货单位id
        $ru_id=intval(I('post.ru_id'));//入货单位id
        $chu_type=intval(I('post.chu_type'));//出货单位类型 1：供应商, 2：平台仓库
        $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,$ru_id);//查找对应商品
        $this->ajaxReturn($data);
    }



    //  搜索供货商或平台商品
    public function sgoods(){
        $name = CONTROLLER_NAME;
        $attr_sn = trim(I('post.attr_sn'));//属性编号
        $goods_sn=trim(I('post.goods_sn'));//商品名称或编号
        $type=intval(I('post.type'));//出货单位类型 2：供应商, 3：平台仓库
        $chu_id=intval(I('post.chu_id'));//出货单位id
        $ru_id=intval(I('post.ru_id'));//供货商单位id（退货单时有）

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

        // var_dump(I('post.'));
        $goods_list = D($name)->search_goods($goods_sn,$chu_id,$type,$ru_id);//查找对应商品
        // var_dump($goods_list);die;

        if($goods_list['status'] == 0){
            $return['msg'] = $goods_list['msg'];
            return $return;
        }
  
        $goods_info = array();
        foreach ($goods_list['info']  as  $v) {
            if ($v['attr_key'] == $attr_sn) {
                $goods_info = $v;
                break;
            }
        }
        GLOBAL $PurchaseCategory;if(empty($PurchaseCategory))$PurchaseCategory=getcache('PurchaseCategory');
            $data['tr'].="<tr>
                <td>".$goods_info['goods_name']."<input type='hidden' name='goods_type[name][]' value='".$goods_info['goods_name']."' /><input type='hidden' name='goods_type[chu_id][]' value='".$chu_id."' /><input type='hidden' name='goods_type[supplier_id][]' value='".$goods_info['supplier_id']."' /></td>
                <td class='goodsn' attr_key = ".$goods_info['attr_key'].">".$goods_info['goods_sn']."<input type='hidden' name='goods_type[sn][]' value='".$goods_info['goods_sn']."' /><input type='hidden' name='goods_type[attr_key][]' value='".$goods_info['attr_key']."' /></td>
                <td><input name='goods_type[num][]' style='width:50px;' type='number' min='1'  onchange='change_price(this)' value='1'></td>
                <td class='stock' goods_name= ".$goods_info['goods_name']." >".$goods_info['stock']."</td>
                <td class='shop_price'><input name='goods_type[supp_price][]' type='hidden' style='width:50px;' value='".$goods_info['shop_price']."'>".$goods_info['shop_price']."</td>
                <td class='money'>".$goods_info['shop_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);
    }


     //生成订货单、入库单、调拨单
    public function add_stock(){/*
        $return = array('status'=>0,'msg'=>'');

        $postdata=I('post.');
        if(empty($postdata)){
            $return['msg'] = '参数错误';
            $this->ajaxReturn($return);
        }
        if(empty($postdata['c_type'])){
            $return['msg']='请选择出库单位类型'; //没有选择出库单位类型
            $this->ajaxReturn($return);
        }
        if(empty($postdata['c_dw'])){
            $return['msg']='请选择出库单位';   //没有选择出库单位
            $this->ajaxReturn($return);
        }
        if(empty($postdata['r_dw'])){
            $return['msg']='请选择入库单位';   //没有选择入库单位
            $this->ajaxReturn($return);
        }        
        if(empty($postdata['goods_type']['attr_key'])){
            $return['msg']='请选择商品';   
            $this->ajaxReturn($return);
        }

        if ($postdata['order_status'] == 4 && $postdata['c_dw'] != 0 && $postdata['r_dw'] != 0) {
            if ($postdata['c_dw'] == $postdata['r_dw']) {
                $return['msg']='出入库不能相同';   
                $this->ajaxReturn($return);
            }

        }

        //判断所有所有商品是否出自一个出库单位
        $chu = $postdata['goods_type']['chu_id'];
        $chu_id = array($postdata['c_dw']);
        $diff = array_diff($chu, $chu_id);
        if ($diff) {
            $return['msg']='商品必须出自一个出库单位';   
            $this->ajaxReturn($return);
        }
        $name = CONTROLLER_NAME;
        //检查出库单位库存是否够与价格是否正确
        $chu_id = $postdata['c_dw'];//出货单位ID
        $attr_key = $postdata['goods_type']['attr_key'];
        $num = $postdata['goods_type']['num'];//下单数量

        // 检查库存
        $check_stock = D($name)->check_stock($postdata['c_type'],$chu_id,$attr_key,$num);
        // var_dump($check_stock_price );die;
        if ($check_stock['status'] == 0) {
            $this->ajaxReturn($check_stock);
        }

        // 添加订单到LibraryInfo表中
        $allmoney = 0;//商品总金额
        foreach ($postdata['goods_type']['num'] as $k => $v) {
            $allmoney += $v * $postdata['goods_type']['supp_price'][$k];
        }
        $sum = array_sum($postdata['goods_type']['num']);//所有商品总数supp_price
        $ordata = array();
        $ordata['chu_type']=$postdata['c_type'];//出库类型  1个人  2供货商  3仓库',
        $ordata['ru_type'] = $postdata['r_type'];//'入库类型  1个人  2供货商  3仓库',
        $ordata['chu_id']=$postdata['c_dw'];//出库单位id   
        $ordata['ru_id']=$postdata['r_dw'];//入库单位id
        $ordata['order_sn']=date('Ymd',NOW_TIME).'_'.NOW_TIME.rand(1000,9999);//生成订货单编号
        $ordata['order_sum']=$sum;//订单商品总数量
        $ordata['goods_allnum']=$sum;//实际商品总数量
        $ordata['goods_allmoney']=$allmoney;//商品总金额
        $ordata['addtime']=NOW_TIME;//创建时间
        $ordata['updatetime']=NOW_TIME;//修改时间
        $ordata['order_status']=$postdata['order_status'];//'1订货单 2发货单 3配货单 4调拨单 5退货单 6入库单',
        $ordata['status']=$postdata['status'];//'0发起订货 1待入库、待收货 2已入库、已完成 （调拨单，订货单，退货单用）
        $resorder=M('LibraryInfo')->add($ordata);   //添加出入库订单
        if(empty($resorder)){
            $return['msg']='添加订单失败';   
            $this->ajaxReturn($return);
        }
    

        // 把订单商品添加到LibraryGoods表中
        $ordata = array();
        foreach ($postdata['goods_type']['attr_key'] as $k => $v) {
            $goods_id = intval($v);
            $goods_name = $postdata['goods_type']['name'][$k];
            $goods_sn = $postdata['goods_type']['sn'][$k];
            $goods_attr_sn = $v;
            $num = $postdata['goods_type']['num'][$k];
            $attr_price = $postdata['goods_type']['supp_price'][$k];
            $all_price = $attr_price * $num;
            if ($postdata['c_type'] == 2) {
                $supplier_id = $postdata['goods_type']['chu_id'][$k];
            }else{
                $supplier_id = $postdata['goods_type']['supplier_id'][$k];
            }
            // $order_status = M('LibraryInfo')->field('order_status')->where('id='.$resorder)->find();//订单类型
            // var_dump($order_status);die;
            $ordata[] = array('libinfo_id'=>$resorder,
                                'goods_id'=>$goods_id,
                                'goods_name'=>$goods_name,
                                'goods_sn'=>$goods_sn,
                                'goods_attr_sn'=>$goods_attr_sn,
                                'order_num'=>$num,
                                'num'=>$num,
                                'attr_price'=>$attr_price,
                                'all_price'=>$all_price,
                                'supplier_id'=>$supplier_id,
                                'order_status'=>$postdata['order_status']
                            );
        }
        // var_dump($ordata);die;
        $gorder = M('LibraryGoods')->addAll($ordata);
        if(empty($gorder)){
            $return['msg']='添加订单商品失败';   
            $this->ajaxReturn($return);
        }

        // '1订货单 2发货单 3配货单 4调拨单 5退货单 6入库单',
        if($postdata['order_status'] == 6 ){//入库单调入库方法

            $out_stock = D($name) -> all_out_stock($resorder);
            if($out_stock['status'] == 0){
                $this->ajaxReturn($out_stock);
            }

            $add_stock = D($name) -> all_add_stock($resorder);
            if($add_stock['status'] == 0){
                $this->ajaxReturn($add_stock);
            }            
        }elseif($postdata['order_status'] == 4 || ($postdata['order_status'] == 5 && $postdata['r_type'] == 2)){//调拨单和仓库给供应商退货单调出库方法
            $stock = D($name) -> all_out_stock($resorder);
            if($stock['status'] == 0){
                $this->ajaxReturn($stock);
            }
        }
        $return['status'] = 1;
        $return['oid'] = $resorder;
        $return['url'] = U('order_print',array('id'=>$resorder));
        $this->ajaxReturn($return);*/
                 
    }


   //仓库调拨单列表
    public function dorderlist(){
        $map=I('param.');
        $data = array(1=>'待入库',2=>'已入库',3=>'已作废');
        $this->assign('order_status',$data);
        $list = D('Storage')->orderlist(4,$map);
         if (!$list['error']) {
           $this->error('参数错误');
        }else{
            $this->assign('searchform','dorderlist');
            $this->assign('library_info',$list['list']);
            $this->assign($list);
            $this->assign('t',4);
        }

        $this->display();
    }


   //仓库入库单列表
    public function stockinlist(){
        $map=I('param.');
        // $data = array(1=>'待入库',2=>'已入库',3=>'已作废');
        // $this->assign('order_status',$data);
        $list = D('Storage')->orderlist(6,$map);
         if (!$list['error']) {
           $this->error('参数错误');
        }else{
            $this->assign('searchform','stockinlist');
            $this->assign('library_info',$list['list']);
            $this->assign($list);
            $this->assign('t',6);
        }

        $this->display('dorderlist');
    }
    
    //仓库订货单列表
    public function orderlist(){
        $map=I('param.');
        $data = array('未确认','待入库','已入库','已作废');
        $this->assign('order_status',$data);
        $list = D('Storage')->orderlist(1,$map);
        if (!$list['error']) {
           $this->error('参数错误');
        }else{
            $this->assign('count',$list['count']);
            $this->assign('searchform','orderlist');
            $this->assign('library_info',$list['list']);
            $this->assign($list);
            $this->assign('t',1);
        }
       
        $this->display("dorderlist");
    }   


    // 出入库记录
    public function stock_records()
    {   
        $name = CONTROLLER_NAME;
        $orderstatus = array(1 => '订货单', 2 => '发货单', 4 => '调拨单', 5 => '退货单', 6 => '入库单');
        $this->assign('orderstatus',$orderstatus);       
        $unit_type = array(1 => '会员', 2 => '供货商', 3 => '仓库');
        $this->assign('unit_type',$unit_type );
        $map = I('post.');
        $list = D($name)->stock_records(1,UID,$map);
        // var_dump($list);
        if ($list['status'] == 0) {
            $this->error($list['msg']);
        }
        $this->assign('count',$list['list']['count']);
        $this->assign('library_goods_info',$list['list']);
        $this->assign($list);
        $this -> display();
    }    


    // 搜索出入库记录中出入库单位
    public function search_records_unit()
    {
        $param = I('post.');
        $name = CONTROLLER_NAME;
        $unit_list = D($name)->search_records_unit(1,UID,$param['type'],$param['unit_type'],$param['unit_name']);
        $this->ajaxReturn($unit_list);
       
    }


     //搜索单位
    public function search_unit(){
        $name = CONTROLLER_NAME;
        $storage_ids = D($name) -> get_storage_ids(UID);//当前管理员的仓库ids
        $whereor = array();
        $map = array();
        if(I('chu')){
            $whereor['name'] = array('like', '%'.(string)I('chu').'%');
          
            if(I('order_type') == "1" || I('order_type') == "6"){//1订货单 6入库单
                $return =  M('Suppliers')->where($whereor)->field('id,name')->select();
            }else if(I('order_type') == "2" || I('order_type') == "3" || I('order_type') == "4" || I('order_type') == "5"){// 4调拨单

                if (I('chu_type') == '1') {//个人
                    if ($storage_ids['data'] != 'all') {//不是超级管理员
                        $map['chu_type'] = 1;
                        $map['order_status'] = 5;//退货单
                        $map['ru_id'] = array('in',$storage_ids['data']);
                        $chu_id =  M('Storage')->where($map)->group("chu_id")->field('chu_id')->select();
                        $where['id'] = array('in',$chu_id);
                    }

                    $where['username'] = $whereor['name'];
                    $return =  M('Member')->where($where)->field('id,username as name')->select();
                }else{//仓库
                    if ($storage_ids['data'] != 'all') {//不是超级管理员
                        $whereor['id'] = array('in',$storage_ids['data']);
                    }
                    $return =  M('Storage')->where($whereor)->field('id,name')->select();
                }

            }
           
        }
        if(I('ru')){
            $whereor['name'] = array('like', '%'.(string)I('ru').'%');
            if(I('order_type') == "1" || I('order_type') == "4" || I('order_type') == "5" || I('order_type') == "6"){//1订货单 4调拨单  5退货单  6入库单

                 if (I('ru_type') == '2') {//供货商
                    if ($storage_ids['data'] != 'all') {//不是超级管理员
                        $map['ru_type'] = 2;
                        $map['order_status'] = 5;//退货单
                        $map['chu_id'] = array('in',$storage_ids['data']);
                        $ru_id =  M('Storage')->where($map)->group("ru_id")->field('ru_id')->select();
                        $whereor['id'] = array('in',$ru_id);
                    }
                    $return =  M('Suppliers')->where($whereor)->field('id,name')->select();
                }else{//仓库
                    if ($storage_ids['data'] != 'all') {//不是超级管理员
                        $whereor['id'] = array('in',$storage_ids['data']);
                        // $sql = M('Storage')->_sql();
                    }
                    $return =  M('Storage')->where($whereor)->field('id,name')->select();
                }
            }
        }
    
        $this->ajaxReturn($return);

    }


    //仓库退货单列表
    public function torderlist(){
        $map=I('param.');
        $data = array('未确认','待入库','已入库');
        $this->assign('order_status',$data);
        $chu_type = array(1=>'个人',3=>'仓库');//1个人  2供货商  3仓库
        $ru_type = array(2=>'供货商',3=>'仓库');//1个人  2供货商  3仓库
        $this->assign('chu_type',$chu_type);
        $this->assign('ru_type',$ru_type);
        $list = D('Storage')->orderlist(5,$map);
        if (!$list['error']) {
            $this->error('参数错误');
        }else{
            $this->assign('searchform','torderlist');
            $this->assign('library_info',$list['list']);
            $this->assign($list);
            $this->assign('t',5);
        }

        $this->display("dorderlist");
    }


    //仓库发货单
    public function invoice(){
        $map=I('param.');
        // $data = array('未确认','待入库','已入库','已作废');
        // $this->assign('order_status',$data);
        $list = D('Storage')->orderlist(2,$map);
        if (!$list['error']) {
           $this->error('参数错误');
        }else{ 
            $this->assign('library_info',$list['list']);
            $this->assign('keyword',$list['keyword']);
            // $this->assign('status',$list['status']);
            $this->assign('time_form',$list['time_form']);
            $this->assign('time_to',$list['time_to']);
            $this->assign('t',2);
        }
        $this->display();
    }

    

    //入库显示
    public function addstock(){/*
        $id=I('get.id');//订单id
        if(empty($id)){$this->error(L('PARAM_ERR'));}
        $map = array();
        $map['id'] = $id;
        $list = M('LibraryInfo')->where($map)->field(true)->find();
        $this->assign('list',$list);// 赋值数据集
        $where = array();
        $where['libinfo_id']=$id;
        $goods = M('LibraryGoods')->where($where)->select();
        foreach ($goods as $k => $v) {
            $attr_key = explode('-', $v['goods_attr_sn']);
            if(!empty($attr_key[1])) {
                $attr_name = attr_key2name($attr_key[1],$attr_key[0]);
                $goods[$k]['attr_name'] = $attr_name;
            }else{
                $goods[$k]['attr_name'] = '';
            }
        }

        $name = CONTROLLER_NAME;
        $storage_ids = D($name) -> get_storage_ids(UID);
        if ($storage_ids['status'] == 0) {
            return $storage_ids;
        }
        $flag = '';
        if ($list['order_status'] == 4 && $list['status'] == 1 && $storage_ids['data'] != 'all') {//调拨单
            $check = in_array($list['ru_id'], $storage_ids['data']);
            if ($check) {
                $flag = 1;
            }
        } 
        $display = 0;       
        if (($list['status'] == 1 || $list['status'] == 0)&& $list['ru_type'] != 2 && $list['ru_type'] != 4 ) {//是否显示查看中的入库按钮
            if ($storage_ids['data']=='all' || $list['order_status'] != 4 || $flag == 1) {
                $display = 1;
            }
        }
		$is_fahuo = 0;
		if ($list['order_status'] == 1 && $list['status'] == 0 && $list['shipping_time'] == 0 && $list['ru_type'] == 4 ) {//是否显示查看中的发货按钮
            $is_fahuo = 1;
        }
		if ($list['order_status'] == 1 && $list['status'] == 2 && $list['shipping_time'] == 0 && $list['ru_type'] == 4 ) {//是否显示查看中的发货按钮
            $is_fahuo = 2;
        }
        $this -> assign('display',$display);
        $this -> assign('is_fahuo',$is_fahuo);
        $this->assign('goods',$goods);
        $this->assign('id',$id);
        $this->display();*/
    }  



    //确认入库 生成入库单
    public function confirm_stock(){/*
        $postdata=I('post.');
        $id=intval($postdata['id']);//订单id
        if (empty($id)) {
            $this->error('参数错误！');
        }

        $map = array();
        $map['id'] = $id;
        $order_status = M('LibraryInfo')->where($map)->getField('order_status');
        if ($order_status == 1 || $order_status == 4) {//1订货单 4调拨单
            $reality_num=I('post.num');
            foreach ($reality_num as $k => $v) {
                $num = intval($v);
                if ($num < 0 ) {
                    $this->error('参数错误！');
                }
            }       
            $goods_allmoney = 0; 
            $goods_allnum = 0; 
            $map = array();
            $data = array();
            $map['libinfo_id'] = $id;
            foreach ($reality_num as $k => $v) {
                $map['goods_attr_sn'] = $k;
                $goods = M('LibraryGoods')->field('id,order_num,attr_price')->where($map)->find();
                $goods_allmoney += $goods['attr_price'] * $v;
                $goods_allnum += $v;
                if ($v > $goods['order_num']) {
                    $this->error('实际数量不能大于订单数量');
                }
                if ($goods['order_num'] != $v) {
                    $data['id']=$goods['id'];
                    $data['num']=$v;
                    $data['all_price']=$goods['attr_price'] * $v;
                    $save = M('LibraryGoods')->save($data);
                    if ($save === false) {
                        $this->error('更新订单商品失败');
                    }
                }
            }
            if (empty($goods_allnum)) {
                $this->error('商品总数为0不允许提交！');
            }
            if (!empty($data)) {
                $data = array();
                $data['id'] = $id;
                $data['goods_allmoney'] = $goods_allmoney;
                $data['goods_allnum'] = $goods_allnum;
                $save = M('LibraryInfo')->save($data);
                if ($save === false) {
                    $this->error('更新订单失败');
                }
            }
        }

        $add_stock = D('Storage')->all_add_stock($postdata['id'],$postdata['chuli_temp']);
        $url = U(CONTROLLER_NAME . '/orderlist');
        if($add_stock['status'] == 0){
            $this->error($add_stock['msg'], $url);exit;
        }            

        if ($postdata['order_status'] == 4) {
            $url = U(CONTROLLER_NAME . '/dorderlist');
        }
        $this->success($add_stock['msg'], $url);*/
    }

        //导出
    public function export()
    {
        $id = $_REQUEST['id'];
        if (!$id) $this->error(L('PARAM_ERR'));

        $map = array();
        $param=I('param.');
        
        if($param['supplier']){
            $map['name'] = array('like', '%'.(string)$param['supplier'].'%');
            $id_ar = M('Suppliers')->where($map)->getField('id',true);
            $ids = implode(',', $id_ar);
        }
        
        if(!empty($param['keyword'])){
            $field_arr=explode(',',$param['keyword_fields']);
            $arr = implode('|',$field_arr);
            $map[$arr] = array('like', '%'.$param['keyword'].'%');
            $keyword = $param['keyword'];
        }

        if(!empty($ids) && !empty($param['supplier'])){
            $map['supplier_id']=array('in',$ids);
        }
        if(!empty($param['supplier']) && empty($ids)){
            $map['supplier_id']=array('eq',-5);
        }
        
        $data = M('storage')->Field('name,allstock')->where('id='.$id)->find();
        
        $map['storage_id'] = $id;
        $price = M('StorageStock')->Field('stock,buy_price')->where($map)->select();
        foreach ($price as $key => $value) {
            $data['price'] += $value['stock'] * $value['buy_price'];
        }
        $field = 'id,goods_id,goods_name,goods_sn,goods_attr_sn,stock,buy_price,in_time,supplier_id';
        $list = M('StorageStock')->field($field)->where($map)->order('stock')->select();

        foreach ($list as $k => $v) {
            $attr_key = explode('-', $v['goods_attr_sn']);
            if(!empty($attr_key[1])) {
                $attr_name = attr_key2name($attr_key[1],$attr_key[0]);
                $list[$k]['goods_attr_sn'] = $attr_name;
            }else{
                $list[$k]['goods_attr_sn'] = '---';
            }
        }
        $title = array('序号', '商品编号', '商品名称','商品属性', '供货商', '库存', '单价', '最近入库时间');
        $data = array();
        foreach ($list as $k => $v) {
            $data[$k][] = $v['id'];
            $data[$k][] = $v['goods_sn'];
            $data[$k][] = $v['goods_name'];
            $data[$k][] = $v['goods_attr_sn'];
            $data[$k][] = idtoname($v['supplier_id'], 'Suppliers');
            $data[$k][] = $v['stock'];
            $data[$k][] = $v['buy_price'];
            $data[$k][] = time_format($v['in_time']);

        }
        export_xls($title, $data, 'utf8');
        unset($title, $data);
        exit;
    }
    //打印 订单
    public function order_print(){
        /*$id = I('get.id');//订单id
        $this->assign('id',$id);
        $order_info = M('library_info')->where('id='.$id)->field(true)->find();
		$template = '';
        switch ( $order_info['order_status'] ) {
            case  1 :
                $order_status = '订货单';
				$template = 'CARGO_LIST';
                break;                    
            case  2 :
                $order_status = '发货单';
				$template = 'CARGO_LIST';
                break;
            case  3 :
                $order_status = '配货单';
				$template = 'CARGO_LIST';
                break;
            case  4 :
                $order_status = '调拨单';
				$template = 'CARGO_LIST';
                break;
            case  5 :
                $order_status = '退货单';
				$template = 'CARGO_LIST';
                break;                    
            case  6 :
                $order_status = '入库单';
				$template = 'CARGO_LIST';
                break;
            default:
                $order_status = '';
        }
        $order_info['order_status'] = $order_status;
        $chu_id = $order_info['chu_id'];
        if ($order_info['chu_type'] == 2) {//供货商
			if($chu_id == 0){
				$order_info['chu_id'] = '供货商';
			}else{
				$order_info['chu_id'] = idtoname($chu_id,'Suppliers');
			}
        }else{
            $order_info['chu_id'] = idtoname($chu_id,'Storage');
        }
        $ru_id = $order_info['ru_id'];
        if ($order_info['ru_type'] == 2) {//供货商
            $order_info['ru_id'] = idtoname($ru_id,'Suppliers');
        }elseif ($order_info['ru_type'] == 4) {//仓库
            $order_info['ru_id'] = idtoname($ru_id,'Shops');
        }else{
            $order_info['ru_id'] = idtoname($ru_id,'Storage');
        }
        $order_info['goods_allmoney'] = format_price($order_info['goods_allmoney']);
        $order_info['addtime'] = time_format($order_info['addtime']);
        $where = array();
        $where['libinfo_id']=$id;
        $goods = M('library_goods')->where($where)->select();
        foreach ($goods as $k => $v) {
            $attr_key = explode('-', $v['goods_attr_sn']);
            if(!empty($attr_key[1])) {
                $attr_name = attr_key2name($attr_key[1],$attr_key[0]);
                $goods[$k]['goods_name'] .= $attr_name;
            }
        }
		$admin = idtoname(UID,'admin','username');
		if($order_status == 1 && $order_info['ru_type'] == 4){
			$admin = idtoname($order_info['ru_id'],'Shops');
		}
        $print_time = date('Y-m-d H:i:s',NOW_TIME);
        $this->assign('admin',$admin);
        $this->assign('print_time',$print_time);
        $this->assign('goods',$goods);
        $this->assign($order_info);

		if($template){
			$map = array();
			$map['code'] = $template;       
			$content = M('PrintTemplate')->where($map)->getField('content');
			$content1 = $this->fetch('',htmlspecialchars_decode($content));
			$this->assign('info',$content1);
		}
        
        $this->display();*/
    }
    public function refund_goods(){/*
        $status=array('1'=>'待收货','2'=>'已收货');
        $map=array();
        $param=I('param.');
        if(!empty($param['chutype'])){
            $map['chu_type']=$param['chutype'];
        }
        $this->assign($param);
        $map['order_status']=5;
        $chu_type=array(1=>'会员',4=>'仓库');
        $this->assign('chu_type',$chu_type);
        $list=$this->lists("LibraryInfo",$map);
        $this->assign('list',$list);
        $this->assign('status',$status);
        $this->display();*/
    }
    public function refund_view(){
       /* $id=I('id');
        $map=array();
        $map['id']=$id;
        $info=M("LibraryInfo")->where($map)->field(true)->find();
        $this->assign($info);
        $g_map=array();
        $g_map['libinfo_id']=$id;
        $goods_info=M("LibraryGoods")->where($g_map)->field(true)->select();
        foreach($goods_info as $key=>$val){
            if($val['goods_attr_sn']){
                $val['goods_attr_sn']=unserialize($val['goods_attr_sn']);
                $goods_info[$key]['attr_name']=$val['goods_attr_sn']['name'];
            }
        }
        $this->assign('goods_info',$goods_info);
        $this->display();*/
    }

    /**
     * 仓库收货
     */
    public function refund_receipt(){/*
        $return=array();
        $libinfo_id=I('libinfo_id');
        $post_data=I('post');
        if(empty($libinfo_id)){
            $return['status']=0;
            $return['msg']='参数错误';
            $this->ajaxReturn($return);
        }
        $number=I('num');
        foreach($number as $key=>$val){
            $g_map=array();
            $g_map['libinfo_id']=$libinfo_id;
            $g_map['goods_id']=$key;
            $r_number=M("LibraryGoods")->where($g_map)->getField('order_num');
            if($val>$r_number){
                $return['status']=0;
                $return['msg']='实际数量不能大于订单商品数量';
                $this->ajaxReturn($return);
            }
        }
        $map=array();
        $map['id']=$libinfo_id;
        $data=array();
        $data['status']=2;
        $data['updatetime']=NOW_TIME;
        $data['chuli_temp']=$post_data['temp'];
        $info=M("LibraryInfo")->where($map)->save($data);
        if($info){
            foreach($number as $key=>$val){
                $g_map=array();
                $g_map['libinfo_id']=$libinfo_id;
                $g_map['goods_id']=$key;
                $r_number=M("LibraryGoods")->where($g_map)->getField('order_num');
                $g_data['num']=$val;
               $res=M("LibraryGoods")->where($g_map)->save($g_data);
            }
            //增加仓库商品库存
            $goods_map=array();
            $goods_map['libinfo_id']=$libinfo_id;
            $goods_info=M("LibraryGoods")->where($goods_map)->field('goods_id,num,goods_attr_sn')->select();
            $add_goods=array();
            foreach($goods_info as $key=>$val){
                $add_goods['goods_info'][$key]['goods_id']=$val['goods_id'];
                $add_goods['goods_info'][$key]['goods_number']=$val['num'];
                if($val['goods_attr_sn']){
                    $attr=unserialize($val['goods_attr_sn']);
                }
                $add_goods['goods_info'][$key]['goods_attr']=$attr[$key];
            }
            $s_map=array();
            $s_map['id']=$libinfo_id;
            $store=M("LibraryInfo")->where($s_map)->getField('ru_id');
            $add_goods['store_id']=$store;
            $add_goods['is_add']=1;
            $res=D("Common/OrderInfo")->reduce_store($add_goods);
            if($res['status']==0){
                $return['status']=0;
                $return['msg']=$res['msg'];
                $this->ajaxReturn($return);
            }
            $return['status']=1;
            $return['msg']='收获成功！';
        }else{
            $return['status']=0;
            $return['msg']='收获失败！';
        }
        $this->ajaxReturn($return);*/
    }
    /* 配货单处理 */
    public function pmanage(){
        $order_id=I('post.order_id');
        $content=I('post.content');
        $order=I('post.order');
        $orderss=idtoname($order_id,'OrderInfo','*');
        if(empty($order_id))$this->error('参数不正确');
        $mod=M('OrderInfo');
        if(I('post.confirm')){$log='确认';$data['confirm_time']=NOW_TIME;$data['status']='2';}
        if(I('post.pay')){
            $log='付款';
            $data['pay_time']=NOW_TIME;
            $data['pay_status']='3';
            $data['status']='2';
            //供货商待结算金额
            $shop_map['id']=$orderss['shop_id'];
            // 获取结算价
            $price_info=get_balance_suprice($order_id);
            $all_supplymoney=$price_info['price'];
            $old_total_revenues=idtoname($shop_map['id'],'Suppliers','total_revenues');
            $old_unbalance=idtoname($shop_map['id'],'Suppliers','unbalance');
            $order_info['id']=$order_id;
            $shop_where['id']=$shop_map['id'];
            $con_data['total_revenues']=$old_total_revenues+$all_supplymoney;
            $con_data['unbalance']=$old_unbalance+$all_supplymoney;
            $up_shop=M('Suppliers')->where($shop_where)->save($con_data);
            supplier_balance_log($shop_map['id'], $price_info['price'], 2,3,$orderss['order_sn'] . '订单付款,未结算总额增加', $orderss);
            supplier_balance_log($shop_map['id'], $price_info['price'], 5,3,$orderss['order_sn'] . '订单付款,销售总额增加', $orderss);

        }
        if(I('post.unpay')){$log='设为未付款';$data['pay_time']=NOW_TIME;$data['pay_status']='1';}
        if(I('post.prepare')){$log='配货';$data['shipping_status']='2';}
        if(I('post.ship')){$log='发货';$data['shipping_time']=NOW_TIME;$data['shipping_status']='3';}
        if(I('post.unship')){$log='未发货';$data['shipping_status']='1';}
        if(I('post.receive')){$log='已收货';$data['status']='3';}
        if(I('post.return')){$log='退货';$data['status']='6';}
        if(I('post.cancel')){$log='取消';$data['status']='4';}
        if(I('post.invalid')){$log='无效';$data['status']='5';}
        if(I('post.after_service') && I('post.content')){$log='售后';}
        $user_info = M('OrderInfo')->where('id='.$order_id)->field('consignee,email')->find();
        //print_r($user_info);exit;
        if($log == '发货'){
            $member=M('OrderInfo')->where('id='.$order_id)->field('uid,mobile')->find();
            if(!empty($member['uid'])){
                $moblie=M('Shops')->where('id='.$member['uid'])->field('phone')->find();
                $phone=$moblie['phone'];
            }else{
                $phone=$member['mobile'];
            }
            $data['to']=$phone;
            $result=sendbytheme($data,'SEND_GOODS');
        }
        if($log == '已收货'){
            $postdata['order_id']=$order_id;
            $postdata['admin_id']=MID;
            $postdata['type']=='Admin';
            $postdata['og_id']=I('post.og_id');
            $postdata['number']=I('post.number');
            $return=D('Common/OrderInfo')->pconfirm_order($postdata);
            if($return['status']){
                // $this->success($return['msg']);exit;
            }else{
                $this->error($return['msg']);exit;
            }
        }
        if($log=="退货"){
            $order_info=M("OrderInfo")->where('id='.$order_id)->field(true)->find();
            $money=$order_info['order_amount']-$order_info['delivery_fee'];
            $info=M("OrderGoods")->where('order_id='.$order_id)->field('id,goods_id,goods_number')->select();
            foreach($info as $k=>$v){
                $goods_info[$k]['goods_id']=$v['goods_id'];
                $goods_info[$k]['number']=$v['goods_number'];
                //改变商品状态
                $g_map['id']=$v['id'];
                $g_map['status']=1;
                $save['status']=3;
                $res=M('OrderGoods')->where($g_map)->save($save);
                $org_id[]=$v['id'];//要生成退货单 org_id
            }

            //订单改为退货中
            $od_save['status']=8;
            M('OrderInfo')->where('id='.$order_id)->save($od_save);

            $str_orgids=implode(',',$org_id);
            //添加退货单
            $add['org_id']=$str_orgids;
            $add['uid']=$order_info['uid'];
            $add['shop_id']=$order_info['shop_id'];
            $add['order_id']=$order_id;
            $add['goods_info']=serialize($goods_info);
            $add['reason']=$content;
            $add['money']=$money;
            $add['add_time']=NOW_TIME;
            $add['type']=2;
            $res=M('ReturnGoods')->add($add);

//            添加仓库退货单
            $store_data=array();
            $store_data['user_id']=$order_info['uid'];
            $store_data['store_id']=$order_info['storage_id'];
            $store_data['order_sn']=$order_info['order_sn'];
            $store_data['order_sum']=count($goods_info);
            $store_data['order_type']=10;
            $goods_allmoney=0;
            foreach($goods_info as $k=>$val){
                $order_map=array();
                $order_map['goods_id']=$val['goods_id'];
                $order_map['order_id']=$order_id;
                $goods_orderprice=M("OrderGoods")->where($order_map)->field('goods_price,goods_number')->find();
                $goods_allmoney+=$goods_orderprice['goods_number']*$goods_orderprice['goods_price'];

            }
            $store_data['goods_allmoney']=$goods_allmoney;
            $resc=D('Common/OrderInfo')->add_stock_refundgoods($store_data);
            if($resc['status']==0){
                $return['msg']='仓库添加退货单失败';
            }


            //生成退款单
            $refund_data['reason']=I('post.content');
            $refund_data['type']=0;
            $refund_data['order_goods']=$str_orgids;
            $result=D("Common/OrderInfo")->add_refund($money,$order_id,$refund_data,1);
            if($result){
                action_log('shop_apply_return', 'Shop', $res, $order_info['uid']);
                //$this->success("退货申请提交成功",U('OrderInfo/view',array('id'=>$order_id)));
            }//日志,$res退货单ID


        }
        if($log){
            if($data)M('OrderInfo')->where('id='.$order_id)->save($data);
            $log=$log.' '.I('post.content');
            action_log('manage_order', 'OrderInfo',$order_id,UID,$log);
            $this->success(L('DO_OK'),U('OrderInfo/pview',array('id'=>$order_id)));
        }else{
            $this->error('参数不正确!');
        }
    }
	public function zc_orderinfo(){/*
		$postdata = I('post.');
		$order_sn = $postdata['order_sn'];
		$status = $postdata['status'];
		$storage_ids = D('Storage') -> get_storage_ids(UID);//当前管理员的仓库ids
		if($storage_ids['status']==1&&$storage_ids['data']!='all' ){
            if($postdata['storage']){
                if(!in_array($postdata['storage'],$storage_ids['data']))$storage_ids['data']=0;
                else $storage_ids['data']=$postdata['storage'];
            }
            $map['chu_id']=is_array($storage_ids['data']) || strpos($storage_ids['data'],',')?array('in',$storage_ids['data']):$storage_ids['data'];
        }elseif($postdata['storage']){
            $map['chu_id']=$postdata['storage'];
        }
		$map['chu_type'] = 3;
		$map['ru_type'] = 4;
		$map['is_delete'] = 0;
		if($order_sn){
			$map['order_sn'] = array('like','%'.$order_sn.'%');
		}
        if($postdata['shopid']){$map['ru_id'] = $postdata['shopid'];}
		if($status == 1){
			$map['status'] = 0;
		}elseif($status == 2){
			$map['status'] = array('egt',1);
		}
		$list = $this->lists('LibraryInfo',$map);
        $this->storage_list($storage_ids);
        $this->assign('list',$list);
        $this->assign($postdata);
		$this->display();*/
	}
    private function storage_list($storage_ids=''){
        if($storage_ids){
        $map=array();
        if($storage_ids['status']==1&&$storage_ids['data']!='all' ){
            $map['id']=array('in',$storage_ids['data']);
        }
        $storage_list=D('Storage')->where($map)->field('id,name')->cache(true)->select();        
        $this->assign('storage_list',format_array2select($storage_list));
        }
        $map=array();
        $map['shop_type']=1;
        $map['status']=1;
        $zhiyinglist=M('Shops')->where($map)->field('id,name')->cache(true)->select();       
        $this->assign('shops_list',format_array2select($zhiyinglist));
    }
	public function zs_orderinfo(){/*
		$postdata = I('post.');
        
        $storage_ids = D('Storage') -> get_storage_ids(UID);//当前管理员的仓库ids
		$order_sn = $postdata['order_sn'];
		$status = $postdata['status'];
        $map=array();
		$map['chu_type'] = 2;        
        $map['chu_id']=array('gt',0);
       
        if($postdata['supplier_id']){
            $map['chu_id']=$postdata['supplier_id'];
        }        
		$map['ru_type'] = 4;
		$map['is_delete'] = 0;
		if($order_sn){
			$map['order_sn'] = array('like','%'.$order_sn.'%');
		}
		if($status == 1){
			$map['status'] = 0;
		}elseif($status == 2){
			$map['status'] = array('egt',1);
		}
        if($postdata['shopid']){$map['ru_id'] = $postdata['shopid'];}
		$list = $this->lists('LibraryInfo',$map);
        $this->assign('list',$list);
        $map=array();
        $map['chu_type'] = 2;        
        $map['chu_id']=array('gt',0);
        $map['ru_type'] = 4;
		$map['is_delete'] = 0;
        $allghs=M('LibraryInfo')->where($map)->cache(true)->group('chu_id')->getField('chu_id',true);
        if($allghs){
            $map=array();
            $map['id']=array('in',$allghs);
			$map['status'] = 1;
            $gonghuo=M('Suppliers')->where($map)->field('id,name')->cache(true)->select();
            $this->assign('gonghuo',format_array2select($gonghuo));
        }
       
        $this->storage_list();
        $this->assign($postdata);
		$this->display();*/
	}
	//仓库给直营店前台订货的发货
	public function sub_ship(){/*
		$return['status'] = 0;
		$return['msg'] = '发货失败！';
		$id = I('param.id');
		if($id){
			$map['id'] = $id;
			$libinfo_status = M('LibraryInfo')->where($map)->getField('status');
			if($libinfo_status == 0){
				$libinfo_save['status'] = 1;
				$libinfo_save['shipping_time'] = NOW_TIME;
				
				$res = M('LibraryInfo')->where($map)->save($libinfo_save);
				if($res){
					$return['status'] = 1;
					$return['msg'] = '发货成功！';
				}
			}else{
				$return['msg'] = '该订单已发货！';
			}
		}else{
			$return['msg'] = '参数错误！';
		}
		$this->ajaxReturn($return);*/
	}
	public function sub_finish(){/*
		$return['status'] = 0;
		$return['msg'] = '发货失败！';
		$id = I('param.id');
		if($id){
			$map['id'] = $id;
			$libinfo_status = M('LibraryInfo')->where($map)->getField('status');
			if($libinfo_status == 2){
				$libinfo_save['shipping_time'] = NOW_TIME;
				
				$res = M('LibraryInfo')->where($map)->save($libinfo_save);
				if($res){
					$return['status'] = 1;
					$return['msg'] = '发货成功！';
				}
			}else{
				$return['msg'] = '该订单已发货！';
			}
		}else{
			$return['msg'] = '参数错误！';
		}
		$this->ajaxReturn($return);*/
	}
	//删除直营店前台订货单
    public function libinfo_delete(){
        /*$id=I('id');
        if(empty($id)){
            $this->error("参数错误");
        }
        $where=array();
        if(isset($id)&&is_array($id)){
            $where = 'id in('.implode(',',$id).')';
        }else{
              $where = 'id='.$id;
        }
		$delete_save['is_delete'] = 1;
        $info = M('LibraryInfo')->where($where)->save($delete_save);
		$type = M('LibraryInfo')->where($where)->field('order_status,chu_type')->find();
		if($type['order_status'] == 1 && $type['chu_type'] == 3){
			$url = U('Admin/Storage/zc_orderinfo');
		}elseif($type['order_status'] == 1 && $type['chu_type'] == 2){
			$url = U('Admin/Storage/zs_orderinfo');
		}
        if($info!==false) {
            $this->success(L('DELETE_SUCCESS'), $url);
        }else{
            $this->error(L('DELETE_FAILED'), $url);
        }
        $this->id=$id;*/
    }
}
?>