<?php
/**
 * 微信小程序支付模块
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaoq <570035208@qq.com>
 */

namespace Wxsmall\Model;
use Think\Model;
class SelfgoModel extends Model{
    protected $tableName = 'Goods';
    /**
     * 获取商品列表页面
     * @param array $param 筛选参数
     * @return array 返回信息
     */
    public function index($param){
        $return = array('status'=>3,'msg'=>'获取信息失败');
        $site_id=C("appid");
        $map = array();
        $map['id'] = array('gt', 0);
        $map['status'] = 1;
        $cate = M('PurchaseCategory')->where($map)->field('id,name')->order('sort asc')->select();
        if($param['catid']>0 && $param['keyword']){unset($param['catid']);}
        if(isset($param['catid'])&&$param['catid']>0){unset($param['keyword']);}
       if(empty($param['catid'])){
           $cateid=$cate[0]['id'];
           $param['catid']=$cateid;
           $param['childcatid']=0;
       }

        //1025新加
        $coupons = get_online_bonus($param['total_money'],$param['uid']);
        if($coupons && $coupons['list']) {
            foreach ($coupons['list'] as $key => $val) {
                if($val['type']==1){
                    $coupons['list'][$key]['start_time']=time_format($val['begin_timestamp']);
                    $coupons['list'][$key]['end_time']='至'.time_format($val['end_timestamp']);
                }else{
                    $coupons['list'][$key]['start_time']='领取后'.$val['fixed_term'].'天后生效';
                    $list['info'][$key]['end_time']=',有效期'.$val['fixed_begin_term'].'天';
                }
                if($val['rank_id']=='CASH'){
                    $coupons['list'][$key]['money']=intval($val['reduce_cost']);
                }elseif($val['rank_id']=='DISCOUNT'){
                    $money=(100-$val['discount'])/10;
                    $coupons['list'][$key]['money']=$val['discount'].'折';
                }
                if($val['is_show']==0){
                    $coupons['list'][$key]['shop_name']='全部门店可用';
                }else{
                    $map=array();
                    $map=array('in',$val['is_show']);
                    $shop_name=M("Shops")->where($map)->getField('name');
                    $coupons['list'][$key]['shop_name']=implode(',',$shop_name);
                }
                $coupons['list'][$key]['least_cost']=intval($val['least_cost']);
                $color=D("Wxsmall/Coupons")->get_cpupon_color();
                $coupons['list'][$key]['color']=$color[$val['color']];
            }
        }
        $return['data']['coupons']=$coupons;
        //end
        $data = D('Common/Takeout')->get_goods_list($param,0);
        $return['data']['goods_list'] = array();
        $return['data']['goods_list'] = $this->format_data($data['goods_list']['list'],2,$cateid,$param);


        // $return['data']['init_list'] = $this->get_cart($param);//默认购物车中已加入的商品
        // 自助购缓存中存在的商品
        $return['data']['init_list'] = $this->get_catchcart($param);

        $return['data']['brand_list']= brand_list(0);//默认购物车中已加入的商品
        $return['data']['catid']= $cateid;//默认分类
        $return['data']['totalpage']= $data['goods_list']['totalPages'];//商品总页数
        $return['status'] = 1;
        return $return;
    }

