<?php
/**
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
 
namespace Common\Model;
use Think\Model;
class OrderInfoModel extends Model{
/**获取结算商品列表
*$cart_ids,array,购物车id
*$return ,array,返回商品列表
*/
public function order_list($cart_ids='',$goods_id,$type,$addre_id){
    $memberinfo = checkuserauthtype();
    $return = array();
    $return['status'] = 1;
    if(!$memberinfo['id']){
        $return['status'] = -1;
        $return['msg'] = '还未登录，请先登录';
        return $return;
    }

    $shop_id=get_wxsmall_shop_id();
//    echo $shop_id;exit;
    $return['address_info']=D('Common/Member')->get_address_list('','','','',C('MEMBER_RECRIVE_ADDRESS_NUM'));
    $return['addr_info']=D('Common/Takeout')->get_order_address($return['address_info']['list'],$shop_id,$addre_id);//默认的收货地址
    if($cart_ids) {
        if (empty($cart_ids)) {
	  $return['status'] = 0;
	  $return['msg'] = '没有可结算的商品';
	  return $return;
        } else {
	  $list = D("Common/Cart")->cartlist('', $cart_ids, 1,$return['addr_info']['address_info']['id'],3);
	   $return['data'] = $list;
        }
    }
    if($goods_id){
        if($type==3){
	  $list = D("Common/GoodsIntegral")->get_cartIntegral($goods_id,$return['addr_info']['address_info']['id']);
        }else {

	  $list = D("Common/Cart")->cartlist($goods_id, '', 1,$return['addr_info']['address_info']['id'],$type);//print_r($list);exit;
        }
        $return['data'] = $list;
        $return['is_addcart'] = $type;
    }
        if($type==14 || $type==11 || $type==3){
            $shops = D('Common/Takeout')->check_location($shop_id);
            $distance=distance($return['addr_info']['address_info']['ypoint'],$return['addr_info']['address_info']['xpoint'],$shops['shops_info']['ypoint'],$shops['shops_info']['xpoint']);
            //配送信息
            $return['delivery']=
                D('Common/Takeout')->get_shops_deliveryfee($shop_id,$return['addr_info']['address_info']['id'],$list['list'][$shop_id]['promot_list'],$list['list'][$shop_id]['shop_info']['allgoods_price'],$list['list'][$shop_id]['shop_info']['shipping_info']['configure'],$return['addr_info']['status'],$distance);

            if($return['addr_info'] && $return['delivery']['status']==0){
                $return=$return['delivery'];return $return;
            }

            $shops_info = $shops['shops_info'];
            //包装费信息
            $return['package']=D('Common/Takeout')->get_shops_package($shop_id);
            //包装费（餐盒费）
            if(floatval($return['data']['shopgoods'][$shop_id]['goods_total_price'])>floatval($return['package']['package_start_price'])){
                $return['lunch_box_price']=0;
            }else {
                $return['lunch_box_price'] = format_decimal(floatval($return['package']['package_price']) * intval(count($return['data']['shopgoods'][$shop_id]['cart_type'])));
            }
            $return['data']['all_price']=format_decimal(floatval($return['data']['all_price'])+floatval($return['lunch_box_price']));
            if($type!=3)$return['data']['list'][$shop_id]['shop_info']['shop_total_price']=format_decimal(floatval($return['data']['list'][$shop_id]['shop_info']['shop_total_price'])+floatval($return['lunch_box_price']));
           // $return['data']['list'][$shop_id]['shop_info']['shipping_fee']=floatval($return['delivery']['delivery_price']);
            $return['service_time']=$this->get_service_time($return['package']['to_time'],$shops_info['business_hours_start'],$shops_info['business_hours_end'],$shops_info['business_week_start'],$shops_info['business_week_end'],$return['package']['time_int'],$return['package']['long_time']);
        }
    return $return;
}

    /**
     * 配送时间数组
     * @param $to_time  配送时长 单位是分钟
     * @param $start_time  门店营业开始时间点(如5:00)
     * @param $end_time  门店营业结束时间点(如15:00)
     * @param $week_start  门店营业开始时间(如周一)
     * @param $week_end  门店营业结束时间(如周六)
	 * @param $time_int 时段细分 1上午下午 2小时 3半小时
	 * @param $long_time 最长预约天数 0是只有今天
     * @return array
     */
	private function get_service_time($to_time,$starttime,$endtime,$week_start,$week_end,$time_int,$long_time){
		$retuan = array();
		$now_time = NOW_TIME;
        $week_start = substr($week_start,3);
        $week_end = substr($week_end,3);
        $weekarray = array("日","一","二","三","四","五","六");
		foreach($weekarray as $k => $v){
			if($week_start == $v){
				$start_week = $k;
			}
			if($week_end == $v){
				$end_week = $k;
				if($end_week == 0){
					$last_end_week = 7;
				}else{
					$last_end_week = $end_week;
				}
			}
		}
		
		//循环日期+周
		$week_time_arr = array();
		if($start_week && $last_end_week){
			$num = $add_num = $start_week;
			if($long_time == 0){
				$num_time = 1;
			}else{
				$num_time = $long_time;
			}
			$endday=$num_time*2;
			$day_num=0;
			$week_time_arr=array();
			for($i = 0; $i < $endday; $i++){
				if($day_num <= $num_time){
					$week_time=strtotime('+ '.$i.'day');
					$week_now=date('w',$week_time);
					if($week_now == 0){
						$week_now = 7;
					}
					if($week_now >= $start_week && $week_now <= $last_end_week){//在配送时间内
						$day_num++;
						if($week_now == 7){
							$week_now = 0;
						}
						// $week_time_arr[date('Y-m-d',$week_time)]=$weekarray[$week_now];
						// $week_time_arr[$week_time]=$weekarray[$week_now];
						if($day_num == 1){
							if($week_now != date('w')){
								$first_date = date('Y-m-d',$week_time).' | 周'.$weekarray[$week_now];
							}else{
								$first_date = date('Y-m-d',$week_time).' | 今天';
							}
							$first_date_time = $week_time;
						}
						$week_time_arr[strtotime(date('Y-m-d',$week_time))]=$weekarray[$week_now];
					}
				}
			}
			if($week_time_arr){
				$return['first_date'] = $first_date;
				$return['first_date_time'] = $first_date_time;
				if($long_time != 0){
					$return['week_time_arr'] = $week_time_arr;
				}else{
					$one_key = key($week_time_arr);
					$one_value = reset($week_time_arr);
					$return['week_time_arr'] = array($one_key => $one_value);
				}
			}
			
			// echo "<pre>";print_r($return['week_time_arr']);exit;
		}
		
		//循环细分时间
		if(date("w") < $start_week || date("w") > $end_week){
			$abc = date('Y-m-d',key($week_time_arr));
		}
		$aa = strtotime($abc." ".$starttime);//开始营业时间戳
		$bb = strtotime($abc." ".$endtime);//结束营业时间戳

		$time_arr = array();
		// echo $time_int;exit;
		if($time_int == 1){
			$shangwu = strtotime(date('Y-m-d 12:00:00'));
			if($shangwu >= $aa){
				$start = $shangwu;
				$time_arr[$shangwu] = '上午';
			}
			if($bb > $shangwu){
				$time_arr[$bb] = '下午';
			}
		}else{
			$cha = ($aa-strtotime(date('Y-m-d')))/3600;
			if(!is_int($cha)){
				$aa = $aa-1800;
			}
			$dd = ($bb - $aa)/3600;
			if($time_int == 2){
				$number = intval($dd);
			}else{
				$number = $dd * 2;
			}
			
			for($i = 1; $i <= $number; $i++){
				if($time_int == 2){
					$time = $aa + (3600*$i);
				}else{
					$time = $aa + (1800*$i);
				}
				$time_arr[$time] = date('H:i',$time);
			}
		}
		// echo "<pre>";
		// print_r($time_arr);exit;
		if($time_arr){
			$return['time_arr'] = $time_arr;
		}
		$return['to_time'] = $to_time;
		return $return;
	}
    /**获取订货结算商品列表
     *$cart_ids,array,购物车id
     *$return ,array,返回商品列表
     */
    public function porder_list($cart_ids='',$goods_id,$type,$addre_id){
        $shop_info = checkshopauthtype();
        $return = array();
        $return['status'] = 1;
        if(!$shop_info['id']){
            $return['status'] = -1;
            $return['msg'] = '还未登录，请先登录';
            return $return;
        }
        //收货地址
        $address = M('Shops')->where('id=' . $shop_info['shop_id'])->field('province,city_id,district')->find();
        $address_a = array();
        if($address){
            $address_a['province'] = idtoname($address['province'], 'Area');
            $address_a['city'] = idtoname($address['city_id'], 'Area');
            $address_a['district'] = idtoname($address['district'], 'Area');
        }
        $address_a['name'] = idtoname($shop_info['shop_id'], 'Shops','name');
        $address_a['address'] = idtoname($shop_info['shop_id'], 'Shops','address');
        $return['address_list'] = $address_a;
        //获取默认地址
        if($cart_ids) {
            if (empty($cart_ids)) {
                $return['status'] = 0;
                $return['msg'] = '没有可结算的商品';
                return $return;
            } else {
                $list = D("Common/Cart")->cartlistp('', $cart_ids, 1);
                $return['data'] = $list;

            }
        }
        if($goods_id){
            $list = D("Common/Cart")->cartlistp($goods_id, '', 1);
            
            $return['data'] = $list;
            $return['is_addcart'] = $type;
        }
        return $return;
    }
	/**修改配送地址
	 *$param,array,结算商品的id
	 *$return ,array,返回商品列表
	 */
	public function modify_address($param=array()){
		$id = intval($param['id']);
		$memberinfo=checkuserauthtype();
		$return['status'] = 0;
    if($param) $regular= new \Common\Vendor\Regular();
		if(trim($param['consignee'])==''){
			$return['msg'] = '请填写收货人姓名';
			return $return;
		}
		if(!$param['province']||!$param['district']||!$param['city_id']){
			 $return['msg'] = '请填写完整的所在地区';
			 return $return;
		}
        $address_info= cookie('dingwei_address');
        if($address_info){
             if($param['province']!=$address_info['province']){
                 $return['msg'] = '此地址不在配送区域请重新填写';
                 return $return;
             }
             if($param['city_id']!=$address_info['city']){
                 $return['msg'] = '此地址不在配送区域请重新填写';
                 return $return;
             }
             if($param['district']!=$address_info['district']){
                 $return['msg'] = '此地址不在配送区域请重新填写';
                 return $return;
             }
        }else{
             $return['msg'] = '请选择配送区域';
             return $return;
        }
		if(trim($param['address'])==''){
			 $return['msg'] = '请填写完整的收货地址';
			 return $return;
		}
        if(!$param['mobile']&&!$param['tel']){
            $return['msg'] = '手机号/固话不能为空';
            return $return;
        }
        if(!$regular->isPhone($param['mobile'])){
            $return['msg']='手机号格式不正确';
            return $return;
        }
		$data = $param;
		$data['city']=$param['city_id'];
		$data['updatetime']=NOW_TIME;
		if($id>0){
			$map['id'] = $id;
			$result = M('MemberAddress')->where($map)->save($data);
		}else{
			unset($data['id']);
			$map = array();
			$data['uid'] = $memberinfo['id'];
			$result = M('MemberAddress')->where($map)->add($data);
		}
		if($result){
			$return['status'] = 1;
			$return['msg'] = '操作成功';

		}else{
			$return['status'] = 0;
			$return['msg'] = '操作失败';
		}
		return $return;
	}
	/**验证活动是否过期
	 *$good_ids,购物车中的ids
	 *$return ,boolean 活动是否过期
	 */
	public function check_active($good_ids){
		$return['status']=1;
		if(empty($good_ids)){
			$return['status']=0;
			$return['msg']='请选择需要验证的商品';
			return $return;
		}
		foreach($good_ids as $k=>$v){
			$cart_id=idtoname($v['id'],'Cart','cart_id');
			if($cart_id>0){
				$promot_info=idtoname($cart_id,'PromotAct');
				if(!empty($promot_info)&&$promot_info['end_time']<NOW_TIME){
					$return['status']=0;
					$return['msg']=$promot_info['act_name'].'活动已过期';
					break;
				}
			}
		}
		return $return;
	}
    /**计算订单的详细价格
     * $param=array(
         *$cart_ids,array,购物车中的ids
        * data,array, 立即购买的数组（goods_id,）
         *$type,string,商品类型1普通商品2积分商品10订货商品
         *$bonu,array,红包/优惠券ids
         *$score,float,使用的积分
         *$use_account,int,是否全额支付
         *$account_money,float,使用的余额
         *$payment_id,int,支付方式
         *$delivery_id,int,配送方式
         *$cart_type,int,1直营2订货
     * )
     *$return ,array
     */
      public function count_total($param){
        $return=array();$return['status']=1;
        $cart_ids=$param['cart_ids'];
        $data=$param['data'];
        $type=intval($param['type'])?intval($param['type']):1;
        $bonu=$param['bonu'];
        $score=intval($param['score']);
        $use_account=intval($param['use_account']);
        $account_money=floatval($param['account_money']);
        $payment_id=intval($param['payment_id']);
        $delivery_id=intval($param['delivery_id']);
        $total_price=$total_shipping_fee=$use_score=$use_score_money=$bonu_money=$active_money=$goods_integral=$integral_price=$total_integral_price=$discount_amount=$gift_price=0;
        $promot_money_json=$act_id=array();
        $total_price_show='';
        $send_type=intval($param['send_type'])>=1?intval($param['send_type']):0;
        if($type==10){
            $memberinfo=checkshopauthtype();
        }else{
            $memberinfo=checkuserauthtype();
        }
        if(empty($memberinfo)){$return['status']=0;$return['msg']='请先登录';return $return;}
        if($type==10){
            $memberinfo=idtoname($memberinfo['shop_id'],'Shops','*');
            $memberinfo['money'] = shopbalance($memberinfo['id']);
        }else{
            $memberinfo=idtoname($memberinfo['id'],'Member','*','id',false);
        }
         if($account_money<=0)$account_money=0;
        $order_type=$type;
        switch($type){
            case 10://订货
                $order_type=$type;
                if($cart_ids) {
                    $cart_list = D("Common/Cart")->cartlistp('', $cart_ids, 1, '');
                }elseif($data){
                    $cart_list = D("Common/Cart")->cartlistp($data, '', 1, '');
                }
                foreach ($cart_list['list'] as $key => $val) {
                    $total_shipping_fee += $val['shop_info']['shipping_fee'];//运费
                    foreach($val['promot_list'] as $k=>$gv){
                        foreach($gv['goods_list'] as $kk=>$v){
                            if($v['is_integral']==0){
                                $integral_price+=$v['goods_num']*$v['shop_price'];
                            }
                        }
                        $total_integral_price+=$integral_price;
                    }
                }
                foreach ($cart_list['shopgoods'] as $key => $val) {
                    $total_price += $val['goods_total_price'];
                }//商品总价格
                break;
            case 3://积分
         
                $cart_list=D("Common/GoodsIntegral")->get_cartIntegral($data);
                if($cart_list['status']==1){
                    foreach($cart_list['list'] as $key=>$val){
                        $total_price+=$val["all_price"];
                        $total_price_show.=$val["all__price_show"];
                        $total_shipping_fee+=$val['shipping_fee'];
                        $goods_integral+=$val['cart_integral']*$val['goods_num'];
                    }

                }
                break;
            case 6://拼团
                  $order_type=6;
                  $cart_list =  D("Common/Cart")->cartlist($data, '', 1,$delivery_id);
                  foreach ($cart_list['shopgoods'] as $key => $val) {
                    $total_price += $val['goods_total_price'];
                  }//商品总价格
                  foreach ($cart_list['list'] as $key => $val) {
                        foreach($val['promot_list'] as $k=>$gv){
                              foreach($gv['goods_list'] as $kk=>$v){
                                if($v['is_integral']==0){
                                   $integral_price+=$v['goods_num']*$v['shop_price'];
                                }
                              }
                              $total_integral_price+=$integral_price;
                        }

                  }
                break;
            default:
                //1,6,11,12,14
                if($cart_ids){
                    $cart_list = D("Common/Cart")->cartlist('', $cart_ids,1,$delivery_id);
                }elseif($data){
                    if($type != 11){
                      $cart_list =  D("Common/Cart")->cartlist($data, '', 1,$delivery_id);
                    }else{
                      $cart_list =  D("Common/Cart")->cartlist($data, '', 1,$delivery_id,$type);
                    }
                }
                $giftall_money=0;
                foreach ($cart_list['list'] as $key => $val) {
                    foreach($val['promot_list'] as $k=>$gv){
                      if($k>0){
                        $act_id[] = $k;
                        $promot_money_json[$k]['type']=$gv['promot_info']['act_type'];
                        if($gv['promot_info']['act_type']==1 || $gv['promot_info']['act_type']==2){
                          $promot_money_json[$k]['money']=$gv['promot_info']['save_prices'];
                        }elseif($gv['promot_info']['act_type']==3){
                          $promot_money_json[$k]['money']=$gv['promot_info']['new_save_price'];
                        }elseif($gv['promot_info']['act_type']==4){
                          $promot_money_json[$k]['money']=$gv['promot_info']['new_save_price'];
                          $promot_money_json[$k]['price']=$gv['promot_info']['act_type_ext'];
                          $gift_price+=$gv['promot_info']['act_type_ext'];
                        }
                      }
                        $gift_money=0;
                        foreach($gv['goods_list'] as $kk=>$v){
                            if($v['is_integral']==0){
                              $integral_price+=$v['goods_num']*$v['shop_price'];
                            }
                        }
                        if($gv['gift_list']){//判断加价购商品 是否参与积分低现
                            $integral_gift=idtoname($gv['gift_list']['id'],'Goods','is_integral','id',false);
                            if($integral_gift==0){
                                $gift_money = $gv['gift_list']['all_price'];
                            }
                            $giftall_money+=$gv['gift_list']['all_price'];
                        }
                        //不参与积分抵现的总价
                        $total_integral_price+=$integral_price;
                        $total_integral_price+=$gift_money;
                    }

                }
                foreach ($cart_list['shopgoods'] as $key => $val) {
                    $total_price += $val['goods_total_price'];
                }
                $total_price=$total_price+$giftall_money;
                break;
        }
        if($cart_list['status']==0){
            return $cart_list;
        }
        $active_money=$cart_list['all_save_price'];//活动优惠的价格
        //红包/优惠抵扣的价格
        if (!empty($bonu['id']) && $bonu['money']>0) {
          $bonu_money=$bonu['money'];
        }
        $lunch_box_price=0;
        if($type==14 || $type==6 || $type==3){
            $shop_id=get_wxsmall_shop_id();
            $shops = D('Common/Takeout')->check_location($shop_id);
            $shops_info = $shops['shops_info'];
            if($send_type==2){
              //包装费信息
              $return['package']=D('Common/Takeout')->get_shops_package($shop_id);
              //包装费（餐盒费）
              if(floatval($total_price)>floatval($return['package']['package_start_price'])){
                  $lunch_box_price=0;
              }else {
                  $lunch_box_price = format_decimal(floatval($return['package']['package_price']) * intval(count($cart_list['shopgoods'][$shop_id]['cart_type'])));
              }
            }else{
              $lunch_box_price=0;
            }
            $configure=$cart_list['list'][$shop_id]['shop_info']['shipping_info'];
            $address_info=D('Common/Member')->get_address_list('','','','',C('MEMBER_RECRIVE_ADDRESS_NUM'));
            $addr_info=D('Common/Takeout')->get_order_address($address_info['list'],$shop_id,$delivery_id);
            $return['delivery']=D('Common/Takeout')->get_shops_deliveryfee($shop_id,$delivery_id,$cart_list['list'][$shop_id]['promot_list'],$cart_list['list'][$shop_id]['shop_info']['allgoods_price'],$configure['configure'],$addr_info['status']);
            if($return['addr_info'] && $return['delivery']['status']==0){
                $return=$return['delivery'];return $return;
            }
            if($send_type==1){
                $total_shipping_fee=0;
            }else{
                $total_shipping_fee=floatval($return['delivery']['delivery_price']);
            }


        }
        //首单立减开始
         if($type!=10 && $type!=1 && $type!=6){
            $map_o=array();
            $map_o['uid']=$memberinfo['id'];
            $count_order = M('OrderInfo')->where($map_o)->count();
            $first_money = idtoname($memberinfo['id'],'Member','first_money','id',false);
            $first_money = floatval($first_money);
            if($first_money==0 && $count_order){
                $s_where=array();
                $s_where['id']=1;
                $s_where['status']=1;
                $s_where['_string'] = "shop_id like '%,".$shop_id.",%' OR shop_id='0'";
                $s_config_ser=M('TakeoutPromote')->where($s_where)->getField('config');
                if(!empty($s_config_ser)){
                    $s_config_info=unserialize($s_config_ser);
                    if(($total_price+$total_shipping_fee-$active_money-$bonu_money+$lunch_box_price) > $s_config_info['discount_amount']){
                        $cartlist['first_order']['act_name'] = '首单立减';
                        $cartlist['first_order']['discount_amount'] = $s_config_info['discount_amount'];
                        $discount_amount=$s_config_info['discount_amount'];
                    }
                }
            }
         }//首单立减结束
        $pay_price=$total_price-$bonu_money-$active_money+$lunch_box_price-$discount_amount;//订单应付金额=总金额优惠-红包-包装费-首单优惠
        if($pay_price<0){
          $pay_price=0;
        }
        $use_score=$pay_score=$use_score_money=$total_refund_money=0;
        if($type!=10) {
            if ($type == 3) {//积分商品的积分支付
                $order_type = 3;
                // print_r($goods_integral);exit();
                // $score_use_total = intval($goods_integral * C('WEB_INTEGRAL_RATIO') / 100);
                $score_use_total = $goods_integral * C('WEB_INTEGRAL_RATIO') / 100;
                if ($pay_price > 0 && $score > 0) { //积分支付
                    if ($memberinfo['usepoints'] >= $score_use_total) {
                        $use_score = $score_use_total;
                        $pay_score = $goods_integral;
                    } else {
                        $use_score = $memberinfo['usepoints'];
                        $pay_score = $use_score;
                    }
                }
                $use_score_money = $use_score;
                $pay_price = $pay_price - $use_score;
            } else {//普通商品的积分支付
                $money = $pay_price - $total_integral_price;//扣除不参与积分抵现的
                $order_score = intval($money * (C('INTGRAL_PAY_RATIO') / 100) * 100 / C('WEB_INTEGRAL_RATIO'));//该订单可使用多少积分
                if ($money > 0 && $score > 0) {
                    if ($memberinfo['usepoints'] >= $order_score) {
                        $use_score = $order_score * (C('WEB_INTEGRAL_RATIO') / 100);//钱
                        $pay_score = intval($order_score);//分

                    } else {
                        $use_score = $memberinfo['usepoints'] * (C('WEB_INTEGRAL_RATIO') / 100);
                        $pay_score = intval($memberinfo['usepoints']);
                    }
                }
                $use_score_money = $use_score;
                $pay_price = $pay_price - $use_score;
            }
        }
	$pay_price=$pay_price+$total_shipping_fee;//+运费
        if($pay_price>0 && $use_account==1 ){   //余额支付
            if($memberinfo['money']>0 && $memberinfo['money']>$pay_price){
                $account_money=$pay_price;
            }else{
                $account_money=$memberinfo['money'];
            }
            $pay_price=$pay_price-$account_money;
        }
        //网银支付
        if($payment_id>0 && $payment_id!=1){    //获取手续费
            $payment_info=idtoname($payment_id,'Payment','*');
            $counter_fee=$payment_info['fee'];
        }
        if($counter_fee>0){
            $pay_fee=$pay_price*$counter_fee/100;//手续费
            $pay_price=$pay_price+$pay_fee;
        }
        //配送信息
        if($delivery_id>0){
            $address_info=idtoname($delivery_id,'MemberAddress','*');
            $address='';
            if(!empty($address_info))$address='寄送至：'.$address_info['address'].'    收货人：'.$address_info['consignee'].$address_info['mobile'];
        }
        if($type==10){
            $address='';
            if(!empty($address_info))$address='寄送至：'.$memberinfo['address'].'    收货人：'.$memberinfo['contacts'].$memberinfo['contacts_phone'];
        }
        if($account_money<0){$account_money=0;}
        $return['data']=$cart_list;
        $return['total_info']=array(
            'send_type'=>$send_type,//配送方式
            'org_allprice'=>format_decimal($cart_list['org_allprice']),//商品没有任何优惠之前的总金额
            'total_price'=>format_decimal($total_price),//商品总价（去掉、会员价/显示促销之后的金额）
            'total_price_show'=> $total_price_show,
            'pay_price'=>format_decimal($pay_price),//线上支付价格
            'pay_fee'=>format_decimal($pay_fee),//手续费
            'total_shipping_fee'=>format_decimal($total_shipping_fee),//总运费
            'use_score'=>format_decimal($use_score),//使用的积分的钱
            'score'=>$pay_score,//使用的积分
            'use_score_money'=>format_decimal($use_score_money),//积分抵扣的价格
            'bonu_money'=>format_decimal($bonu_money),//红包/优惠抵扣的价格
            'active_money'=>format_decimal($active_money),//活动优惠
            'account_money'=>format_decimal($account_money),//使用余额
            'payment_info'=>$payment_info,//使网银支付信息
            'pay_total_price'=>format_decimal($total_price+$total_shipping_fee-$active_money-$bonu_money+$lunch_box_price-$discount_amount),//订单实际支付的金额=商品总价+总运费-活动折扣-红包折扣
            'address_info'=>$address,//配送地址
            'order_type'=>$order_type,//订单类型
            'discount_amount'=>$discount_amount,//首单立减金额
            'lunch_box_price'=>$lunch_box_price,//包装费
            'new_save_price'=>format_decimal($cart_list['new_save_price']),//满赠 加价购商品优惠金额
            'promot_money_json'=>$promot_money_json,//优惠活动详情
            'gift_price'=>$gift_price,//加价购 所加金额
            'act_id'=>$act_id,//活动id
        );
        return $return;
      }

    /**
     * 获取自营发放的红包（后台发放的红包）
     */
    public function get_userbouns(){
        $memberinfo=checkuserauthtype();
        $map=$bouns_info=array();
        $map['bonus_type_id']=5;
        $map['used_time']=0;
        $now_time=NOW_TIME;
        $map['_string']='(start_time = 0 or start_time <= '.$now_time.') and (end_time = 0 or end_time >= '.$now_time.')';
        $bouns_info=M("MemberBonus")->where($map)->select();
        return $bouns_info;
    }

    /**验证红包是否有效
     * @param $bonus_id 红包id
     * @return array
     */
    public function check_user_bonus($bonus_id){
        $return=array();
        $return['status']=1;

        if(empty($bonus_id)){
            $return['status']=0;
            $return['msg']='请选择红包';
            return $return;
        }
        $map['id']=$bonus_id;
        $bonus_info=M("MemberBonus")->where($map)->field(true)->find();
        if(!empty($bonus_info)&&$bonus_info['end_time']<NOW_TIME && $bonus_info['end_time']!=0){
            $return['status']=0;
            $return['msg']=$bonus_info['type_name'].'优惠券已过期';
            return $return;
        }
        return $return;
    }

    /**
     * 提交订单
     * @param array $param
     * @return array
     */
    public function sub_order($param=array()){
        $return =array('status'=>0,'msg'=>'');
        $goods_ids = unserialize(C('PRO_GOODS'));
        if($param['type']==10){
            $memberinfo=checkshopauthtype();
            if(empty($memberinfo)){$return['msg']='请先登录';$return['url'] = getjumpurl('JUMP_8');return $return;}
        }else{
            $memberinfo=checkuserauthtype();
            if(empty($memberinfo)){$return['msg']='请先登录';$return['url'] = getjumpurl('JUMP_1');return $return;}
        }
        $cart_ids=$param['ids'];//订单页传过来的ids
        if($param['type']==10){
            $address = getshopaddress($memberinfo['shop_id']);
            $address['consignee'] = idtoname($memberinfo['shop_id'],'Shops','contacts');
            $address['address'] = idtoname($memberinfo['shop_id'],'Shops','address');
            $address['mobile'] = idtoname($memberinfo['shop_id'],'Shops','contacts_phone');
            $address['email'] = idtoname($memberinfo['shop_id'],'Shops','email');
        }else if($param['type']==11 || $param['type']==12){
	  $best_time = intval($param['best_time']);
	  if(empty($best_time) && $param['type']==11){
	      $return['msg']='请输入服务时间';
	      return $return;
	  }
	  if($param['service_type'] == 2){
	      $addr_id = $param['addr_id'];//地址
	      if($addr_id>0){
		$a_map['id']=$addr_id;
		$address=M('MemberAddress')->field(true)->where($a_map)->find();
	      }
	  }
	  $score=$param['score']?$param['score']:0;//积分
        }else{
            $addr_id = $param['addr_id'];//地址
            $bonu=$param['boun'];//红包
            // $content=$param['content'];
            $score=$param['score']?$param['score']:0;//积分
            $pt_id = $param['pt_id'];
            $pid = $param['pid'];
            if($addr_id>0){
                $a_map['id']=$addr_id;
                $address=M('MemberAddress')->field(true)->where($a_map)->find();
            }elseif(in_array($param['type'],array(1,3,14)) && empty($addr_id) && $param['send_type']!=1){
                $return['status']=0;$return['msg']='请先选择收货地址';return $return;
            }
            //发票信息
            $invoice_type=$param['invoice_type'];//发票类型
            $invoce_map=array();
            $invoce_map['uid']=$memberinfo['id'];
            $invoce_info=M("MemberInvoice")->where($invoce_map)->getField('invoice_info');
            if($invoice_type>0 && $invoce_info){
                $invoice_data=$invoce_info;
            }
        }
        if(empty($address) && $param['service_type'] != 1 && $param['type'] != 12 && $param['send_type'] !=1){$return['msg']='收货地址不存在';return $return;}
        $type=$param['type'];//类型1普通商品2积分商品4其他10订货商品14外卖6拼团
        $use_account=$param['use_account'];//是否全额使用
        $account_money=floatval($param['account_money'])?floatval($param['account_money']):0;//余额
        $payment_id=$param['payment_id']?$param['payment_id']:0;//支付方式
        $source=$param['source'];//来源：0电脑，1手机2app
        $pay_pwd=$param['pay_pwd'];//交易密码
        $data=$param['order_info'];//订单信息
        $content=$param['temp'];
		

        //开始验证订单
        // $map['id']=array("in",$cart_ids);
        if($cart_ids){
            if($param['type']==10){
                $carts_map['c.user_id'] = $memberinfo['shop_id'];
                if (!empty($cart_ids)) $carts_map['c.id'] = array('in', $cart_ids);
                $cart_info=M('Cart')->alias('c')->JOIN('LEFT JOIN __GOODS__ g ON g.id=c.goods_id')->where($carts_map)->field('c.cart_type,g.*,g.id as goods_id,c.id as id,c.user_id,c.cookie_id,c.goods_attr,c.goods_num,c.cart_id,c.pack_id,c.supplier_price')->order('g.suppliers_id asc')->select();
            }else{
                $carts_map['c.user_id'] = $memberinfo['id'];
                if (!empty($cart_ids)) $carts_map['c.id'] = array('in', $cart_ids);
                $cart_info=M('Cart')->alias('c')->JOIN('LEFT JOIN __GOODS__ g ON g.id=c.goods_id')->where($carts_map)->field('c.cart_type,g.*,g.id as goods_id,c.id as id,c.user_id,c.cookie_id,c.goods_attr,c.goods_num,c.cart_id,c.actgoodsid')->order('g.shop_id asc')->select();
            }
        }elseif($data){
            $goodsinfo=$this->buy_now($data,$param['type']);
            $cart_info=$goodsinfo['data'];
        }
        $list=array();
        if($param['type'] == 10){
            foreach($cart_info as $key=>$val){
                $gooda_attrs=unserialize($val['goods_attr']);
                $goods_attr_value=array_values($gooda_attrs);
                //验证商品库存等
                if(C('IS_WAREHOUSE')==1){// 判断该商品是否在配送范围
                    $check=D("Common/Cart")->check_carts($val['goods_id'],$goods_attr_value[0],$val['goods_num'],$goods_attr_value[1],$val['cart_type'],$val['pack_id']);
                }else{
                    $check=D("Common/Cart")->check_cart($val['goods_id'],$goods_attr_value[0],$val['goods_num'],$goods_attr_value[1],0,2,$val['pack_id']);
                }
                if($val['cart_id']>0){//判断活动是否有效
                    $act_status = D('Common/Cart')->format_goods_promot($val['cart_id']);
                    if(!$act_status || $act_status['is_valid']==0){
                        $return['status']=0;$return['msg']='活动已失效，请回首页重新下单';return $return;
                    }
                }
                if($check['status']!=2){
                    $return['msg']=$check['msg'];return $return;
                }
                $list[$val['suppliers_id']]['goods_list'][]=$val;
                $list[$val['suppliers_id']]['shop_info']=0;
            }
        }else if($param['type'] != 11 && $param['type'] != 12){
            if($param['type']==14 && $param['send_type']!=1){
                $address=D('Common/Member')->address_cont($addr_id);
                if(empty($address['id'])){$return['status']=0;$return['msg']='请先选择收货地址';return $return;}
                $address['best_time']=$param['best_time'];

	      // 判断是否在配送区域
                if($address['xpoint']>0 && $address['ypoint']>0){
                    $distribution_area=D('Wxsmall/Login')->judge_shop($address['xpoint'],$address['ypoint'],$param['shop_id']);
                }else{
                    $return['msg']='收货地址不明确，请重新填写';return $return;
                }
                if($distribution_area['status']==3){
                    $return['address']=$address;
                    $return['status']=4;
                    $return['msg']='该地址不在配送范围，用该地址需返回首页';
                    $return['url']=U('Index/index');
                    if($address){
                        $siteinfo['temp_lng'] = $address['xpoint'];
                        $siteinfo['temp_lat'] = $address['ypoint'];
                        $siteinfo['temp_name'] = $address['address'];
                        session('siteinfo',$siteinfo);
                        cookie('siteinfo',$siteinfo);
                    }
                    return $return;
                }
            }
            foreach($cart_info as $key=>$val){
	      $val['cart_type'] = 3;
                $gooda_attrs=unserialize($val['goods_attr']);
                $goods_attr_value=array_values($gooda_attrs);
                if($val['cart_id'] >0 && $val['actgoodsid']){
                    $actgoodsid=array();
                    $actgoodsid=explode('-',$val['actgoodsid']);
                    $checkact=D("Common/Cart")->check_cart($actgoodsid[0],$actgoodsid[1],1,'',$addr_id,$val['cart_type']);

                    if($checkact['status']!=2){
                        $return['msg']=$checkact['msg'];return $return;
                    }
                }

                //验证商品库存等
                $check=D("Common/Cart")->check_cart($val['goods_id'],$goods_attr_value[0],$val['goods_num'],$goods_attr_value[1],$addr_id,$val['cart_type']);
                if($check['status']!=2){
                    $return['msg']=$check['msg'];return $return;
                }
                //验证活动
                if($type!=3){
                    $check_act=$this->check_active($val['id']);
                    if($check_act['status']==0){
                        $return['msg']=$check_act['msg'];return $return;
                    }
                }

                $list[$val['shop_id']]['goods_list'][]=$val;
                $list[$val['shop_id']]['shop_info']=0;
            }
        }
        $info=array();$info=$param;
        $info['cart_ids']=$cart_ids;
        $info['data']=$data;
        $info['type']=intval($type);
        $info['bonu']=$bonu;
        $info['score']=$score;
        $info['use_account']=$use_account;
        $info['account_money']=$account_money;
        $info['payment_id']=$payment_id;
        $info['delivery_id']=$addr_id;
        $info['num']=$param['num'];
        $info['goods_id']=$param['goods_id'];
        $info['location_id']=$param['location_id'];
        $info['money']=$param['money'];
        $data=D('Common/OrderInfo')->count_total($info);
        if($data['status']==0){$return=$data;return $return;}
       //print_r($data);exit;
        if($data['total_info']['pay_price']>0 && $payment_id<=1){$return['msg']='请选择支付方式';$return['app_paydata']='app_notpay';return $return;}
        if($data['total_info']['account_money'] >0 || $score >0 ){
            $return['status']=3;
            if($pay_pwd==''){
                $return['msg']='请输入支付密码';
                return $return;
            }
            if($type==10){
                $m['id']=$memberinfo['shop_id'];
                $userinfo=M("Shops")->where($m)->field('paypassword,salt')->find();
                if($userinfo['paypassword'] == ''){
                    $return['msg']="您没设置交易密码,请设置交易密码";
                    $return['url']=getjumpurl('JUMP_9');
                    return $return;
                }
            }else{
                $m['id']=$memberinfo['id'];
                $userinfo=M("Member")->where($m)->field('paypassword,salt')->find();
                if($userinfo['paypassword'] == ''){
                    $return['msg']="您没设置交易密码,请设置交易密码";
                    $return['wxsmall']=3;
                    $return['url']=getjumpurl('JUMP_3');
                    return $return;
                }

            }


            if($pay_pwd=='' || creatpwd($pay_pwd,'HANCHAO'.$userinfo['salt']) != $userinfo['paypassword']){
                $return['msg']='支付密码错误';
                return $return;
            }
        }
        //生成订单
        if($type==3){
            $data['temp']=$param['temp'];
            $best_time = intval($param['best_time']);
            $data['best_time'] = $best_time;
            $order_info=$this->add_integra_order($data,$address,$payment_id,$source,$invoice_data,$param['send_type']);
        }elseif($type == 11){
	  $data['best_time'] = $best_time;
	  $data['temp']=$param['temp'];
	  $data['service_type']=$param['service_type'];
	  $data['spec_attr']=$param['spec_attr'];
	  $order_info=$this->add_order($data,$address,$payment_id,$bonu,$source,$invoice_data,$type);
        }elseif($type==14){
	  $data['temp']=$param['temp'];
	  $best_time = intval($param['best_time']);
	  $data['best_time'] = $best_time;
	  $order_info=$this->add_order($data,$address,$payment_id,$bonu,$source,$invoice_data,$type,$param['send_type']);
        }elseif($type==10){
	  foreach($param['temp'] as $kt=>$vt){
	      $data['temp'][$param['shop_id'][$kt]]=$vt;
	  }
	  $order_info=$this->add_order($data,$address,$payment_id,$bonu,$source,$invoice_data,$type);
        }elseif($type==1 || $type==12 || $type==6){
	  $data['pt_id'] = $pt_id;
	  $data['pid'] = $pid;
	  $data['temp']=$content;
	  $order_info=$this->add_order($data,$address,$payment_id,$bonu,$source,$invoice_data,$type);
        }

        //验证红包
        if($type!=3 && $type!=10 && $type!=11 && $type!=12) {
            if (!empty($bonu['id']) && $bonu['money']>0) {
                $bonu_money=$bonu['money'];
                //更改会员使用的红包的状态
                $b_data['status'] = 1;
                $b_map['id'] = $bonu['id'];
                M("CouponsGet")->where($b_map)->save($b_data);

            }
        }
        if($order_info['status']==1){
            $order_ids=$order_info['order_id'];
        }else{
            $return['msg']=$order_info['msg'];return $return;
        }
        $payment_info=array();
        $payment_info['order_id']=$order_ids;
        if($type==10){
            $payment_info['user_id']= $memberinfo['shop_id'];
        }else{
            $payment_info['user_id']= $memberinfo['id'];
        }
		
        // return $orderids_arr;
        $payment_info['type']=$data['total_info']['order_type'];
        $payment_info['order_sn']= createOrderNo();
        $payment_info['use_money']=$data['total_info']['account_money'];//余额
        $payment_info['need_pay']=($data['total_info']['pay_price']<0?0:$data['total_info']['pay_price']);//还需支付的金额
        $payment_info['use_score']=$data['total_info']['score'];//积分
        $payment_info['use_score_money']=$data['total_info']['use_score_money'];//积分所抵的钱
        $payment_info['order_total_price']=$data['total_info']['pay_total_price'];//订单实际支付的金额=商品总价+总运费-活动折扣-红包折扣
        $payment_info['payment_id']=$payment_id;//支付方式
        $payment_info['payment_fee']=$data['total_info']['pay_fee'];//支付手续费
        $payment_info['pay_amount']=$data['total_info']['pay_price']<0?0:$data['total_info']['pay_price'];//
        $payment_info['pay_code']=idtoname($payment_id,"Payment",'code');//支付code
        $payment_info['is_paid']=0;
        $payment_info['create_time']=NOW_TIME;
        $payment_info['wxsmall_formid_cache']=empty($param['formId'])?'':$param['formId'];
        $payment_info['shop_id']=$param['shop_id'];
        //生成支付单
        $pay_log_id=M('PayLog')->add($payment_info);
        if($pay_log_id){
            //删除购物车
            if($cart_ids){
                $this->delcartgoods($cart_ids);
            }
            //订单扣款
            //积分支付
            if($data['total_info']['score']){
                account_change($memberinfo['id'],-$data['total_info']['score'],4,4,'购买商品支付,订单'.$order_info['order_sn']);
            }
            //余额支付
            if($type==10){
                if($data['total_info']['account_money']>0){
                    shop_balance_log($memberinfo['shop_id'],-$data['total_info']['account_money'],1,5,'购买商品支付','',$order_info);
                }
            }else{
                if($data['total_info']['account_money']>0){
                    account_change($memberinfo['id'],-$data['total_info']['account_money'],1,4,'购买商品支付，订单'.$order_info['order_sn']);
                }
            }
            //线上支付价格
            if($data['total_info']['pay_price']>0 && $data['total_info']['payment_info']){
                $return['pay']=$pay_log_id;
                $return['status']=1;
                return $return;
            }
			
            //处理订单
            $pay_info=array();
            $pay_info['out_trade_no']=$payment_info['order_sn'];
            $pay_info['type']=$payment_info['type'];
	  if($type == 11)$pay_info['service_type']=$param['service_type'];
            $res=$this->endorder($pay_info);
            if($res['status']==1){
	      if($type == 12){
		  //处理订单
		  $o_ids =array_filter(explode(',', $payment_info['order_id']));
		  $oinfo['order_id'] = $o_ids[1];
		  $oinfo['admin_id'] = $payment_info['user_id'];
		  $oinfo['type'] = 'Member';
		  $ret = $this->confirm_order($oinfo);
	      }
                $return['status']=1;
                $return['data']=$order_ids;
                return $return;
            }else{
                $return['msg']=$res['msg'];
                return $return;
            }

        }else{
            $return['msg']="支付单生成失败";return $return;
        }

        return $return;

    }
    /**插入积分订单信息和积分订单信息的商品信息
     * @param $data
     * @param $address
     * @param $payment_id
     */
    public function add_integra_order($data,$address,$payment_id,$source,$invoice_data,$send_type=0){
        $memberinfo=checkuserauthtype();
        $return=array();
        $return['status']=0;
        $list=$data['data']['list'][0];
        if($list) {
            $order = array();
            $order['order_sn'] = createOrderNo();
            $order['type'] = $data['total_info']['order_type'];
            $order['uid'] = $memberinfo['id'];
            $order['consignee'] = $address['consignee'];//收货人
            $order['province'] = $address['province'];//省
            $order['city'] = $address['city'];//市
            $order['district'] = $address['district'];//县
            $order['address'] = $address['address'];//地址
            $order['zipcode'] = $address['zipcode'];//邮编
            $order['mobile'] = !empty($address['mobile']) ? $address['mobile'] : $memberinfo['mobile'];//电话
            $order['email'] = !empty($address['emai']) ? $address['email'] : $memberinfo['email'];//邮件
            $order['temp'] = $data['temp'];
            // if($data['total_info']['send_type'] == 1){
            //     $order['best_time']       = $data['best_time'];//预约自提时间
            // }else{
            //     $order['best_time']       = $address['best_time'];//最佳配送时间
            // }
            $order['send_type']=$data['total_info']['send_type'];
           	$order['best_time'] = $data['best_time'];//最佳配送时间
            $order['sign_building'] = $address['sign_building'];//标志建筑
            $order['shop_id'] = $list['shop_info']['id'];//商家id
            $order['temp'] = $data['temp'];//订单留言
            $order['shipping_status'] = 1;//配送状态
            $order['pay_code'] = idtoname($payment_id, 'Payment', 'code');//支付方式id
            $order['payment_id'] = $payment_id;//支付方式id
            $order['pay_status'] = 1;//支付状态
            $order['goods_amount'] = $list['all_price'];//商品实际金额(减去折扣的)
            $order['goods_allmoney'] = $list['all_price'];//商品总价
            $order['order_amount'] = $list['shop_total_price'];//应付款金额
            $order['order_money'] = $list['shop_total_price'];//应付款金额
            // $order['delivery_fee'] = $list['shipping_fee'];//运费
            $order['delivery_fee']=$data['total_info']['total_shipping_fee'];//运费
            $order['used_score']  =$data['total_info']['score'];//积分
            $order['used_score_money'] =  $data['total_info']['use_score'];//积分的钱
            $order['used_money'] =  $data['total_info']['account_money'];//余额支付的钱
            $order['pay_amount'] =  $data['total_info']['pay_price'];//线上支付的钱
            $order['lunch_box_price']=$data['total_info']['lunch_box_price'];//打包费
            $order['status'] = 1;//订单状态
            $order['xpoint'] = $address['xpoint'];//经度
            $order['ypoint'] = $address['ypoint'];//纬度
            $order['addtime'] = NOW_TIME;
            $order['source'] = $source;//来源
            $order['invoice_info'] = $invoice_data;//发票信息
            $order_id = M('OrderInfo')->add($order);
            if(empty($order_id)){
                $return['msg']='添加订单失败';return $return;
            }else {//添加order_goods信息
                $order_ids[] = $order_id;//所有订单id
                if ($data['total_info']['order_type'] == 3) {    //积分商品
                    $goodsinfo= idtoname($list['goods_id'],'Goods','staff_comm,money,is_referral,commission,sale_type,supply_price','id',false);

                    $order_goods = array();
                    $order_goods['order_id'] = $order_id;
                    $order_goods['goods_id'] = $list['goods_id'];
                    $order_goods['goods_name'] = $list['goods_name'];
                    $order_goods['goods_sn'] = $list['goods_sn'];
                    $order_goods['goods_number'] = $list['goods_num'];
                    $order_goods['attr_price'] = $list['shop_price'];
                    $order_goods['goods_price'] = $list['shop_price'];
                    $order_goods['goods_attr'] = $list['goods_attr'];//属性
                    $order_goods['staff_comm'] = $goodsinfo['staff_comm'];//导购员提成0不提成 1固定金额2系统设定
                    $order_goods['money'] = $goodsinfo['money'];//员工提成的固定金额
                    $order_goods['is_referral'] = $goodsinfo['is_referral'];
                    $order_goods['commission'] = $data['total_info']['order_type']==14?$goodsinfo['commission']:$list['commission'];//加固定分佣金额
                    $sale_type=$goodsinfo['sale_type'];
                    if($sale_type==1){
                        $supply_price =D('Common/Cart')->groupprice($list['goods_id'],$list['shop_info']['id']);
                        $order_goods['supplier_price'] =$supply_price['supply_price'];
                    }else{
                        $map_sg=array();
                        $map_sg['goods_id']=$list['goods_id'];
                        $map_sg['shop_id']=$list['shop_info']['id'];
                        $supply_price=M('ShopsGoods')->where($map_sg)->getField('avg_price');
                        $order_goods['supplier_price'] = $supply_price>0?$supply_price:$goodsinfo['supply_price'];
                    }
                    $order_goods['promot_id'] = $list['cart_id'];//活动id
                    $order_goods['shop_id'] = $list['shop_info']['id'];//店铺id
                    $order_goods['suppliers_id'] = $list['suppliers_id'];//供货商
                    $order_goods['goods_integral'] = $list['cart_integral'];//积分
                    $order_goods['addtime'] = NOW_TIME;
                    $order_goods['status'] = 0;//商品的发货状态
                    $order_goods['is_balance'] = 0;//未结算
                    $list[] = $order_goods;
                    $order_goods_id = M('OrderGoods')->add($order_goods);
                }
            }
        }else{
            $return['status']=0;
            $return['msg']="订单信息错误";
        }
        $return['status']=1;
        $return['order_id']=",".implode(',',$order_ids).",";
        return $return;
    }

    /**插入订单信息和订单的商品信息
     * @param $data店铺下的所有商品信息
     * @param $data['data']['list]//商品列表，包含商户信息和活动信息
     * @param $data['total_info']//订单的总价格
     * @param $source//订单的来源
     * @param $address//收货地址
     * @param $payment_id//支付方式
     * @param $type//商品类型
     * @param $send_type//配送方式
     */
    public function add_order($data,$address,$payment_id,$bonus,$source,$invoice_data,$type=1,$send_type=0){
        if($type==10){
          $memberinfo=checkshopauthtype();
        }else{
          $memberinfo=checkuserauthtype();
        }
        $return=array();
        $return['status']=0;
        $act_id=array();
        $act_ids=0;
        foreach($data['data']['list'] as $key=>$val){
            //获取店铺下所有商品的活动
            $act_id=$data['total_info']['act_id'];
            if (!empty($act_id)) {
              $act_ids = implode(',', $act_id);
            }
            //红包/优惠抵扣的价格
            if (!empty($bonus['id']) && $bonus['money']>0) {
              $bonus_id = $bonus['id'];
              $bonus_money = $bonus['money'];
            }

            $order=array();
            $order['order_sn']        = createOrderNo();
            $order['type']            = $data['total_info']['order_type'];
            if($data['total_info']['order_type']==10){
                $order['uid']             = $memberinfo['shop_id'];
                if(C('IS_WAREHOUSE')==1){
                    $area = idtoname($memberinfo['shop_id'],'Shops','province,city_id,district');
                    $area_id='';
                    if($area['district']){
                        $area_id = $area['district'];
                    }
                    if(!$area_id){
                        $area_id = $area['city_id'];
                    }
                    if(!$area_id){
                        $area_id = $area['province'];
                    }
                    $store_id=get_area_stid($area_id);
                    $order['storage_id']=$store_id['0'];
                }
            }else{
                $order['uid']             = $memberinfo['id'];
            }
            $order['consignee']       = $address['consignee'];//收货人
            $order['province']        = $address['province'];//省
            $order['city']            = $address['city'];//市
            $order['district']        = $address['district'];//县
            $order['address']         = $address['address'].$address['house_no'];//地址
            $order['zipcode']         = $address['zipcode'];//邮编
	    if($data['total_info']['order_type'] == 6){
		    $order['xpoint'] 		  = $address['xpoint'];//经度
		    $order['ypoint'] 		  = $address['ypoint'];//纬度
	      if($data['total_info']['send_type'] == 1){
		  $order['best_time']       = $data['best_time'];//预约自提时间
	        }else{
		  $order['best_time']       = $address['best_time'];//最佳配送时间
	        }
      			}
            $order['mobile']          = !empty($address['mobile'])?$address['mobile']:$memberinfo['mobile'];//电话
            $order['email']           = !empty($address['emai'])?$address['email']:$memberinfo['email'];//邮件
            if($data['total_info']['order_type'] == 11){
                $order['best_time']       = $data['best_time'];//最佳配送时间
	      $order['service_type']       = $data['service_type'];//最佳配送时间
            }else{
                if($data['total_info']['order_type'] == 14 && $data['total_info']['send_type'] == 1){
                    $order['best_time']       = $data['best_time'];//预约自提时间
                }else{
                    $order['best_time']       = $address['best_time'];//最佳配送时间
                }
            }
            $order['send_type']=$data['total_info']['send_type'];
            $order['sign_building']   = $address['sign_building'];//标志建筑
            $order['shop_id'] = $val['shop_info']['id'];//商家id
            if($data['total_info']['order_type']==10){
              $order['temp'] = $data['temp'][$val['shop_info']['id']];
            }elseif($data['total_info']['order_type']==1 || $data['total_info']['order_type']==12 || $data['total_info']['order_type']==11|| $data['total_info']['order_type']==14){
              $order['temp'] = $data['temp'];
            }else{
              $order['temp'] = '';//订单留言
            }
            if($data['total_info']['order_type'] == 11 || $data['total_info']['order_type'] == 12 || $send_type==1){
              $order['shipping_status'] = 3;//配送状态
            }elseif($type == 6){
              $order['shipping_status'] = 6;//待成团
            }else{
              $order['shipping_status'] = 1;//配送状态
            }
            $order['pay_code'] = idtoname($payment_id,'Payment','code');//支付方式id
            $order['payment_id'] = $payment_id;//支付方式id
            $order['pay_status'] = 1;//支付状态
            $order['goods_amount'] = $val['shop_info']['allgoods_price'];//商品实际金额(减去折扣的)
            $order['bonus_money'] = $bonus_money;//使用红包金额
            $order['bonus_id'] = $bonus_id;//使用红包id
            $order['used_money'] = $data['total_info']['account_money'];//使用余额
            $order['pay_amount'] = $data['total_info']['pay_price'];//线上支付金额
	  $order['pay_fee'] = $data['total_info']['pay_fee'];//线上支付金额
            $order['used_score'] =  $data['total_info']['score']?$data['total_info']['score']:0;//积分
            $order['used_score_money'] =  $data['total_info']['use_score']?$data['total_info']['use_score']:0;//积分的钱
            if($data['total_info']['order_type']==14 || $data['total_info']['order_type']==6){
                $order['delivery_fee']=$data['total_info']['total_shipping_fee'];//运费
            }else{
                $order['delivery_fee']=$val['shop_info']['shipping_fee'];//运费
            }
            $order['status'] = 1;//订单状态
            $order['addtime'] = NOW_TIME;
            $order['source'] = $source;//来源
            $order['invoice_info'] = $invoice_data;//发票信息
            $order['pt_id'] = $data['pt_id'];//拼团活动id
            $order['pid'] = $data['pid'];//拼团活动id
              
            if($data['total_info']['order_type']==14){
                $order['goods_allmoney'] = $data['total_info']['org_allprice'];//商品总价
                $order['discount'] = $data['total_info']['org_allprice']-$data['total_info']['total_price']+$bonus_money+$data['total_info']['discount_amount']+$order['used_score_money']+$data['total_info']['active_money'];//所有优惠

                $order['lunch_box_price']=$data['total_info']['lunch_box_price'];//打包费
                $order['xpoint'] = $address['xpoint'];//经度
                $order['ypoint'] = $address['ypoint'];//纬度
            }else{
                if($data['total_info']['order_type']==6){
					$order['lunch_box_price']=$data['total_info']['lunch_box_price'];//打包费
				}else{
					$order['lunch_box_price']=0;
				}
                $order['goods_allmoney'] = $data['data']['shopgoods'][$val['shop_info']['id']]['goods_total_price'];//商品总价
                $order['discount'] = $data['data']['shopgoods'][$val['shop_info']['id']]['goods_total_price']-$val['shop_info']['allgoods_price'];//折扣金额
            }
            if($data['total_info']['active_money'] > 0 || $data['total_info']['new_save_price'] > 0){
              $order['promot_id']=$act_ids;//店铺下所有商品参与的活动id(以逗号分隔)
              $order['promot_money']=$data['total_info']['active_money']+$data['total_info']['new_save_price'];
              $order['promot_money_json']=json_encode($data['total_info']['promot_money_json']);
            }else{
              $order['promot_id']=0;
              $order['promot_money']=0;
              $order['promot_money_json']='';
            }
            
            $order['order_amount'] = $val['shop_info']['shop_total_price']-$bonus_money+$order['lunch_box_price']-$order['used_score_money']-$data['total_info']['discount_amount']+$order['delivery_fee'];//应付款金额
	  $order['order_money'] = $val['shop_info']['shop_total_price']-$bonus_money+$order['lunch_box_price']-$order['used_score_money']-$data['total_info']['discount_amount'];//商品支付总金额
            $order['first_money']=$data['total_info']['discount_amount'];
            $guide_data = M('Config')->field('value')->where("name='GUIDE'")->find();
            $guid = unserialize($guide_data['value']);
            if($guid['market_way'] == 2){                
                $order['guide'] = M('Member')->where('id='.$order['uid'])->getField('guide');
            }else{
                $order['guide'] = 0;
            }
            //gyc 2019 1.23
            $lshop_id=cookie("lshop_id");
            if($lshop_id){
              $order['lshop_id']=$lshop_id;
            }
            //gyc
            $order_id=M('OrderInfo')->add($order);
            if(empty($order_id)){
                $return['msg']='添加订单失败';return $return;
            }else {//添加order_goods信息
                $order_ids[] = $order_id;//所有订单id
                if($data['total_info']['discount_amount'] > 0){
                    $m_map=$m_data=array();
                    $m_map['id']=$memberinfo['id'];
                    $m_data['first_money']=$data['total_info']['discount_amount'];
                    M('Member')->where($m_map)->save($m_data);
                }
                if($data['total_info']['order_type']==1 || $data['total_info']['order_type']==6 || $data['total_info']['order_type']==10 || $data['total_info']['order_type']==11 || $data['total_info']['order_type']==12 || $data['total_info']['order_type']==14) { //普通商品

                   foreach ($val['promot_list'] as $k => $v) {
					   
                        if(empty($v['goods_list'])){
                           $return['msg']='订单信息错误';return $return;
                        }
                       foreach ($v['goods_list'] as $kk => $vv) {
                        $goodsinfo= idtoname($vv['goods_id'],'Goods','staff_comm,money,is_referral,commission,sale_type,supply_price','id',false);
                        $order_goods = array();
                        $order_goods['order_id'] = $order_id;
                        $order_goods['goods_id'] = $vv['goods_id'];
                        $order_goods['goods_name'] = $vv['goods_name'];
                        $order_goods['goods_sn'] = $vv['goods_sn'];
                        $order_goods['goods_number'] = $vv['goods_num'];
                        $order_goods['attr_price'] = $vv['attr_price'];
                        $order_goods['goods_price'] = $vv['shop_price'];
                        if($vv['live_anchor_id'])$order_goods['live_anchor_id'] = $vv['live_anchor_id'];//主播id
                        if($vv['live_history_id'])$order_goods['live_history_id'] = $vv['live_history_id'];//直播记录ID
                        if($vv['price_type']==2){//会员价
                          $order_goods['discount_member'] = $vv['attr_price']-$vv['shop_price'];
                        }elseif($vv['price_type']==3){
                          $order_goods['discount_xianshi'] = $vv['attr_price']-$vv['shop_price'];
                        }
                        $order_goods['is_referral'] = $goodsinfo['is_referral'];
                        $order_goods['commission'] = $data['total_info']['order_type']==14?$goodsinfo['commission']:$vv['commission'];//加固定分佣金额
                           if($data['total_info']['order_type']==14){
                               $sale_type=$goodsinfo['sale_type'];
                               if($sale_type==1){
                                  $supply_price =D('Common/Cart')->groupprice($vv['goods_id'],$val['shop_info']['id']);
                                  $order_goods['supplier_price'] =$supply_price['supply_price'];
                               }else{
                                   $map_sg=array();
                                   $map_sg['goods_id']=$vv['goods_id'];
                                   $map_sg['shop_id']=$val['shop_info']['id'];
                                   $supply_price=M('ShopsGoods')->where($map_sg)->getField('avg_price');
                                   $order_goods['supplier_price'] = $supply_price>0?$supply_price:$goodsinfo['supply_price'];
                               }

                           }elseif($data['total_info']['order_type']==1){
                               //存储商家结算价或者结算率
                               if (empty($vv['shop_id'])) {//若是自营，计算该商品的结算价
                                   if (!empty($vv['goods_attr'])) {
                                       $goods_attr_data = unserialize($vv['goods_attr']);
                                       $where = array();
                                       $where['id'] = array('in', explode('_', $goods_attr_data['key']));
                                       $add_shop_balance = M('GoodsAttr')->where($where)->getField('sum(supplier_price)');//属性递加结算价
                                   } else {
                                       $add_shop_balance = 0;
                                   }
                                   $supply_price = $goodsinfo['supply_price'];
                                   $order_goods['supplier_price'] = format_decimal(($add_shop_balance + $supply_price) * $vv['goods_num']);
                               }

                           }else{
                               $order_goods['supplier_price'] = $vv['supplier_price'];
                           }
                           $order_goods['goods_attr'] = $vv['goods_attr'];//属性
                           $order_goods['promot_id'] = $vv['cart_id'];//活动id
                           $order_goods['shop_id'] = $vv['shop_id'];//店铺id
                           $order_goods['suppliers_id'] = empty($vv['suppliers_id'])?idtoname($vv['goods_id'],'Goods','suppliers_id'):$vv['suppliers_id'];//供货商
                           $order_goods['addtime'] = NOW_TIME;
	     if($data['total_info']['order_type']==11){
		     //服务属性
		     if($data['spec_attr']){
			     $spec_attr['key'] = $data['spec_attr'];
			     $order_goods['spec_attr'] = serialize($spec_attr);
		     }else{
			     $order_goods['spec_attr'] = '';//属性
		     }
		     $order_goods['status'] = 1;//服务的发货状态
	     }elseif($data['total_info']['order_type']==12){
		     $order_goods['status'] = 2;//服务的发货状态
	     }elseif($send_type==1 && $data['total_info']['order_type']==14){
                    $order_goods['status'] = 1;
               }else{
		$order_goods['status'] = 0;//商品的发货状态
	     }
	    $order_goods['is_balance'] = 0;//未结算
	    $order_goods['pack_id'] = $vv['pack_id'];//包装id
	    $order_goods_id = M('OrderGoods')->add($order_goods);
	 }
                       if($v['gift_list']){
                           $gift_list_info=idtoname($v['gift_list']['id'],'Goods','goods_sn,staff_comm,money,is_referral,commission,sale_type,supply_price,suppliers_id','id',false);
                           $order_goods = array();
                           $order_goods['order_id'] = $order_id;
                           $order_goods['promot_id'] = $v['gift_list']['act_id'];//活动id
                           $order_goods['goods_id'] = $v['gift_list']['id'];
                           $order_goods['goods_name'] = $v['gift_list']['goods_name'];
                           $order_goods['goods_number'] = 1;
                           $order_goods['attr_price'] = $v['gift_list']['shop_price'];
                           $order_goods['goods_price'] = $v['gift_list']['all_price'];
                           // $order_goods['staff_comm'] = $gift_list_info['staff_comm'];//导购员提成0不提成 1固定金额2系统设定
                           // $order_goods['money'] = $gift_list_info['money'];//员工提成的固定金额
                           $order_goods['is_referral'] = $gift_list_info['is_referral'];
                           $order_goods['commission'] = $gift_list_info['commission'];//加固定分佣金额
                           if($data['total_info']['order_type']==14){
                               $sale_type=$gift_list_info['sale_type'];
                               if($sale_type==1){
                                   $supply_price =D('Common/Cart')->groupprice($v['gift_list']['id']);
                                   $order_goods['supplier_price'] =$supply_price['supply_price'];
                               }else{
                                   $order_goods['supplier_price'] = $gift_list_info['supply_price'];
                               }

                           }
                           $attr=array();
                           if($v['gift_list']['goods_attr']){
                              $attr['key']=$v['gift_list']['goods_attr'];
                              $attr['name']=$v['gift_list']['goods_attr_format'];
                              $order_goods['goods_attr'] = serialize($attr);//属性
                              $order_goods['goods_sn'] = idtoname($attr['key'],'GoodsAttrStock','goods_attr_sn','attr_key',false);
                           }else{
                              $order_goods['goods_attr'] = '';//属性
                              $order_goods['goods_sn'] = $gift_list_info['goods_sn'];
                           }

                           $order_goods['shop_id'] = $val['shop_info']['id'];//店铺id
                           $order_goods['suppliers_id'] =$gift_list_info['suppliers_id'];//供货商
                           $order_goods['addtime'] = NOW_TIME;
                           $order_goods['status'] = 0;//商品的发货状态
                           switch($v['gift_list']['act_type']){
                              case 3:
                                $order_goods['goods_type'] = 1;
                              break;
                              case 4:
                                $order_goods['goods_type'] = 2;
                              break;
                           }
                           $order_goods['is_balance'] = 0;//未结算
                           $order_goods_id = M('OrderGoods')->add($order_goods);
                       }
                   }
               }
            }

        }
        $return['status']=1;
        $return['order_sn']=$order['order_sn'];
        $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($pay_info['type']==13){
          $result=D('Pad/Cashier')->endorder($info);
          if($result['status']==0){$root['msg']=$result['msg']; return $root;}
        }elseif($pay_info['type']==30){
            $result=D('Pad/InvoicingOrder')->endorder($info);
            return $result;
        } else{
            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));
                    if ($pay_info['wxsmall_formid_cache']) {//推送小程序模板消息
                       // $this->send_wxsmall_message($pay_info);
                        $send_data['to'] = idtoname($pay_info['user_id'], 'Member', 'mobile');
                        $send_data['pay_id'] = $pay_info['id'];
                        sendbytheme($send_data, 'WXSMALL_ORDER_SUCCESS');
                    }
                    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) {
                                    if ($orderinfo['type'] == 6 && $orderinfo['pt_id'] > 0) {
                                        $pt_id = idtoname($val, 'OrderInfo', 'pt_id');//需要人数
                                        $sum = M('PromotAct')->where('id=' . $pt_id)->getField('group_number');//现在人数
                                        if ($orderinfo['pid'] == 0) {
                                            //开团
                                            $count = M('OrderInfo')->where('pid=' . $val)->count();
                                        } else {
                                            //参团
                                            $oid = $orderinfo['pid'];
                                            $o_map=array();
                                            $o_map['pay_status']=3;
                                            $o_map['pid']=$oid;
                                            $count = M('OrderInfo')->where($o_map)->count();
                                        }
                                        $number = $count + 1;
                                        if ($number == $sum) {
                                            $shipping['shipping_status'] = 1;
                                            if ($orderinfo['pid'] == 0) {
                                                $save = M('OrderInfo')->where('pid=' . $val)->save($shipping);
                                            } else {
                                                $save = M('OrderInfo')->where('pid=' . $oid)->save($shipping);
                                                $u = M('OrderInfo')->where('id=' . $oid)->save($shipping);
                                            }
                                            //自己订单的状态
                                            $updatedata['status'] = 2;//已确认
                                            $updatedata['shipping_status'] = 1;//待成团
                                            $updatedata['confirm_time'] = NOW_TIME;
                                        } else {
                                            $updatedata['status'] = 2;//已确认
                                            $updatedata['shipping_status'] = 6;//待成团
                                            $updatedata['confirm_time'] = NOW_TIME;
                                        }
                                    } else {
                                        $updatedata['status'] = 2;
                                        $updatedata['confirm_time'] = NOW_TIME;
                                    }
                                } elseif ($orderinfo['status'] == 2 && ($orderinfo['type'] == 2 || $orderinfo['type'] == 5)) {
                                    $updatedata['status'] = 3;//充值订单改为已完成
                                    if($orderinfo['uid']){guide_divide($val, 2);}
                                }elseif($orderinfo['type'] == 20){//现金买券
                                    $updatedata['status'] = 3;//现金买券订单改为已完成
                                }
                                M('OrderInfo')->where($orderwhere)->save($updatedata);                                
                                shops_customer($orderinfo['uid'],$orderinfo['shop_id']);//存入仓库顾客中间表
                                if ($val && $pay_info['type'] == 14) {
                                    // 核销优惠券
                                    if($orderinfo['bonus_id']){//核销优惠券
                                        $code=idtoname($orderinfo['bonus_id'],'CouponsGet','code','id',false);
                                        D('Shop/CouponsGet')->confirm_coupons($orderinfo['bonus_id'],$orderinfo['shop_id'],1,$code);
                                    }
    //                                新增外卖订单数
                                    $mobile = idtoname($orderinfo['shop_id'], 'ShopsAccount', 'mobile');
                                    $map_order['pay_status'] = 3;
                                    $date = date('Ymd', NOW_TIME);
                                    $timestart = strtotime("$date 00:00:00");
                                    $timeend = strtotime("$date 23:59:59");
                                    $map_order['type'] = 14;
                                    $map_order['shop_id'] = $orderinfo['shop_id'];
                                    $map_order['pay_time'][] = array('elt', $timeend);
                                    $map_order['pay_time'][] = array('egt', $timestart);
                                    $orderinfonum = M('OrderInfo')->where($map_order)->count();
                                    $msg = 'takeout,' . $orderinfonum;
                                    sendIm($mobile, $msg);
    //                               新增外卖订单数
                                    if(C('BUCKLE_STOCK')==1){
                                        $kucun_re = D('Shop/OrderInfo')->lessstock($val);
                                        if ($kucun_re['status'] == 0) {
                                            $return['msg'] = $kucun_re['info'];
                                            return $return;
                                        }
                                    }
                                    $discount = idtoname($val, 'OrderInfo', 'discount,first_money,guide', 'id', false);
                                    $this->get_profit($val);
                                    if($discount['guide']){
                                        $this->guide_money($val);//存导购员佣金
                                    }
				                    if($orderinfo['send_type']==1){
				                        $send_data2=array();
				                        $send_data2['to'] = idtoname($orderinfo['uid'],'Member','mobile');
				                        $send_data2['code'] = $orderinfo['order_sn'];
				                        sendbytheme($send_data2, 'SINCE_SN');
				                    }
                                }elseif ($val && $pay_info['type'] == 3) {
                                    // 核销优惠券
                                    if($orderinfo['bonus_id']){//核销优惠券
                                        $code=idtoname($orderinfo['bonus_id'],'CouponsGet','code','id',false);
                                        D('Shop/CouponsGet')->confirm_coupons($orderinfo['bonus_id'],$orderinfo['shop_id'],1,$code);
                                    }
    //                                新增外卖订单数
                                    $mobile = idtoname($orderinfo['shop_id'], 'ShopsAccount', 'mobile');
                                    $map_order['pay_status'] = 3;
                                    $date = date('Ymd', NOW_TIME);
                                    $timestart = strtotime("$date 00:00:00");
                                    $timeend = strtotime("$date 23:59:59");
                                    $map_order['type'] = 3;
                                    $map_order['shop_id'] = $orderinfo['shop_id'];
                                    $map_order['pay_time'][] = array('elt', $timeend);
                                    $map_order['pay_time'][] = array('egt', $timestart);
                                    $orderinfonum = M('OrderInfo')->where($map_order)->count();
                                    $msg = 'jifen,' . $orderinfonum;
                                    sendIm($mobile, $msg);
    //                               新增外卖订单数
                                    if(C('BUCKLE_STOCK')==1){
                                        $kucun_re = D('Shop/OrderInfo')->lessstock($val);
                                        if ($kucun_re['status'] == 0) {
                                            $return['msg'] = $kucun_re['info'];
                                            return $return;
                                        }
                                    }
				                    if($orderinfo['send_type']==1){
				                        $send_data2=array();
				                        $send_data2['to'] = idtoname($orderinfo['uid'],'Member','mobile');
				                        $send_data2['code'] = $orderinfo['order_sn'];
				                        sendbytheme($send_data2, 'SINCE_SN');
				                    }
                                } elseif ($val && $pay_info['type'] == 6) {
                                    if(C('BUCKLE_STOCK')==1){
                                        $kucun_re = D('Shop/OrderInfo')->lessstock($val);
                                        if ($kucun_re['status'] == 0) {
                                            $return['msg'] = $kucun_re['info'];
                                            return $return;
                                        }
                                    }
                                } elseif (!$val && $pay_info['type'] == 14) {
                                    $return['msg'] = "订单不存在";
                                    return $return;
                                } elseif (!$val && $pay_info['type'] == 6) {
                                    $return['msg'] = "拼团订单不存在";
                                    return $return;
                                }
                                if ($pay_info['type'] == 1 || $pay_info['type'] == 3 || $pay_info['type'] == 14 || $pay_info['type'] == 6) {//普通商品和积分商品、外卖商品、拼团商品
                                    //增加商家未结算金额
                                    $shop_unsettled = $this->shop_unbalance($val, 0);
                                    if (!$shop_unsettled) {
                                        $root['msg'] = "增加商户待结算金额失败";
                                        return $root;
                                    }
                                    //会员待分成记录
                                    if (C('EXTENSION_SETTING')) {
                                        $affiliate = affiliate($val);
                                    }
                                    if ($info['money'] > 0) {
                                        account_change($pay_info['user_id'], $info['money'], 1, 1, "会员支付（平台入账）", '0', false, 3);
                                    }//平台入账日志
                                } elseif ($pay_info['type'] == 10) {//订货商品
    //                                if(C('IS_WAREHOUSE')==0) {
                                    // 获取结算价
                                    $price_info = get_balance_suprice($val);
                                    //增加供货商未结算金额、销售总额
                                    supplier_balance_log($orderinfo['shop_id'], $price_info['price'], 2, 3, $orderinfo['order_sn'] . '订单付款,未结算总额增加', $orderinfo);
                                    supplier_balance_log($orderinfo['shop_id'], $price_info['price'], 5, 3, $orderinfo['order_sn'] . '订单付款,销售总额增加', $orderinfo);
    //                                }
                                } elseif ($pay_info['type'] == 2 && $pay_info['user_id']) {//会员充值
                                    account_change($pay_info['user_id'], $info['money'], 1, 1, "会员充值,订单".$orderinfo['order_sn']);
                                    $ret=give_double_points($val);//多倍积分
                                    if($ret['get_score']>0 || $ret['get_money']>0){
                                        $map=array();
                                        $map['id']=$orderinfo['id'];
                                        $savedata=array();
                                        $savedata['get_score']=$ret['get_score'];
                                        $savedata['get_money']=$ret['get_money'];
                                        M('OrderInfo')->where($map)->save($savedata);
                                    }
                                    // $this->change_member_moneys($val);//充值赠积分
                                    account_change($pay_info['user_id'], $info['money'], 1, 1, "会员充值（平台入账）", '0', false, 3);//平台入账日志
                                    account_change($pay_info['user_id'], $info['money'], 7, 1, '累计充值');//增加累计充值
                                    // 变更会员等级
                                    $grade_choices = C('GRADE_CHOICES');//会员升级选择
                                    if (C('IS_MEMBER_UPGRADE')) {
                                        if ($grade_choices == 2) {//累计充值升级
                                            // user_ranks($pay_info['user_id']);
                                        }
                                    }

                                } elseif ($pay_info['type'] == 5 && $pay_info['user_id']) {//店铺充值
                                    // shop_balance_log($pay_info['user_id'], $info['money'], 1, 1, '店铺充值', $orderinfo);
                                    account_change($pay_info['user_id'], $info['money'], 1, 1, "店铺充值（平台入账）", '0', false, 3);//平台入账日志
                                } elseif ($pay_info['type'] == 1 || $pay_info['type'] == 3) {//店铺订货
                                    //增加商家未结算金额
                                    $supplier_unsettled = $this->supplier_unbalance($val, 0);
                                    if (!$supplier_unsettled) {
                                        $root['msg'] = "增加商户待结算金额失败";
                                        return $root;
                                    }

                                    if ($info['money'] > 0) {
                                        account_change($pay_info['user_id'], $info['money'], 1, 1, "店铺支付（平台入账）", '0', false, 3);
                                    }//平台入账日志
                                } elseif ($pay_info['type'] == 11) {
                                    $og_map['order_id'] = intval($orderinfo['id']);
                                    $g_id = M("OrderGoods")->where($og_map)->getField('goods_id');
                                    $m_package = array();
                                    $m_package['uid'] = $pay_info['user_id'];
                                    $m_package['order_id'] = intval($orderinfo['id']);
                                    $m_package['service_sn'] = createOrderNo();
                                    $m_package['package_id'] = 0;
                                    $m_package['goods_id'] = $g_id;
                                    $m_package['service_num'] = 1;
                                    $m_package['service_type'] = $info['service_type'];
                                    $m_package['use_shop'] = 0;
                                    $m_package['use_num'] = 0;
                                    $m_package['continued'] = 0;
                                    if ($g_id) {
                                        $gwhere['id'] = $g_id;
                                        $g_info = M("Goods")->where($gwhere)->field('id,supply_price')->find();
                                    }
                                    $m_package['addtime'] = NOW_TIME;
                                    $m_package['endtime'] = 0;
                                    $m_package['package_price'] = $orderinfo['order_amount'];//余额
                                    $m_package['supply_price'] = $g_info['supply_price'];
                                    $m_package['use_time'] = 0;
                                    // print_r($m_package);exit;
                                    M('MemberPackage')->add($m_package);
                                    if ($info['money'] > 0) {
                                        account_change($pay_info['user_id'], $info['money'], 1, 4, "店铺支付（平台入账）", '0', false, 3);
                                    }//平台入账日志
									//增加商家未结算金额
                                    $shop_unsettled = $this->shop_unbalance(intval($orderinfo['id']), 11);
                                    if (!$shop_unsettled) {
                                        $root['msg'] = "增加商户待结算金额失败";
                                        return $root;
                                    }
                                    //发送服务短信
                                    $send_data['to'] = idtoname($m_package['uid'], 'Member', 'mobile');
                                    $send_data['code'] = $m_package['service_sn'];
                                    sendbytheme($send_data, 'BUY_SERVICE_CODE');


                                } elseif ($pay_info['type'] == 12) {
                                    $shop_unsettled = $this->shop_unbalance($val, 0);
                                    $og_map['order_id'] = intval($orderinfo['id']);
                                    $g_id = M("OrderGoods")->where($og_map)->getField('goods_id');
                                    $service_info = M('Goods')->field(true)->find($g_id);
                                    $service_info['contain_service'] = json_decode($service_info['contain_service'], true);
                                    if ($service_info['contain_service']) {
                                        foreach ($service_info['contain_service'] as $k => $v) {
                                            $m_package = array();
                                            $m_package['uid'] = $pay_info['user_id'];
                                            $m_package['order_id'] = intval($orderinfo['id']);
                                            $m_package['service_sn'] = createOrderNo();
                                            $m_package['package_id'] = $g_id;
                                            $m_package['goods_id'] = $k;
                                            $m_package['service_num'] = $v;
                                            $m_package['service_type'] = 0;
                                            $m_package['use_shop'] = 0;
                                            $m_package['use_num'] = 0;
                                            $m_package['continued'] = $service_info['continued'];
                                            if ($g_id) {
                                                $gwhere['id'] = $k;
                                                $g_info = M("Goods")->where($gwhere)->field('id,supply_price')->find();
                                            }
                                            $m_package['addtime'] = NOW_TIME;
                                            $endtime = NOW_TIME + $service_info['continued'] * 86400;
                                            $m_package['endtime'] = $endtime;
                                            $m_package['package_price'] = $orderinfo['order_amount'];//余额
                                            $m_package['supply_price'] = $g_info['supply_price'];
                                            $m_package['use_time'] = 0;
                                            // print_r($m_package);exit;
                                            M('MemberPackage')->add($m_package);
                                        }
                                        unset($k, $v);
                                    }
                                    if ($info['money'] > 0) {
                                        account_change($pay_info['user_id'], $info['money'], 1, 4, "店铺支付（平台入账）", '0', false, 3);
                                    }//平台入账日志
                                }
                            }
                        } else {
                            $root['msg'] = "没有此订单信息";
                            return $root;
                        }
                    }
                    $where_config = array();
                    $where_config['name'] = 'PRO_GOODS';
                    $pro_config = M('Config')->field('value')->where($where_config)->find();
                    $pro_config=unserialize($pro_config['value']);
                    if($pro_config['config']==2){
                      member_upgrade($pay_info['user_id'],$orderids_arr);
                    }
                    $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;
                        }
                    }
                    if(in_array($pay_info['type'],array(6,12,14))){
                        //极光推送（app/pad）
                        $map=array();
                        $map['type']=array('in','6,12,14');
                        $map['pay_status']=3;
                        $map['shipping_status']=1;
                        $map['status']=2;
                        $map['shop_id']=$orderinfo['shop_id'];
                        $dingdan_count=M('OrderInfo')->where($map)->count();
                        $tip_count=count($orderids_arr);
                        $content="新增".$tip_count."个网上订单";
                        $paramdata=array('type'=>2,'txt'=>$dingdan_count);
                        $ids=getpushids(1,$orderinfo['shop_id']);            
                        if(!empty($ids[1]))$result = pushSend($ids[1],$content,'app',1,$paramdata);
                        if(!empty($ids[2]))$result = pushSend($ids[2],$content,'app',2,$paramdata);
                    }
                } else {
                    $root['msg'] = "改变支付单状态失败";
                    return $root;
                }
            } else {
                $root['msg'] = "支付失败";
                return $root;
            }
        }
        $root['status']=1;
        return $root;
    }
	/**
	* 去掉购物车里的商品
	*@param $cart_id 购物车id
	*/
	public function delcartgoods($cart_id){
        $return =array('status'=>0,'msg'=>'');
        if (empty($cart_id)) {
            $return['msg']='参数错误';
			return $return;
        }
		$map['id']=array('in',explode(',',$cart_id));
		$result=M('Cart')->where($map)->delete();
        if ($result!==false) {
            $return['msg']='删除购物车商品成功';
            $return['status']=1;
        }else{
            $return['msg']='删除购物车商品失败';
        }
        return $return;
	}
	/**
	*商家营业额 未结算
	*@param $order_id int  订单id
	*@param $type int  0加1减
	*/  
    public function shop_unbalance($order_id,$type){
        $map['id']=$order_id;
        $map['pay_status']=3;
        $order_info=$this->where($map)->field(true)->find();
        if (!$order_info) {return false;}
        $price_info=get_balance_new_price($order_id);//获取订单的结算价

        if($type){$price_info['price']=-$price_info['price'];}
        $order_type_name='';
        if($order_info['type']==1){
            $order_type_name='商城';
        }elseif($order_info['type']==3){
            $order_type_name='积分商城';
        }elseif($order_info['type']==14){
            $order_type_name='线上订单';
        }elseif($order_info['type']==6){
            $order_type_name='到店付';
        }elseif($order_info['type']==7){
            $order_type_name='团购';
        }elseif($order_info['type']==11){
			$order_type_name='服务';
		}elseif($order_info['type']==12){
			$order_type_name='套餐';
		}
        $order_type_name.='订单';
       shop_balance_log($order_info['shop_id'], $price_info['price'], 2,3,$order_type_name . $order_info['order_sn'] . '付款,未结算总额增加', $order_info);
       shop_balance_log($order_info['shop_id'], $order_info['order_money'], 6,3,$order_type_name . $order_info['order_sn'] . '付款,销售总额增加', $order_info);
        return true;
    } 
    /**
    *供货商营业额 未结算
    *@param $order_id int  订单id
    *@param $type int  0加1减
    */  
    public function supplier_unbalance($order_id,$type){
        $map['id']=$order_id;
        $map['pay_status']=3;
        $order_info=$this->where($map)->field(true)->find();
        if (!$order_info) {return false;}
        $price_info=get_balance_price($order_id);//获取订单的结算价
        if($type){$price_info['price']=-$price_info['price'];}
        supplier_balance_log($order_info['shop_id'], $price_info['price'], 2,3,'订单' . $order_info['order_sn'] . '付款,未结算总额增加', $order_info);
        return true;
    }
	/**
	 * 发货
	 * @param $postdata order_id  int  订单id
	 * @param $postdata admin_id  int  店铺id或后台管理员id
	 * @param $postdata type  string   Shop店铺发货，Admin后台发货,Supplier供货商发货
	 * @return  mixed
	 */
	public function ship_goods($postdata){
		$return=array('status'=>0,'info'=>'');
		$order_id=$postdata['order_id'];
		$admin_id=$postdata['admin_id'];
        $order_type=intval($postdata['order_type']);//订单类型
        if(empty($order_type)){$order_type=1;}
		if(!$order_id){$return['info']='请选择要发货的订单';return $return;}
		
		if($postdata['type']=='Supplier'){
			$is_have['shop_id']=$postdata['admin_id'];
			$is_have['id']=$order_id;
            $is_have['type']=10;
			$yes=M('OrderInfo')->where($is_have)->count();
			if(!$yes){$return['info']='无此操作权限';return $return;}
		}
		
		//检测订单是否能发货
		$ship_map['id']=$order_id;
		$ship_map['pay_status']=3;
		if($order_type==14 || $order_type==3 || $order_type==6){
            $ship_map['shipping_status']=5;//商品准备中
        }elseif($order_type==1 && $postdata['type']=='store'){
            $ship_map['shipping_status']=5;//商品配货中
        }else {
            $ship_map['shipping_status']=1;
        }
		$ship_map['status']=array('lt',3);
		$ship_map['send_type']=array('neq',1);
		$is_ship=M('OrderInfo')->where($ship_map)->count();
		if(!$is_ship){$return['info']='该订单不满足发货条件';return $return;}
		$send_type=M('OrderInfo')->where($ship_map)->getField('send_type');
		//更改订单商品表发货状态
		$og_map['order_id']=$order_id;
		$og_map['status']=0;
		$org_ids=M('OrderGoods')->where($og_map)->getField('id',true);
		if(empty($org_ids)){$return['info']='暂无可发货的商品';return $return;}

        if(C('BUCKLE_STOCK')!=1){
            $kucun_re = D('Shop/OrderInfo')->lessstock($order_id);
            if ($kucun_re['status'] == 0) {
            	$return['info']=$kucun_re['info'];return $return;
            }
        }
        $result=array();$result['status']=0;
        if(($order_type==3 || $order_type==14 || $order_type==6) && C('DIS_TRIBUTE') == 1 && $send_type==2){
            if($postdata['wuliu']=='Local'){
                $save_data['accept_time'] = time();
                M('OrderInfo')->where('id='.$order_id)->save($save_data);
                $result['status'] = 1;
            }
            $req=D('Common/Distribute')->add_order($postdata);
            if($req['status'] == 1){
                $result['status'] = 1;
                $save_data['accept_time'] = time();
                M('OrderInfo')->where('id='.$order_id)->save($save_data);
            }else{
                $return['info'] ='订单成功,第三方物流失败:'. $req['msg'];return $return;
            }
        }elseif(C('DIS_TRIBUTE') == 0 && ($order_type==3 || $order_type==14 || $order_type==6)){
            $save_data['accept_time'] = time();
            M('OrderInfo')->where('id='.$order_id)->save($save_data);
            $result['status'] = 1;
        }
        if($send_type!=2 || (($order_type==3 || $order_type==14 || $order_type==6) && $result['status']==1)){
            $org_map['id']=array('in',$org_ids);
            $org_save['status']=1;
            M('OrderGoods')->where($org_map)->save($org_save);
            
            //更改订单表发货状态
            $save['shipping_status']=3;
            $res=M('OrderInfo')->where('id='.$order_id)->save($save);
            if($res===false){$return['info']='发货失败,或重复发货';return $return;}else{
              $this->order_manage($order_id);
            }
        }
		
		if($send_type!=2){
            //生成发货单
            $g_map['id']=array('in',$org_ids);
            $goods_ids=M('OrderGoods')->where($g_map)->getField('goods_id',true);
            
            $order_info=idtoname($order_id,'OrderInfo','uid,shop_id,order_sn,mobile,type,storage_id');
            $ship_data['ship_time']=NOW_TIME;
            $ship_data['remark']=$postdata['remark'];
            $ship_data['notice_sn']=$postdata['notice_sn'];
            $ship_data['send_type']=$postdata['send_type'];
            $ship_data['uid']=$order_info['uid'];
            if(empty($order_info['storage_id']) && $order_info['type']==1) {
                $ship_data['shop_id'] = $order_info['shop_id'];
            }else{
                $ship_data['shop_id']=$order_info['storage_id'];
            }
            $ship_data['goods_id']=implode(',',$goods_ids);
            $ship_data['org_id']=implode(',',$org_ids);
            $ship_data['order_id']=$order_id;
            if($order_info['type']==10){
                $ship_data['type']=2;
            }
            if($postdata['type']=='Admin' && $order_type==1){
                $ship_data['take_style']=$postdata['take_style'];
                $ship_data['take_location_id']=$postdata['take_location_id'];
            }
            $ship_result=M('ShipOrder')->add($ship_data);
            if($ship_result){$result['status']=1; $return['id']=$ship_result;}
        }
		
		if($result['status']==1){
			$return['status']=1;
			$return['info']='发货成功';
            //若开启仓库，仓库扣库存
            if(C("IS_WAREHOUSE") && $order_info['type']!=10 && $order_info['storage_id']){
                $o_map['order_id']=$order_id;
                $order_goods_info=M("OrderGoods")->where($o_map)->field('goods_id,goods_number,goods_attr')->select();
                $data=array();
                $data['store_id']=$order_info['storage_id'];
                foreach($order_goods_info as $key=>$val){
                    $data['goods_info'][$key]['goods_id']=$val['goods_id'];
                    $data['goods_info'][$key]['goods_number']=$val['goods_number'];
                    if($val['goods_attr']) {
                        $goods_attr = unserialize($val['goods_attr']);
                    }
                    $data['goods_info'][$key]['goods_attr']=$goods_attr['key'];
                }
                $re_stock=$this->reduce_store($data);
                if($re_stock['status']==0){
                    $return['info']='仓库扣库存失败';
                }
            }
			//发货日志
			if($postdata['type']=='Shop'){
				action_log('shop_ship_order', 'Shop', $order_id, $admin_id);
				$send_data['from']=idtoname($admin_id,'Shops','name');
			}elseif($postdata['type']=='Admin'){
				action_log('admin_ship_order', 'Admin', $order_id, $admin_id);
				$send_data['from']='admin(系统)';
			}elseif($postdata['type']=='Supplier'){
                action_log('supplier_ship_order', 'Supplier', $order_id, $admin_id);
                $send_data['from']=idtoname($admin_id,'Suppliers','name');
            }
            if($order_type!=14 || $order_type!=6){
                //发货提醒--3站内信
                $send_data['to']=$order_info['uid'];
                $send_data['type']=1;//会员
                $send_data['content']='您的订单'.$order_info['order_sn'].'已发货啦！';
                send_method(3,$send_data);
            }
			//发货短信
			$code_data['to'] = $order_info['mobile'];
			$code_data['code'] = $order_info['order_sn'];
            if($order_type==14 || $order_type==6){
                $order_info=idtoname($order_id,'OrderInfo','uid,mobile,order_sn');
                $code_data['first'] = '订单发货通知';
//                $code_data['to'] = $order_info['uid'];
                $code_data['order_sn'] = $order_info['order_sn'];
                $code_data['status'] = '已发货';
                sendbytheme($code_data, 'SEND_GOODS');
            }else{
                $order_goods = idtoname($order_id,'OrderGoods','goods_name','order_id');
                $code_data['goods_name'] = $order_goods;
                $code_data['order_sn'] =$order_info['order_sn'];
                $code_data['shops_name'] = C('WEB_SITE_NAME');
                sendbytheme($code_data, 'SEND_GOODS');
            }
		}else{
			$return['info']='发货失败';
		}
		return $return;
	}
  /**
    *更新第三方配送
    */
    public function order_manage($id){
      $return=array('status'=>'0','msg'=>'');
      $order_info=M('OrderInfo')->where('id='.$id)->field(true)->find();
      $apitype=$order_info['distribute'];
      if(empty($apitype))return $return;
      if($apitype=='Dada' || $apitype=='Meituan')$order_id=$order_sn=$order_info['order_sn'];
      if($apitype=='Local'){
          $map=array();
          $map['order_sn']=$order_info['order_sn'];
          $order_sn=M('LocalOrder')->where($map)->getField('origin_id');
          $order_id=$order_info['order_sn'];
      }
      $dis = new \Common\Vendor\Distribute($apitype);
      $input=array(
          'origin_id'=>$order_sn,
          'client_id'=>$order_id,
          'order_code'=>$order_id,
          'order_sn'=>$order_id,
          'shipping_status'=>$order_info['shipping_status'],
          'finish_time'=>NOW_TIME,
      );
      $result= $dis->notify_order($input);
      if($result['status']==1){
          $return['status']=1;
      }
      return $return;
  }
	/**
	 * 申请退货
     *   *@param postdata=> Array (
     * [data] => Array (    订单信息
     *          [20] => Array (
     *                  [money] => 0    应退的余额
     *                  [order_goods] => 17 订单商品
     *
     *              )
     *           )
     * [content] => 123456 退款理由
     * )
	 * @return  mixed
	 */
	public function apply_return($postdata){
		$return=array('status'=>0,'msg'=>'');
        if($postdata['order_type']==10){
            $member_info=checkshopauthtype();
            $type=1;
        }else{
            $member_info=checkuserauthtype();
            $type=0;
        }
		if(!$member_info['id']){$return['msg']='登录信息有误,请重新登录';return $return;}
		foreach($postdata['data'] as $key=>$val){
            $order_info=M("OrderInfo")->where('id='.$key)->field(true)->find();
            if($type==1 && $order_info['storage_id']>0){
                $type=2;
            }
            if(isset($val['order_goods'])){//退订单商品
                $org_id=$val['order_goods'];
                if(!$org_id){$return['msg']='参数错误';return $return;}
                //查看订单商品信息
                $goods_map['id']=array("in",$org_id);
                $info=M('OrderGoods')->where($goods_map)->field('order_id,goods_id,shop_id,goods_number')->select();
                foreach($info as $k=>$v){
                    if($val['number']>$v['goods_number']){
                        $return['msg']='退货数量大于购买数量,不能退货';return $return;
                    }
                    $goods_info[$k]['goods_id']=$v['goods_id'];
                    $goods_info[$k]['number']=$v['goods_number'];
                }
				//改变商品状态
                $map['id']=array("in",$org_id);
                $map['status']=1;
                $save['status']=3;
                $res=M('OrderGoods')->where($map)->save($save);
                if(!$res){$return['msg']='申请失败,可能原因（正在退货中,或还未收货）';return $return;}
				//是否要改变订单状态
				$od_map['order_id']=$key;
				$od_map['status']=array('lt',3);
				$have=M('OrderGoods')->where($od_map)->count();
				if(!$have){
					$od_save['status']=8;//订单改为退货中
					M('OrderInfo')->where('id='.$key)->save($od_save);
				}
                //获取应退货的钱
                $data['type']='th';
                $data['order_info']=array($key=>$org_id);
                $refund_info=$this->check_refund_money($data);
                $money=$refund_info['data'][$key]['money'];
            }else{//退整个订单
                $money=$order_info['order_amount']-$order_info['delivery_fee'];
				$og_map['order_id']=$key;
				$og_map['status']=1;
                $info=M("OrderGoods")->where($og_map)->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='.$key)->save($od_save);
            }
			$str_orgids=implode(',',$org_id);
            //添加退货单
            $add['org_id']=$str_orgids;
            if($postdata['order_type']==10){
                $add['uid']=$member_info['shop_id'];
            }else{
                $add['uid']=$member_info['id'];
            }
            $add['uid']=$member_info['id'];
            $add['shop_id']=$order_info['shop_id'];
            $add['order_id']=$key;
            $add['goods_info']=serialize($goods_info);
            $add['reason']=$postdata['content'];
            $add['money']=$money;
			$add['add_time']=NOW_TIME;
            if($order_info['type']==14 || $order_info['type']==11){
                $add['type']=3;
            }else{
                $add['type']=$type;
            }

            $res=M('ReturnGoods')->add($add);
            //仓库添加退货单
            if($type==2){
                $store_data=array();
                $store_data['user_id']=$member_info['id'];
                $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']=$postdata['order_type'];
                $goods_allmoney=0;
                foreach($goods_info as $k=>$val){
                    $order_map=array();
                    $order_map['goods_id']=$val['goods_id'];
                    $order_map['order_id']=$key;
                    $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;
               $res=$this->add_stock_refundgoods($store_data);
                if($res['status']==0){
                    $return['msg']='仓库添加退货单失败';
                }
            }
            //生成退款单
            $refund_data['reason']=$postdata['content'];
            $refund_data['type']=$type;
            $refund_data['order_goods']=$str_orgids;
            if($type==1 || $type==2){
                $result=$this->add_refund($money,$key,$refund_data,1);
            }else{
                $result=$this->add_refund($money,$key,$refund_data);
            }
			if($result){
                if($postdata['order_type']==10){
                    action_log('shop_apply_return', 'Shops', $res, $member_info['shop_id']);//日志,$res退货单ID
                }else{
                    action_log('user_apply_return', 'Member', $res, $member_info['id']);//日志,$res退货单ID
                }
            }
        }
		if($result){
			$return['status']=1;
			$return['msg']='申请已提交';
		}else{
			$return['msg']='申请提交失败';
		}
		return $return;
	}
	/**
	 * 退货的确认收货
	 * @param $postdata['id'] int  退货单id
	 * @param $postdata admin_id  int  店铺id或后台管理员id
	 * @param $postdata type  string   Shop店铺操作，Admin后台操作
	 * @return  mixed
	 */
	public function confirm_goods($postdata){
		$return=array('status'=>0,'msg'=>'');
		$id=$postdata['id'];
		$admin_id=$postdata['admin_id'];
        if(!$id){$return['msg']='参数错误';return $return;}
		
		if($postdata['type']=='Shop'){
			$is_have['shop_id']=$postdata['admin_id'];
			$is_have['id']=$id;
			$yes=M('ReturnGoods')->where($is_have)->count();
			if(!$yes){$return['msg']='无此操作权限';return $return;}
		}

		//更改状态
		$save['shop_status']=1;
        $result=M('ReturnGoods')->where('id='.$id)->save($save);
		if($result !== false){
            $return['status']=1;$return['msg']='收货成功';
			//收货日志
			if($postdata['type']=='Shop'){
				action_log('shop_confirm_goods', 'Shop', $id, $admin_id);
			}elseif($postdata['type']=='Admin'){
				action_log('admin_confirm_good', 'Admin', $id, $admin_id);
			}
		}else{
			$return['msg']='收货失败';
		}
		return $return;
	}
    /**
    * 处理退货
    * @param $postdata array
    * @return  mixed
    */
    public function return_goods($postdata){
        $return=array('status'=>0,'info'=>'');
        $id=$postdata['id'];
        $admin_id=$postdata['admin_id'];
        if(!$id){$return['info']='参数错误';return $return;}

        $info=M('ReturnGoods')->where('id='.$id)->field(true)->find();
        if(empty($info)){$return['info']='没有此退货信息';return $return;}
        if($postdata['type']==1){//同意
            $yes_map['id']=$id;$yes_map['status']=0;$save['status']=1;$save['update_time']=NOW_TIME;
            $res=M('ReturnGoods')->where($yes_map)->save($save);
            if(!$res){$return['info']='处理失败,可能原因（重复处理）';return $return;}
            //修改订单商品表状态
            if(strpos($info['org_id'],',')){
                $org_map['id']=array('in',$info['org_id']);
            }else{
                $org_map['id']=$info['org_id'];
            }
            $org_map['status']=3;$org_save['status']=4;
            $result=M('OrderGoods')->where($org_map)->save($org_save);
            if(!$result){$return['info']='数据错误';return $return;}
            //执行退款
            $where['status'] = 0;
            $where['order_id'] =$info['order_id'];
            $refund_order=M("RefundOrder")->where($where)->getField("id");
            $refund=$this->handle_order($refund_order,$postdata['margin_type'],$admin_id,0);

        }elseif($postdata['type']==2){//不同意
            $no_map['id']=$id;$no_map['status']=0;
            $save['status']=2;$save['update_time']=NOW_TIME;
            $save['not_content']=$postdata['content'];
            $res=M('ReturnGoods')->where($no_map)->save($save);
            if(!$res){$return['info']='处理失败,可能原因（重复处理）';return $return;}
            //修改订单商品表状态
            $org_map['id']=$info['org_id'];$org_map['status']=3;$org_save['status']=5;
            $result=M('OrderGoods')->where($org_map)->save($org_save);
            if(!$result){$return['info']='数据错误';return $return;}
      }
      $return['status']=1;
      $return['info']='处理成功';
      if($postdata['margin_type']=='Admin')action_log('admin_return_goods', 'Admin', $id, $admin_id);
      return $return;
    }
     /**
     * 处理订货退货
     * @param $postdata array
     * @return  mixed
     */
    public function return_pgoods($postdata){
        $return=array('status'=>0,'info'=>'');
        $id=$postdata['id'];
        $admin_id=$postdata['admin_id'];
        if(!$id){$return['info']='参数错误';return $return;}
        
        $info=M('ReturnGoods')->where('id='.$id)->field(true)->find();
        if(empty($info)){$return['info']='没有此退货信息';return $return;}
        if($postdata['type']==1){//同意
            //修改订单商品表状态
            if(strpos($info['org_id'],',')){
                $org_map['id']=array('in',$info['org_id']);
            }else{
                $org_map['id']=$info['org_id'];
            }
            $org_map['status']=2;$org_save['status']=6;
            $result=M('OrderGoods')->where($org_map)->save($org_save);
            if(!$result){$return['info']='数据错误';return $return;}
            $yes_map['id']=$id;$yes_map['status']=0;$save['status']=1;$save['update_time']=NOW_TIME;
            $res=M('ReturnGoods')->where($yes_map)->save($save);
            if(!$res){$return['info']='处理失败,可能原因（重复处理）';return $return;}
            //执行退款
            $where['status'] = 0;
            $where['order_id'] =$info['order_id'];
            $refund_order=M("RefundOrder")->where($where)->getField("id");
            $refund=$this->handle_order($refund_order,$postdata['margin_type'],$admin_id,$info['type']);
            
        }elseif($postdata['type']==2){//不同意
            $no_map['id']=$id;$no_map['status']=0;
            $save['status']=2;$save['update_time']=NOW_TIME;
            $save['content']=$postdata['content'];
            $res=M('ReturnGoods')->where($no_map)->save($save);
            if(!$res){$return['info']='处理失败,可能原因（重复处理）';return $return;}
            //修改订单商品表状态
            $org_map['id']=$info['org_id'];$org_map['status']=3;$org_save['status']=5;
            $result=M('OrderGoods')->where($org_map)->save($org_save);
            if(!$result){$return['info']='数据错误';return $return;}
        }
        $return['status']=1;
        $return['info']='处理成功';
        if($postdata['margin_type']=='Admin')action_log('admin_return_goods', 'Admin', $id, $admin_id);
        return $return;
    }
    /**
    * 取消订单
    * @param $postdata order_id int  订单id
    * @param $postdata admin_id int  操作人ID
    * @param $postdata type int      Member会员，Admin管理员
    * @return  mixed
    */
    public function cancel_order($postdata){
        $return=array('status'=>0,'msg'=>'');
        $order_id=$postdata['order_id'];
        $admin_id=$postdata['admin_id'];
        if(empty($order_id)){$return['msg']='参数错误';return $return;}
        //查询订单信息
        $map['id']=$order_id;
        $map['is_delete']=0;
        $type = idtoname($order_id,'OrderInfo','type,send_type,pay_status','id',false);
        if($type['type'] == 11 || $type['type'] == 12){
            $map['shipping_status']=array('IN','1,3,5');
            $map['pay_status'] = array('IN','1,3');
        }elseif($type['send_type'] == 1){
            $map['shipping_status']=array('IN','1,3,5,6');
            // $map['pay_status'] = 3;
        }elseif($type['type'] == 6){//拼团订单（到期未成团）
    			if($type['pay_status'] == 3) $map['status'] = 2;
    			else $map['status'] = 1;
          $map['shipping_status'] = 6;
          $map['pt_id'] = array('gt',0);
        }else{
            $map['shipping_status']=array('IN','1,5');
        }
        // $map['shipping_status']=1;
        $order_info=M('OrderInfo')->where($map)->field(true)->find();
        if(empty($order_info)){$return['msg']='订单有误';return $return;}

        //更改订单状态
        $save = array();
        if($type['type'] == 6){
            $save['shipping_status']=7;
            $save['status']=10;
        }else{
            $save['status']=4;
        }
        $info=M('OrderInfo')->where($map)->save($save);

        //支付单信息
        $o_where = array();
        $o_where['order_id'] = array("like", "%," . $order_id . ",%");
        $pay_info = M("PayLog")->where($o_where)->field(true)->find();
        //根据有没有付款生成退款单
        if($order_info['pay_status']<3 ){
            if($pay_info['use_money']>0 || $pay_info['use_score']>0) {
                $where['order_id'] = $order_id;
                $order_goods = M("OrderGoods")->where($where)->getField('id', true);
                $data['order_goods'] = implode(',', $order_goods);
                $data['reason'] = '';
                $data['type'] = 1;
                $money = $pay_info['order_total_price'] - $pay_info['need_pay'];
                if ($type == 14 || $type == 11 || $type == 6) {
                    //外卖、拼团取消订单加库存
                    if (($order_info['type'] == 6 || $type == 14) && C('BUCKLE_STOCK')==1) {
                        D('Shop/OrderInfo')->addstock($order_id);
                    }
                    $refund_id = $this->add_refund($money, $order_id, $data, 3);
                } else {
                    $refund_id = $this->add_refund($money, $order_id, $data);
                }
                //增加退款流水
            $param=array();
            $param['order_id']=$order_info['id'];$param['order_sn']=$order_info['order_sn'];
            $param['user_id']=$order_info['uid'];
            $param['type']=20;
            $param['pay_sn']=$pay_info['pay_sn'];
            $param['use_money']=$order_info['used_money'];
            $param['use_score']=$order_info['used_score'];
            $param['use_score_money']=$order_info['used_score_money'];$param['order_total_price']=$order_info['order_amount'];
            $param['pay_amount_type']=0;$param['in_online']=$order_info['in_online'];
            $param['payment_id']=$order_info['payment_id'];$param['pay_code']=$order_info['pay_code'];
            $param['shop_id']=$order_info['shop_id'];
            $this->return_goods_log($param);
            }
            $return['status']=1;$return['msg']='取消成功';
        }else{
    //            if($order_info['type']==14){
    //                $this->del_goods_numt($order_id);
    //			}elseif($order_info['type']==6){
    //                if(C('BUCKLE_STOCK')==1){
    //                    D('Shop/OrderInfo')->addstock($order_id);
    //                }
    //            }else if($order_info['type']!=11){
    //                $this->del_goods_num($order_id);
    //            }

          if($order_info['type']==14 || $order_info['type']==6){
            $bs_num = C('BUCKLE_STOCK');
    				if(!isset($bs_num)){
    					$map_bs = array();$map_bs['name'] = 'BUCKLE_STOCK';
    					$bs_num = M('Config')->where($map_bs)->getField('value');
    				} 
            if($bs_num==1){
              D('Shop/OrderInfo')->addstock($order_id);
            }
          }else if($order_info['type']!=11){
            $this->del_goods_num($order_id);
          }
          //增加退款流水
            $param=array();
            $param['order_id']=$order_info['id'];$param['order_sn']=$order_info['order_sn'];
            $param['user_id']=$order_info['uid'];
            $param['pay_sn']=$pay_info['pay_sn'];
            $param['type']=20;
            $param['use_money']=$order_info['used_money'];
            $param['need_pay']=$param['pay_amount']=$order_info['pay_amount'];$param['use_score']=$order_info['used_score'];
            $param['use_score_money']=$order_info['used_score_money'];$param['order_total_price']=$order_info['order_amount'];
            $param['pay_amount_type']=0;$param['in_online']=$order_info['in_online'];
            $param['payment_id']=$order_info['payment_id'];$param['pay_code']=$order_info['pay_code'];
            $param['shop_id']=$order_info['shop_id'];
            $this->return_goods_log($param);
            $return['status']=1;$return['msg']='取消成功';
        }
        //处理订单信息
        if($info !== false){
            if($order_info['pay_status']==3){
                $money=$pay_info['order_total_price'];
                $data=$where=array();
                $where['order_id']=$order_id;
                $order_goods=M("OrderGoods")->where($where)->getField('id',true);
                $data['order_goods']=implode(',',$order_goods);
                $data['reason']='';
                $data['type']=0;
                $refund_id=$this->add_refund($money,$order_id,$data);
            }
            if($refund_id){$refund=$this->handle_order($refund_id,$postdata['type'],$admin_id);}

            if($order_info['guide']>0 && $order_info['sales_maid']>0){
                $log='订单'.$order_info['order_sn'].'取消订单佣金扣除'.$type['sales_maid'].'元';
                account_change($order_info['guide'],-$type['sales_maid'],1,10,$log,'','',5);
            }
            
            //日志
            if($postdata['type']=='Member'){
                action_log('user_cancel_order', 'Member', $order_id, $admin_id);
            }elseif($postdata['type']=='Admin'){
                action_log('admin_cancel_order', 'Admin', $order_id, $admin_id);
            }elseif($postdata['type']=='Shop'){
                action_log('Shop_cancel_order', 'Admin', $order_id, $admin_id);
            }
        }else{
            $return['msg']='取消失败';
        }
        return $return;
    }
    /**
    * 取消订单增加库存
    * @param $order_id int  订单id
    * @return  boolean
    */
    public function del_goods_num($order_id){
        if(!$order_id)return false;
        $map['order_id']=$order_id;
        $map['status']=0;
        $goods_info=M('OrderGoods')->where($map)->field('goods_id,goods_number,goods_attr')->select();
        foreach($goods_info as $k=>$v){
            if($v['goods_attr']){
                $attr=unserialize($v['goods_attr']);
                $attr_map['goods_id']=$v['goods_id'];
                $attr_map['attr_key']=$attr['key'];
                M('GoodsAttrStock')->where($attr_map)->setInc('stock_cfg',$v['goods_number']);
            }else{
                M('Goods')->where('id='.$v['goods_id'])->setInc('goods_number',$v['goods_number']);
            }
        }
        return true;
    }
    /**
     * 取消外卖订单增加库存
     * @param $order_id int  订单id
     * @return  boolean
     */
    public function del_goods_numt($order_id){
        if(!$order_id)return false;
        $map['order_id']=$order_id;
        $map['status']=0;
        $goods_info=M('OrderGoods')->where($map)->field('goods_id,goods_number,goods_attr')->select();

        $map_o['id']=$order_id;
        $order_info=M('OrderInfo')->where($map_o)->field('shop_id')->find();
        foreach($goods_info as $k=>$v){
            //增加库存
            $map_s=$data=array();
            $map_s['shop_id']=$order_info['shop_id'];
            $map_s['goods_id']=$v['goods_id'];
            if($v['goods_attr']){
                $shops_goods_attr = unserialize($v['goods_attr']);
                $map_s['goods_stock']=$shops_goods_attr['key'];
                //$map['goods_stock']=$v['goods_attr'];
            }
            $data['updatetime']=NOW_TIME;
            $data['goods_number']=array('exp','goods_number+'.$v['goods_number']);
            $data['sell_count']=array('exp','sell_count-'.$v['goods_number']);
            M('ShopsGoodsStock')->where($map_s)->save($data);
        }
        return true;
    }
    /**
    * 删除订单
    * @param $postdata['id'] int  订单id
    * @param $postdata admin_id  int  会员id或后台管理员id
    * @param $postdata type  string   Member会员操作，Admin后台操作
    * @return  mixed
    */
    public function del_order($postdata){
        $return=array('status'=>0,'msg'=>'');
        $order_id=$postdata['order_id'];
        $admin_id=$postdata['admin_id'];
        if(!$order_id){$return['msg']='参数错误';return $return;}
		
        //检测订单是否能删除
        $map['id']=$order_id;
        $map['status']=array('lt',3);
        $is_del=M('OrderInfo')->where($map)->find();
        if($is_del){$return['msg']='订单未完成，暂不能删除';return $return;}

        //更改订单状态
        $save['is_delete']=1;
        $result=M('OrderInfo')->where('id='.$order_id)->save($save);
        if($result !== false){
            $return['status']=1;$return['msg']='删除成功';
            //删除日志
            if($postdata['type']=='Member'){
                action_log('user_del_order', 'Member', $order_id, $admin_id);
            }elseif($postdata['type']=='Admin'){
                action_log('admin_del_order', 'Admin', $order_id, $admin_id);
            }elseif($postdata['type']=='Shops'){
                action_log('shop_del_order', 'Shops', $order_id, $admin_id);
            }elseif($postdata['type']=='Suppliers'){
                action_log('supplier_del_order', 'Shops', $order_id, $admin_id);
            }
        }else{
            $return['msg']='删除失败';
        }
        return $return;
    }
    /**
    * 确认收货
    * @param $postdata order_id int  订单id
    * @param $postdata admin_id  int  会员id或后台管理员id
    * @param $postdata type  string   Member会员操作，Admin后台操作
    * @return  mixed
    */
    public function confirm_order($postdata){
       
        $return=array('status'=>0,'msg'=>'');
        $order_id=$postdata['order_id'];
        $admin_id=$postdata['admin_id'];
        if(empty($order_id)){$return['msg']='参数错误';return $return;}
		    $or_map=array();
        //验证订单是否满足确认收货
        $or_map['id']=$order_id;
        $or_map['pay_status']=3;
        $send_type=M('OrderInfo')->where($or_map)->getField('send_type');
        if($send_type==1){
            if(C('BUCKLE_STOCK')!=1){
                // 扣库存
                $kucun_re = D('Shop/OrderInfo')->lessstock($order_id);
                if ($kucun_re['status'] == 0) {
                    $return['msg'] = $kucun_re['info'];
                    return $return;
                }//	扣库存结束
            }
            // $or_map['shipping_status']=array('in','3,5');
        }else{
            $or_map['shipping_status']=3;
        }
        $or_map['status']=array('lt',3);
        $is_confirm=M('OrderInfo')->where($or_map)->count();
        if(!$is_confirm){$return['msg']='该订单不满足收货条件';return $return;}
        $order_info = M('OrderInfo')->where($or_map)->field('uid,shop_id,type,guide,order_money')->find();
        //验证OrderGoods是否有正在退货中的商品
        $og_map=array();
        $og_map['order_id']=$order_id;
        $og_map['status']=3;
        $is_goods=M('OrderGoods')->where($og_map)->count();
        if($is_goods){$return['msg']='该订单有正在退货的商品，暂不能收货';return $return;}
        $map=$og_save=$save=$maps=$ship_save=array();
        //更改OrderGoods
        $map['order_id']=$order_id;
        $map['status']=1;
        $og_save['status']=2;
        M('OrderGoods')->where($map)->save($og_save);

        //修改订单状态
        $save['status']=3;
        $save['shipping_status']=4;
        $save['finish_time']=time();
        $res=M('OrderInfo')->where('id='.$order_id)->save($save);
        if($res===false){$return['msg']='确认收货失败,或重复确认收货';return $return;}
        //1.19 累计消费增加
        change_member_pay($order_info['uid'],$order_info['order_money']);
        //1.19 会员晋升
        $where_config = array();
        $where_config['name'] = 'PRO_GOODS';
        $pro_config = M('Config')->field('value')->where($where_config)->find();
        $pro_config=unserialize($pro_config['value']);
        if($pro_config['config']==1){ 
          $order_ids[]=$order_id; 
          member_upgrade($order_info['uid'],$order_ids);
        }
        
        //更改发货单
        if($send_type==3){
          $maps['order_id']=$order_id;
          $maps['status']=0;
          $ship_save['status']=1;
          $ship_save['get_time']=NOW_TIME;
          M('ShipOrder')->where($maps)->save($ship_save);
        }
        if($order_info['type']==14){// zjn 3-15
          $this->add_sell($order_id);//增加销量
        }
        if($order_info['type']==10){
            $this->add_sell($order_id);//增加销量
            get_suppliers_balance($order_id); //供货商结算
        }
        $g_points = give_double_points($order_id);//多倍积分
        give_shop_balance($order_id);//商户结算
        TooKeenAward($postdata['order_id'],2);//推荐三级返利
        // $guide=unserialize(C('GUIDE'));
        // if(!empty($guide))$guide_way=$guide['market_way'];
        // if($guide_way==2 && $order_info['guide'])guide_divide($postdata['order_id'],1);//导购员提成
        if(check_use_auth('LiveSmall'))D('Wxsmall/LiveAnchor')->give_livehis($order_id);/**添加主播分佣信息*/
        shops_customer($order_info['uid'],$order_info['shop_id']);//存入仓库顾客中间表
        $ret=array();
        if($g_points['points'] != 1) $ret['get_score']=$this->change_member_points($order_id);
		else $this->change_member_points($order_id,0,1);
        if(empty($ret['get_money'])) $ret['get_money']=$g_points['get_money'];
        if(empty($ret['get_score'])) $ret['get_score']=$g_points['get_score'];
        if($ret['get_score']>0 || $ret['get_money']>0){
            $map=array();
            $map['id']=$order_id;
            $savedata=array();
            $savedata['get_score']=$ret['get_score'];
            $savedata['get_money']=$ret['get_money'];
            M('OrderInfo')->where($map)->save($savedata);
        }
        $map_r=array();
        $map_r['name']='IS_REBATE';
        $is_rebate=M('Config')->where($map_r)->getField('value');
        if($is_rebate){affiliate_yes($order_id);}//处理分成(自动)

		
		if($order_info['type'] == 6){
			$map = $p_map = array();$map['id'] = $order_id;
			$pin_order_info = M('OrderInfo')->where($map)->field(true)->find();
			if($pin_order_info && $pin_order_info['pid'] == 0){
				$p_map=array();$p_map['pid']=$order_id;
				$count = M('OrderInfo')->where($p_map)->count();
				if($count > 0 && $pin_order_info['shipping_status'] == 4){
					$this->fan_tuanz($order_id);
				}
			}
		}
		
        $return['status']=1;
        $return['msg']='确认收货成功';
        //会员收货日志
        if($postdata['type']=='Member'){
            action_log('user_confirm_order', 'Member', $order_id, $admin_id);
        }elseif($postdata['type']=='Admin'){
            action_log('admin_confirm_order', 'Admin', $order_id, $admin_id);
        }elseif($postdata['type']=='Shop'){
            action_log('shop_confirm_order', 'Admin', $order_id, $admin_id);
        }
        return $return;
    }
	
	/**拼团订单给团长返现
     * @param $order_pid
     */
	public function fan_tuanz($order_pid){
		if(!isset($order_pid)){return false;}
		$map = array();$map['id'] = $order_pid;
		$order_info = M('OrderInfo')->where($map)->field(true)->find();
		if($order_info && $order_info['pid'] == 0 && $order_info['shipping_status'] == 4){
			$p_map=array();$p_map['pid']=$order_pid;
			$count = M('OrderInfo')->where($p_map)->count();
			if($count > 0){
				$pt_map = array();$pt_map['id'] = $order_info['pt_id'];$pt_map['is_pt'] = 1;
				$pint_info = M('PromotAct')->where($pt_map)->field(true)->find();
				if($pint_info && $pint_info['head_commission_rate']>0){
					$f_money = $order_info['order_money']*$pint_info['head_commission_rate']/100;
					if($f_money > 0){
						account_change($order_info['uid'],$f_money,1,5,'拼团订单('.$order_info['order_sn'].')确认收货，团长得到返现');
						// 门店余额减少
						shop_balance_log($order_info['shop_id'],-$f_money,1,3,'订单'.$order_info['order_sn'].'收货,店铺余额减少', $order_info);
					}
					
				}
			}
		}
	}
    /**
     * 订货确认收货
     * @param $postdata order_id int  订单id
     * @param $postdata admin_id  int  店铺id或后台管理员id
     * @param $postdata type  string   Member会员操作，Admin后台操作
     * @return  mixed
     */
    public function pconfirm_order($postdata){
        $return=array('status'=>0,'msg'=>'');
        $order_id=$postdata['order_id'];
        if(is_array($postdata['og_id'])){
            $og_id=$postdata['og_id'];
        }else{
            $og_id=explode(',', $postdata['og_id']);
        }
        if(is_array($postdata['number'])){
            $number=$postdata['number'];
        }else{
            $number=explode(',', $postdata['number']);
        }
        $admin_id=$postdata['admin_id'];
        if(empty($order_id)){$return['msg']='参数错误';return $return;}
        
        //验证订单是否满足确认收货
        $or_map['id']=$order_id;
        $or_map['pay_status']=3;
        $or_map['shipping_status']=3;
        $or_map['status']=array('lt',3);
        $is_confirm=M('OrderInfo')->where($or_map)->count();
        if(!$is_confirm){$return['msg']='该订单不满足收货条件';return $return;}
        $order_info=M('OrderInfo')->where($or_map)->find();
        //验证OrderGoods是否有正在退货中的商品
        $og_map['order_id']=$order_id;
        $og_map['status']=3;
        $is_goods=M('OrderGoods')->where($og_map)->count();
        if($is_goods){$return['msg']='该订单有正在退货的商品，暂不能收货';return $return;}
        
        //更改OrderGoods
        $order_goods=M('OrderGoods')->where('order_id='.$order_id)->field(true)->select();
        $map['order_id']=$order_id;
        $map['status']=1;
        $og_ids = '';
        $tui_num = '';
        $money = 0;
        foreach($order_goods as $k=>$v){
            $map['id'] = $v['id'];
            $goods_info=array();
            if($v['id'] == $og_id[$k]){
                if(intval($number[$k]) > $v['goods_number'] || intval($number[$k])<=0){
                    $return['msg']=$v['goods_name'].'商品，请正确核实收货数量';return $return;
                }elseif(intval($number[$k]) < $v['goods_number']){
                    $og_save['original_num']=$v['goods_number'];
                    if($number[$k]<0){
                        $number[$k]=0;
                    }
                    $og_save['goods_number']=$number[$k];
                    $tuinum = intval($v['goods_number']-$number[$k]);
                    $tuiorg_id .= $v['id'].',';
                    $tuimoney += floatval($tuinum*$v['goods_price']);
                    $goods_info['goods_id'] = $v['goods_id'];
                    $goods_info['number'] = $tuinum;
                    $tuiinfo[] = $goods_info;
                    
                }
                $og_save['status']=2;
                M('OrderGoods')->where($map)->save($og_save);

            }
            if($v['pack_id']){//转换最小单位 计算数量
                $ratio = M('GoodsPackage')->where('id='.$v['pack_id'])->getField('ratio');
                if($ratio){
                    $goods_number = $ratio*idtoname($v['id'],'OrderGoods','goods_number','id',false);
                }
            }else{
                $goods_number = idtoname($v['id'],'OrderGoods','goods_number','id',false);
            }
            $sg_map['goods_id'] = $v['goods_id'];
            $sg_map['goods_sn'] = $v['goods_sn'];
            $sg_map['suppliers_id'] = $v['suppliers_id'];
            $sg_map['shop_id'] = idtoname($order_id,'OrderInfo','uid');
            $sg_count = M('ShopsGoods')->where($sg_map)->count();
            if(!$sg_count){//入库开始
                $sg['goods_id'] = $v['goods_id'];
                $sg['goods_sn'] = $v['goods_sn'];
                $sg['suppliers_id'] = $v['suppliers_id'];
                $sg['shop_id'] = idtoname($order_id,'OrderInfo','uid');
                $sg['qh_count'] = idtoname($v['goods_id'],'Goods','qh_count','id',false);
                $sg['addtime'] = NOW_TIME;
                $sg['status'] = 1;
                $sg['goods_type'] = 1;
                $sg_res = M('ShopsGoods')->add($sg);
            }
            $sgs_map = $sg_map;
            if($v['goods_attr']){
                $shops_goods_attr = unserialize($v['goods_attr']);
                $sgs_map['goods_stock'] = $shops_goods_attr['key'];
            }else{
                $sgs_map['goods_stock'] = 0;
            }
            
            $sgs_count = M('ShopsGoodsStock')->where($sgs_map)->count();
            if($sgs_count){
                $y_num = M('ShopsGoodsStock')->where($sgs_map)->getField('goods_number');
                $sgs_save['goods_number'] = intval($goods_number)+intval($y_num);
                $sgs_save['updatetime'] = NOW_TIME;
                $sgs_save['status'] = 1;
                $sgs_res = M('ShopsGoodsStock')->where($sgs_map)->save($sgs_save);
            }else{
                $sgs_map['goods_number'] = intval($goods_number);
                $sgs_map['qh_count'] = idtoname($v['goods_id'],'Goods','qh_count','id',false);
                $sgs_map['addtime'] = NOW_TIME;
                $sgs_map['updatetime'] = NOW_TIME;
                $sgs_map['status'] = 1;
                $sgs_res = M('ShopsGoodsStock')->add($sgs_map);
            }
            //入库结束
        }
        if($order_info['storage_id']>0){
            $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($tuiinfo);
            $store_data['order_type']=10;
            $store_data['goods_allmoney']=$tuimoney;
            $store_data['order_goods']=$tuiorg_id;
            $res=$this->add_stock_refundgoods($store_data);
            if($res['status']==0){
                $return['msg']='仓库添加退货单失败';
            }else{
                $refund_data['reason']='仓库入库问题商品自动生成退货单';
                $refund_data['type']=0;
                $refund_data['order_goods']=$tuiorg_id;
                $result=$this->add_refund($tuimoney,$order_info['id'],$refund_data,1);
            }
        }else{
            //添加退货单
            $add['uid']=$order_info['uid'];
            $add['shop_id']=$order_info['shop_id'];
            $add['order_id']=$order_id;
            $add['org_id']=$tuiorg_id;
            $add['goods_info']=serialize($tuiinfo);
            $add['money']=$tuimoney;
            $add['add_time']=NOW_TIME;
            $add['type']=1;
            $shop['shop_status']=1;
            $money = $tuimoney;
            $refund_data['type']=0;
            $refund_data['order_goods']=$tuiorg_id;
            $rg_res=M('ReturnGoods')->add($add);
            if($money>0){
                $result=$this->add_refund($money,$order_id,$refund_data,1);
            }
        }

        //修改订单状态
        $save['status']=3;
        $save['shipping_status']=4;
        $res=M('OrderInfo')->where('id='.$order_id)->save($save);
        if($res===false){$return['msg']='确认收货失败,或重复确认收货';return $return;}
        
        //更改发货单
        $maps['order_id']=$order_id;
        $maps['status']=0;
        $ship_save['status']=1;
        $ship_save['get_time']=NOW_TIME;
        M('ShipOrder')->where($maps)->save($ship_save);
        $this->add_sell($order_id);//增加销量
        get_suppliers_balance($order_id);//商户结算
//        if(C('IS_WAREHOUSE')==0) {
//            get_suppliers_balance($order_id); //供货商结算
//        }
        // $this->change_member_points($order_id);
        if(C('IS_REBATE')){affiliate_yes($order_id);}//处理分成(自动)
        
        $return['status']=1;
        $return['msg']='确认收货成功';
        //店铺收货日志
        if($postdata['type']=='Shops'){
            action_log('user_confirm_order', 'Shops', $order_id, $admin_id);
        }elseif($postdata['type']=='Admin'){
            action_log('admin_confirm_order', 'Admin', $order_id, $admin_id);
        }
        return $return;
    }
	/**
     * 消费赠积分
     * @param $order_id
     * @param $is_jifen 是否赠积分
     * @parma $is_xiaofei 是否赠累计消费
     * @return bool
     */
    public function change_member_points($order_id,$is_jifen=1,$is_xiaofei=1){
        if(empty($order_id))return false;
        $order_info=idtoname($order_id,'OrderInfo','uid,order_sn,order_amount','id',false);
		$uid=$order_info['uid'];
		$order_sn=$order_info['order_sn'];
        if(empty($uid))return false;   
        $jifen=$xiaofei=false;     
        if($is_xiaofei){
            $order_money=$order_info["order_amount"];
            account_change($uid,$order_money,3,4,"订单".$order_sn."确认收货，累计消费增加");
            if(C('IS_MEMBER_UPGRADE')){
    			// user_ranks($uid);//累计消费升级
    		}
            $xiaofei=true;
        }        
        if($is_jifen){
            $sell_points=C("SALES_GAIN_SELL_INTEGRAL_RATE");//消费赠消费积分比例
            $gift_sell_points=format_decimal($order_money*$sell_points/100,0,3);// 消费积分
            account_change($uid,$gift_sell_points,4,4,"消费赠积分,订单".$order_sn);
            $jifen=true;
            return $gift_sell_points;
        }
        return $jifen || $xiaofei;
    }
	/**
	 * 收货增加销量
	 * @param $order_id int  订单id
	 * @return  boolean
	 */
	public function add_sell($order_id){
		if(!$order_id)return false;
		$map['order_id']=$order_id;
		$map['status']=2;
		$goods_info=M('OrderGoods')->where($map)->field('goods_id,goods_number,goods_attr')->select();
		foreach($goods_info as $k=>$v){
			if($v['goods_attr']){
				$attr=unserialize($v['goods_attr']);
				$attr_map['goods_id']=$v['goods_id'];
				$attr_map['attr_key']=$attr['key'];
				M('GoodsAttrStock')->where($attr_map)->setInc('sell_count',$v['goods_number']);
			}
			M('Goods')->where('id='.$v['goods_id'])->setInc('sell_count',$v['goods_number']);
		}
		return true;
	}
    /**验证是否退款
     **@param postdata=> Array (
     * [order_info] =>array(
            ['order_id']=>order_goods(以逗号分隔)
     *      )
     *
     * [content] => 123456 退款理由
     * [type] => tk 退款,th退货
     * )
     */
    public function check_refund_money($postdata)
    {
        $return = array("status" => 0, "msg" => '');
        if($postdata['order_type']==10){
            $memberinfo=checkshopauthtype();
        }else{
            $memberinfo = checkuserauthtype();
        }
        if (empty($memberinfo)) {
            $return['msg'] = "您没登陆，请登录";
            return $return;
        }

        $refund_order = $postdata['order_info'];
        foreach ($refund_order as $key => $val) {
            //获取订单信息
            $order_where['id'] = $key;
            $order_info = M("OrderInfo")->where($order_where)->field(true)->find();
            if($postdata['type']=='tk'){//退款
                if ($order_info['shipping_status'] >= 2 || $order_info['pay_status'] != 3) {
                    $return['status'] = 0;
                    $return['msg'] = "该商品已经发货或者该订单还没付款，不能退款";
                    return $return;
                }
            }else{
                if ($order_info['shipping_status'] == 1 || $order_info['pay_status'] != 3) {
                    $return['status'] = 0;
                    $return['msg'] = "该商品未发货或者该订单还没付款，不能退货";
                    return $return;
                }
            }
            //检查是否是退全部订单
            $g_map=array();
            $order_goods=$goods_count=$money=0;
            $g_map['order_id']=$key;
            $order_goods=M("OrderGoods")->where($g_map)->count();
            $goods_count=count(array_filter(explode(',',$val)));
            //部分退
            if($order_goods>$goods_count) {
                //获取订单商品总价格
                $goods_map['order_id'] = $key;
                $goods_map['id'] = array("in", $val);
                $total_price = M("OrderGoods")->where($goods_map)->field("sum(goods_number*goods_price) as total_price,promot_id,is_pro_enable")->group('promot_id')->select();
                $price = $order_info['goods_allmoney'];
                //计算商品活动
                foreach ($total_price as $k => $va) {
                    $goods_total_price = $va['total_price'];
                    //订单减去退款商品
                    $price -= $goods_total_price;
                    $money = $goods_total_price;
                    //判断商品是否参加活动
                    if ($va['promot_id'] && $va['is_pro_enable']==0) {
                        $p_where = $promot_info = array();
                        $promot_price = 0;
                        $p_where['id'] = $va['promot_id'];
                        $promot_info = M("PromotAct")->where($p_where)->find();

                        //订单减去退款商品是否满足该活动，
                        if ($price > $promot_info['min_amount']) {  //若满足则可直接按商品原价退商品，

                            $return['data'][$key]['order_goods'] = $val;
                        } else {  //若不满足，判断此商品是否大于活动折扣了的价格
                            if ($promot_info['act_type'] == 2) {
                                $promot_price = $goods_total_price * (1 - ($promot_info['act_type_ext'] / 10));//折扣的价格
                            } else {
                                $promot_price = $promot_info['act_type_ext'];
                            }
                            if ($price > $promot_price) {    //若大于，则退款金额=商品总价-活动折扣的价
                                $money = $goods_total_price - $promot_price;
                                //更改此活动下的所有商品的活动为无效
                                $p_map=$data=array();
                                $p_map['order_id']=$key;
                                $p_map['promot_id']=$va['promot_id'];
                                $data['is_pro_enable']=1;
                                M("OrderGoods")->where($p_map)->save($data);
                                $return['data'][$key]['order_goods'] = $val;
                            } else {
                                $return['data'][$key]['money']=$order_info['goods_allmoney'];
                                $return['list'] .= $order_info['order_sn'] . "订单因参与" . $promot_info['act_name'] . "活动,若退款后，此活动不满足,所以不允许退款,若想退款则可以退当前的整个订单,您确定要退整个订单吗？";
                                $return['status'] = 1;
                                return $return;
                                break;
                            }
                        }
                    }
                }

                //计算商品红包
                if ($order_info['bonus_id']) {
                    $map['id'] = $order_info['bonus_id'];
                    $bonus_info = M("MemberBonus")->where($map)->field('min_goods_money,bonus_name')->find();
                    if ($price > $bonus_info['min_goods_money']) {//若满足则可直接按商品原价退商品，
                        $money = $price;
                    } else {
                        $return['list'] .= $order_info['order_sn'] . "订单因使用" . $bonus_info['bonus_name'] . "红包,若退款后，此红包不满足,所以不允许退款,若想退款则可以退当前的整个订单,您确定要退整个订单吗？";
                    }
                }
                $return['data'][$key]['order_goods'] = $val;

            }else{
                $money=$order_info['goods_allmoney'];
            }
            $return['data'][$key]['money']=$money;
            $return['status']=1;
        }
        return $return;
    }

    /**申请退款
     *@param postdata=> Array (
     * [data] => Array (    订单信息
     *          [20] => Array (
     *                  [money] => 0    应退的余额
     *                  [order_goods] => 17 订单商品
     *              )
     *           )
     * [content] => 123456 退款理由
     * )
     */
    public function refund_audit($postdata){
        $return=array("status"=>0,"msg"=>'');
        if($postdata['order_type']==10){
            $memberinfo=checkshopauthtype();
            $type=1;
        }else{
            $memberinfo=checkuserauthtype();
            $type=0;
        }

        if(empty($memberinfo)){
            $return['msg']="您没登录，请登录";
            return $return;
        }
        $refund_order=$postdata['data'];
        foreach($refund_order as $key=>$val){
            if($type==1){//门店向仓库订货的商品
                $storage_id=idtoname($key,'OrderInfo','storage_id');
                if($storage_id>0){
                    $type=2;
                }
            }
			//验证订单是否可以退款
			$result=$this->check_refund_audit($key);
           // print_r($result);exit;
			if($result['status']==0)return $result;
			
            $goods_map['order_id']=$key;
            if(isset($val['order_goods'])){//退订单商品
                $goods_map['id']=array("in",$val['order_goods']);
                $goods_data['status']=3; //退款中
                M("OrderGoods")->where($goods_map)->save($goods_data);
                $refund_data['order_goods']=$val['order_goods'];
				
				//是否要改变订单状态
				$od_map['order_id']=$key;
				$od_map['status']=array('lt',2);
				$have=M('OrderGoods')->where($od_map)->count();
				if(!$have){
					$od_save['status']=6;//订单改为退款中
					M('OrderInfo')->where('id='.$key)->save($od_save);
				}
				
				//是否退运费
				$order_info=M('OrderInfo')->where('id='.$key)->field('delivery_fee,shipping_status')->find();
				$g_map['order_id']=$key;
				$g_map['status']=array('neq',3);
				$is_have=M("OrderGoods")->where($g_map)->count();
				if($is_have > 0){//不退运费
					$money=$val['money'];
				}else{
					if($order_info['shipping_status']==1){//退运费
						$money=$val['money']+$order_info['delivery_fee'];
					}else{//不退运费
						$money=$val['money'];
					}
				}
            }else{//退整个订单
				$go_map['order_id']=$key;
				$go_map['status']=0;
				$order_goods= M("OrderGoods")->where($go_map)->getField('id',true);
				$order_goods=implode(',',$order_goods);
				$refund_data['order_goods']=$order_goods;
				
                $map['id']=$key;
                $order_info=M("OrderInfo")->where($map)->field("order_amount,delivery_fee,shipping_status")->find();
                $goods_map['order_id']=$key;
                $goods_data['status']=3; //退款中
                M("OrderGoods")->where($goods_map)->save($goods_data);
				
				//订单改为退款中
				$od_save['status']=6;
				M('OrderInfo')->where('id='.$key)->save($od_save);
				
				//是否退运费
				if($order_info['shipping_status']==1){//退运费
					$money=$order_info['order_amount'];
				}else{//不退运费
					$money=$order_info['order_amount']-$order_info['delivery_fee'];
				}
            }
            //修改商品退款状态
            $refund_data['reason']=$postdata['content'];
            $refund_data['type']=0;
            //添加退款单
            $data=$this->add_refund($money,$key,$refund_data,$type);
			if($data){
                if($postdata['order_type']==10){
                    action_log('user_refund_audit', 'Shop', $data, $memberinfo['shop_id']);//会员退款日志
                }else{
                    action_log('user_refund_audit', 'Member', $data, $memberinfo['id']);//会员退款日志
                }
            }
            $shop_id=M('OrderInfo')->where('id='.$key)->getField('shop_id');
        }
        if($data){
            $return['status']=1;
            $return['msg']="退款申请已提交，请等待审核";
            return $return;
        }else{
            $return['status']=0;
            $return['msg']="退款申请提交失败";
            return $return;
        }
		return $return;
    }
	/**验证订单是否可以退款
     * @param $order_id 订单id
     */
	public function check_refund_audit($order_id){
		$return=array("status"=>0,"msg"=>'');
		if(empty($order_id)){$return['msg']='请选择要退款的订单';return $return;}
		$order_info=idtoname($order_id,'OrderInfo','order_sn,status,shipping_status','id',false);
		$order_sn=$order_info['order_sn'];
		if($order_info['status']>=3){$return['msg']='订单'.$order_sn.'已完成不能退款';return $return;}
		if($order_info['shipping_status']>=3){$return['msg']='订单'.$order_sn.'已发货不能退款';return $return;}
		$return['status']=1;
		return $return;
	}
	/**生成退款单
     * @param $data=array(
        order_goods 订单商品id，
     *  reason      退款理由
     *  )
     * @param $money 退款金额
     * @param $order_id 订单id
     * @param $type 0默认，1门店向供货商订货商品，2门店向仓库订货商品,3外卖服务
     */
  public function add_refund($money,$order_id,$data,$type=0){
        if($type==1){
            $storage_id = idtoname($order_id,'OrderInfo','storage_id');
            if($storage_id>0){
                $type=2;
            }
        }
        //查询支付单
        $o_where['is_delete'] = 0;
        $o_where['order_id'] = array("like", "%," . $order_id . ",%");
        $pay_info = M("PayLog")->where($o_where)->field(true)->find();

        //返回余额
        $refund_scores=$refund_money=$refund_web=$total_refund_money=0;
        $total_refund_money=$money;
        if($total_refund_money>0 && $pay_info['use_score_money']>0){//积分支付
            if($pay_info['use_score_money']<$total_refund_money){
                $score_money=$pay_info['use_score_money'];
                $refund_scores=$pay_info['use_score'];
                $total_refund_money=$total_refund_money-$pay_info['use_score_money'];
            }else{
                $refund_scores=$pay_info['use_score'];
                $score_money=$total_refund_money;
                $total_refund_money=0;
            }
        }
    if($total_refund_money>0 && $pay_info['use_money']>0){//余额支付
        if($pay_info['use_money']<=$total_refund_money){
            $refund_money=$pay_info['use_money'];
            $total_refund_money=$total_refund_money-$pay_info['use_money'];
        }else{
            $refund_money=$total_refund_money;
            $total_refund_money=0;
        }
    }
    if($total_refund_money>0){ //剩下的部分全部是网银
        $refund_web=$total_refund_money;
    }
		$refund_data['order_id']=$order_id;
		$refund_data['order_goods']=$data['order_goods'];
		$refund_data['money']=$refund_money+$score_money+$refund_web;
		$refund_data['refund_money']=$refund_money;
		$refund_data['refund_scores']=$refund_scores;
		$refund_data['refund_web']=$refund_web;
		$refund_data['payment_id']=$pay_info['payment_id'];
		$refund_data['payment_code']=$pay_info['payment_code'];
		$refund_data['reason']=$data['reason'];
		$refund_data['addtime']=NOW_TIME;
		$refund_data['status']=$data['type'];
		$refund_data['uid']=$pay_info['user_id'];
    $refund_data['type']=$type;
		$refund_data['shop_id']=idtoname($order_id,'OrderInfo','shop_id');
		$result=M("RefundOrder")->add($refund_data);
		return $result;
	}
    /** 原路退回并且作废支付单取消分成操作（暂时适用于退款和取消订单）
     * @param $pay_money 	将要退款的商品总价
     * @param $order_id 	订单id
     * @param $type 		Admin:操作日志
     * @param $admin_id 	管理员ID
     * @param $refund_type     退货类类型 0：普通退款，1：门店向供货商订货退款，2门店向仓库订货退款
     */
    public function handle_order($refund_id,$type,$admin_id,$refund_type=0){
        $return=array("status"=>0,"msg"=>'');
        if(!$refund_id){$return['msg']="参数错误";return $return;}
        $where['id']=$refund_id;
        $refund_info=M("RefundOrder")->where($where)->field(true)->find();
        if(empty($refund_info)){$return['msg']="没有退款信息";return $return;}
        //查询支付单
        $o_where['is_delete'] = 0;
        $o_where['order_id'] = array("like", "%," . $refund_info['order_id'] . ",%");
        $pay_info = M("PayLog")->where($o_where)->field(true)->find();
        if(empty($pay_info)){$return['msg']="支付单已处理";return $return;}
		
        //获取订单信息
        $order_where['id']=$refund_info['order_id'];
        $order_info=M("OrderInfo")->where($order_where)->field(true)->find();
        if(empty($order_info)){$return['msg']="没有订单信息";return $return;}
        //如果是退货生成的 判断退货单是否同意了
        $org_map['uid']=$refund_info['uid'];
        $org_map['order_id']=$refund_info['order_id'];
        $org_map['org_id']=$refund_info['order_goods'];
        $reg_info=M('ReturnGoods')->where($org_map)->field('id,status,shop_status')->find();
        if(!empty($reg_info)){
	if($reg_info['status']==0 || $reg_info['shop_status']==0 ){
	    $return['msg']='请先处理退货单';
	  if($refund_type==1){
	      $return['url']=U('TuiHuo/index',array('id'=>$reg_info['id']));
	  }elseif($refund_type==2){
	      $return['url']=U('Storage/refund_goods',array('id'=>$reg_info['id']));
	  }else{
	      $return['url']=U('TuiHuan/index',array('id'=>$reg_info['id']));
	  }
		return $return;
	}
	    if($order_info['status']==8){//退货中改为已退货
		    $od_save['status']=9;
		    M('OrderInfo')->where('id='.$refund_info['order_id'])->save($od_save);
	    }
        }else{
	    $og_map['status']=4;
	    $og_where['id']=array('in',$refund_info['order_goods']);
	    M('OrderGoods')->where($og_where)->save($og_map);//退款的把订单商品状态改为已退款
	    if($order_info['status']==6){//退款中改为已退款
		$od_save['status']=7;
		M('OrderInfo')->where('id='.$refund_info['order_id'])->save($od_save);
	    }
        }
        if($order_info['type']==1 || ($order_info['type']==10 && !$order_info['storage_id'])){
            //加库存
            $g_where['order_id']=$refund_info['order_id'];
            $g_where['id']=array("in",$refund_info['order_goods']);
            $order_goods=M('OrderGoods')->where($g_where)->field('goods_id,goods_number,goods_attr')->select();
            foreach($order_goods as $ke=>$vo){
                if($vo['goods_attr']){
                    $attr=unserialize($vo['goods_attr']);
                    $attr_map['goods_id']=$vo['goods_id'];
                    $attr_map['attr_key']=$attr['key'];
                    M('GoodsAttrStock')->where($attr_map)->setInc('stock_cfg',$vo['goods_number']);
                }else{
                    M('Goods')->where('id='.$vo['goods_id'])->setInc('goods_number',$vo['goods_number']);
                }
            }
        }

        //修改服务记录

        if($order_info['type'] == 11){
	    $s_where['order_id']=$order_info['id'];
	    $mp_id = M('MemberPackage')->where($s_where)->getField('id');
	    $mp_map['id'] = $mp_id;
	    $s_save['status'] = 2;
	    M('MemberPackage')->where($mp_map)->save($s_save);
        }
        //执行退款
        if($refund_info){
            if($refund_type==1 || $refund_type==2){
                if($refund_info['refund_web']>0){//退网银
                    //shop_balance_log($pay_info['user_id'],$refund_info['refund_web'],1,5,'取消订单'.$order_info['order_sn']);
                    $this->refund($pay_info['user_id'],$refund_info['refund_web'],$order_info['order_sn'],1);
                }
                if($refund_info['refund_money']>0){//退余额
                    shop_balance_log($pay_info['user_id'],$refund_info['refund_money'],6,5,'取消订单'.$order_info['order_sn']);
                }
                
            }else{
                if($refund_info['refund_web']>0){//退网银
                    //account_change($pay_info['user_id'],$refund_info['refund_web'],1,4,'取消订单'.$order_info['order_sn']);
                    $this->refund($pay_info['user_id'],$refund_info['refund_web'],$order_info['order_sn'],1);
                }
                if($refund_info['refund_money']>0){//退余额
                    account_change($pay_info['user_id'],$refund_info['refund_money'],1,8,'取消订单'.$order_info['order_sn']);
                }
                if($refund_info['refund_scores']>0){//退积分
                    account_change($pay_info['user_id'],$refund_info['refund_scores'],4,8,'取消订单'.$order_info['order_sn']);
                }
            }

            //作废支付单
            $p_where['is_delete'] = 0;
            $p_where['order_id'] = array("like", "%," . $refund_info['order_id']. ",%");
            $o_data['is_delete']=1;
            $del_pay= M("PayLog")->where($p_where)->save($o_data);
			
            //重新生成支付单
            $order_ids=explode(',',$pay_info['order_id']);
            foreach(array_filter($order_ids) as $key=>$val){
                if($val==$refund_info['order_id']){
                    $org_maps['status']=array('in',array(0,1));
                    $org_maps['order_id']=$refund_info['order_id'];
                    $is_del=M('OrderGoods')->where($org_maps)->count();
                    if(!$is_del)unset($val);
                }
                if($val==0){
                    unset($val);
                }
                $pay_order_id[]=$val;
            }
            $pay_order_id=array_filter($pay_order_id);
            if(!empty($pay_order_id)){
                $payment_id=','.implode(',',$pay_order_id).',';
                $use_money=$pay_info['use_money']-$refund_info['refund_money'];
                $use_score=$pay_info['use_score']-$refund_info['refund_scores'];
                $use_web=$pay_info['pay_amount']-$refund_info['refund_web'];
                $need_pay=$pay_info['need_pay']-$refund_info['refund_web'];
                $payment=array();
                $payment['pay_sn']=$order_info['pay_sn'];
                $payment['order_sn']=$order_info['order_sn'];
                $payment['order_id']=$payment_id;
                $payment['type']=$order_info['type'];
                $payment['shop_id']=$order_info['shop_id'];
                $payment['shop_id']=$order_info['shop_id'];
                $payment['user_id']=$order_info['uid'];
                $payment['need_pay']=$need_pay;
                $payment['use_money']=$use_money;
                $payment['use_score']=$use_score;
                $payment['use_score_money']=$use_score*C('WEB_INTEGRAL_RATIO')/100;
                $payment['pay_amount']=$use_web;
                $payment['order_total_price']=$use_web+$use_money+$use_score;
                $payment['payment_id']=$pay_info['payment_id'];
                $payment['pay_code']=$pay_info['pay_code'];
                $payment['is_paid']=$pay_info['is_paid'];
                $payment['create_time']=NOW_TIME;
                M("PayLog")->add($payment);

            }
            //如果订单支付成功则取消订单分成
            if($order_info['pay_status']==3){
                if($refund_type==1){
                    //取消订单分成
                    $where['order_id']=$refund_info['order_id'];
                    $data['is_separate']=2;
                    M("AffiliateLog")->where($where)->save($data);
                    // 获取结算价
                    $price_info = get_balance_suprice($order_info['id']);
                    //减少供货商未结算金额、销售总额
                    supplier_balance_log($order_info['shop_id'], -$price_info['price'], 2,3,'订单' . $order_info['order_sn'] . '取消,未结算总额减少', $order_info);

                    supplier_balance_log($order_info['shop_id'], -$price_info['price'], 5, 3, $order_info['order_sn'] . '订单取消,未结算总额减少', $order_info);
                }else {
                    //取消订单分成
                    $where['order_id'] = $refund_info['order_id'];
                    $data['is_separate'] = 2;
                    M("AffiliateLog")->where($where)->save($data);
                    //减少店铺待结算金额
                    if (empty($order_info['storage_id'])) {
                        shop_balance_log($order_info['shop_id'], -$refund_info['money'], 2, 3, '订单' . $order_info['order_sn'] . '付款,未结算总额减少', $order_info);
                    }
                }

            }
        }
        //确认退款单
        $refund_map['id']=$refund_id;
        $refund_data['status']=1;
        $refund_data['update_time']=NOW_TIME;
        M("RefundOrder")->where($refund_map)->save($refund_data);
		if($type && $admin_id)action_log('admin_do_refund', $type, $refund_id, $admin_id);
    $return['status']=1;
    $return['msg']='退款成功';
    if($refund_info['refund_money']>0 || $refund_info['refund_web']>0){
        $code_data=array();
        //退款通知
        $code_data['to'] = $order_info['mobile'];
        $code_data['order_sn'] = $order_info['order_sn'];
        $code_data['shop_name'] = idtoname($order_info['shop_id'],'Shops','name');
        if($order_info['pay_code']){
            $code_data['payment'] = idtoname($order_info['pay_code'],'Payment','name','code',false)==false?'':idtoname($order_info['pay_code'],'Payment','name','code',false);
        }else{
            $code_data['payment'] = '余额支付';
        }
        $code_data['tui_money'] = $refund_info['money'];
        $code_data['tui_time'] = time_format(NOW_TIME);
        sendbytheme($code_data, 'REFUND_MONEY');
        }
        return $return;
    }
	/**
	 * 所有订单信息
	 * @param $postdata['uid'] int  会员id
	 * @order_status $type int  订单状态  1：全部订单，2：待付款，3：待发货，4：待收货，5：待评论,6：拼团订单
	 * @is_num $is_num true  只取数量
	 * @page_num $page_num int  每页显示的订单数量
	 * @field  string  要查询的订单字段
     * @type  ordertype 订单类型1商品2会员充值3积分4其它5店铺充值 10订货商品11服务12店铺订单13店铺收银 14外卖订单
	 * @return  mixed
	 */
	public function all_order($postdata,$type=1,$is_num=0,$page_num=5,$field=true,$ordertype=1){
        if($ordertype==10){
            $member_info=checkshopauthtype();
            $uid=$member_info['shop_id'];
        }else{
            $member_info=checkuserauthtype();
            $uid=$member_info['id'];
        }
		    $map['uid']=$uid;$map['is_delete']=0;
        if(!empty($type)) {
            if ($type == 'no_pay' || $type == 2) {
                $map['pay_status'] = 1;
                $map['status'] = array('lt', 3);
                $map['type'] = array('in', '1,3,11,12,14,6');
            } elseif ($type == 'no_ship' || $type == 3) {
      				// $map['pay_status']=3;$map['shipping_status']=1;$map['status']=array('lt',3);
      				//判断是否有配送状态限制（打印外卖小票时用）
      				if($postdata['is_shipping']==1){
      					$map['pay_status']=3;$map['status']=array('lt',3);
      				}else{
      				  $map['pay_status']=3;$map['shipping_status']=array('in','1,5');$map['status']=array('lt',3);
      				} 
            } elseif ($type == 'yes_ship' || $type == 4) {
                $map['pay_status'] = 3;
                $map['shipping_status'] = 3;
                $map['status'] = array('lt', 3);
            } elseif ($type == 'no_comment' || $type == 5) {
                $map['status'] = 3;
                $map['is_comment'] = 0;
            } elseif ($type == 'no_group' || $type == 6) {
                $map['pay_status'] = 3;
                $map['shipping_status'] = 6;
            }elseif ($type == 'group') {
                $map['pay_status'] = 3;
                // $map['shipping_status'] = array('neq',6);
				        $map['shipping_status'] = array('not in','6,7');
            }elseif ($type == 'service_order' || $type == 7) {
                $map['pay_status'] = 3;
                $map['shipping_status'] = 3;
                $map['status'] = array('lt',3);
                // $map['type'] = array('IN', '11,12');
            } elseif ($type == 'no_ship' || $type == 8) {
                $map['pay_status'] = 3;
                $map['shipping_status'] = 1;
                $map['status'] = array('lt', 3);
            } elseif ($type = 'tui_kuan' || $type == 9) {
                $map['pay_status'] = 3;
                $map['status'] = array('in','4,6,7,8,9');
            }
        }
        if($ordertype==10 || $ordertype==6){
            $map['type']=$ordertype;
        }elseif($ordertype==14){
            $map['type']=14;
            $map['goods_allmoney']=array('gt',0);
        }elseif($ordertype==15){
			$map['type']=array('in','1,3,6,11,12,13,14');
            if($type != 3){
                $map['shipping_status'] = array('neq',6);
            }
		}elseif($ordertype==7){
			$map['type']=array('in','11,12');
		}else{
            $map['type']=array('in','1,3,6,11,14');
        }
		if($is_num){$all_order['num']=M('OrderInfo')->where($map)->count();return $all_order;}
		//搜索条件
		if(!empty($postdata['time_form']))$map['addtime'][]=array('egt',strtotime($postdata['time_form']));
		if(!empty($postdata['time_to']))$map['addtime'][]=array('elt',strtotime($postdata['time_to']));
		
		if(!empty($postdata['keyword'])){
			$search_map['goods_name']=array('like','%'.$postdata['keyword'].'%');
			$search_goods=M('OrderGoods')->where($search_map)->getField('order_id',true);
			if($search_goods)$whereor['id']=array('in',$search_goods);
			$whereor['order_sn']=$postdata['keyword'];
			$whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
		}
		//打印外卖小票时用
        if($postdata['order_sn']){
            $map['order_sn']=$postdata['order_sn'];
        }
		$page=empty($postdata['page'])?1:$postdata['page'];
		$all_order=page_list('OrderInfo',$map,'id desc',$field,$page_num,'',$page);
		//格式化订单数据
		if($all_order){
			foreach($all_order['list'] as $k=>$v){
				$goods_info['all_num']=$goods_info['num']=0;
				$all_order['list'][$k]=$v;
                if($v['type']==3){
                    $all_order['list'][$k]['goods_amount']=$v['goods_amount']-$v['used_score_money'];
                }else{
                    $all_order['list'][$k]['goods_amount']=$v['goods_amount'];
                }
				$goods_map['order_id']=$v['id'];
				$goods_info['num']=M('OrderGoods')->where($goods_map)->count();
				if($goods_info['num']) {
				    $goods_info['list']=M('OrderGoods')->where($goods_map)->getField('id,goods_id,goods_name,goods_attr,goods_price,goods_number,status,goods_integral',true);
                    foreach ($goods_info['list'] as $ke => $vo) {
                        $attr = unserialize($vo['goods_attr']);
                        $goods_info['list'][$ke] = $vo;
                        $goods_info['all_num'] += $vo['goods_number'];
                        $goods_info['list'][$ke]['goods_price'] = $vo['goods_price'];
                        $goods_info['list'][$ke]['img'] = idtoname($vo['goods_id'], 'Goods', 'img');
                        $goods_info['list'][$ke]['attr_name'] = $attr['name'];
                        $goods_info['list'][$ke]['status'] = $vo['status'];
                        $goods_info['list'][$ke]['goods_number']=intval($vo['goods_number']);
                    }
					$all_order['list'][$k]['goods']=$goods_info;
                }
			}
			
			if($all_order['count'] > $page_num*$page){
				$all_order['show'] = 1;
			}else{
				$all_order['show'] = 0;
			}
		}
		return $all_order;
	}
	
	/**
	 * 修改运费
	 * @param $post mixed
	 * @return  mixed  
	*/
	public function change_ship_free($post){
		$return=array('status'=>0,'info'=>'');
		//订单信息
		$order_id=$post['id'];$free=$post['free'];
		$info=M('OrderInfo')->where('id='.$order_id)->field('order_amount,delivery_fee')->find();
		if($free >= $info['delivery_fee']){$return['info']='运费应小于默认运费';return $return;}
		$change_num=$info['delivery_fee']-$free;//运费改变量
		
		if($post['type']=='Shop'){
			$is_have['shop_id']=$post['admin_id'];
			$is_have['id']=$order_id;
			$yes=M('OrderInfo')->where($is_have)->count();
			if(!$yes){$return['info']='无此操作权限';return $return;}
		}
		
		//付款单信息
		$where['is_delete'] = 0;
		$where['order_id'] = array("like", "%," . $order_id . ",%");
		$pay_info = M("PayLog")->where($where)->field(true)->find();
		if($change_num > $pay_info['need_pay']){$return['info']='改变量超出应付款金额';return $return;}
		
		//修改订单信息
		$order_save['order_amount']=$info['order_amount']-$change_num;//修改订单应付款金额
		$order_save['delivery_fee']=$free;//修改运费金额
		M('OrderInfo')->where('id='.$order_id)->save($order_save);
		
		//作废旧付款单
		$old_save['is_delete']=1;
		$old_save['update_time']=NOW_TIME;
		M("PayLog")->where($where)->save($old_save);
		
		//生成新付款单
		unset($pay_info['id']);
		$pay_info['need_pay']=$pay_info['need_pay']-$change_num;
		$pay_info['order_total_price']=$pay_info['order_total_price']-$change_num;
		$pay_info['create_time']=NOW_TIME;
		M("PayLog")->add($pay_info);
		
		$return['status']=1;
		$return['info']='修改成功';
		
		if($post['type']=='Shop'){
			action_log('shop_ship_free', 'Shop', $order_id, $post['admin_id']);//操作日志
		}elseif($post['type']=='Admin'){
			action_log('admin_ship_free', 'Admin', $order_id, $post['admin_id']);//操作日志
		}
		return $return;
		
	}
    /**作废支付单，并切退回已支付的金额
     * @param $pay_id 支付单id
     */
    public function cancel_pay($pay_id){
        $root=array('status'=>0,'msg'=>'');
        if(!$pay_id){
            $root['msg']="无效的支付单";return $root;
        }
        $where['id']=$pay_id;
        $where['is_delete']=0;
        $pay_info=M("PayLog")->where($where)->field(true)->find();
		
        if(empty($pay_info)){
            $root['msg']="无效的支付单信息";return $root;
        }
        if($pay_info['use_money']){
            $msg="作废支付单，退回支付的余额";
            account_change($pay_info['user_id'],$pay_info['use_money'],1,3,$msg);
        }
        if($pay_info['use_score']){
            $msg="作废支付单，退回支付的积分";
            account_change($pay_info['user_id'],$pay_info['use_score'],4,3,$msg);
        }
        //改变支付单的状态
        $data['is_delete']=1;
        $data['update_time']=NOW_TIME;
        $res=M("PayLog")->where($where)->save($data);
        if($res){
            $root['status']=1;return $root;
        }else{
            $root['msg']="修改支付单失败";return $root;
        }
    }

    /**继续付款
     * @param array $order_id 订单id
     * @return array 返回值
     */
    public function continu_pay($order_id=array()){
        $root=array('status'=>0,'msg'=>'');
		
        if(empty($order_id)){$root['msg']="请选择订单";return $root;}
		//转化为数组order_ids
		$order_ids=array();
		if(!is_array($order_id)){
			$order_ids[]=$order_id;
		}else{
			$order_ids=$order_id;
		}
		$order_ids=array_filter($order_ids);
		foreach ($order_ids as $key => $id) {
			$where['is_delete'] = 0;
			$where['order_id'] = array("like", "%," . $id . ",%");
			$pay_info = M("PayLog")->where($where)->field(true)->find();
			if (!$pay_info) {$root['msg'] = "没有支付单信息";return $root;}

            //拼团是否过期
            $act_id = idtoname($id,'OrderInfo','pt_id');
            if(!empty($act_id)){
                $p_end = idtoname($act_id,'PromotAct','end_time');
                if($p_end < NOW_TIME){
                    $status['status'] = 10;
                    M('OrderInfo')->where('id='.$id)->save($status);
                    $root['msg'] = "该团已过期,此订单过期,不可付款";
                    return $root;
                }
                //参加的团是否已过期，已成团
                $pid = idtoname($id,'OrderInfo','pid');
                if(!empty($pid)){
                    $p_begintime = idtoname($pid,'OrderInfo','confirm_time');
                    $group_time_limit = idtoname($act_id,'PromotAct','group_time_limit');
                    $p_ends = idtoname($act_id,'PromotAct','end_time');
                    $end_time = $p_begintime + ($group_time_limit * 3600);
                    // if($end_time < NOW_TIME || $end_time > $p_ends){
                    if($end_time < NOW_TIME || $p_ends < NOW_TIME){
                        $status['status'] = 10;
                        M('OrderInfo')->where('id='.$id)->save($status);
                        $root['msg'] = "该团已过期,此订单过期,不可付款2";
                        return $root;
                    }
                    $group_number = idtoname($act_id,'PromotAct','group_number');
                    $map['pid'] = $pid;
                    $map['status'] = 2;
                    $map['pay_status'] = 3;
                    $map['shipping_status'] = 5;
                    $now_count = M('OrderInfo')->where($map)->count();
                    $number = $group_number - $now_count -1;
                    if(empty($number)){
                        $status['status'] = 10;
                        M('OrderInfo')->where('id='.$id)->save($status);
                        $root['msg'] = "该团已成团,此订单过期,不可付款";
                        return $root;
                    }
                }
            }

		}
		$root['status']=1;
		$root['order_id']=implode(',',$order_ids);
        return $root;
    }

    /**继续付款计算总价
     * @param $order_id 以逗号分隔的字符串
     * @param $ordertype 订单类型 10订货订单
     */
    public function count_order_total($order_id,$type=1,$score=0,$use_account=0,$account_money=0,$payment_id=0){
        $root=array('status'=>0);
        $goods_integral=0;
        $root['status']=0;
        $total_price=0;
        if($type==10){
            $memberinfo=checkshopauthtype();
            $where_s=array();
            $where_s['id']=$memberinfo['shop_id'];
            $shopsinfo=M('Shops')->where($where_s)->field('total_revenues')->find();
        }else{
            $memberinfo=checkuserauthtype();
        }
        if(empty($memberinfo)){$root['msg']="请登录";return $root;}
        if(!$order_id){
            $root['msg']="参数无效";
            return $root;
        }
            $where['id'] = array("in", $order_id);
            $order_info = M("OrderInfo")->where($where)->field(true)->select();
            foreach ($order_info as $k => $val) {
                $total_price+=$val['order_amount'];
                if($val['type']==3){
                    $goods_integral+=$val['used_score'];
                }
            }
            if($score>0) {
                //可使用积分的总额=商品总价-活动优惠的价格-红包/优惠抵扣的价格
                if($type==1 || $type==6 || $type==14) {
                $score_use_total = $total_price;
                $order_score =intval($score_use_total * (C('INTGRAL_PAY_RATIO') / 100) * 100 / C('WEB_INTEGRAL_RATIO'));//该订单可使用多少积分
                if ($memberinfo['usepoints'] > 0) {
                    if ($memberinfo['usepoints'] >= $order_score) {
                        $use_score = $order_score * (C('WEB_INTEGRAL_RATIO') / 100);//钱
                        $pay_score = intval($order_score);//分
                    } else {
                        $use_score = $memberinfo['usepoints'] * (C('WEB_INTEGRAL_RATIO') / 100);
                        $pay_score = intval($memberinfo['usepoints']);
                    }
                }
                $use_score_money =$use_score;
            }else {
                    $score_use_total = $goods_integral * C('WEB_INTEGRAL_RATIO') / 100;
                    if ($memberinfo['usepoints'] > 0) {
                        if ($memberinfo['usepoints'] >= $score_use_total) {
                            $use_score = $score_use_total;
                            $pay_score = $goods_integral;
                        } else {
                            $use_score = $memberinfo['usepoints'];
                            $pay_score = $use_score;
                        }
                    }
                    $use_score_money = intval($use_score);
                }
           /*     if($memberinfo['usepoints']>0){
                    if($memberinfo['usepoints']>=$score_use_total){
                        $use_score=$score_use_total*C('INTGRAL_PAY_RATIO')/100;
                    }else{
                        $use_score=$memberinfo['usepoints']*C('INTGRAL_PAY_RATIO')/100;
                    }
                }
                $use_score_money=$use_score*C('WEB_INTEGRAL_RATIO')/100;*/
            }
            if($account_money<=0)$account_money=0;
            //余额支付
        if($type==10){
            if($shopsinfo['total_revenues']>0){
                $pay_price=$total_price;
                if($use_account==1 && $account_money==0){
                    $account_money=$shopsinfo['total_revenues'];
                }else if($use_account==1 && $account_money>0){
                    $account_money=$account_money;
                }
                if($account_money>$pay_price){
                    $account_money=$pay_price;
                }
            }else{
                $account_money=$shopsinfo['total_revenues'];
            }
        }else{
            if($memberinfo['money']>0){
                $pay_price=$total_price-$use_score_money;
                if($use_account==1 && $account_money==0){
                    $account_money=$memberinfo['money'];
                }else if($use_account==1 && $account_money>0){
                    $account_money=$account_money;
                }
                if($account_money>$pay_price){
                    $account_money=$pay_price;
                }
            }else{
                $account_money=$memberinfo['money'];
            }
        }
            //支付信息
            if($payment_id>0 && $payment_id!=1){
                $payment_info=idtoname($payment_id,'Payment','*');
                $counter_fee=$payment_info['fee'];
            }
            $pay_price=$total_price-$use_score_money-$account_money;
            if($counter_fee>0){
            $pay_fee=$pay_price*$counter_fee/100;//手续费
            $pay_price=$pay_price+$pay_fee;
        }

        $return = array('status'=>1);
        //$return['data']=$cart_list;
        $return['total_info']=array(
            'total_price'=>$total_price,//商品总价
            'total_price_show'=>format_price($total_price-$use_score_money)."+ ".$pay_score."分",//商品总价
            'pay_price'=>$pay_price,//线上支付价格
            'pay_fee'=>$pay_fee,//手续费
            'score'=>$pay_score,//使用的积分
            'use_score_money'=>$use_score_money,//积分抵扣的价格
            'account_money'=>$account_money,//使用余额
            'payment_info'=>$payment_info,//使网银支付信息
            'pay_total_price'=>	$total_price,//订单实际支付的金额=商品总价+总运费-活动折扣-红包折扣
            'order_type'=>$type

        );
        return $return;
    }

    /**提交继续付款订单
     * @param $param
     * @param $param['ids'] 订单号  以逗号分隔的字符串
     */
    public function sub_continue_order($param){
        $return=array();
        $memberinfo=checkuserauthtype();
        $return['status']=0;
        $order_id=$param['ids'];//以逗号分隔的字符串
        $score=$param['score'];//积分
        $use_account=$param['use_account'];//是否全额使用
        $account_money=$param['account_money'];//余额
        $payment_id=$param['payment_id']?$param['payment_id']:0;//支付方式
        $pay_pwd=$param['pay_pwd'];//交易密码
        $type=$param['type'];//交易密码
        if($account_money >0 || $score >0 ){
            $return['status']=3;
            if($pay_pwd==''){
                $return['msg']='请输入支付密码';
                return $return;
            }

            $m['id']=$memberinfo['id'];
            $userinfo=M("Member")->where($m)->field('paypassword,salt')->find();
            if($userinfo['paypassword'] == ''){
                $return['msg']="您没设置交易密码,请设置交易密码";
                $return['wxsmall']=3;
                $return['url']=getjumpurl('JUMP_3');
                return $return;
            }

            if($pay_pwd=='' || creatpwd($pay_pwd,'HANCHAO'.$userinfo['salt']) != $userinfo['paypassword']){
                $return['msg']='支付密码错误';
                return $return;
            }
        }
        //判断活动是否过期
        if($type == 6){
            $act_id = idtoname($order_id,'OrderInfo','pt_id');
            $end_time = idtoname($act_id,'PromotAct','end_time');
            if($end_time<NOW_TIME){
                $y_map=array();
                $y_map['id']=array('in',$order_id);
                if($type==6){
                    $status['status'] = 10;
                    M('OrderInfo')->where($y_map)->save($status);
                }else{
                    $status['status'] = 4;
                    M('OrderInfo')->where($y_map)->save($status);
                }
                $return['msg']='活动已过期,不可付款';
                return $return;
            }
        }
        $where=array();
        $where['o.id']=array("in",$order_id);
        $order_info=M("OrderInfo")->alias('o')->where($where)->JOIN('LEFT JOIN __ORDER_GOODS__ g ON o.id=g.order_id')->field('o.*,g.*')->select();
        //计算订单总金额
        if($type == 6){
            $data=$this->count_order_total($order_id,$type,$score,$use_account,$account_money,$payment_id);
        }else{
            $data=$this->count_order_total($order_id,1,$score,$use_account,$account_money,$payment_id);
        }
        if($data['total_info']['pay_price']>0 && $payment_id<=0){$return['msg']='请选择支付方式';$return['app_paydata']='app_notpay';return $return;}
        //判断提交的订单有没有支付单，如果有作废
        // $log_map=array();
        // $log_map['is_delete'] = 0;
        // 2-19 zjn
        // if(strpos($order_id,',')!==false){
        //   $log_map['order_id'] = $order_id;
        // }else{
        //   $log_map['order_id'] = array("like", "%," . $order_id . ",%");
        // }
        // $return['log_map']=$log_map;
        // ----end-----
        
        // $log_info = M("PayLog")->where($log_map)->field(true)->find();
        // zjn 3-11
        $order_ids=explode(',',$order_id);
       foreach($order_ids as $ke=>$id){
            $log_map=array();
            $log_map['is_delete'] = 0;
            if(strpos($id,',')!==false){
              $log_map['order_id'] = $order_id;
            }else{
              $log_map['order_id'] = array("like", "%," . $id . ",%");
            }
            $log_id = M("PayLog")->where($log_map)->getField('id');//->field(true)->find();
            if($log_id){
                $result = $this->cancel_pay($log_id);
                if($result['status']==0)return $result;
            }
        }
        $payment_info=array();
        if(strpos($order_id,',')!==false){
          $payment_info['order_id'] = $order_id;
        }else{
          $payment_info['order_id'] = ",".$order_id.",";
        }
        // $payment_info['order_id']=",".$order_id.",";
        $payment_info['user_id']= $memberinfo['id'];
        $payment_info['shop_id']= $order_info[0]['shop_id']; // zjn
        $payment_info['type']=$type;
        $payment_info['order_sn']= createOrderNo();
        $payment_info['use_money']=$data['total_info']['account_money'];//余额
        $payment_info['need_pay']=$data['total_info']['pay_price'];//还需支付的金额
        $payment_info['use_score']=$data['total_info']['score'];//积分
        $payment_info['use_score_money']=$data['total_info']['use_score_money'];//积分所抵的钱
        $payment_info['order_total_price']=$data['total_info']['pay_total_price'];//订单实际支付的金额=商品总价+总运费-活动折扣-红包折扣
        $payment_info['payment_id']=$payment_id;//支付方式
        $payment_info['payment_fee']=$data['total_info']['pay_fee'];//手续费;//支付方式
        $payment_info['pay_amount']=0;//
        $payment_info['pay_code']=idtoname($payment_id,"Payment",'code');//支付code
        $payment_info['is_paid']=0;
        $payment_info['create_time']=NOW_TIME;

        //生成支付单
        $pay_log_id=M('PayLog')->add($payment_info);
        if($pay_log_id){
        //订单扣款
          //积分支付
          if($data['total_info']['score']){// --zjn---use_score-->score
              account_change($memberinfo['id'],-$data['total_info']['score'],4,4,'购买商品支付,订单'.$order_info[0]['order_sn']); //--zjn---use_score-->score
          }
          //余额支付
          if($data['total_info']['account_money']>0){
              account_change($memberinfo['id'],-$data['total_info']['account_money'],1,4,'购买商品支付，订单'.$order_info[0]['order_sn']);
              //account_change($memberinfo['id'],-$data['total_info']['account_money'],1,'','购买商品支付,订单'.$order_info['order_sn']);
          }
          //线上支付价格
          if($data['total_info']['pay_price']>0 && $data['total_info']['payment_info']){
              $return['pay']=$pay_log_id;//$log_info['id'];
              $return['status']=1;
              return $return;
          }
          //处理订单
          $pay_info=array();
          $pay_info['out_trade_no']=$payment_info['order_sn'];
          $pay_info['type']=$payment_info['type'];
          $res=$this->endorder($pay_info);
          if($res['status']==1){
              $return['status']=1;
              $return['data']=$order_id;
              // zjn ----begin----
              $map=$save_data=array();
              $save_data['payment_id']=$payment_id;
              $save_data['pay_code']=idtoname($payment_id,"Payment",'code');
              // $map['id']=$order_id;
              $map['id']=array('in',$order_id);
              M("OrderInfo")->where($map)->save($save_data);
              // ---------end--------
              return $return;
          }else{
              $return['msg']=$res['msg'];
              return $return;
          }
         }else{
             $return['msg']="支付单生成失败";return $return;
         }
        return $return;
    }
    public function get_continue($order_id){
        $return=array('status'=>0,'msg'=>'','url'=>'');
        if(empty($order_id)){
            $return['msg']='参数错误';
            $return['url']=getjumpurl('JUMP_4');
            return $return;
        }
        $where['id']=array("in",$order_id);
        $order_info=M("OrderInfo")->where($where)->field(true)->select();
        foreach($order_info as $key=>$val){
            $g_map['order_id']=$val['id'];
            $order_info[$key]['goods_list']=M("OrderGoods")->where($g_map)->field('goods_id,goods_name,goods_number,goods_price,goods_attr,goods_integral')->select();
            if($order_info[$key]['goods_list']){
                foreach($order_info[$key]['goods_list'] as $gk=>$gv){
                    $order_info[$key]['goods_list'][$gk]['format_goods_attr']=unserialize($gv['goods_attr']);
                    $map['id']=$gv['goods_id'];
                    $goods_info=M("Goods")->where($map)->Field('goods_weight,img')->find();
                    $order_info[$key]['goods_list'][$gk]['img']=$goods_info['img'];
                    $order_info[$key]['goods_list'][$gk]['goods_weight']=$goods_info['goods_weight'];
                    if($val['type']==3){
                        $is_addcart=3;
                        $order_info[$key]['goods_list'][$gk]['goods_total_price'] =format_price($gv['goods_price'] * $gv['goods_number'])." + ".$gv['goods_integral']*$gv['goods_number']."分";
                    }elseif($val['type']==10){
                        $is_addcart=$val['type'];
                        $order_info[$key]['goods_list'][$gk]['goods_total_price'] = format_decimal($gv['goods_price'] * $gv['goods_number']);
                    }else {
                        $is_addcart=$val['type'];
                        $order_info[$key]['goods_list'][$gk]['goods_total_price'] = format_decimal($gv['goods_price'] * $gv['goods_number']);
                    }

                }
            }
        }
        $return['data']=$order_info;
        $return['is_addcart']=$is_addcart;
        $return['status']=1;
        return $return;
    }

    /**
     * @param $postdata=array(
    'goods_id'=>商品id
     * 'number'=>数量
     * 'attr'=>属性
     * 'act'=>活动
     * 'name'=>属性名称
     * 'integra'=>付款方式（1纯积分2积分+现金）
     * 'type'=>付款方式（1商品3积分）)
     * $param $order_type  0 其他，10订货,3外卖（包括拼团）
     * @return array
     */
    public function buy_now($postdata,$order_type=0){
        $return=array('status'=>0,'msg'=>'');
        if($order_type==10){
            $memberinfo = checkshopauthtype();
        }else{
            $memberinfo = checkuserauthtype();
        }

        if(session('getdata')){
            $postdata=session('getdata');
        }
        if(is_numeric($postdata)){
          $postdata=I('param.');
        }
        $goods_id=intval($postdata['goods_id'])?intval($postdata['goods_id']):0;
        $number=intval($postdata['number'])?intval($postdata['number']):0;
        $integra=intval($postdata['integra'])?$postdata['integra']:0;
        $act=intval($postdata['act'])?intval($postdata['act']):0;
        if($postdata['goods_attr']=='undefined')$postdata['goods_attr']=0;
        $attr=$postdata['goods_attr'];
        // $attr=0;//0325临时
        $name=D("Common/GoodsAttr")->goods_to_attrname($attr);
        $type=$postdata['type'];
        /*if(cookie('dingwei_address')){
            $address_info = cookie('dingwei_address');
        }elseif(session('dingwei_address')){
            $address_info =session('dingwei_address');
        }
        if (empty($address_info)) {
            $root['status'] = 0;
            $root['msg'] = '请选择配送地区';
            return $root;
        }*/
        if($type==3){//积分商品
            if($integra<=0){
                $return['msg']="请选择付款方式";
                return $return;
            }
        }
        //验证商品
        if(C('IS_WAREHOUSE')==1&&$order_type==10){// 判断该商品是否在配送范围
            $check = D("Common/Cart")->check_carts($goods_id, $attr, $number, $name,'',$postdata['pack_id']);
        }else if($order_type == 11){
             $check = D("Common/Cart")->check_cart($goods_id, $attr, $number, $name,0,11);
        }else{
            $check = D("Common/Cart")->check_cart($goods_id, $attr, $number, $name,0,3);
        }        
        if($check['status']<2){
            $return['msg']=$check['msg'];
            return $return;
        }else{
            //将属性和属性名称组合
            if ($attr) {
                $goodsattr_info = array(
                    'key' => $attr,
                    'name' => $name
                );
                $attr_info = serialize($goodsattr_info);
            }
            
			$carts_map = array();
            $carts_map['id']=$goods_id;
            $goods_info=M("Goods")->where($carts_map)->field(true)->order('shop_id asc')->select();
            if($type==1){
              $price_info=D("Common/Cart")->getminprice($goods_id,$attr);
              foreach($goods_info as $k=>$val){
					      if($val['goods_type'] == 4 || $val['goods_type'] == 6 || $val['goods_type'] == 5){
					
						      if($val['shop_ids'] != '0'){
  							    $shop_ids = implode(',',array_filter(explode(',',$val['shop_ids'])));
  							    $val['shop_id']= getShopid($shop_ids);
						      }else{
  							    $val['shop_id']=get_wxsmall_shop_id();
  						    }
  					    }
                $goods_info[$k]['shop_price']=$price_info['price'];//商品实际价格
                $goods_info[$k]['goods_attr']=$attr_info;//商品属性
                $goods_info[$k]['goods_num']=$number;//商品购买的数量
                $goods_info[$k]['goods_id']=$goods_id;//商品id
                $goods_info[$k]['cart_id']=$act;//活动id
              }
            }elseif($type==11 || $type == 12){
      				$shop_id = get_wxsmall_shop_id();
      				$ret = D("Common/OrderInfo")->check_service($goods_id,$shop_id,$postdata['spec_attr']);
      				if($ret['status'] == 0){
      					$return['status'] = 0;
      					$return['msg'] = $ret['msg'];
                return $return;
      				}
              // $price_info=D("Common/Cart")->getminprice($goods_id,$attr);
              // $price_info=D("Common/Takeout")->get_min_price($shop_id,$goods_id);
              foreach($goods_info as $k=>$val){
                $goods_info[$k]['shop_price']=$ret['price'];//商品实际价格
                $goods_info[$k]['goods_attr']=$attr_info;//商品属性
                $goods_info[$k]['goods_num']=$number;//商品购买的数量
                $goods_info[$k]['goods_id']=$goods_id;//商品id
                $goods_info[$k]['cart_id']=$act;//活动id
					      $goods_info[$k]['shop_id']=$shop_id;
              }
            }elseif($type == 6){
              $where=array();
              $where['style_ext_id'] = $goods_id;
              $now_time = NOW_TIME;
              $map['c.end_time'] = array('gt',$now_time);
              $map['a.style_ext_id'] = $goods_id;
              $act_id = M('PromotExt')->alias('a')->join('__PROMOT_ACT__ c on c.id=a.act_id')->where($map)->order('a.id desc')->getField('act_id');
              $where['act_id']=$act_id;
              $where['style']=4;
              $price = M('PromotExt')->where($where)->order('id desc')->getField('remarks');
              $pt_id = idtoname($act_id,'PromotAct','id');
              $group_price = unserialize($price);
              $group_pprice =D("Common/GoodsAttr")->get_goods_attrprice($attr,$group_price);
              $goods_info[0]['shop_price'] = $group_price;//拼团价格
              $goods_info[0]['goods_attr']=$attr_info;//商品属性
              $goods_info[0]['goods_num']=$number;//商品购买的数量
              $goods_info[0]['goods_id']=$goods_id;//商品id
              $goods_info[0]['pt_id']=$pt_id;//活动id
              $goods_info[0]['pid']=$postdata['pid'];//父id
              $goods_info[0]['shop_id']=get_wxsmall_shop_id();
            }elseif($type==3){
                if($integra==1){
                  $map['goods_id']=$goods_id;
                  $only_integral=M("GoodsIntegral")->where($map)->getField("only_integral");
                }else{
                  $map['goods_id']=$goods_id;
                  $goods_integral=M("GoodsIntegral")->where($map)->field("integral,money")->find();
                  $only_integral=$goods_integral['integral'];
                  $price=$goods_integral['money'];
                }
                $member_map = $cart_map = $map_c = array();
                $member_map['id'] = $memberinfo['id'];
                $user_integra = M("Member")->where($member_map)->getField('usepoints');
                if ($only_integral > $user_integra || $only_integral * $number > $user_integra) {
                  $return['status'] = 0;
                  $return['msg'] = '您的积分不足,不能购买';
                  return $return;
                }
                foreach($goods_info as $k=>$val){
                  $goods_info[$k]['shop_price']=$price;//商品实际价格
                  $goods_info[$k]['cart_integral']=$only_integral;//商品实际价格
                  $goods_info[$k]['goods_attr']=$attr_info;//商品属性
                  $goods_info[$k]['goods_num']=$number;//商品购买的数量
                  $goods_info[$k]['goods_id']=$goods_id;//商品id
                  $goods_info[$k]['shop_id']=get_wxsmall_shop_id();
                }
            }elseif($type==14){
				      $shop_id = session('main_shop_id');
              $price_info=D('Common/Takeout')->get_min_price($shop_id,$goods_id);
              $price_info['price']=$price_info['goods_price'];
              $price_info['type'] = $price_info['price_type'];
      				if($attr){
      					$map = array();
      					$map['attr_key'] = $attr;
      					$map['goods_id'] = $goods_id;
      					$price_info['price'] = M('GoodsAttrStock')->where($map)->getField('attr_price');
      					$price_info['type'] = 6;
      					if(empty($price_info['price'])){
      						$attr_info='';
      					}
      				}
              foreach($goods_info as $k=>$val){

                  if($val['shop_ids'] != '0'){
                      $shop_ids = implode(',',array_filter(explode(',',$val['shop_ids'])));
                      $val['shop_id']= getShopid($shop_ids);
                  }else{
                      $val['shop_id']=get_wxsmall_shop_id();
                  }

                  if($price_info['price'])$goods_info[$k]['shop_price']=$price_info['price'];//商品实际价格
                  $goods_info[$k]['goods_attr']=$attr_info;//商品属性
                  $goods_info[$k]['goods_num']=$number;//商品购买的数量
                  $goods_info[$k]['goods_id']=$goods_id;//商品id
                  $goods_info[$k]['cart_id']=$act;//活动id
                  $goods_info[$k]['shop_id']=$val['shop_id'];
              }
            }
            $return['data']=$goods_info;
            $return['status']=1;
		}
		return $return;
    }
    /**
     * 得到外卖下单的订单信息
     * @param $shop_id
     * @param $address_id
     * @return array
     */
    private function get_takeout_cart_list($param){
        $return=array();$return['status']=1;
        $shop_id=intval($param['shop_id']);
        $shop_info=D('Common/Takeout')->check_location($shop_id);
        if($shop_info['status']==0){return $shop_info;}
        $address_id=intval($param['delivery_id']);
        if(empty($address_id)){$return['status']=0;$return['info']='请先选择收货地址';return $return;}
        $address_arr=D('Common/Member')->address_cont($address_id);
        if(empty($address_arr['id'])){$return['status']=0;$return['info']='请先选择收货地址';return $return;}
        if(empty($address_arr['xpoint']) || empty($address_arr['ypoint'])){$return['status']=0;$return['info']='收货地址有误';return $return;}
        $cart_list=D('Common/Takeout')->get_cart_goods_list($shop_id,$address_arr);
        if($cart_list['status']==0){return $cart_list;}
        $return['list']=array();$shop_info=array();
        $shop_info['id']=$shop_id;//门店id
        $shop_info['name']=idtoname($shop_id,'Shops');//门店名称
        $shop_info['shipping_fee']=format_decimal($cart_list['delivery']['delivery_price']);//运费
        $shop_info['shop_total_price']=format_decimal($cart_list['order_total_price']);//门店需支付的总价，包含运费
        $shop_info['goods_total_price']=format_decimal($cart_list['cart_total_price']);//优惠之前的商品总价，不包含运费
        $shop_info['allgoods_price']=format_decimal($cart_list['cart_price']);//优惠之后的商品总价，不包含运费
        $shop_info['discount']=format_decimal($cart_list['cart_minus_price']);//优惠价格
        /**外卖订单的购物车自己需要的*/
        $shop_info['lunch_box_price']=format_decimal($cart_list['lunch_box_price']);//包装费
        $shop_info['cart_active']=$cart_list['cart_active'];//门店的优惠活动
        $return['list'][$shop_id]['promot_list'][0]['goods_list']=$cart_list['cart_list'];//门店下的商品
        $return['all_total_price']=format_decimal($cart_list['all_total_price']);//订单总价格，包含运费，包装费
        /**外卖订单的购物车自己需要的*/
        $return['list'][$shop_id]['shop_info']=$shop_info;//门店里信息
        $return['total_integral_price']=$cart_list['total_integral_price'];//不参与积分抵现的总金额
        $return['total_price']=format_decimal($cart_list['cart_total_price']);//商品没有优惠之前的总价，不包含运费
        $return['all_save_price']=format_decimal($cart_list['cart_minus_price']);//总共优惠节省的费用
        $return['all_price']=format_decimal($cart_list['cart_price']);//优惠之后的商品总价，不包含运费
        $return['address_arr']=$address_arr;
        return $return;
    }
    /**减库存
     * @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;
    }

    /**
     * 订单简单的变化，比如商家接单
     * @param $param
     * @return array
     */
    public function order_change($param){
        $return=$where=$data=array();
        $return['status']=1;
        $where['id']=intval($param['id']);
        if(empty($where['id'])){
            $return['status']=0;
            $return['msg']='参数错误';
            return $return;
        }
        $where['type']=intval($param['type']);
        if(isset($param['shipping_status'])){$data['shipping_status']=intval($param['shipping_status']);}
        $count=M('OrderInfo')->where($where)->save($data);
        if($count<=0){
            $return['status']=0;
            $return['msg']='更改失败';
        }else {
            $order_info=M('OrderInfo')->where($where)->field('shop_id,order_sn')->find();
            $order_sn = $order_info['order_sn'];
            $shop_id=$order_info['shop_id'];

            //给会员发送消息
            $send_data = array();
            $send_data['type'] = 2;
            $send_data['to'] = idtoname($param['id'], 'OrderInfo', 'uid');
            $send_data['code'] = $order_sn;
            sendbytheme($send_data, 'TAKEOUT_TAKE');
            $return['status']=1;
            //外卖接单时打印小票
            if(intval($param['type'])==14 && intval($param['shipping_status']==5)) {
                $machine_code = idtoname($shop_id, 'Shops', 'machine_code');
                if ($machine_code) {
                    $data = del_print_template($order_sn);
                    if ($data['status'] == 1) {
                        doPrint($machine_code, $data['content'], $order_sn);
                    } else {
                        $return['msg']=$data['info'];
                    }
                }
            }
        }
        return $return;
    }


    /**添加中奖
     * @param $data['order_id'] 订单id
     * @param $data['goods_id'] 商品id
     * @param $data['type'] 1积分商品
     * @param $data['user_id'] 会员id
     * @param $data['gift_number'] 礼品数量
     */
    public function add_win_gift($data){
        $return=array('status'=>0,'msg'=>'');
        if(empty($data['order_id'])){
            $return['msg']='参数错误';
            return $return;
        }
        if(empty($data['goods_id'])){
            $return['msg']='奖品不能为空';
            return $return;
        }
        if(empty($data['user_id'])){
            $return['msg']='会员不能为空';
            return $return;
        }
        $gift_data=array();
        $gift_data['order_id']=$data['order_id'];
        $gift_data['gift_id']=$data['goods_id'];
        $gift_data['sn_number']=createOrderNo();
        $gift_data['win_type']=$data['type'];
        $gift_data['user_id']=$data['user_id'];
        $gift_data['gift_number']=$data['gift_number'];
        $gift_data['check_status']=0;
        $gift_data['add_time']=NOW_TIME;
        $id=M("WinGift")->add($gift_data);
        if($id){
            $return['status']=1;
            $return['id']=$id;
        }else{
            $return['msg']='添加中奖纪录失败！';
        }
        return $return;
    }
    /**
     * 重新向第三方添加订单
     */
    function add_orders(){
        if(C("DIS_TRIBUTE") == 0)return;
        $order_id = I('get.order_id');
        $reqStatus = D('Common/Distribute')->readd_order($order_id);
        if($reqStatus["status"] == 0){
            $this->error($reqStatus["msg"],U('Shop/order/to_order'));return;
        }else{
            $this->success('操作成功',U('Shop/order/to_order'));return;
        }
    }

    /**加减仓库库存
     * @param $data=array('
     *  'store_id'=>仓库id,
     *  'is_add'=>是否是加库存1是0否
     *  'goods_info'=>array(
         * 0=>array(
                'goods_id'=>商品id
         *      'goods_number'=>商品数量
         *      'goods_attr'=>商品属性
         *      )
     * )
     * ')
     */
    public function reduce_store($data){
        $return=array('status'=>1);
        if(empty($data['store_id'])){
            $return['status']=0;
            $return['msg']='参数错误';
            return $return;
        }
        if(empty($data['goods_info'])){
            $return['status']=0;
            $return['msg']='商品信息不能为空';
            return $return;
        }
        foreach($data['goods_info'] as $key=>$val){
            $where['store_id']=$data['store_id'];
            $where['goods_id']=$val['goods_id'];
            $where['goods_attr_sn'] = $val['goods_id'] . '-' . $val['goods_attr'];
            if($data['is_add']==1){//加库存
                $res = M("StorageStock")->where($where)->setInc('stock', $val['goods_number']);
            }else {//减库存
                $res = M("StorageStock")->where($where)->setDec('stock', $val['goods_number']);
            }
        }
        return $return;

    }

    /**添加仓库退货单
     * @param $add_data=array(
            'user_id'=>会员id
     *      'store_id'=>仓库id
     *      'order_sn'=>订单编号
     *      'order_sum'=>订单商品总数量
     *      'goods_allmoney'=>商品总金额
     * )
     */
    public function add_stock_refundgoods($add_data){/*
        $return=array('status'=>1);
        if($add_data['order_type']==10){
            $data['chu_type']=4;
            $data['ru_type']=3;
        }else{
            $data['chu_type']=1;
            $data['ru_type']=3;
        }

        $data['chu_id']=$add_data['user_id'];
        $data['ru_id']=$add_data['store_id'];
        $data['order_sn']=$add_data['order_sn'];
        $data['order_sum']=$add_data['order_sum'];
        $data['goods_allmoney']=$add_data['goods_allmoney'];
        $data['addtime']=NOW_TIME;
        $data['order_status']=5;
        $data['status']=1;
        $data['is_delete']=0;
        $res=M("LibraryInfo")->add($data);
        if($res){
            $map=array();
            $map['order_sn']=$add_data['order_sn'];
            $order_id=M("OrderInfo")->where($map)->getField('id');
            if($order_id){
                $g_map=array();
                $g_map['order_id']=$order_id;
                $g_map['status']=3;
                $order_goods=M("OrderGoods")->where($g_map)->field('goods_id,goods_name,goods_sn,goods_price,goods_number,goods_attr')->select();
                $param=0;//判断是否是确认收货时由于数量少产生的退货，还是自己申请的退货
                if($add_data['order_type']==10 && !$order_goods && $add_data['order_goods']){
                    $g_map2['id']=array('in',$add_data['order_goods']);
                    $order_goods=M("OrderGoods")->where($g_map2)->field('goods_id,goods_name,goods_sn,goods_price,goods_number,original_num,goods_attr')->select();
                    $param=1;
                }
                if($order_goods){
                    foreach($order_goods as $key=>$val){
                        $lgoods_data['goods_id']=$val['goods_id'];
                        $lgoods_data['goods_name']=$val['goods_name'];
                        $lgoods_data['goods_sn']=$val['goods_sn'];
                        $lgoods_data['goods_attr_sn']=$val['goods_attr'];
                        $lgoods_data['attr_price']=$val['goods_price'];
                        $lgoods_data['libinfo_id']=$res;
                        if($param>0 && $val['original_num']>$val['goods_number']){
                            $lgoods_data['order_num']=$val['original_num']-$val['goods_number'];
                            $lgoods_data['all_price']=$val['goods_price']*$lgoods_data['order_num'];
                            M("LibraryGoods")->add($lgoods_data);
                        }elseif($param==0){
                            $lgoods_data['order_num']=$val['goods_number'];
                            $lgoods_data['all_price']=$val['goods_price']*$val['goods_number'];
                            M("LibraryGoods")->add($lgoods_data);
                        }

                    }
                }
            }
            $return['msg']='添加成功';
        }else{
            $return['status']=0;
            $return['msg']='添加失败';
        }*/
    }


    /**
     * 退款原路退回
     * @param 'uid'=>会员id
     * @param 'money'=>退款金额
     * @param 'order_sn'=>订单号
     * @param 'type'=>退款类型 1退款 2退货
     */
    public function refund($uid,$money,$order_sn,$type){
        $money=floatval($money);$type=intval($type);
        if(empty($money) || empty($order_sn) || empty($type)) return false;
        $map=array();
        $map['order_sn']=$order_sn;
        $mpa['pay_status']=3;
        $mpa['is_delete']=0;
        $mpa['status']=array('in','2,6,7,8,9');
        $orderinfo = M('OrderInfo')->where($map)->field(true)->find();
        $paylog = idtoname($orderinfo['pay_sn'],'PayLog','*','pay_sn');
        if(empty($orderinfo)) return false;
        if(empty($uid))$uid=$orderinfo['uid'];
        if(!empty($uid) && $uid!=$orderinfo['uid'])return false;
        if($money<=0 || $money>$orderinfo['pay_amount'])return false;
        
        $save['refund_sn'] = date("Ymdhis").rand(100,999);
        $save['uid'] = $orderinfo['uid'];
        $save['shop_id'] = $orderinfo['shop_id'];
        $save['order_id'] = $orderinfo['id'];
        $save['money'] = $orderinfo['pay_amount'];
        $save['payment_id'] = $orderinfo['payment_id'];
        $save['payment_code'] = $orderinfo['pay_code'];
        $save['trade_no'] = $orderinfo['pay_sn'];
        $save['addtime'] = NOW_TIME;
        $save['type'] = $type;
        $save['status'] = 0;
        $save['is_effect'] = 1;
        $insertid = M('PaymentRefund')->add($save);
        $map = array();
        $map['status'] = 1;
        $map['code'] = $orderinfo['pay_code'];

        $payment=M('Payment')->where($map)->field(true)->order('id desc')->find();
        if(empty($payment)) return false;
        $newDriver = '\\Common\\Vendor\\Pay\\Driver\\' . ucfirst(strtolower($payment['code']));
        $new = new $newDriver($payment);; 
        if(method_exists($new,'refund')){
            $pay = new \Common\Vendor\Pay($payment['code'],$payment);
            $res=$pay->refund($paylog['order_sn'],$orderinfo['pay_sn'],$orderinfo['pay_amount'],$save['refund_sn']);
            return $res;
        }else{
            account_change($uid,$money,1,8,'取消订单'.$order_sn);
            return true;
        }
        exit;
    }
     /** 
      * 原路退回处理订单
      * @param $refund_sn    退款单号
      * @param $refund_sn    退款状态
      * @param $refund_sn    处理时间
      */
    public function payment_refund($refund_sn,$status='',$deal_time=''){
        $status = intval($status);
        $root=array('status'=>0,'msg'=>'');
        if(empty($refund_sn)){$root['msg']="参数错误";return $root;}
        if(empty($status)){$root['msg']="参数错误";return $root;}
        if(empty($deal_time))$deal_time = NOW_TIME;
        $where = array();
        $save['deal_time'] = $deal_time;
        $save['update_time'] = NOW_TIME;
        $save['status'] = $status;
        $where['refund_sn'] = $refund_sn;
        M('PaymentRefund')->where($where)->save($save);
    }
     /** 原路退回处理订单
     * @param $info    订单信息
     */
    public function refund_order($info){
        $root=array('status'=>0,'msg'=>'');
        if(empty($info['out_trade_no'])){$root['msg']="参数错误";return $root;}
        $order_info = idtoname($info['out_trade_no'],'OrderInfo','*','id');
        $refund_info = idtoname($info['out_trade_no'],'RefundOrder','*','order_id');
        $o_where['is_delete'] = 0;
        $o_where['order_id'] = array("like", "%," . $refund_info['order_id'] . ",%");
        $pay_info = M("PayLog")->where($o_where)->field(true)->find();

        
            if($refund_info['refund_money']>0 && $order_info['pay_status'] != 5){//退余额
                account_change($pay_info['user_id'],$refund_info['refund_money'],1,8,'取消订单'.$order_info['order_sn']);
            }
            if($refund_info['refund_scores']>0 && $order_info['pay_status'] != 5){//退积分
                account_change($pay_info['user_id'],$refund_info['refund_scores'],4,8,'取消订单'.$order_info['order_sn']);
            }
        //作废支付单
        $p_where['is_delete'] = 0;
        $p_where['order_id'] = array("like", "%," . $refund_info['order_id']. ",%");
        $o_data['is_delete']=1;
        $del_pay= M("PayLog")->where($p_where)->save($o_data);

        //重新生成支付单
        $order_ids=explode(',',$pay_info['order_id']);
        foreach(array_filter($order_ids) as $key=>$val){
            if($val==$refund_info['order_id']){
                $org_maps['status']=array('in',array(0,1));
                $org_maps['order_id']=$refund_info['order_id'];
                $is_del=M('OrderGoods')->where($org_maps)->count();
                if(!$is_del)unset($val);
            }
            if($val==0){
                unset($val);
            }
            $pay_order_id[]=$val;
        }
        $pay_order_id=array_filter($pay_order_id);
        if(!empty($pay_order_id)){
            $payment_id=','.implode(',',$pay_order_id).',';
            $use_money=$pay_info['use_money']-$refund_info['refund_money'];
            $use_score=$pay_info['use_score']-$refund_info['refund_scores'];
            $use_web=$pay_info['pay_amount']-$refund_info['refund_web'];
            $payment=array();
            $payment['order_id']=$payment_id;
            $payment['type']=$order_info['type'];
            $payment['user_id']=$order_info['uid'];
            $payment['use_money']=$use_money;
            $payment['use_score']=$use_score;
            $payment['use_score_money']=$use_score*C('WEB_INTEGRAL_RATIO')/100;
            $payment['pay_amount']=$use_web;
            $payment['order_total_price']=$use_web+$use_money+$use_score;
            $payment['payment_id']=$pay_info['payment_id'];
            $payment['pay_code']=$pay_info['pay_code'];
            $payment['is_paid']=$pay_info['is_paid'];
            $payment['create_time']=NOW_TIME;
            M("PayLog")->add($payment);

        }
        //如果订单支付成功则取消订单分成
        if($order_info['pay_status']==3) {
            if ($refund_info['type'] == 1) {//10订货商品
                //取消订单分成
                $where['order_id'] = $refund_info['order_id'];
                $data['is_separate'] = 2;
                M("AffiliateLog")->where($where)->save($data);
                //减少店铺待结算金额
                supplier_balance_log($order_info['shop_id'], -$refund_info['money'], 2, 3, '订单' . $order_info['order_sn'] . '付款,未结算总额减少', $order_info);
            } else {
                //取消订单分成
                $where['order_id'] = $refund_info['order_id'];
                $data['is_separate'] = 2;
                M("AffiliateLog")->where($where)->save($data);
                //减少店铺待结算金额
                if (empty($order_info['storage_id'])) {
                    shop_balance_log($order_info['shop_id'], -$refund_info['money'], 2, 3, '订单' . $order_info['order_sn'] . '付款,未结算总额减少', $order_info);
                }
            }
        }
        //确认退款单
        $refund_map['id']=$refund_info['id'];
        $refund_data['status']=1;
        $refund_data['update_time']=NOW_TIME;
        M("RefundOrder")->where($refund_map)->save($refund_data);
        return $root;
    }
/** 计算利润
  *1.先计算整单优惠的均摊
  *2.再计算部分优惠的均摊
  第一部分 优惠1=（整单优惠金额/所有商品总金额）*商品金额 需支付1 = 商品金额-优惠1
  第二部分 优惠2=（部分优惠金/部分商品的总金额）*商品金额 需支付2 = 商品金额-优惠2
  利润 $profit= 需支付2-供货价
 * @param $order_id 订单id
 */
  public function get_profit($order_id){
    if(!$order_id){return false;}
    $where=array();
    $where['id']=$order_id;
    $order_info=M('OrderInfo')->where($where)->field('type,bonus_money,first_money,used_score_money,custom_discount,moling_discount,promot_money_json,member_discount')->find();
    if($order_info['type']==2 || $order_info['type']==5 || $order_info['type']==15){//充值、卡销售
      return true;
    }
    $pay_money=$map=array();
    $map['order_id']=$order_id;
    $order_goods = M('OrderGoods')->where($map)->field(true)->select();
    if(empty($order_goods)){return false;}
    if($order_info['type']==3 || $order_info['type']==6 || $order_info['type']==11){//积分、拼团、服务此类订单均为一种商品
      $profit=0;
      foreach ($order_goods as $k => $v) {
        $data=$map_og=array();
        $profit=($v['goods_price']-$v['supplier_price'])*$v['goods_number']-$order_info['used_score_money'];
        $data['profit']=round($profit,2);
        $map_og['id']=$v['id'];
        M('OrderGoods')->where($map_og)->save($data);
      }unset($k,$v);
    }else{
      //第一部分优惠
      $discount=$order_info['bonus_money']+$order_info['first_money']+$order_info['custom_discount']+$order_info['moling_discount'];
      $count1=$percent1=$all_base=$base_price=$count=0;
      if($discount > 0){
        foreach ($order_goods as $k => $v) {
          if($v['goods_type']==0){
            $base_price=$order_goods[$k]['base_price']=$v['attr_price']-$v['discount_member']-$v['discount_xianshi']-$v['discount_custom'];//基础价
            $count++;
            $all_base+=$base_price*$v['goods_number'];
          }else{
            $order_goods[$k]['base_price']=$order_goods[$k]['goods_price'];
          }
        }unset($k,$v);
        $percent1=$discount/$all_base;//第一部分优惠金额占比
        $all_dis=0;
        foreach ($order_goods as $k => $v) {
          $dis_money=0;//整单优惠 均摊的金额
          if($v['goods_type']==0){
            $count1++;
            if($count1==$count){
              $order_goods[$k]['base_price']=$order_goods[$k]['base_price']-round(($discount-$all_dis)/$v['goods_number'],2);
            }else{
              $dis_money=round($order_goods[$k]['base_price']*$percent1,2);
              $order_goods[$k]['base_price']=$order_goods[$k]['base_price']-$dis_money;
              $all_dis+=($dis_money*$v['goods_number']);
            }
            
          }
        }
      }else{
        foreach ($order_goods as $k => $v) {
          $order_goods[$k]['base_price']=$v['goods_price'];
        }unset($k,$v);
      }

      // 第二部分优惠开始
      if($order_info['promot_money_json']){
        $promot=json_decode($order_info['promot_money_json'],true);
        foreach($promot as $k=>$v){
          $count2=$percent2=$all_goods=0;
          if($v['type']==1 || $v['type']==2){
            foreach ($order_goods as $ke => $va) {
              if($va['goods_type']==0 && $k==$va['promot_id']){
                $count2++;
                $all_goods+=$order_goods[$ke]['base_price']*$va['goods_number'];
              }
            }unset($ke,$va);
            $data=$map_og=array();
            $percent2=$v['money']/$all_goods;//部分优惠金额占比
          }
          
          $promot_num=$all_promot=0;
          foreach ($order_goods as $ke => $va) {
            if($k==$va['promot_id'] && $v['type']<3){
              if($va['goods_type']==0){
                $promot_num++;
                if($promot_num==$count2){
                  $order_goods[$ke]['base_price']=$order_goods[$ke]['base_price']-round(($v['money']-$all_promot)/$va['goods_number'],2);//修改基础价
                }else{
                  $promt_m=round($order_goods[$ke]['base_price']*$percent2,2);//商品优惠的金额
                  $order_goods[$ke]['base_price']=$order_goods[$ke]['base_price']-$promt_m;//修改基础价
                  $all_promot+=$promt_m*$va['goods_number'];
                }
              }
            }unset($ke,$va);
          }
        }
      }
      // 判断是否存在积分抵现
      if($order_info['used_score_money']>0){
        $goods_id=array();
        foreach ($order_goods as $k => $v) {
          $goods_id[]=$v['goods_id'];
        }unset($k,$v);
        $goods_map=array();
        $goods_map['id']=array('in',$goods_id);
        $goods_map['is_integral']=1;
        $goodsids=M('Goods')->where($goods_map)->getField('id',true);
        $goods_allmoney=$count_g=0;
        foreach ($order_goods as $k => $v) {
          if(in_array($v['goods_id'],$goodsids)){
            $count_g++;
            $goods_allmoney+=$v['base_price']*$v['goods_number'];
          }
        }unset($k,$v);
        $point_percent=$order_info['used_score_money']/$goods_allmoney;
        $count_gg=$point_money=$point_price=0;
        foreach($order_goods as $k => $v){
          if(in_array($v['goods_id'],$goodsids)){
            $count_gg++;
            if($count_gg==$count_g){
              $order_goods[$k]['base_price']=$order_goods[$k]['base_price']-(round(($order_info['used_score_money']-$point_money)/$v['goods_number'],2));
            }else{
              $point_price=round($order_goods[$k]['base_price']*$point_percent,2);
              $order_goods[$k]['base_price']=$order_goods[$k]['base_price']-$point_price;
              $point_money+=$point_price*$v['goods_number'];
            }
          }
        }
      }
      foreach ($order_goods as $k => $v) {
        $map_og=$data=array();
        $data['goods_price']=$order_goods[$k]['base_price'];
        $data['profit']=round(($order_goods[$k]['base_price']-$v['supplier_price'])*$v['goods_number'],2);
        $map_og['id']=$v['id'];
        M('OrderGoods')->where($map_og)->save($data);
      }unset($k,$v);
    }

    // 计算order_info总利润
    $map_oi=$data_oi=array();
    $p_res=M('OrderGoods')->where($map)->field('sum(profit) as profit,sum(discount_member*goods_number) as member_discount')->find();
    $data_oi['profit']=$p_res['profit'];
    if($order_info['member_discount']==0){
      $data_oi['member_discount']=$p_res['member_discount'];
    }
    $map_oi['id']=$order_id;
    $res = M('OrderInfo')->where($map_oi)->save($data_oi);
  }
    public function send_wxsmall_message($pay_info = array()){
        if(empty($pay_info)||empty($pay_info['wxsmall_formid_cache']))return;
        $orderids_arr =array_filter(explode(',', $pay_info['order_id']));
        $goods = array();
        foreach($orderids_arr as $v){
            $map = array();
            $map['order_id'] = $v;
            $goods[] = M('OrderGoods')->where($map)->getField('goods_name');
        }
        $OPENID = idtoname($pay_info['user_id'],'Member','wxsmall_openid','id',false);
        $wxsmall = new \Common\Vendor\Wxsmallopen;
        $data = array();
        $data['OPENID'] = $OPENID;
        $data['formId'] = $pay_info['wxsmall_formid_cache'];
        $data['keyword1'] = $pay_info['order_sn'];
        $data['keyword2'] =format_price($pay_info['order_total_price']);
        $data['keyword3'] = time_format(NOW_TIME);
        $data['keyword4'] =  empty($goods)?'':implode(' ',$goods);
        $template_id = $pay_info['theme_id']?$pay_info['theme_id']:$pay_info['theme_remark'];
        $message = $wxsmall->sendTplMsg($data,$template_id);
        return $message;
    }
	public function check_service($goods_id,$shop_id,$spec_attr){
		$return = array();$return['status'] = 0;
		$map = array();
		$map['id'] = $goods_id;
		$map['goods_type'] = 4;
		$map['status'] = 1;
		$map['is_delete'] = 0;
		$info = M('Goods')->where($map)->field('id,shop_ids,shop_price,service_spec')->find();
		
		if($info['id'] > 0){
			if($info['shop_ids'] == 0 || $info['shop_ids'] == $shop_id){
				$return['status'] = 1;
				if($spec_attr){
					$service_spec = json_decode($info['service_spec'],true);
					
					$return['price'] = $service_spec[$spec_attr];
				}else{
					$return['price'] = $info['shop_price'];
				}
			}else{
				$return['msg'] = '该项服务不在仓库服务范围';
			}
		}else{
			$return['msg'] = '该服务已下架';
		}
		return $return;
	}

    // 线上订单退货
    public function check_tui($postdata){
        $return=array('status'=>0,'msg'=>'');
        $order_id=intval($postdata['order_id']);
        $money=floatval($postdata['tui_money']);
        $tui_number=floatval($postdata['tui_number']);
        $og_id=intval($postdata['og_id']);
        $where=array();
        $where['id']=$order_id;
        $order_info=M("OrderInfo")->where($where)->field('uid,scan_money,goods_amount,goods_allmoney,order_amount,order_money,profit,shop_id,type')->find();
        if(!$order_info){
            $return['msg']='无此商品订单';
            return $return;
        }
        $map_og=$data_oi=$refund_data=$map=$data=$add=array();
        $map['order_id']=$order_id;
        $map['id']=$og_id;
        $order_goods=M("OrderGoods")->where($map)->field('goods_id,goods_number,goods_attr')->find();
        if(!$order_goods){
            $return['msg']='该订单无此商品';
            return $return;
        }
        if($tui_number > $order_goods['goods_number']){
            $return['msg']='退货数量不得大于购买量';
            return $return;
        }
        $data['status']=3;
        // 修改订单
        M("OrderGoods")->where($map)->save($data);
        $data_oi['status']=8;
        M('OrderInfo')->where($where)->save($data_oi);
         //添加退货单
        $goods_info['goods_id']=$order_goods['goods_id'];
        $goods_info['number']=$tui_number;
        if($order_goods['goods_attr']){
            $attr = unserialize($order_goods['goods_attr']);
            $goods_info['goods_attr']=$attr['key'];  
        }
        
        //生成退款单
        $refund_data['reason']=$postdata['content'];
        $refund_data['type']=2;
        $refund_data['order_goods']=$og_id;
        $refund_data['order_id']=$order_id;
        $refund_data['shop_id']=$order_info['shop_id'];
        $refund_data['money']=$money;
        $refund_data['status']=0;
        $refund_data['uid']=$order_info['uid'];
        $refund_data['order_type']=$order_info['type'];
        $refund_data['addtime']=NOW_TIME;
        $res_ro=M("RefundOrder")->add($refund_data);
        
        
        
        $add['rorder_id']=$res_ro;
        $add['org_id']=$og_id;
        $add['uid']=$order_info['uid'];
        $add['order_id']=$order_id;
        $add['goods_info']=serialize($goods_info);
        $add['reason']=$postdata['content'];
        $add['money']=$money;
        $add['add_time']=NOW_TIME;
        $add['status']=0;
        $add['shop_status']=0;
        $add['shop_id']=$order_info['shop_id'];
        $add['type']=2;
        $res=M('ReturnGoods')->add($add);
        
        if($res && $res_ro){
        	$return['status']=1;
        	$return['msg']='申请退货成功';
        }else{
        	$return['msg']='申请退货失败';
        }
        return $return;
      }
    public function tui_goods($postdata){
        $id=$postdata['id'];
        $admin_id=$postdata['admin_id'];
        if(!$id){$return['info']='参数错误';return $return;}
        $info=M('ReturnGoods')->where('id='.$id)->field(true)->find();
        if(empty($info)){$return['info']='没有此退货信息';return $return;}
        if($postdata['type']==1){//同意
            $yes_map['id']=$id;$yes_map['status']=0;$save['status']=1;$save['update_time']=NOW_TIME;$save['shop_status']=1;
            $res=M('ReturnGoods')->where($yes_map)->save($save);
            if(!$res){$return['info']='处理失败,可能原因（重复处理）';return $return;}	
        }elseif($postdata['type']==2){//不同意
            $no_map['id']=$id;$no_map['status']=0;
            $save['status']=2;$save['update_time']=NOW_TIME;
            $save['not_content']=$postdata['content'];
            $res=M('ReturnGoods')->where($no_map)->save($save);
            if(!$res){$return['info']='处理失败,可能原因（重复处理）';return $return;}
            //修改订单商品表状态
            $org_map['id']=$info['org_id'];$org_map['status']=3;$org_save['status']=5;
            $result=M('OrderGoods')->where($org_map)->save($org_save);
            $og_map['order_id']=$info['order_id'];
            $og_info=M('OrderGoods')->where($og_map)->getField('status',true);
            if(!in_array(3,$og_info) && !in_array(2,$og_info)){
                $oi_map['id']=$info['order_id'];
                $oi_save['status']=2;
                M('OrderInfo')->where($oi_map)->save($oi_save);
            }
            if(!$result){$return['info']='数据错误';return $return;}
        }
        $return['status']=1;
        $return['info']='处理成功';
        if($postdata['margin_type']=='Admin')action_log('admin_return_goods', 'Admin', $id, $admin_id);
        return $return;
    }

    /* 退货退款线上订单
    * @param $type 		Admin:操作日志
    * @param $admin_id 	管理员ID
    */
    public function tui_kuan($refund_id,$type,$admin_id){
        $return=array("status"=>0,"msg"=>'');
        if(!$refund_id){$return['msg']="参数错误";return $return;}
        $where['id']=$refund_id;
        $refund_info=M("RefundOrder")->where($where)->field(true)->find();
        if(empty($refund_info)){$return['msg']="没有退款信息";return $return;}
		
        //获取订单信息
        $order_where['id']=$refund_info['order_id'];
        $order_info=M("OrderInfo")->where($order_where)->field(true)->find();
        if(empty($order_info)){$return['msg']="没有订单信息";return $return;}
        if($order_info['status']==4){
            return $this->handle_order($refund_id,$type,$admin_id);
        }
        //如果是退货生成的 判断退货单是否同意了
        $org_map['uid']=$refund_info['uid'];
        $org_map['order_id']=$refund_info['order_id'];
        $org_map['org_id']=$refund_info['order_goods'];
        $reg_info=M('ReturnGoods')->where($org_map)->field('id,status,shop_status,goods_info,org_id')->find();
        if(!empty($reg_info)){
            if($reg_info['status']==0 || $reg_info['shop_status']==0 ){
                $return['msg']='请先处理退货单';
                $return['url']=U('TuiHuan/index',array('id'=>$reg_info['id']));
                return $return;
            }
            // 修改订单
            $tui_info=unserialize($reg_info['goods_info']);
            $org_map['id']=$reg_info['org_id'];
            $org_map['status']=3;
            $og_info=M('OrderGoods')->where($org_map)->field(true)->find();
            if($tui_info['number'] == $og_info['goods_number']){
                $org_save['status']=4;
            }elseif($tui_info['number'] < $og_info['goods_number']){
                $org_save['status']=6;
            }
            if($og_info['original_num']==0){
                $org_save['original_num']=$og_info['goods_number'];
            }
            $org_save['goods_number']=$og_info['goods_number']-$tui_info['number'];
            if($org_save['status']==4){
                $org_save['profit']=0;
                $org_save['money']=0;
                $kou_money=$og_info['money'];
                $profit=$og_info['profit'];
	        }else{
	            $profit = ($og_info['profit']/$org_save['original_num'])*$tui_info['number'];
              $money = ($og_info['money']/$org_save['original_num'])*$tui_info['number'];
	            $org_save['profit']=round($og_info['profit']-$profit,2);
              $org_save['money']=round($og_info['money']-$money,2);
              $kou_money=$money;
	        }
            $result=M('OrderGoods')->where($org_map)->save($org_save);
            $map_og['order_id']=$refund_info['order_id'];
            $allgoodsnum = M("OrderGoods")->where($map_og)->sum('goods_number');
            $allgoodsnum=floatval($allgoodsnum);
            // 修改订单表
            if($allgoodsnum>0){
                $data_oi['status']=2;
            }else{
                $data_oi['status']=7;
            }
            $data_oi['goods_amount']=$order_info['goods_amount']-$refund_info['money'];
            $data_oi['goods_allmoney']=$order_info['goods_allmoney']-$tui_info['number']*$og_info['attr_price'];
            $data_oi['order_amount']=$order_info['order_amount']-$refund_info['money'];
            $data_oi['order_money']=$order_info['order_money']-$refund_info['money'];
            $data_oi['profit']=$order_info['profit']-$profit;
            $data_oi['sales_maid']=$order_info['sales_maid']-$kou_money;
            M('OrderInfo')->where($order_where)->save($data_oi);
            $log='订单'.$order_info['order_sn'].'退货'.$tui_info['number'].'件，佣金扣除'.$kou_money.'元';
            account_change($order_info['guide'],-$kou_money,1,10,$log,'','',5);
	        // 加库存
	        $map=array();
	        $map['shop_id']=$order_info['shop_id'];
	        $map['goods_id']=$og_info['goods_id'];
            $where=array();
            $where['id']=$og_info['goods_id'];
	        $sale_type = M('Goods')->where($where)->getField('sale_type');
            $tuigoods['goods_number']=$tui_info['number'];
	        if($sale_type == 1){//组合商品
                $tuigoods['goods_id']=$og_info['goods_id'];
	            D('Shop/OrderInfo')->add_group_goods($map,$tuigoods,$refund_info['order_id'],1);
	        }else{
                $tuigoods['goods_attr']=$tui_info['goods_attr'];
                D('Shop/OrderInfo')->add_stock($map,$tuigoods,$refund_info['order_id'],1,1);
	        }
	        //执行退款
        	if($refund_info){
                if($refund_info['refund_web']>0){//退网银
                    $this->refund($order_info['uid'],$refund_info['refund_web'],$order_info['order_sn'],1);
                }
                if($refund_info['refund_money']>0){//退余额
                    account_change($order_info['uid'],$refund_info['refund_money'],1,8,'退货,订单'.$order_info['order_sn']);
                }
                if($refund_info['refund_scores']>0){//退积分
                    account_change($order_info['uid'],$refund_info['refund_scores'],4,8,'退货，订单'.$order_info['order_sn']);
                }
        	}
	        //确认退款单
	        $refund_map['id']=$refund_id;
	        $refund_data['status']=1;
	        $refund_data['update_time']=NOW_TIME;
	        M("RefundOrder")->where($refund_map)->save($refund_data);
            // 退货退款营业额减少
            shop_balance_log($order_info['shop_id'], -$refund_info['money'], 6,3,'订单'.$order_info['order_sn'].'退货退款,销售总额减少', $order_info,$admin_id,true);
            // 退货退款余额减少
            shop_balance_log($order_info['shop_id'], -$refund_info['money'], 1,3,'订单'.$order_info['order_sn'].'退货退款,余额减少', $order_info,$admin_id,true);
			if($type && $admin_id)action_log('admin_do_refund', $type, $refund_id, $admin_id);
			$return['status']=1;
			$return['msg']='退款成功';
	    $code_data=array();
      //退款通知
      $code_data['to'] = $order_info['mobile'];
      $code_data['order_sn'] = $order_info['order_sn'];
      $code_data['shop_name'] = idtoname($order_info['shop_id'],'Shops','name');
      if($order_info['pay_code']){$pay_codename=idtoname($order_info['pay_code'],'Payment','name','code');
          $code_data['payment'] = $pay_codename?$pay_codename:'';
      }else{
          $code_data['payment'] = '余额支付';
      }
      $code_data['tui_money'] = $refund_info['money'];
      $code_data['tui_time'] = time_format(NOW_TIME);
      sendbytheme($code_data, 'REFUND_MONEY');
      $return['status']=1;
      $return['msg']='退款成功';

        // 增加退款流水
        $param=array();
        $param['order_id']=$order_info['id'];$param['order_sn']=$order_info['order_sn'];
        $param['user_id']=$order_info['uid'];
        $param['type']=21;
        $param['pay_amount']=$refund_info['refund_web'];
        $param['use_score']=$refund_info['refund_scores'];
        $param['use_money']=$refund_info['refund_money'];
        $param['shop_id']=$order_info['shop_id'];
        // $param['order_total_price']=$order_info['order_money'];
        $param['in_online']=$order_info['in_online'];
        $this->return_goods_log($param);

      return $return;
		}else{
			$return['msg']='无退货商品';
	        return $return;
		}

	}

    /* 存导购员佣金
    * @param $order_id
    */
    public function guide_money($order_id){
        $map = array();
        $map['id'] = $order_id;
        $order_info = M('OrderInfo')->where($map)->field('uid,guide,order_sn,order_amount')->find();
        $map=array();
        $map['order_id']=$order_id;
        $order_goods = M('OrderGoods')->where($map)->field('id,goods_id,goods_number,goods_price,profit')->select();
        $map = array();
        $map['id'] = $order_info['guide'];
        $map['status'] = 1;
        $guide_name = M('ShopsAccount')->where($map)->getfield('name');
        $money=0;
        $res = M('Config')->field('value')->where("name='GUIDE'")->find();
        $affiliate = unserialize($res['value']);
        if(!empty($order_goods)) {
            foreach ($order_goods as $k => $vv) {
                $map_g = $data = array();
                $goodsinfo = idtoname($vv['goods_id'], 'Goods', 'staff_comm,money,is_referral,commission,sale_type,supply_price', 'id', false);
                if ($goodsinfo['staff_comm'] == 0) {//不提成
                    $data['money'] = 0;
                } elseif ($goodsinfo['staff_comm'] == 1 && $vv['goods_price'] > 0) {//按系统设定
                    $all_money = floatval($vv['goods_price'] * $vv['goods_number']);
                    if ($affiliate['market_status'] == 1) {//按商品金额%
                        $data['money'] = format_decimal($all_money * $affiliate['market'] / 100);
                        $money += $data['money'];
                    } else {//按商品利润%
                        $data['money'] = format_decimal($vv['profit'] * $affiliate['market'] / 100);
                        $money += $data['money'];
                    }
                    $map_g['id'] = $vv['id'];
                    M('OrderGoods')->where($map_g)->save($data);
                } elseif ($goodsinfo['staff_comm'] == 2 && $vv['goods_price'] > 0) {//按固定金额
                    $data['money'] = $goodsinfo['money'];
                    $money += $data['money'];
                    $map_g['id'] = $vv['id'];
                    M('OrderGoods')->where($map_g)->save($data);
                }

            }
        }else{
            $all_money = $order_info['order_amount'];
            if ($affiliate['market_status'] == 1) {//按商品金额%
                $data['money'] = format_decimal($all_money * $affiliate['market'] / 100);
                $money = $data['money'];
            } else {//按商品利润%
                $money = 0;
            }
        }
        if($money > 0){
            $map_oi=array();
            $map_oi['id']=$order_id;
            $data_oi['sales_maid']=$money;
            M('OrderInfo')->where($map_oi)->save($data_oi);
            $log='';
            if($order_info['uid']){$log.='会员('.idtoname($order_info['uid'],'Member','username;nickname').')';}
            $log.='下单('.$order_info['order_sn'].')，将赠导购员('.$guide_name.')佣金'.$money.'元';
            account_change($order_info['guide'],$money,1,10,$log,'','',5);
            //门店扣除余额
            shop_balance_log($order_info['shop_id'],-$money,1,3,$log.',扣除店铺余额','',$order_info);
        }
    }
    
    /* 退货取消订单新增pay_log
    * @param $postdata  存pay_log需要的信息
    */
    public function return_goods_log($postdata){
        if(empty($postdata['order_id'])) return false;
        if(empty($postdata['pay_sn'])){
            //支付单信息
            $o_where = array();
            $o_where['order_id'] = array("like", "%," . $postdata['order_id'] . ",%");
            $o_where['order_id'] = $postdata['order_id'];
            $o_where['_logic'] = 'OR';
            $postdata['pay_sn']=M("PayLog")->where($o_where)->getField('pay_sn');            
        }
        $add=array();
        $add['user_id'] = $postdata['user_id'];
        $add['type'] = $postdata['type'];//20取消订单 21退货
        $add['pay_sn'] = $postdata['pay_sn'];
        $add['order_sn'] = $postdata['order_sn'];
        $add['serial_number'] = '';
        $add['order_id'] = $postdata['order_id'];
        $add['use_money'] = $postdata['use_money'];
        $add['cash_money'] = $postdata['cash_money'];
        $add['scan_money'] = $postdata['scan_money'];
        $add['bank_money'] = $postdata['bank_money'];
        $add['card_money'] = $postdata['card_money'];
        $add['need_pay'] = $postdata['need_pay'];
        $add['use_score'] = $postdata['use_score'];
        $add['use_score_money'] = $postdata['use_score_money'];
        $add['order_total_price'] = $postdata['use_money']+$postdata['cash_money']+$postdata['scan_money']+$postdata['bank_money']+$postdata['card_money'];
        $add['pay_amount'] = $postdata['pay_amount'];
        $add['pay_amount_type'] = $postdata['pay_amount_type'];
        $add['payment_fee'] = $postdata['payment_fee'];
        $add['payment_id'] = $postdata['payment_id'];
        $add['pay_code'] = $postdata['pay_code'];
        $add['is_paid'] = 1;
        $add['create_time'] = NOW_TIME;
        $add['update_time'] = NOW_TIME;
        $add['is_delete'] = 0;
        $add['wxsmall_formid_cache']='';
        $add['in_online']=$postdata['in_online'];
        $add['shop_id']=$postdata['shop_id'];
        M('PayLog')->add($add);
    }

    /**
     * @param $order_id 第三方订单id
     * @param $type 0加库存 1减库存
     * 第三方订单库存变更
     */
    public function three_order_stock($order_id,$type){
        $return=array('status'=>0,'msg'=>'');
        $order_id=intval($order_id);
        if(empty($order_id)){$return['msg'] = "参数错误";return $return;}
        $map = array();
        $map['id'] = $order_id;
        if($type==1) $map['order_status'] = 3;
        else {
            $map['order_status'] = array('in','5,7'); $map['is_reduce']=0;
        }
        $order_info = M('ThreeOrder')->where($map)->field(true)->find();
        if (empty($order_info)) {
            $return['msg'] = "订单不存在";
            return $return;
        }
        $goods=unserialize($order_info['goods_info']);
        foreach ($goods as $v) {
            $map = $data = $type_map = array();
            $map['shop_id'] = $order_info['shop_id'];
            if(strpos($v['act_good_ids'],"-")){
                $new_arr=array();
                $new_arr = explode('-',$v['act_good_ids']);
                $map['goods_stock'] = $new_arr[1];//属性值
                $map['goods_id'] = $new_arr[0];//商品id
                $type_map['id'] = $new_arr[0];//商品id
            }else{
                $map['goods_stock'] = 0;//属性值
                $map['goods_id'] = $v['act_good_ids'];//商品id
                $type_map['id'] = $v['act_good_ids'];//商品id
            }
            $sale_type = M('Goods')->where($type_map)->getField('sale_type');
            if ($sale_type == 1) {//组合商品
                if($type==1)$this->three_group_goods($map,$v,$order_id);
                else $this->add_three_group_goods($map,$v,$order_id);
            } else {
                if($type==1) $this->reduce_three_stock($map, $v, $order_id);
                else $this->add_three_stock($map,$v,$order_id);
            }

        }
        $return['status'] = 1;
        $return['msg'] = "操作成功";
        return $return;
    }
    public function three_group_goods($map,$v,$order_id){//组合商品减库存
        $mapg=array();
        $mapg['goodsid'] = $map['goods_id'];
        $group = M('GroupGoods')->where($mapg)->select();
        $info=array();
        foreach($group as $kk=>$vv){
            $info['goods_attr']=$vv['attr_key'];
            $info['goods_number'] = $v['goods_number'] * $vv['ratio'];
            $map['goods_id'] = $vv['linkid'];
            $this->reduce_three_stock($map,$info,$order_id,1);
        }
    }
    public function add_three_group_goods($map,$v,$order_id){//组合商品加库存
        $mapg=array();
        $mapg['goodsid'] = $map['goods_id'];
        $group = M('GroupGoods')->where($mapg)->select();
        $info=array();
        foreach($group as $kk=>$vv){
            $info['goods_attr']=$vv['attr_key'];
            $info['goods_number'] = $v['goods_number'] * $vv['ratio'];
            $map['goods_id'] = $vv['linkid'];
            $this->add_stock($map,$info,$order_id);
        }
    }
    public function reduce_three_stock($map,$v,$order_id){//减库存
        $pre_num=M('ShopsGoodsStock')->where($map)->getField('goods_number');
        if(empty($pre_num)){
            unset($map['goods_stock']);
            $pre_info=M('ShopsGoodsStock')->where($map)->order('goods_number desc')->field('id,goods_number')->find();
            if($pre_info['id']){
                $map['id']=$pre_info['id'];
                $pre_num=$pre_info['goods_number'];
            }
        }
        $order_sn=idtoname($order_id,'ThreeOrder','ordersn');
        $attr_key=empty($map['goods_stock'])?'':$map['goods_stock'];
        if($pre_num<$v['goods_number']){
            $g_map=array();
            $g_map['gp.sid']=$map['goods_id'];
            if($map['goods_stock']){
                $g_map['s.goods_stock']=$map['goods_stock'];
                $g_map['gp.sattr_key']=$map['goods_id'].'-'.$map['goods_stock'];
            }
            $p_info=M('GoodsPackage')->alias('gp')->where($g_map)->JOIN('LEFT JOIN __SHOPS_GOODS_STOCK__ s ON s.goods_id=gp.pid')->field('s.goods_number,gp.ratio,gp.pid')->find();
            if($p_info){
                $big_num = ceil(($v['goods_number']-$pre_num)/$p_info['ratio']);//需要大单位商品的量
                $mapb=$datab=array();
                $mapb['goods_id']=$p_info['pid'];
                $mapb['shop_id']=$map['shop_id'];
                if($map['goods_stock'])$mapb['goods_stock']=$map['goods_stock'];
                $datab['updatetime']=NOW_TIME;
                $datab['goods_number']=array('exp','goods_number-'.$big_num);
                $resb=M('ShopsGoodsStock')->where($mapb)->save($datab);
                if($resb){
                    $desc='大单位拆包';
                    change_stock_log($map['shop_id'],$order_id,$p_info['goods_number'],$p_info['pid'],$big_num,1,$desc,10,$attr_key);
                }
                $datas=array();
                $datas['updatetime']=NOW_TIME;
                $s_num=$big_num*$p_info['ratio'];
                $datas['goods_number']=array('exp','goods_number+'.$s_num);
                $ress=M('ShopsGoodsStock')->where($map)->save($datas);
                if($ress){
                    $desc='小单位入库';
                    change_stock_log($map['shop_id'],$order_id,$pre_num,$map['goods_id'],$big_num*$p_info['ratio'],0,$desc,10,$attr_key);
                }
            }
        }
        $data['updatetime']=NOW_TIME;
        $data['goods_number']=array('exp','goods_number-'.$v['goods_number']);
        $data['sell_count']=array('exp','sell_count+'.$v['goods_number']);
        $res=M('ShopsGoodsStock')->where($map)->save($data);
        if($res){
            $t_map=array();$t_map['id']=$order_id;
            $t_data=array(); $t_data['is_reduce']=0;
            M('ThreeOrder')->where($t_map)->save($t_data);
            $code=idtoname($order_id,'ThreeOrder','code');
            $code_msg='京东到家';
            if($code=='ele')$code_msg='饿了么';
            //增加存库存变更日志
            $desc=$code_msg.'订单'.$order_sn.'下单成功扣库存';
            change_stock_log($map['shop_id'],$order_id,$pre_num+$s_num,$map['goods_id'],$v['goods_number'],1,$desc,1,$attr_key);
        }
    }
    public function add_three_stock($map,$v,$order_id){//加库存
        $pre_num=M('ShopsGoodsStock')->where($map)->getField('goods_number');
        $data['updatetime']=NOW_TIME;
        $data['goods_number']=array('exp','goods_number+'.$v['goods_number']);
        $data['sell_count']=array('exp','sell_count-'.$v['goods_number']);
        $res=M('ShopsGoodsStock')->where($map)->save($data);
        $order_sn=idtoname($order_id,'ThreeOrder','ordersn');
        if($res){
            $t_map=array();$t_map['id']=$order_id;
            $t_data=array(); $t_data['is_reduce']=1;
            M('ThreeOrder')->where($t_map)->save($t_data);
            $code=idtoname($order_id,'ThreeOrder','code');
            $code_msg='京东到家';
            if($code=='ele')$code_msg='饿了么';
            $desc=$code_msg."订单".$order_sn."退货库存增加";
            $attr_key=empty($map['goods_stock'])?'':$map['goods_stock'];
            change_stock_log($map['shop_id'],$order_id,$pre_num,$map['goods_id'],$v['goods_number'],0,$desc,11,$attr_key);
        }
    }
}
?>