    //获取订单详情1025
    public function get_orderinfo($order_id,$erw=''){
        if(empty($order_id)) return false;
        $return=array('status'=>1);
        $where=$map=array();
        $where['id'] = $order_id;
        $order_info = M('OrderInfo')->where($where)->field(true)->find();
        if($order_info['shop_id']>0) $order_info['shop_name'] =  idtoname($order_info['shop_id'],'Shops','name','id',false);
        $order_info['pay_time'] = time_format($order_info['pay_time']);

        //是否需要生成二维码
        if($erw){
            $url = 'http://'.C('appid').'.'.BASE_DOMAIN.U('Home/qrcode/index',array('data'=>$order_info['order_sn']));

            // $erwe = phpgrcode(urlencode($url),'','4','img_'.$order_info['order_sn']);
            $erwe = format_url($url);
            
            $order_info['ordersn_erwe'] = $erwe;
        }
        
        $return['data']['order_info'] = $order_info;

        
        $map['order_id']=$order_id;
        $order_goods = M('OrderGoods')->where($map)->field(true)->select();
        $heji = 0;

        
        foreach($order_goods as $key=>$val){
            $order_goods[$key]['img'] = idtoname($val['goods_id'],'Goods','img','id',false);
            $order_goods[$key]['goods_number'] = intval($val['goods_number']);
            $heji += intval($val['goods_number']);

        }

        $return['data']['count_num'] = $heji;
        $return['data']['order_goods'] = $order_goods;

        $end_time = (C('WEB_SELFGO_TIME')*60)+$order_info['addtime'];
        $return['data']['overtime'] = $end_time;

        $osave=array();
        $osave['id'] = $order_id;
        $osave['type'] = 25;
        $osave['shipping_status'] = 4;
        $osave['status'] = 3;
        $is_true = M('OrderInfo')->where($map)->count();
        $return['data']['is_true'] = $is_true;


        return $return;
    }
    //end
    public function format_data($list = array(),$type,$cateid=0,$param=array()){
        $result = array();
        $is_first=$param['is_first'];
        if($list){
            foreach($list as $k=>$v){
                if($type==1){
                    $result[$k]['id'] = $v['id'];
                    $result[$k]['name'] = $v['name'];
                }elseif($type==2){
                   // if($cateid>0&&$cateid!=$v['cat_id'])continue;
                    $result[$k]['id'] = $v['id'];
                    $result[$k]['cat_id'] = $v['cat_id'];
                    $result[$k]['name'] = $v['goods_name'];
                    $result[$k]['market_price'] = $v['market_price'];
                    if($is_first>1){
                        $price_info=D('Common/Takeout')->get_min_price($param['shop_id'],$v['id']);
                        $result[$k]['shop_price'] = $price_info['goods_price'];
                        $result[$k]['sprice'] = format_price($price_info['goods_price']);
                    }else{
                        $result[$k]['shop_price'] = $v['shop_price'];
                        $result[$k]['sprice'] = format_price($v['shop_price']);
                    }
                    //$price_info=D('Common/Takeout')->get_min_price($param['shop_id'],$v['id']);

                    //$result[$k]['shop_price'] = $price_info['goods_price'];
                    $result[$k]['mprice'] = format_price($v['market_price']);

                    //$result[$k]['sprice'] = format_price($price_info['goods_price']);
                    $result[$k]['img'] = thumb($v['img']);
                    $result[$k]['format_spec'] = D("Common/GoodsAttr")->get_shop_attr($v['id']);
                    $v['format_spec']=$result[$k]['format_spec'];
                    //$result[$k]['format_spec'] = $v['format_spec'];
                    $result[$k]['stock'] = $this->format_stock($param['shop_id'],$v);//根据当前定位的门店信息取出对门店商品库存

                }
            }
        }
        return $result;
    }
    public function format_stock($shop_id=0,$data=array()){
        $return = array();
        $map = array();
        $map['goods_id'] = $data['id'];
        $map['shop_id'] = $shop_id;
        $map['status'] = 1;
        if($data['format_spec']['newarr']){//此商品有规格属性
            if(!empty($shop_id)){
                $specarr = json_decode($data['format_spec']['combination']);
                $specstrarr = array();
                foreach($specarr as $v){
                    if(empty($v))continue;
                    sort($v);$specstrarr[] = implode('_',$v);
                }
                if($specstrarr){
                    $format = array();
                    foreach($specstrarr as $v){
                        $format[$v] = 0;//初始化商品规格库存
                    }
                    $map['goods_stock'] = array('IN',$specstrarr);
                    $result = M('ShopsGoodsStock')->where($map)->field('goods_stock,goods_number')->select(); 
                    if($result){
                        foreach($result as $k=>$v){
                            $format[$v['goods_stock']] = $v['goods_number'];
                        }
                    }
                    $return['goods_stock_number'] = $format;
                }
            }else{
                $return['goods_stock_number'] = 0;
            }
        }else{
            if($data['sale_type']==1){//组合商品
                $goods_number = $this->get_group_goods_stock($data['id'],$shop_id);
                $return['goods_number'] = $goods_number?$goods_number:0;
            }else{
                $format = M('ShopsGoodsStock')->where($map)->getField('goods_number');
                $return['goods_number'] = $format?$format:0;
            }
        }
        return $return;
    }
    //获取组合商品的库存
    public function get_group_goods_stock($goodsid,$shop_id){
        $map=array();
        $map['goodsid']=$goodsid;
        $list = M('GroupGoods')->where($map)->field('linkid,attr_key,ratio')->select();
        foreach($list as $k=>$v){
            $map=array();
            $map['goods_id'] = $v['linkid'];
            $map['shop_id'] = $shop_id;
            $map['status'] = 1;
            $goods_number=M('ShopsGoodsStock')->where($map)->getField('goods_number');
            if($goods_number==false){
                $goodsnum[]=0;
            }else{
                $goods_number=floatval($goods_number);
                $goodsnum[]=intval($goods_number/$v['ratio']);
            }
        }
        return min($goodsnum);
    }
    public function get_other($code){
        switch($code){
            case 1:
                $result = array(
                    array('order'=>'','name'=>'默认排序'),
                    array('order'=>'sell_count','name'=>'销量排序'),
                    array('order'=>'money_desc','name'=>'价格由高到低'),
                    array('order'=>'money_asc','name'=>'价格由低到高')
                );
                break;
            case 2:
                $result = array(
                    array('screen_order'=>'1','name'=>'热卖'),
                    array('screen_order'=>'2','name'=>'新品'),
                    array('screen_order'=>'3','name'=>'限时促销'),
                    array('screen_order'=>'4','name'=>'优惠活动'),
                    array('screen_order'=>'5','name'=>'会员专享')
                );
                break;
            default:
                $result = array();
                break;
        }
        return $result;
    }

    /**
    *获取缓存的商品数据
    *@param array $param 用户信息
     * @return array 返回信息
    */
   
    public function get_catchcart($param){
        $return = $map = array();
        // if($param['uid']&&$param['shop_id']){
           
            $params = json_decode(htmlspecialchars_decode($param['catch_goods']),true);
            $result = $params;
            if($result){
                foreach($result as $k=>$v){


                    if(str_exists($k,'-')){
                        $goods_ids = explode('-',$k);
                        $goods_id = $goods_ids[0];
                        if(empty($v['goods_attr'])){
                            $key = $goods_id;
                        }else{

                            $attrs = json_decode(htmlspecialchars_decode($v['goods_attr']),true);

                            $attr_id = idtoname($attrs['key'],'GoodsAttr','attr_id','id',false);

                           
                            // $attr_keys = $attrs['key'].'_'.idtoname($attr_id,'GoodsAttribute','name','id',false).':'.$attrs['name'];

                            $list =array(
                                    'key'=>$attrs['key'],
                                    'name'=>idtoname($attr_id,'GoodsAttribute','name','id',false).':'.$attrs['name'],
                            );
                            $key = $list['key'];
                            $return[$key]['spec_format'] = $list;
                        }
                    $return[$key]['id'] = $goods_id;
                    $return[$key]['num'] = $v['num'];
                    $return[$key]['price'] = $v['price'];
                    }
                }
            }
        // }
        return $return;
    }
    
    /**
     * 获取购物车已经存在的商品
     * @param array $param 用户信息
     * @return array 返回信息
     */
    public function get_cart($param){
        $return = $map = array();
        if($param['uid']&&$param['shop_id']){
            $map['user_id'] = $param['uid'];
            $map['shop_id'] = $param['shop_id'];
            $map['is_valid'] = 1;
            $result = M('Cart')->where($map)->field(true)->select();
            if($result){
                foreach($result as $k=>$v){
                    if(empty($v['goods_attr'])){
                        $key = $v['goods_id'];
                    }else{
                        $list = unserialize($v['goods_attr']);
                        $key = $list['key'];
                        $return[$key]['spec_format'] = $list;
                    }
                    $return[$key]['id'] = $v['goods_id'];
                    $return[$key]['num'] = $v['goods_num'];
                    $return[$key]['price'] = $v['shop_price'];
                }
            }
        }
        return $return;
	}
    public function cont($param){
        $return=array('status'=>1);
        if(empty($param['id'])){
            $return['status']=3;
            $return['msg']='参数错误';
            return $return;
        }
        if($param['shop_id']){
            $map=array();
            $map['id']=$param['shop_id'];
            $shop_name=M("Shops")->where($map)->getField('name');
        }else{
            $shop_name='暂无配送门店';
        }
        $goods_id=$param['id'];
        $type=$param['type'];
        $goods_info= D("Common/Goods")->get_goods_item($goods_id);
        if($goods_info['status']==0){
            $return['status']=3;
            $return['msg']=$goods_info['msg'];
            return $return;
        }
        //商品相册
        $where['goods_id']=$goods_id;
        $goods_imgs = M("GoodsGallery")->where($where)->select();
        if (empty($goods_imgs)) $goods_imgs[0]['goods_img'] = $goods_info['data']['img'];
        foreach($goods_imgs as $key=>$val){
            $goods_imgs[$key]['goods_img']=$val['goods_img'];
        }
        //获取商品属性和规格
        $data = D("Common/GoodsAttr")->get_shop_attr($goods_id);
        //评论列表
        $commlist = D('Mobile/Dp')->get_goods($goods_id);
        if($commlist['dp_list']){
            foreach($commlist['dp_list'] as $key=>$val){
                $commlist['dp_list'][$key]['addtime']=time_format($val['addtime']);
                $commlist['dp_list'][$key]['img']=thumb($val['img']);
                if(empty($val['username'])){
                    $map=array();
                    $map['id']=$val['uid'];
                    $member_info=M("Member")->where($map)->field('nickname,mobile')->find();
                    if($member_info['nickname']){
                        $commlist['dp_list'][$key]['username']=$member_info['nickname'];
                    }else if($member_info['mobile']){
                        $commlist['dp_list'][$key]['username']=$member_info['mobile'];
                    }else{
                        $commlist['dp_list'][$key]['username']='';
                    }
                }
            }
        }
        $dp_count=count($commlist['dp_id']);
        //商品最小价格
        $price_info=D('Common/Takeout')->get_min_price($param['shop_id'],$goods_id);
        $goods_info['stock'] = $this->format_stock($param['shop_id'],$param);//根据当前定位的门店信息取出对门店商品库存
        $goods_info['data']['min_price_format']=format_price($price_info['goods_price']);
        $goods_info['data']['min_price']=$price_info['goods_price'];
        $goods_info['data']['goods_imgs']=$goods_imgs;
        //判断是否收藏
        $where = $map = array();
        //是否收藏
        $map['uid'] = $param['uid'];
        $map['goods_id'] = $goods_id;
        $map['type'] = $type;
        if ($type == 1) {
            $where['goods_id'] = $goods_id;
            $map['integral_id'] = M('GoodsIntegral')->where($where)->getField('id');
        }
        $is_collection = M('GoodsCollect')->where($map)->count();
        //获取活动
        //限时促销
        if($goods_info['data']['promote_id']>0 && NOW_TIME>=$goods_info['data']['promote_start_time'] && NOW_TIME<$goods_info['data']['promote_end_time']){
            $map=array();
            $map['id']=$goods_info['data']['promote_id'];
            $promat_info=M("PromotAct")->where($map)->field(true)->find();
            if($promat_info['shop_id']==0){
                $return['promat_info']=$promat_info;
            }else{
                 $shop_ids=array_filter(explode(',',$promat_info['shop_id']));
                if(in_array($param['shop_id'],$shop_ids)){
                    $return['promat_info']=$promat_info;
                }
            }
        }
        //优惠活动
        $active_arr=array();
        $activelist=D("Common/Promot")->goods_to_promot($goods_id,0,3);
        if($activelist){
            foreach($activelist['list'] as $key=>$val){
                if($val['style']!=5){
                    $active_arr = $val;
                }

            }
        }
        //购物车数量
        $map=array();
        $map['user_id']=$param['uid'];
        $cart_num_list=M("Cart")->where($map)->field('goods_num')->select();
        $cart_num = 0;
        foreach($cart_num_list as $k=>$v){
            $cart_num += $v['goods_num'];
        }
        $goods_info['data']['is_collection']=$is_collection;
        $return['goods_info']=$goods_info['data'];
        $return['goods_info']['shop_name']=$shop_name;
        $return['goods_attrs']=$data;
        $return['commlist']=$commlist;
        $return['dp_count']=$dp_count;
        $return['activelist']=$active_arr;
        $return['cart_num']=$cart_num?$cart_num:0;
        return $return;
    }

    /**获取商品简介
     * @param $param
     */
    public function get_goods_content($param){
        $return=array('status'=>1);
        if(empty($param['id'])){
            $return['status']=3;
            $return['msg']='参数错误';
            return $return;
        }
        $map=array();
        $map['goods_id']=$param['id'];
        $data=M("GoodsContent")->where($map)->getField('content');
       if($data){
           $return['data']=h($data);
       }else{
           $return['data']='暂无内容';
       }
        return $return;
    }
    public function collect_goods($param){
        $return=array('status'=>1);
        if(empty($param['id'])){
            $return['status']=3;
            $return['msg']='参数错误';
            return $return;
        }
        $goods_id=$param['id'];
        $uid=$param['uid'];
        $type=$param['type'];
        $collect = M('GoodsCollect');
        $map_co['goods_id'] = $goods_id;
        $map_co['uid'] = $uid;
        $map_co['type'] = $type;
        if ($type == 1) {
            $where['goods_id'] = $goods_id;
            $map_co['integral_id'] = M('GoodsIntegral')->where($where)->getField('id');
        }
        $favinfo = $collect->where($map_co)->count();
        if ($favinfo) {
            $favinfo = $collect->where($map_co)->delete();
            $return['status'] = 2;
            $return['msg'] = '取消收藏成功!';
            return $return;
        } else {
            $postdata['goods_id'] = $goods_id;
            $postdata['uid'] = $uid;
            $postdata['addtime'] = NOW_TIME;
            $postdata['status'] = 1;
            $postdata['type'] = $type;
            if ($type == 1) {
                $where['goods_id'] = $goods_id;
                $postdata['integral_id'] = M('GoodsIntegral')->where($where)->getField('id');
            }
            $result = $collect->add($postdata);
            if ($result) {
                $return['status'] = 1;
                $return['msg'] = '收藏成功';
            } else {
                $return['status'] = 3;
                $return['msg'] = '收藏失败!';
            }
            return $return;
        }
    }
    public function add_cart($param=array()){
        $return = array('status'=>3,'msg'=>'参数错误');
        $model='Common/Takeout';
		$data=array();
        $shop_id = $param['shop_id'];
        $param['sub_list'] = json_decode(htmlspecialchars_decode($param['sub_list']),true);
        if(empty($param['sub_list'])){
            $return['msg']='请选择商品';
            return $return;
        }
        if(empty($param['shop_id'])){
            $return['msg']='无门店可配送';
            return $return;
        }
        foreach($param['sub_list'] as $k=>$v){
            $attr_info = '';
            if ($v['spec_format']) {
                $goodsattr_info = array(
                    'key' => $v['spec_format']['key'],
                    'name' => $v['spec_format']['name']
                );
                $attr_info = serialize($goodsattr_info);
            }
            if($param['add_type']=='cont'){
                $map = array();
                $map['user_id'] = $param['uid'];
                $map['shop_id'] = $shop_id;
                $map['goods_id']=$v['id'];
                if($attr_info){
                    $map['goods_attr'] = $attr_info;
                }
                $goods_num = M('Cart')->where($map)->getField('goods_num');
                if($goods_num>0){
                    $v['num'] = $v['num']+$goods_num;
                }
            }
            $map = array();
            $map['goods_id']=$v['id'];
            $map['shop_id']=$shop_id;
            $map['goods_stock']=$v['spec_format']? $v['spec_format']['key'] : 0;
            $sgsinfo=M('ShopsGoodsStock')->where($map)->field(true)->find();

            // $return['msg_sql'] =  M('ShopsGoodsStock')->getLastSql();
            $map = array();
            $map['id']=$v['id'];
            $goods_info=M('Goods')->where($map)->field('goods_name,img,market_price,goods_sn,cat_id,promote_id,promote_price,promote_start_time,promote_end_time,sale_type')->find();	
            if($v['num']<=0){
                $return['msg'] = '请加入商品【'.$goods_info['goods_name'].'】数量';
                return $return;
            }
            if($goods_info['sale_type']==1){//组合商品库存
                $goods_number = $this->get_group_goods_stock($v['id'],$shop_id);
                if($v['num']>$goods_number){
                    $return['msg'] = $goods_info['goods_name'].'【库存不足，库存量'.$goods_number.'】';
                    return $return;
                }
            }else{
                if($sgsinfo){
                    if($v['num']>$sgsinfo['goods_number']){
                        $return['msg'] = $goods_info['goods_name'].'【库存不足，库存量'.$sgsinfo['goods_number'].'】';
                        return $return;
                    }
                }else{
                    $return['msg'] = $goods_info['goods_name'].'【没有规格商品】';
                    return $return;
                }
            }
            $savedata[$k]['user_id'] = $param['uid'];
            $savedata[$k]['goods_id']=$v['id'];
            $savedata[$k]['shop_id']=$shop_id;
            $savedata[$k]['goods_name']=$goods_info['goods_name'];
            $savedata[$k]['goods_sn']=$goods_info['goods_sn'];
            $savedata[$k]['goods_img']=$goods_info['img'];
            $savedata[$k]['catid']=$goods_info['cat_id'];
            $savedata[$k]['goods_num']=$v['num'];
			$savedata[$k]['goods_attr']=$attr_info;
			if($v['spec_format']){
				$map = array();
				$map['attr_key'] = $v['spec_format']['key'];
				$map['goods_id'] = $v['id'];
				$price_info['goods_price'] = M('GoodsAttrStock')->where($map)->getField('attr_price');
				$price_info['price_type'] = 6;
			}else{
				$price_info=D('Common/Takeout')->get_min_price($shop_id,$v['id']);//获取商品最终价格
			}
			$savedata[$k]['shop_price']=$price_info['goods_price'];
			$savedata[$k]['all_price']=$v['num']*$price_info['goods_price'];
			$savedata[$k]['price_type'] = $price_info['price_type'];
			$savedata[$k]['cart_type']=3;
//			//活动id
//			if($savedata[$k]['price_type'] == 3){
//				$savedata[$k]['cart_id'] = $price_info['act_id'];
//			}else{
				$ret = D('Common/Promot')->goods_to_promot($v['id'],0,$savedata[$k]['cart_type']);
				if($ret['count'] > 0){
					$act_info = current($ret['list']);
					$savedata[$k]['cart_id'] = $act_info['id'];
//				}
			}
        }
        if($param['add_type']!='cont'){
            $map = array();
            $map['user_id'] = $param['uid'];
            $map['shop_id'] = $shop_id;
            M('Cart')->where($map)->delete();
        }
        if($param['add_type']=='cont'){
            foreach($savedata as $k=>$v){
                $map = array();
                $map['user_id'] = $param['uid'];
                $map['shop_id'] = $shop_id;
                $map['goods_id']=$v['goods_id'];
                $cart_count=M("Cart")->where($map)->count();
                if($cart_count>0){
                    $result = M('Cart')->where($map)->save($v);

                }else {
                    $result = M('Cart')->add($v);
                }
            }
        }else {
            foreach ($savedata as $k => $v) {
                $result = M('Cart')->add($v);
            }
        }
        if($result){
            $map=array();
            $map['user_id']=$param['uid'];
            $cart_num_list=M("Cart")->where($map)->field('goods_num')->select();
            $cart_num = 0;
            foreach($cart_num_list as $k=>$v){
                $cart_num += $v['goods_num'];
            }
            $return['status'] = 1;
            $return['cart_num'] = $cart_num;
            $return['msg'] = '操作成功';
        }
        return $return;
    }
    public function get_cart_total_info($uid){
        //购物车数量
        $map=array();
        $map['user_id']=$uid;
        $cart_num_list=M("Cart")->where($map)->field('goods_num,shop_price')->select();
        $cart_num = 0;
        $cart_total_price=0;
        foreach($cart_num_list as $k=>$v){
            $cart_num += $v['goods_num'];
            $cart_total_price += $v['goods_num']*$v['shop_price'];
        }
        $return['cart_num']=$cart_num;
        $return['cart_total_price']=format_decimal($cart_total_price);
        return $return;
    }


    //1019新加
    public function add_order($goods_list,$payment_id,$source,$type,$user_info=''){

        $shop_id=1;
        $user_info=$user_info;
        $order=array();
        $order['order_sn'] = createOrderNo();
        $order['type'] = $type;
        if($user_info) $order['uid'] = $user_info['id'];
        else $order['uid'] = 0;
        $order['shop_id'] = $shop_id;//商家id
        $order['shipping_status'] = 1;//配送状态
        $order['pay_code'] = idtoname($payment_id,'Payment','code');//支付方式id
        $order['payment_id'] = $payment_id;//支付方式id
        $order['pay_status'] = 1;//支付状态
        $total_money=0;
        foreach($goods_list as $key=>$val){
            $total_money+=$val['price'];
        }
        $order['goods_amount'] = $total_money; //实际支付金额
        $order['goods_allmoney'] =  $total_money;
        $order['order_amount'] = $total_money;//应付款金额
        $order['order_money'] = $total_money;//应付款金额
        $order['discount'] = 0;//折扣金额
        $order['delivery_fee']=0;//运费
        $order['status'] = 1;//订单状态
        $order['addtime'] = NOW_TIME;
        $order['source'] = $source;//来源
        //1027新加
        $order['open_id'] = 'o2Bwc5IBB8-iF6yLhadVr5o8cHRI'; //后边从user_info拿出来
        //end
        $order_id=M('OrderInfo')->add($order);
        if(empty($order_id)){
            $return['status'] = 3;
            $return['msg']='添加订单失败';
        }else{
            // $order_ids[] = $order_id;
            $order_ids = $order_id;
            foreach($goods_list as $ks=>$vs){
                if(str_exists($ks,'-')){
                    $goods_ids = explode('-',$ks);
                    $goods_id = $goods_ids[0];
                    $order_goods = array();
                    $order_goods['order_id'] = $order_id;
                    $order_goods['goods_id'] = $goods_id;
                    $order_goods['goods_number'] = $vs['num'];

                    $info = idtoname($goods_id,'Goods','goods_sn,goods_name,img','id',false);
                    if(!empty($vs['goods_attr'])){
                        $params_h = json_decode(htmlspecialchars_decode($vs['goods_attr']),true);
                        $order_goods['goods_name'] = $info['goods_name'] . '(' . $params_h['name'] . ')';
                        $order_goods['attr_price'] = format_decimal($vs['price']/$vs['num']);

                        $wh=array();
                        $wh['goods_id'] = $goods_id;
                        $wh['id'] = $params_h['key'];
                        $attrs=M('GoodsAttr')->where($wh)->getField('attr_id');
                        $attr_keys = array(
                            'key'=>$params_h['key'],
                            'name'=>idtoname($attrs,'GoodsAttribute','name','id',false).':'.$params_h['name']
                            );
                        $order_goods['goods_attr'] = serialize($attr_keys);//属性

                    }else{
                        $order_goods['goods_name'] = $info['goods_name'];
                    } 


                   $order_goods['goods_price'] = format_decimal($vs['price']/$vs['num']);
                   $order_goods['location_id'] = $shop_id;//门店id
                   $order_goods['goods_sn'] = $info['goods_sn'];
                   $order_goods['addtime'] = NOW_TIME;
                   $order_goods['status'] = 1;//商品的发货状态
                   $order_goods_id = M('OrderGoods')->add($order_goods);
                }
            }
        }
        $return['status']=1;
        $return['order_sn']=$order['order_sn'];
        $return['order_id']= $order_ids;
        // $return['order_id']=",".implode(',',$order_ids).",";
        return $return;
    }

    /**
     * 处理订单 结单
     * @param $info 订单信息
     */
    public function endorder($info){
        $root = array('status' => 0, 'msg' => '');
        if (empty($info['out_trade_no'])) {
            $root['msg'] = "参数错误";
            return $root;
        }
        $map['order_sn'] = $info['out_trade_no'];
        $pay_info = M("PayLog")->where($map)->field(true)->find();
        if (format_decimal($pay_info['use_money'] + $pay_info['use_score_money'] + $info['money']) >= format_decimal($pay_info['order_total_price'])) {
                $paylogsave['is_paid'] = 1;
                $paylogsave['pay_sn'] = $info['pay_sn'];
                $paylogsave['update_time'] = NOW_TIME;
                $paylogwhere['is_delete'] = 0;
                $paylogwhere['order_sn'] = $info['out_trade_no'];
                $res = M('PayLog')->where($paylogwhere)->save($paylogsave);

                if ($res) {
                    $orderids = M('PayLog')->where($paylogwhere)->getField('order_id');
                    $orderids_arr = array_filter(explode(',', $orderids));
                    foreach ($orderids_arr as $val) {
                        $orderwhere['id'] = $val;
                        $orderwhere['is_delete'] = 0;
                        $orderwhere['pay_status'] = array('neq', 3);
                        $orderwhere['status'] = array('lt', 3);
                        $orderinfo = M('OrderInfo')->where($orderwhere)->field(true)->find();
                        if ($orderinfo) {
                            if ($orderinfo['pay_status'] <= 1 || $orderinfo['pay_status'] == 4) {
                                $updatedata['pay_status'] = 3;
                                $updatedata['pay_sn'] = $info['pay_sn'];//支付接口返回的订单号
                                $updatedata['pay_amount'] = $info['money'];//线上支付
                                $updatedata['pay_time'] = NOW_TIME;
                                if ($orderinfo['status'] <= 1) {
                                    $updatedata['status'] = 2;
                                    $updatedata['confirm_time'] = NOW_TIME;
                                }
                                M('OrderInfo')->where($orderwhere)->save($updatedata);
                                shops_customer($orderinfo['uid'],$orderinfo['shop_id']);//存入门店顾客中间表
                                $pay_log_id = M('PayLog')->where($paylogwhere)->getField('id');
                                // 扣除商品库存
                                if ($pay_info['type'] != 14 && $pay_info['type'] != 6 && $pay_info['type'] != 2) {
                                    $result = $this->reduce_inventory($pay_log_id);
                                    if ($result['status'] == 2) {
                                        $root['msg'] = $result['msg'];
                                        return $root;
                                    }
                                }
                            }
                        }else{
                            $root['msg'] = "没有此订单信息";
                            return $root;
                        }
                    }

                }else {
                    $root['msg'] = "改变支付单状态失败";
                    return $root;
                }
        }else {
            $root['msg'] = "支付失败";
            return $root;
        }

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

    /**减库存
     * @param $pay_log_id //paylog表里的id
     */
    private function reduce_inventory($pay_log_id){
        $root=array();
        //扣除商品库存
        $paylogwhere['id']=$pay_log_id;
        $orderids = M('PayLog')->where($paylogwhere)->getField('order_id');
        $orderids_arr =array_filter(explode(',', $orderids));
        $store_id='';
        foreach($orderids_arr as $key=>$val) {
            $g_map['order_id'] = $val;
            $order_goods = M("OrderGoods")->where($g_map)->field('goods_id,goods_attr,goods_number,pack_id')->select();
            $store_id=idtoname($val,'OrderInfo','storage_id');
            if ($order_goods) {
                foreach ($order_goods as $key => $gv) {
                    if(C('IS_WAREHOUSE')==1){
                        if ($gv['goods_attr']) {
                            $attrs=unserialize($gv['goods_attr']);
                        } else {
                            $attrs['key']='';
                        }
                        if($gv['pack_id']){//转换最小单位 计算数量
                            $ratio = M('GoodsPackage')->where('id='.$gv['pack_id'])->getField('ratio');
                            if($ratio){
                                $gv['goods_number'] = $ratio*$gv['goods_number'];
                            }
                        }
                        $goods_map['store_id']=$store_id;
                        $goods_map['goods_id']=$gv['goods_id'];
                        $goods_map['goods_attr_sn'] = $gv['goods_id'] . '-' . $attrs['key'];
                        $goods_attr_stock=M("StorageStock")->where($goods_map)->setDec('stock',$gv['goods_number']);
                    }else{
                        if ($gv['goods_attr']) {
                            $attrs=unserialize($gv['goods_attr']);
                            $attr['goods_id'] = $gv['goods_id'];
                            $attr['attr_key'] = $attrs['key'];
                            $goods_stock = M("GoodsAttrStock")->where($attr)->getField("stock_cfg");
                            $attr_data['stock_cfg'] = $goods_stock - $gv['goods_number'];
                            $goods_attr_stock = M("GoodsAttrStock")->where($attr)->save($attr_data);
                        } else {
                            $goods_map['id'] = $gv['goods_id'];
                            $stock = M("Goods")->where($goods_map)->getField("goods_number");
                            $gmap['goods_number'] = $stock - $gv['goods_number'];
                            $goods_attr_stock = M("Goods")->where($goods_map)->save($gmap);
                        }
                    }
                }
            } else {
                $root['status'] = 2;
                $root['msg'] = "订单商品不存在";
                return $root;
            }
        }
        return $root;
    }
    //end
}
