<?php
/** 收银
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author lss <lss@qq.com>
 */

namespace Pad\Model;
use Think\Model;
class CashierModel extends Model{
    protected $tableName = 'member';
    /**
     * 查询会员优惠信息 点击向他收款需要信息
     * @param $postdata
     * @return array
     */
    public function member_discount($postdata){
        $return=array('status'=>0,'msg'=>'');
        $uid=$postdata['uid'];
        $shop_id=$postdata['shop_id'];
        $keyword=$postdata['keyword'];
        if(empty($uid) && empty($keyword)){$return['msg']='请选择会员';return $return;}
        $map=array();
        if($uid) $map['id']=$uid;
        if($keyword) $map['mobile|card_sn']=$keyword;
        $map['status']=1;
        $map['is_tmp']=0;
        $count=M('Member')->where($map)->count();
        if($count){
            $return['status']=1;
            $member_info=M('Member')->where($map)->field('id,mobile,nickname,rank_id,usepoints,money,real_name,guide,header_img')->find();
            /*查询会员等级start*/
            $map=array();
            $map['status']=1;
            $map['id']=$member_info['rank_id'];
            $member_rank=M('MemberRank')->where($map)->field('name,goods_price')->find();
            if(empty($member_rank['goods_price'])) $member_discount=0;
            else $member_discount=$member_rank['goods_price'];
            /*查询会员等级end*/
            /*查询等级特权start*/
            $map = array();
            $rank_limit = "'0,".$member_info['rank_id']."'";
            $map['rank_limit'] = array('IN',$rank_limit);
            $map['status'] = 1;
            $map['consumption_type']=2;
            $order='id desc';
            $info = M('ManypointsRule')->where($map)->order($order)->field(true)->find();
            if($info){
                $member['huodong_min']=$info['money_limit'];
                $member['huodong_num']=$info['give_num'];
            }
            /*查询等级特权end*/
            $member=$member_info;//会员信息
            $member['daogou_name']=empty($member['guide'])?'':idtoname($member['guide'],'ShopsAccount','name','id',false);
			$member['username']=show_user_name($member_info['id']);
            $member['header_img']=thumb($member['header_img']);
            $member['score']=$member_info['usepoints'];//会员可使用积分
            $member['member_discount']=$member_discount;//会员等级优惠
            $member['user_rank']=$member_rank['name'];//会员等级名称
            $member['rank_id']=$member_info['rank_id'];//会员等级id
            $member['pay_rate']=C('INTGRAL_PAY_RATIO');
            $member['web_rate']=C('WEB_INTEGRAL_RATIO');
            
            
            if($shop_id && ($member['mobile'] || $member['real_name'] || $member['username'] || $member['nickname'])){
                $is_hide_phone=idtoname($shop_id,'Shops','is_hide_phone');
                if($is_hide_phone==1){
                    if($member['nickname'] && $member['nickname']==$member['mobile'])$member['nickname']=str_cutmobile($member['nickname']);
                    if($member['mobile'])$member['mobile']=str_cutmobile($member['mobile']);
                    if($member['real_name'] && strlen($member['real_name'])==11)$member['real_name']=str_cutmobile($member['real_name']);
                    if($member['username'] && strlen($member['username'])==11)$member['username']=str_cutmobile($member['username']);
                }
            }
            
            $return['data']=$member;
        }else{
            $return['msg']='请确认此会员是否存在';
        }
        return $return;
    }
    /*首页挂单相关操作start*/
    //挂单
    public function guadan($postdata){
        $return=array('status'=>0,'msg'=>'');
        $postdata=I('post.');
        if(empty($postdata['goods_info']) || $postdata['goods_info']==',' || empty($postdata['goods_table']) || empty($postdata['total_price'])){
            $return['msg']='请先添加商品';return $return;
        }
        if(empty($postdata['shop_id'])){
            $return['msg']='商家参数错误';return $return;
        }
        unset($postdata['id']);
        $data=$postdata;
        $data['goods_table']=htmlspecialchars_decode(urldecode($data['goods_table']));
        $data['shop_id']=$postdata['shop_id'];
        if(!empty($postdata['shop_loginname']))$data['shop_loginname']=$postdata['shop_loginname'];
        $check=D('ShopsGuadan')->where($data)->count();
        if($check){
            $return['msg']='请不要重复提交';return $return;
        }
        $data['addtime']=NOW_TIME;
        $res=D('ShopsGuadan')->add($data);
        if($res){
            $info=array('id'=>$res,'username'=>$data['username'],'total_price'=>$data['total_price'],'addtime'=>time_format($data['addtime'],'H:i:s'));
            $return['status']=1;
            $return['data']=$info;
            return $return;
        }else{
            $return['msg']='挂单失败';return $return;
        }
    }
    //删除挂单
    public function del_guadan($postdata){
        $return=array('status'=>0,'msg'=>'');
        $id=intval($postdata['id']);
        if(empty($id)){$return['msg']='参数错误'; return $return;}
        $map=array();
        $map['shop_id']=$postdata['shop_id'];
        $map['id']=$id;
        $info=D('ShopsGuadan')->where($map)->delete();
        if(empty($info)){
            $return['msg']='挂单删除失败';return $return;
        }else{
            $return['status']=1;return $return;
        }
    }
    //提单
    public function tidan($postdata){
        $return=array('status'=>0,'msg'=>'');
        $id=intval($postdata['id']);
        if(empty($id)){$return['msg']='参数错误';return $return;}
        $map=array();
        $map['shop_id']=$postdata['shop_id'];
        $map['id']=$id;
        $info=D('ShopsGuadan')->where($map)->field('uid,goods_info,goods_table')->find();
        if(empty($info)){
            $return['msg']='您所提单不存在';return $return;
        }
        $info['goods_table']=json_decode($info['goods_table'],1);
        $return['status']=1;
        $return['data']=$info;
        D('ShopsGuadan')->where($map)->delete();
        return $return;
    }
    /*首页挂单相关操作end*/

    /**
     * 计算总价
     */
    public function count_total($postdata){
        $return=array('status'=>0,'msg'=>'');$promot_money_json=array();
        $total_price=$pay_price=$pay_fee=$account_money=$bonu_money=$bonus_id=$member_discount=$custom_discount=$single_discount=$discount=$promote_discount=$goods_custom_discount=0;
        $uid=intval($postdata['uid']);//会员id（不是必须的用来查询会员的折扣率）
        $coupon_id=intval($postdata['coupon_id']);//优惠券id
        $coupon_code=trim($postdata['coupon_code']);//优惠券号
        $code_type=intval($postdata['coupon_type']);//优惠券检查方式 1是code，2是id
        $single_discount=floatval($postdata['single_discount']);//自定义优惠
        $single_type=intval($postdata['single_type']);//自定义优惠类型
        $pay_type=$postdata['pay_type'];//支付方式
        $use_score=intval($postdata['is_score']);
        $cash_money=floatval($postdata['cash_receivable']);//应收现金
        $cash_in_hand=floatval($postdata['cash_money']);//实收现金
        $back_money=floatval($postdata['back_money']);//找零现金
        $card_money=floatval($postdata['card_money']);//刷卡金额
        $bank_money=floatval($postdata['bank_money']);//台卡金额
        $scan_money=floatval($postdata['scan_money']);//扫码金额
        $money=floatval($postdata['money']);//余额
        $is_mix=intval($postdata['is_mix']);//是否组合支付
        $delivery_fee=floatval($postdata['delivery_fee']);//配送费
        /*处理商品相关信息计算总价格start*/
        if(!empty($postdata['cart_list'])) {
            //如果是app商品列表不用做处理
            if($postdata['is_app']==1){$cart_list = $postdata['cart_list'];}
            else{$cart_list = json_decode(htmlspecialchars_decode($postdata['cart_list']), true);}
            //循环选中的商品列表得到需要的数据
            foreach ($cart_list as $k => $v) {
                $karr = explode('-', $k);//得到属性值
                $is_sanhuo = 0;
                $goods_id = intval($karr[0]);
                if (!empty($goods_id)){
                    //判断库存
                    $num = D('Common/Cart')->shopgoodsstock($goods_id,$postdata['shop_id'],$karr[1]);
                    if(C('SHOUYIN_JINSHOU')==1 && ($num['goods_number'] <= 0 || $num['goods_number'] < $v['number'])){$return['msg'] = '库存不足！';return $return;}
                }
                if ($is_sanhuo == 0 && !empty($goods_id)) {//判断是不是散货
                    $goods_attr = array();
                    $goods_attr_key = $goods_attr['key'] = $karr[1];
                    if ($goods_attr_key) $goods_attr['name'] = attr_key2name($goods_attr_key, $goods_id);
                }
                if($v['is_redit']==1){
                    $discount_list=array();
                    $discount_list['discount_type']=$v['discount_type'];
                    $discount_list['discount_num']=$v['discount_num'];
                    $discount_list['remarks']=$v['remarks'];
                }
                $postdata['goods_list'][$k]['is_redit'] = $v['is_redit'];
                $postdata['goods_list'][$k]['goods_name'] = $v['goods_name'];
                $postdata['goods_list'][$k]['goods_number'] = $v['number'];
                $postdata['goods_list'][$k]['shop_price'] = $v['shop_price'];
                $postdata['goods_list'][$k]['active_id'] = $v['active_id'];//活动id
                $postdata['goods_list'][$k]['attr_price'] = $v['attr_price']?$v['attr_price']:$v['shop_price'];
                if($v['is_redit'])$postdata['goods_list'][$k]['after_discount_price'] = $v['attr_price'];//自定义折扣后的价格
                //无码商品的判断
                if($goods_id) $postdata['goods_list'][$k]['goods_id'] = $goods_id;
                else {
                    $postdata['goods_list'][$k]['goods_id']=0;
                }
                $postdata['goods_list'][$k]['goods_sn']=$v['goods_sn'];
                $postdata['goods_list'][$k]['shop_id']=$postdata['shop_id'];
                if($v['goods_attr_sn']) $postdata['goods_list'][$k]['goods_attr_sn']=$v['goods_attr_sn'];
                if ($goods_attr_key) {
                    $postdata['goods_list'][$k]['attr_key']=$goods_attr_key;
                    $postdata['goods_list'][$k]['goods_attr'] = serialize($goods_attr);
                }else{$postdata['goods_list'][$k]['attr_key']='';}
                if($v['is_redit'] && !empty($discount_list)) $postdata['goods_list'][$k]['custom_discount'] = serialize($discount_list);
            }
        }
        $promat_goods=array();
        if($postdata['goods_list']){
            $result=$this->goods_info($postdata['goods_list'],$uid,$postdata['shop_id']);
            if($result['status']==0){ $return['msg']=$result['info']; return $return;}
            $goods_list=$result['info']['goods_list'];
            foreach ($goods_list as $k => $v) {
                if($v['promot_id']>0)$act_id[] = $v['promot_id'];
            }
            if (!empty($act_id)) {
                $act_id=array_unique($act_id);
                $act_ids = implode(',', $act_id);
            }
            $promat_goods=$result['info']['promat_goods'];//单品优惠详情
            $yingshou=$result['info']['total_price'];//优惠后的价格
            $total_price=$result['info']['goods_amount'];//总价
            $member_discount=$result['info']['member_discount'];//折扣价格
            $promote_discount=$result['info']['promote_discount'];//限时促销
            $promot_money=floatval($result['info']['promot_money']);//优惠活动优惠总金额
            $promot_money_json=$result['info']['promot_money_json'];//优惠活动详情
            $goods_custom_discount=$result['info']['goods_custom_discount'];//商品自定义折扣价格
        }else if(!empty($postdata['ids_list'])){
			$ids_list = $postdata['ids_list'];
            //循环礼品卡列表得到需要的数据
			$ids_arr = array();
            foreach ($ids_list as $k => $v) {
                $res = $this->search_by_id($v);
				if($res['status'] == 0){
					$return['msg'] = $res['msg'];
                    return $return;
				}else{
					$ids_arr[] = $v;
				}
            }
			if($postdata['ids_list'] && $ids_arr){
				$map = array();$map['id'] = array('in',$ids_arr);$map['status'] = 0;
				$total_price = M('GiftCard')->where($map)->sum('shop_price');
				$yingshou = floatval($total_price);
			}
			$postdata['is_recharge']=2;
		}else{
            $total_price=floatval($postdata['total_price']);//订单总金额 充值用的
            $yingshou = $total_price;
            if($uid && $postdata['is_recharge']!=1 && $postdata['is_pos']!=1){
                $user_discount=$this->count_member_discount($uid,$postdata['total_price']);
                if($user_discount['status']==1) {
                    $member_discount=$user_discount['user_discount'];
                    $yingshou = $yingshou - $member_discount;
                }
            }
        }
        /*处理商品相关信息计算总价格end*/
        if($postdata['is_recharge']==1){
            $order_type=2;
        }else if($postdata['is_recharge']==2){
            $order_type=15;
        }else{
            //优惠券优惠金额
            if ($coupon_id) {
                $yingshou_coupon=$yingshou;
                if($promot_money_json){
                    foreach($promot_money_json as $v){
                        if($v['type']==4 && $v['price']>0)$yingshou_coupon=$yingshou_coupon-$v['price'];
                    }
                    foreach ($goods_list as $k => $v) {
                        if($v['promot_id']>0)$act_id[] = $v['promot_id'];
                    }
                }
                if($yingshou_coupon>0){
                    $coupons_id=idtoname($coupon_id,'CouponsGet','coupons_id');
                    $goodsids=M('PromotExt')->where('style=6 and act_id='.$coupons_id)->getField('style_ext_id',true);if(empty($goodsids))$goodsids='';
                    if(!empty($goodsids)){
                        if(empty($goods_list)){
                            $coupon_id=$yingshou_coupon=0;
                        }else{
                             foreach ($goods_list as $k => $v) {
                                if(!in_array($v['goods_id'],$goodsids)){
                                    $yingshou_coupon=$yingshou_coupon-floatval($v['real_price']);
                                }
                            }
                        }
                    }
                }
        
                if($coupon_id && $yingshou_coupon>0){
                    $coupon_discount = $this->count_coupon_discount($coupon_id, $coupon_code, $yingshou_coupon, $code_type,$postdata['shop_id']);//获取优惠的价格
                    if ($coupon_discount['status']) {
                        $bonu_money = $coupon_discount['coupon_discount']['bonu_money'];
                        $bonus_id = $coupon_discount['coupon_discount']['bonus_id'];
                        $yingshou = $yingshou - $bonu_money;//计算优惠后的实付金额
                    } else {
                        $return['msg'] = $coupon_discount['msg'];
                        return $return;
                    }
                }
            }
            //自定义优惠
            if ($single_discount > 0) {
                $discount_percent=0;
                if($single_type==1){
                    $discount_percent=(10-$single_discount)*10;
                }else if($single_type==2){
                    $discount_percent=$single_discount/$total_price*100;
                }
                if($discount_percent>C('SHOUYIN_MAXYOUHUI')){
                    $return['msg']='自定义优惠不能小于最大优惠百分比';
                    return $return;
                }
                $defined_discount = $this->count_custom_discount($single_type, $single_discount, $yingshou);//获取优惠金额
                //print_r($defined_discount);exit;
                if ($defined_discount['status']) {
                    $custom_discount = $defined_discount['custom_discount'];
                    $yingshou = $yingshou - $custom_discount;//计算优惠后的实付金额
                    if($yingshou<0){$yingshou=0;}
                } else {
                    $return['msg'] = $custom_discount['msg'];
                    return $return;
                }
            }
            //如果使用积分计算积分抵扣的钱
            if ($use_score && $uid > 0) {
                $map['id'] = $uid;
                $map['status'] = 1;
                $count = M('Member')->where($map)->count();
                if ($count) {
                    $score = M('Member')->where($map)->getField('usepoints');
                    if ($score > 0) {
                        $order_score = intval($yingshou * (C('INTGRAL_PAY_RATIO') / 100) * 100 / C('WEB_INTEGRAL_RATIO'));
                        if ($score >= $order_score) {
                            $use_score_money = $order_score * (C('WEB_INTEGRAL_RATIO') / 100);//钱
                            $use_score_num = intval($order_score);//分

                        } else {
                            $use_score_money = $score * (C('WEB_INTEGRAL_RATIO') / 100);
                            $use_score_num = intval($score);
                        }
                        $yingshou = $yingshou - $use_score_money;
                    } else {
                        $return['msg'] = '积分不足';
                        return $return;
                    }
                }
            }
            $order_type=13;
        }
        $old_pay_total_price=$total_price+$pay_fee+$delivery_fee-$bonu_money-$member_discount-$custom_discount-$use_score_money-$goods_custom_discount-$promote_discount-$promot_money;//加上手续费后的实付款金额
        $discount=$bonu_money+$member_discount+$custom_discount+$goods_custom_discount+$promote_discount+$promot_money+$use_score_money;//所有优惠的价格
        /*抹零计算start*/
        $moling=C('SHOUYIN_MOLING');
        if($moling==1){
            $pay_total_price=floatval(format_decimal($old_pay_total_price,1,3));
        }elseif($moling==2){
            $pay_total_price=floatval(format_decimal($old_pay_total_price,0,3));
        }elseif($moling==3){
            $pay_total_price=floatval(format_decimal($old_pay_total_price,1,2));
        }else{
            $pay_total_price = format_decimal($old_pay_total_price);
        }
        
        if($moling>=1){
            $moling_money=format_decimal($old_pay_total_price-$pay_total_price);
            if($moling_money>0){
                $moling_info['moling_money']=$moling_money;
                $moling_info['moling_type']=$moling;
                $moling_discount=serialize($moling_info);
                $discount=$discount+$moling_money;//优惠里增加抹零金额
            }            
        }
        /*抹零计算end*/
        /*计算支付金额参数start*/
        $pay_list=array();
        $pay_list['is_mix']=$is_mix;//是否混合支付
        $pay_list['pay_type']=$pay_type;//支付方式
        $pay_list['pay_total_price']=$pay_total_price;//需要支付的总钱数
        $pay_list['cash_money']=$cash_money;//现金支付钱数
        $pay_list['card_money']=$card_money;//刷卡支付钱数
        $pay_list['bank_money']=$bank_money;//被扫支付钱数
        $pay_list['scan_money']=$scan_money;//扫码支付钱数
        $pay_list['money']=$money;//余额支付钱数
        $pay_list['cash_in_hand']=$cash_in_hand;
        $pay_list['back_money']=$back_money;
        $pay_list['number']=$postdata['number'];//扫码支付的编号
        $pay_list['is_recharge']=$postdata['is_recharge'];//是否是充值订单
        $pay_list['shop_id']=$postdata['shop_id'];
        //$pay_list['test']=$old_pay_total_price;
        /*判读是否是混合支付得到需要的钱数start*/
        if(in_array(2,$pay_type)){
            $pay_data=$this->only_paytype($pay_list);
            $paymentinfo=$pay_data['data']['payment_info'];
        }
        if(in_array(3,$pay_type)){
            $pay_data=$this->only_paytype($pay_list);
            $paymentinfo=$pay_data['data']['payment_info'];
        }
        if(in_array(4,$pay_type)){
            $pay_data=$this->only_paytype($pay_list);
            $paymentinfo=$pay_data['data']['payment_info'];
        }
        if(in_array(5,$pay_type)){
            $pay_data=$this->only_paytype($pay_list);
            $paymentinfo=$pay_data['data']['payment_info'];
        }
        if(in_array(1,$pay_type)){
            $pay_data=$this->only_paytype($pay_list);
            $paymentinfo=$pay_data['data']['payment_info'];
        }
        if($pay_data['status']==0){$return['msg']=$pay_data['msg']; return $return;}
        $payment_info=array();
        $payment_info=$paymentinfo;
        $use_money=$pay_data['data']['use_money'];
        $cash_money=$pay_data['data']['cash_money'];
        $act_cash_in_hand=$pay_data['data']['cash_in_hand'];
        $act_back_money=$pay_data['data']['back_money'];
        $card_money=$pay_data['data']['card_money'];
        $scan_money=$pay_data['data']['scan_money'];
        $bank_money=$pay_data['data']['bank_money'];
        $pay_price=$pay_data['data']['pay_price'];
        $pay_amount_type=$pay_data['data']['pay_amount_type'];
        /*判断是否是混合支付得到需要的钱数end*/
        /*计算支付金额参数end*/
        $return['status']=1;
        $return['data']=$goods_list;
		$return['ids_arr'] = $ids_arr;
        $return['total_info']=array(
            'total_price'=>$total_price,//商品总价
            'pay_price'=>$pay_price,//线上支付价格
            'pay_amount_type'=>$pay_amount_type,
            'pay_fee'=>format_decimal($pay_fee),//手续费
            'delivery_fee'=>format_decimal($delivery_fee),//配送费
            'discount'=>$discount,//总优惠价格
            'promat_goods'=>$promat_goods,//单品优惠详情
            'promot_money'=>floatval($promot_money+$promote_discount),//优惠活动/限时促销优惠总金额
            'promot_money_json'=>$promot_money_json,//优惠活动详情
            'payment_info'=>$payment_info,//使网银支付信息
            'pay_total_price'=>$pay_total_price,//订单实际支付的金额=商品总价+总运费-活动折扣-红包折扣-积分抵扣
            'bonus_id'=>$bonus_id,//红包 ID
            'bonu_money'=>$bonu_money,//红包/优惠抵扣的价格
            'member_discount'=>$member_discount,//会员折扣价格
            'custom_discount'=>$custom_discount,//自定义折扣价格
            'moling_discount'=>$moling_discount,//抹零信息
            'goods_custom_discount'=>$goods_custom_discount,//商品自定义折扣价格
            'cash_in_hand'=>$act_cash_in_hand,//实收现金
            'cash_money'=>$cash_money,//现金支付金额
            'card_money'=>$card_money,//刷卡支付金额
            'scan_money'=>$scan_money,//扫码支付金额
            'bank_money'=>$bank_money, //网银支付金额
            'back_money'=>$act_back_money,//找零现金
            'use_money'=>$use_money,//余额支付金额
            'used_score'=>$use_score_num,//使用积分个数
            'used_score_money'=>$use_score_money,//使用积分抵扣钱数
            'order_type'=>$order_type,//订单类型
            'act_ids'=>$act_ids,//活动id
        );
        return $return;
    }

    public function only_paytype($pay_info){
        $return=array('status'=>0,'msg'=>'');
        $cash_money=$use_money=$scan_money=$bank_money=$card_money=$cash_in_hand=$back_money=0;
        $pay_amount_type=0;
        if(!in_array($pay_info['pay_type'],array(3))){
            $site_paytype=check_re_pay();
            switch($site_paytype){
                case "1":
                    $pay_codepos='MMSCAN';
                    $pay_code='MMSCAN';
                    break;
                case "2":
                    $pay_codepos='STARPOS';
                    $pay_code='STARPOS';
                    break;
                case "3":
                    $pay_codepos='CHINAUMSPOS';
                    $pay_code='CHINAUMS';
                    break;
                default:
                    $return['msg']='您还没有认证，请先认证';
                    return $return;
                    break;
            }
        }
        foreach($pay_info['pay_type'] as $k => $v){
            switch($v){
                case "1"://现金支付
                    //判断现金支付金额是否小于0，若小于等于0则这个支付方式直接跳过
                    if($pay_info['cash_money']<0){ continue;}
                    $payment_info=array('id'=>2,'code'=>'HANCHAO_XIANJIN','assist_code'=>'HANCHAO_XIANJIN','name'=>'现金支付');
                    $cash_money=$pay_info['cash_money'];
                    $cash_in_hand = $pay_info['cash_in_hand'];
                    $back_money=$pay_info['back_money'];
                    break;
                case "5"://5 刷卡
                    //判断刷卡支付金额是否小于0，若小于等于0则这个支付方式直接跳过
                    if($pay_info['card_money']<0){ continue;}
                    $payment_info=array('id'=>'19','code'=>'HANCHAO_CARD','assist_code'=>'HANCHAO_CARD','name'=>'刷卡支付');
                    $card_money=$pay_info['card_money'];
                    break;
                case "4"://4 台卡
                    //判断台卡支付金额是否小于0，若小于等于0则这个支付方式直接跳过
                    if($pay_info['bank_money']<0){ continue;}
                    $payment_info=array('id'=>'21','code'=>'HANCHAO_DECCA','assist_code'=>'HANCHAO_DECCA','name'=>'台卡支付');
                    $bank_money=$pay_info['bank_money'];
                    break;
                case "3"://3 扫码支付 主扫
                    //判断扫码支付金额是否小于0，若小于等于0则这个支付方式直接跳过
                    if($pay_info['scan_money']<0){ continue;}
                    //$site_paytype=check_re_pay();
                    $scan_money=$pay_info['scan_money'];
                    $pay_price=$pay_info['scan_money'];
                    if(intval($pay_info['number'])){
                        $pay_first=substr($pay_info['number'],0,1);
                        if($pay_first==1){//微信
                            $payment_info=array('id'=>'20','code'=>$pay_codepos,'assist_code'=>'HANCHAO_S_WEIXIN','name'=>'微信支付');
                        }
                        if($pay_first==2){//支付宝
                            $payment_info=array('id'=>'20','code'=>$pay_codepos,'assist_code'=>'HANCHAO_S_ALIPAY','name'=>'支付宝支付');
                        }
                    }
                    $pay_amount_type=2;//线上支付扫码支付类型
                    break;
                case "2"://2 余额支付
                    //判断余额支付金额是否小于0，若小于等于0则这个支付方式直接跳过
                    if($pay_info['is_recharge']==1){
                        $return['msg']='该业务不支持余额支付';
                        return $return;
                    }
                    $map=array();
                    $map['id']=$pay_info['shop_id'];
                    $is_share_money=M('Shops')->where($map)->getField('is_share_money');
                    if($is_share_money==0){$return['msg']='未开通余额支付';return $return;}
                    if($pay_info['money']<0){ continue;}
                    $use_money=$pay_info['money'];
                    $payment_info=array('id'=>1,'code'=>'HANCHAO','assist_code'=>'HANCHAO','name'=>'余额支付');
                    break;
            }
        }

        $total_money=$cash_in_hand+$card_money+$bank_money+$scan_money+$use_money;
        if(($total_money+0.1)<=$pay_info['pay_total_price']){
            $return['msg']='输入的支付金额不能小于总金额';//.$total_money.'<'.$pay_info['pay_total_price'].'<'.$pay_info['test']
            return $return;
        }
        if($total_money-0.1>=$pay_info['pay_total_price'] && !in_array(1,$pay_info['pay_type'])){
            $return['msg']='输入的支付金额不能大于总金额';//.$total_money.'<'.$pay_info['pay_total_price']
            return $return;
        }
        $return['status']=1;
        $return['data']['payment_info']=$payment_info;
        $return['data']['cash_money']=$cash_money;//现金支付金额
        $return['data']['cash_in_hand']=$cash_in_hand;//现金实际支付金额
        $return['data']['back_money']=$back_money;
        $return['data']['use_money']=$use_money;//余额支付金额
        $return['data']['scan_money']=$scan_money;//扫码支付金额
        $return['data']['bank_money']=$bank_money;//网银支付金额
        $return['data']['card_money']=$card_money;//刷卡支付金额
        $return['data']['pay_price']=$pay_price;//线上支付总金额
        $return['data']['pay_amount_type']=$pay_amount_type;//线上支付方式类型0没有线上支付 1台卡支付 2 扫码支付
        return $return;
    }

    /**
     * 添加订单
     */
    public function add_order($postdata){
        $return=array('status'=>0,'msg'=>'');
        //判断支付方式
        $pay_type=$postdata['pay_type'];
        if(empty($pay_type)){$return['msg']='支付方式错误';return $return;}
        if(empty($postdata['cart_list']) && floatval($postdata['total_price'])<=0){ $return['msg']='请选择商品或输入金额';return $return;}
        $uid=intval($postdata['uid']);
        $pwd=$postdata['paypassword'];
        $userinfo=array();
        if($uid){
            $map=array();
            $map['id']=$uid;
            $map['status']=1;
            //$map['is_tmp']=0;
            $userinfo=M('Member')->where($map)->field('id,username,nickname,mobile,email,rank_id,paypassword,money,usepoints,salt')->find();
            if(empty($userinfo)){$return['msg']='该会员不存在!';return $return;}
            $is_on_credit=C('IS_ON_CREDIT');
            $on_credit_val=C('MAX_ON_CREDIT');
            if($is_on_credit==1 && $on_credit_val==0){
                $max_on_credit=format_decimal(20000000000);
            }elseif($is_on_credit==1 && $on_credit_val>0){
                $max_on_credit=format_decimal($on_credit_val);
            }else $max_on_credit=format_decimal(0);
            $user_money = $userinfo['money']+$max_on_credit;
        }
        $check_usermoney=false;//是否检查会员账户余额
        foreach($pay_type as $k => $v){
            switch($v){
                case "1"://1 现金支付
                    break;
                case "2"://2 余额支付
                    $map=array();
                    $map['id']=$postdata['shop_id'];
                    $is_share_money=M('Shops')->where($map)->getField('is_share_money');
                    if($postdata['is_recharge']==1){$return['msg']='该业务不支持余额支付!';return $return;}
                    if($is_share_money==0){$return['msg']='未开通余额支付';return $return;}
                    if(empty($uid)){$return['msg']='请选择余额支付的会员!';return $return;}
                    $is_open_pwd=C('OPEN_CASHIER_PAYPSW');
                    if($is_open_pwd==1){
                        if(empty($userinfo['paypassword'])){
                            if(!empty($pwd)){$return['msg']='该会员没有设置支付密码'; return $return;}
                        }else{
                            if(empty($pwd)){$return['msg']='请输入支付密码'; return $return;}
                            if(!preg_match("/^\d{6}$/",$pwd)){
                                $return['msg']='支付密码必须为六位数字';
                                return $return;
                            }
                            if(creatpwd($pwd,'HANCHAO'.$userinfo['salt']) != $userinfo['paypassword']){
                                $return['msg']='支付密码错误'; return $return;
                            }
                        }
                    }
                    //赊账判断
                    if($user_money<=0){$return['msg']='该会员余额不足!';return $return;}
                    $check_usermoney=true;
                    break;
                case "3"://3 扫码支付（主扫）
                    break;
                case "4"://4 台卡（被扫）
                    break;
                case "5"://5 刷卡
                    break;
            }
        }
        $data=$this->count_total($postdata);
        if($data['status']==0){$return['msg']=$data['msg']; return $return;}
        if ($check_usermoney && $data['total_info']['use_money'] > $user_money) {//检查会员余额是否足够支付
            $return['msg'] = '该会员余额不足!';
            return $return;
        }
        $order=array();
        $order['order_sn']        = createOrderNo();//订单编号
        $order['type']            = $data['total_info']['order_type'];//订单类型
        $order['uid']             = $userinfo['id']; //会员id（可以为空，用于看是否是会员抵扣）
        $order['shop_id']         = $postdata['shop_id'];//商家id
        $order['sa_id'] = $postdata['sid'];
        $order['in_online']=1;
        $order['sign_building']   = $postdata['login_name'];//借用字段记录当前收银员用户名
        $order['shipping_status'] = 1;//配送状态
        $order['pay_code']        = $data['total_info']['payment_info']['code'];//支付方式id
        $order['assist_code']    =$data['total_info']['payment_info']['assist_code'];//支付方式辅助code
        $order['payment_id']      = $data['total_info']['payment_info']['id'];//支付方式id
        $order['pay_fee']         = $data['total_info']['pay_fee'];//支付手续费
        $order['pay_status']      = 1;//支付状态
        $order['goods_amount']    = $data['total_info']['total_price']-$data['total_info']['bonu_money']-$data['total_info']['member_discount']-$data['total_info']['custom_discount'];//订单实际金额(减去折扣的) 没减红包
        $order['goods_allmoney']  = $data['total_info']['total_price'];//商品总价
        $order['pay_amount']      = $data['total_info']['pay_price'];//在线支付的金额
        $order['pay_amount_type'] = $data['total_info']['pay_amount_type'];//在线支付方式的类型
        $order['order_amount']    = $data['total_info']['pay_total_price'];//应付款金额减去折扣和红包 订单总金额
        $order['order_money']     = $data['total_info']['pay_total_price']-$data['total_info']['delivery_fee']-$data['total_info']['pay_fee'];//应付款金额减去折扣和红包 订单总金额
        $order['discount']        = $data['total_info']['discount'];//折扣金额
        $order['bonus_money']     = $data['total_info']['bonu_money'];//使用红包金额
        $order['bonus_id']        = $data['total_info']['bonus_id'];//使用红包id
        $order['member_discount'] = $data['total_info']['member_discount'];
        $order['custom_discount'] = $data['total_info']['custom_discount'];
        $order['moling_discount'] = $data['total_info']['moling_discount'];
        if($data['total_info']['promot_money']>0){
            $order['promot_money']      = $data['total_info']['promot_money'];//优惠活动优惠总金额
            $order['promot_money_json'] = json_encode($data['total_info']['promot_money_json']);//优惠活动详情
        }
        /*每个支付方式支付的钱数start*/
        $order['cash_in_hand']   = $data['total_info']['cash_in_hand'];//实收现金
        $order['cash_money']     = $data['total_info']['cash_money'];//使用现金支付的钱
        $order['used_money']     = $data['total_info']['use_money'];//使用余额支付的钱
        $order['card_money']     = $data['total_info']['card_money'];//刷卡支付的钱
        $order['scan_money']     = $data['total_info']['scan_money'];//扫码支付的钱
        $order['bank_money']     = $data['total_info']['bank_money'];//网银支付的钱
        $order['back_money']     = $data['total_info']['back_money'];//找零现金
        if($data['total_info']['use_money']>0) {
            if ($userinfo['money'] > 0 && $userinfo['money'] < $data['total_info']['use_money']) {
                $order['on_credit_money'] = $data['total_info']['use_money'] - $userinfo['money'];
            } elseif ($userinfo['money'] < 0) {
                $order['on_credit_money'] = $data['total_info']['use_money'];
            }
            if($order['on_credit_money']>0) $order['on_credit_status']=1;
        }else{
            $order['on_credit_money'] = format_decimal(0);
            $order['on_credit_status'] = 0;
        }
        /*每个支付方式支付的钱数end*/
        /*配送信息start*/
        $order['delivery_fee']    = $data['total_info']['delivery_fee'];//运费
        if($data['total_info']['order_type']==13){
            $order['consignee'] = empty($postdata['consignee'])?'':$postdata['consignee'];
            $order['province'] = $postdata['province'];
            $order['city'] = $postdata['city'];
            $order['district'] = $postdata['district'];
            $order['address'] = empty($postdata['address'])?'':$postdata['address'];
            $order['mobile'] = $postdata['mobile'];
            $order['xpoint'] = $postdata['xpoint'];
            $order['ypoint'] = $postdata['ypoint'];
            if(empty($postdata['best_time']) && $postdata['peisong_time']==1) {$best_time=NOW_TIME;}
            elseif(!empty($postdata['best_time'])){$best_time=strtotime(date("Y-m-d").$postdata['best_time']);}
            $order['best_time']=$best_time;
            if(!empty($postdata['code'])) {
                $order['distribute'] = empty($postdata['code'])?'':$postdata['code'];//配送物流
                $order['send_type'] = 2;
            }
        }
        /*配送信息end*/
        $order['promot_id']       = $data['total_info']['act_ids'];//店铺下所有商品参与的活动id(以逗号分隔)
        if($data['total_info']['order_type']==2) $order['status']          = 2;//订单状态
        else $order['status']          = 1;//订单状态
        $order['used_score']      = $data['total_info']['used_score'];//使用积分
        $order['used_score_money']= $data['total_info']['used_score_money'];//使用积分对应金额
        $order['addtime']         = NOW_TIME;
        if($postdata['source']) $order['source'] = $postdata['source'];
        else $order['source']          = 4;//来源0电脑，1手机版，2app
        $order['profit']          =0;//利润
        $order['first_money']    =0;//首单减免金额
        $order['guide']      = $postdata['cashier_id'];//导购员id
        $order_id=M('OrderInfo')->add($order);
        if(empty($order_id)) {$return['msg']='添加订单失败';return $return;}
		if($order_id && $data['ids_arr'] && $order['type'] == 15){
			$gc_save_data = $gc_map = array();
			$gc_map['id'] = array('in',$data['ids_arr']);$gc_map['status'] = 0;
			$gc_save_data['order_id'] = $order_id;
			M('GiftCard')->where($gc_map)->save($gc_save_data);
		}
        //如果有商品添加商品
        if($data['data']){
            foreach($data['data'] as $index=> $vv){
                $order_goods = array();
                $goodsinfo= idtoname($vv['goods_id'],'Goods','staff_comm,money,is_referral,commission,sale_type,supply_price','id',false);
                $supplier_price=0;
                $order_goods['order_id']     = $order_id;
                $order_goods['goods_id']     = $vv['goods_id'];
                $order_goods['goods_name']   = $vv['goods_name'];
                if($vv['goods_attr_sn']) $order_goods['goods_sn'] = $vv['goods_attr_sn'];
                else $order_goods['goods_sn']     = $vv['goods_sn'];
                $order_goods['goods_number'] = $vv['goods_number'];
                $order_goods['attr_price']   = $vv['attr_price'];
                $order_goods['goods_price']  = $vv['goods_price'];
                if($goodsinfo['sale_type']==1){
                    $supply_price =D('Common/Cart')->groupprice($vv['goods_id'],$vv['shop_id']);
                    $order_goods['supplier_price'] =$supply_price['supply_price'];
                }else{
                    $map_sg=array();
                    $map_sg['goods_id']=$vv['goods_id'];
                    $map_sg['shop_id']=$vv['shop_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['goods_attr']   = $vv['goods_attr'];//属性
                $order_goods['promot_id']    = $vv['promot_id'];//活动id
                $order_goods['shop_id']      = $vv['shop_id'];//店铺id
                $order_goods['suppliers_id'] = $vv['suppliers_id'];//供货商
                $order_goods['addtime']      = NOW_TIME;
                $order_goods['status']       = 0;//商品的发货状态
                $order_goods['is_balance']   = 0;//未结算
                $order_goods['is_sanhuo']    = $vv['is_sanhuo'];//未结算
                $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'] = $goodsinfo['commission'];//加固定分佣金额
                if($v['custom_discount']) $order_goods['custom_discount'] = $vv['custom_discount'];
                if(!empty($data['total_info']['promat_goods'][$index])){
                    $promat_goods=$data['total_info']['promat_goods'][$index];
                    if(!empty($promat_goods['discount_member']))$order_goods['discount_member']=$promat_goods['discount_member'];//会员优惠金额(单个)
                    if(!empty($promat_goods['discount_xianshi']))$order_goods['discount_xianshi']=$promat_goods['discount_xianshi'];//限时促销优惠金额(单个)
                    if(!empty($promat_goods['discount_custom']))$order_goods['discount_custom']=$promat_goods['discount_custom'];//自定义优惠金额(单个) 
                }                
                M('OrderGoods')->add($order_goods);
            }
        }
        $return=$this->payorder($order_id,$postdata['number'],$postdata['coupon_code'],$pay_type);//去支付
        if($postdata['save_address']==1 && $postdata['uid'] && $return['status']=1){
            $address_data=array();
            $address_data['uid']=$postdata['uid'];
            $address_data['address_id']=$postdata['address_id'];
            $address_data['province']=$postdata['province'];
            $address_data['city']=$postdata['city'];
            $address_data['district']=$postdata['district'];
            $address_data['consignee']=$postdata['consignee'];
            $address_data['mobile']=$postdata['mobile'];
            $address_data['address']=$postdata['address'];
            $address_data['xpoint']=$postdata['xpoint'];
            $address_data['ypoint']=$postdata['ypoint'];
            $this->edit_address($address_data);
        }
        return $return;
    }
    //支付订单
    public function payorder($order_id,$number,$code='',$pay_type){
        $return=array('status'=>0,'msg'=>'');
        if(empty($order_id)){$return['msg']='订单信息错误!';return $return;}
        $map=array();
        $map['id']=$order_id;
        $map['pay_status']=1;
        $order_info=M('OrderInfo')->where($map)->field(true)->find();
        if(empty($order_info)){$return['msg']='订单信息错误!';return $return;}
        $pay_code=strtoupper($order_info['pay_code']);
        $payment_info=array();
        $payment_info['order_id']         =$order_id;
        $payment_info['user_id']          =$order_info['uid'];
        $payment_info['type']             =$order_info['type'];
        $payment_info['order_sn']         =createOrderNo();
        $payment_info['shop_id'] = $order_info['shop_id'];
        $payment_info['cashier_name'] = $order_info['sign_building'];
        $payment_info['guide'] = $order_info['guide'];
        $payment_info['in_online'] = $order_info['in_online'];
        /*每个支付方式支付的钱数start*/
        $payment_info['cash_money']     = $order_info['cash_money'];//使用现金支付的钱
        $payment_info['use_money']     = $order_info['used_money'];//使用余额支付的钱
        $payment_info['card_money']     = $order_info['card_money'];//刷卡支付的钱
        $payment_info['scan_money']     = $order_info['scan_money'];//扫码支付的钱
        $payment_info['bank_money']     = $order_info['bank_money'];//网银支付的钱
        $payment_info['back_money'] = $order_info['back_money'];//找零金额
        /*每个支付方式支付的钱数end*/
        $payment_info['need_pay']         =$order_info['pay_amount'];//还需支付的金额
        $payment_info['use_score']        =$order_info['used_score'];//积分
        $payment_info['use_score_money']  =$order_info['used_score_money'];//积分所抵的钱
        $payment_info['order_total_price']=$order_info['order_money'];//订单实际支付的金额=商品总价+总运费-活动折扣-红包折扣
        $payment_info['payment_id']       =$order_info['payment_id'];//支付方式
        $payment_info['payment_fee']      =$order_info['pay_fee'];//支付手续费
        $payment_info['pay_amount']       =$order_info['pay_amount'];//
        $payment_info['pay_amount_type'] =$order_info['pay_amount_type'];
        $payment_info['pay_code']         =$pay_code;//支付code
        $payment_info['is_paid']          =0;
        $payment_info['create_time']      =NOW_TIME;
        //生成支付单
        $pay_log_id=M('PayLog')->add($payment_info);
        if(empty($pay_log_id)){$return['msg']='支付单信息错误!';return $return;}
        //积分支付扣除会员积分
        if($order_info['used_score'] >0 && $order_info['uid']){
            account_change($order_info['uid'],-$order_info['used_score'],4,4,'积分抵现消费,订单'.$order_info['order_sn']);
        }
        //余额支付判断以及查询会员信息
        $userinfo=array();
        if($order_info['uid'] && (in_array(2,$pay_type) || $order_info['used_score']>0)){
            $map=array();
            $map['id']=$order_info['uid'];
            $userinfo=M('Member')->where($map)->field('money,usepoints')->find();
        }
        $is_payed=0;
        foreach($pay_type as $k => $v) {
            switch ($v) {
                case '1'://现金付
                    $is_payed = 1;
                    break;
                case '2'://余额支付
                    $is_on_credit = C('IS_ON_CREDIT');
                    $on_credit_val = C('MAX_ON_CREDIT');
                    if ($is_on_credit == 1 && $on_credit_val == 0) {
                        $max_on_credit = format_decimal(20000000000);
                    } elseif ($is_on_credit == 1 && $on_credit_val > 0) {
                        $max_on_credit = format_decimal($on_credit_val);
                    } else $max_on_credit = format_decimal(0);
                    $user_money = $userinfo['money'] + $max_on_credit;
                    if ($user_money >= $order_info['used_money']) {
                        account_change($order_info['uid'], -$order_info['used_money'], 1, 4, '收银商品支付,订单' . $order_info['order_sn']);
                        $is_payed = 1;
                    }
                    break;
                case '5'://刷卡支付
                    $is_payed = 1;
                    break;
                case '4'://台卡支付
                    $is_payed = 1;
                    break;
                case '3'://双乾C扫B接口、B扫C接口
                    $is_payed = 0;
                    $return['status'] = 2;
                    $return['pay'] = $pay_log_id;
                    break;
                default:
                    $return['msg'] = '支付方式错误!';
                    return $return;
                    break;
            }
        }
        $pay_info=array();
        $pay_info['code']=$code;
        if($return['status']==2 && $is_payed==0){
            $snpay=$this->scan_pay($pay_log_id,$number);//扫码支付
            return $snpay;
        }
        if($is_payed){
            //处理订单
            if(empty($pay_info['out_trade_no']))$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['order_id']=$order_id;
                $return['is_success']=1;
            }else{
                $return['msg']=$res['msg'];
                return $return;
            }
        }else{
            $return['msg']='支付失败!';return $return;
        }
        return $return;
    }
    /**
     * 多种接口的扫码支付共用方法
     * @param string $pay_log_id  paylog表的id 用来查询所有的订单信息
     * @param string $number B扫C的时候获取到用户的支付码
     * @return array
     */
    private function scan_pay($pay_log_id='',$number=''){
        $return=array('status'=>0,'msg'=>'');
        $pay_log_id=intval($pay_log_id);//格式化pay_log_id
        if(empty($pay_log_id)){$return['msg']='支付单信息错误!';return $return;}
        $where=array();
        $where['id']=$pay_log_id;
        $where['is_paid']=array('neq',1);
        $pay_info = M('PayLog')->where($where)->field(true)->find();//查询符合条件的支付单信息
        if(empty($pay_info['order_sn'])){$return['msg']='支付单信息错误!';return $return;}
        $pay_code=ucfirst(strtolower($pay_info['pay_code']));//转化支付方式code为首字母大写其他小写
        if(empty($pay_code)){$return['msg']='支付方式错误!';return $return;}
        $p_map=array();
        $p_map['status']=1;
        $p_map['code']=$pay_code;
        $payconfig=M('Payment')->where($p_map)->field(true)->find();
        if(empty($payconfig) || empty($payconfig['config_account'])){$return['msg']='支付通道未开通！'; return $return;}
        $paycode=strtoupper($pay_info['pay_code']);
        $return['paycode']=$paycode;
        switch($paycode){
            case 'CHINAUMS'://银联C扫B接口
                $pay = new \Common\Vendor\Pay($pay_code,$payconfig);
                $vo = new \Common\Vendor\Pay\PayVo();
                $vo->setFee($pay_info['bank_money'])
                    ->setOrderNo($pay_info['order_sn'])
                    ->setParam($pay_info);
                $RequestForm=$pay->buildRequestForm($vo);
                if($RequestForm['status']){
                    $return['status']=1;
                    $pay_save = array();
                    $pay_save['serial_number'] = $RequestForm['url'];
                    $map = array();
                    $map['order_sn'] = $pay_info['order_sn'];
                    M('PayLog')->where($map)->save($pay_save);
                    $return['order_id']=$pay_info['order_id'];
                    $url= $RequestForm['url'];
                    $return['url']=$url;
                    return $return;
                }else{
                    return $RequestForm;
                }
                break;
            case 'CHINAUMSPOS'://银联B扫C接口
                if(empty($number)){$return['msg']='付款码错误!';return $return;}
                $payconfig['is_app']=1;//是否是APP
                $pay = new \Common\Vendor\Pay($pay_code,$payconfig);
                $vo = new \Common\Vendor\Pay\PayVo();
                $title_name='收银';
                $vo->setBody($title_name)
                    ->setFee($pay_info['need_pay'])
                    ->setTitle($title_name)
                    ->setOrderNo($pay_info['order_sn'])
                    ->setParam($payconfig)
                    ->setProduct_id($number);
                $RequestForm=$pay->buildRequestForm($vo);
                $return['status']=1;
                $return['order_id']=$pay_info['order_id'];
                return $return;
                break;
            case 'MMSCAN'://双乾C扫B接口、B扫C接口调用接口类
                $map=array();
                $map['id']=$pay_info['order_id'];
                $assist_code=M('OrderInfo')->where($map)->getField('assist_code');//获取辅助码
                //支付接口用到的支付类型
                if($assist_code=='HANCHAO_S_ALIPAY'){//支付宝支付
                    $pay_info['pay_type']='ZFBZF';
                }
                if($assist_code=='HANCHAO_S_WEIXIN'){//微信支付
                    $pay_info['pay_type']='WXZF';
                }
                if($assist_code=='HANCHAO_S_ALIPAY' || $assist_code=='HANCHAO_S_WEIXIN'){
                    if(empty($number)){$return['msg']='付款码错误!';return $return;}
                    $pay_info['tran_code']='SMZF003';//B扫C接口编号
                    $pay_info['scene']=1;
                }else{
                    $pay_info['tran_code']='SMZF010';
                    $pay_info['user_id']=get_openid();
                }
                //标题
                $title_name=$pay_info['order_sn']."扫码支付";
                $pay = new \Common\Vendor\Pay($pay_code,$payconfig);
                $vo = new \Common\Vendor\Pay\PayVo();
                $vo->setBody($title_name)
                    ->setFee($pay_info['need_pay'])
                    ->setTitle($title_name)
                    ->setOrderNo($pay_info['order_sn'])
                    ->setParam($pay_info)
                    ->setProduct_id($number);
                $RequestForm=$pay->buildRequestForm($vo);
                $snpay=json_decode($RequestForm);
                //print_r($snpay);exit;
                if($snpay[0]->respCode=='88'){
                    $return['is_success']=1;
                    $return['status']=1;
                    //$return['data']['status']=1;
                    if($assist_code=='HANCHAO_S_WEIXIN'){
                        $return['content']='微信到账'.$pay_info['need_pay'].'元';
                    }
                    if($assist_code=='HANCHAO_S_ALIPAY'){
                        $return['content']='支付宝到账'.$pay_info['need_pay'].'元';
                    }
                    $return['order_id']=$pay_info['order_id'];
                    return $return;
                }elseif($snpay[0]->respCode=='100000' || $snpay[0]->respCode=='200000' || $snpay[0]->respCode=='000000'){
                    $return['status']=1;
                    $return['order_id']=$pay_info['order_id'];
                    return $return;
                }else{
                    $return['msg']=$snpay[0]->respMess;                 
                    return $return;
                }
                break;
            default:
                $return['msg']='支付方式错误!';return $return;
                break;
        }
    }
    //结束订单支付
    public function endorder($info){
        $return=array('status'=>0,'msg'=>'');
        if(empty($info)){$return['msg']='支付单信息错误!';return $return;}
        $map=array();
        $map['order_sn'] = $info['out_trade_no'];
        $pay_info = M("PayLog")->where($map)->field(true)->find();
        $all_money=format_decimal($pay_info['use_money']+$pay_info['cash_money']+$pay_info['card_money']+$info['money']+$pay_info['bank_money']);
        $order_total_price=format_decimal($pay_info['order_total_price']);
        $differ_price=format_decimal($order_total_price-$all_money);
        //if (format_decimal($pay_info['use_money']+$pay_info['cash_money']+$pay_info['card_money']+$info['money']+$pay_info['bank_money']) >= format_decimal($pay_info['order_total_price'])) {
        if($differ_price<=0.1 && $differ_price>=-0.1){
            $map=array();
            $map['id']=$pay_info['order_id'];
            $order_info=M('OrderInfo')->where($map)->field('bonus_id,shop_id,guide,order_sn,uid')->find();
            if($order_info['bonus_id']){//核销优惠券
                D('Shop/CouponsGet')->confirm_coupons($order_info['bonus_id'],$order_info['shop_id'],1,$info['code']);
            }
            $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) {
                $orderwhere=$updatedata=array();
                $orderwhere['id'] = $pay_info['order_id'];
                $orderwhere['pay_status'] = array('neq',3);
                $orderwhere['status'] = array('lt',3);
                $updatedata['pay_status'] =3;
                if($info['pay_sn'])$updatedata['pay_sn'] = $info['pay_sn'];//支付接口返回的订单号
                if($info['money'])$updatedata['pay_amount'] = $info['money'];//线上支付
                if($info['pay_code'])$updatedata['assist_code'] = $info['pay_code'];
                $updatedata['pay_time'] = NOW_TIME;
                
                $updatedata['status'] = 3;
                $updatedata['confirm_time'] = NOW_TIME;
                $updatedata['shipping_status']=4;
                $orderwhere['is_delete'] = 0;
                M('OrderInfo')->where($orderwhere)->save($updatedata);
                //推送消息
                //PushReadSend($pay_info['order_id']);
                shops_customer($order_info['uid'],$order_info['shop_id']);//存入门店顾客中间表
                //推送消息end
                if($pay_info['type'] == 2){//充值订单处理
                    $data=calculation($pay_info['order_total_price'],$pay_info['user_id']);
                    account_change($pay_info['user_id'], $pay_info['order_total_price'], 1, 1, "会员充值,订单".$order_info['order_sn']);
                    $ret = give_double_points($pay_info['order_id']);//多倍积分
                    if($ret['points'] != 1){
                        $points=$data['data']['points'];//充值需要变更的会员积分数
                        if($points){account_change($pay_info['user_id'],$points,4,5,"参与会员充值有礼等级特权活动赠送,订单".$order_info['order_sn']);}
                    }
                    if($ret['get_score']>0 || $ret['get_money']>0){
                        $map=array();
                        $map['id']=$pay_info['order_id'];
                        $savedata=array();
                        $savedata['get_score']=$ret['get_score'];
                        $savedata['get_money']=$ret['get_money'];
                        M('OrderInfo')->where($map)->save($savedata);
                    }
                    account_change($pay_info['user_id'], $pay_info['order_total_price'], 1, 1, "会员充值（平台入账）",'0',false,3);//平台入账日志
                    account_change($pay_info['user_id'],$pay_info['order_total_price'],7,1,'累计充值');//增加累计充值
                    // 变更会员等级
                    $grade_choices = C('GRADE_CHOICES');//会员升级选择
                    if (C('IS_MEMBER_UPGRADE')) {
                        if ($grade_choices == 2) {//累计充值升级
                            // user_ranks($pay_info['user_id']);
                        }
                    }
                    guide_divide($pay_info['order_id'],2);
                }else if($pay_info['type'] == 15){//礼品卡订单处理
					$this->change_gift_code($pay_info['order_id']);
					guide_divide($pay_info['order_id'],4);				
                }else {//收银订单处理
                    //减库存
                    $kucun_re = D('Shop/OrderInfo')->lessstock($pay_info['order_id']);
                    if ($kucun_re['status'] == 0) {
                        $return['msg'] = $kucun_re['info'];
                        return $return;
                    }
                    //物流
                    if(C('DIS_TRIBUTE')==1 && !empty($order_info['distribute'])){$this->send_distribute($pay_info['order_id']);}
                    $discount = idtoname($pay_info['order_id'], 'OrderInfo', 'discount,first_money', 'id', false);
                    D('Common/OrderInfo')->get_profit($pay_info['order_id'], $discount['discount'], $discount['first_money']);
                    //if($order_info['guide']>0) D('Common/OrderInfo')->guide_money($pay_info['order_id']);
                    guide_divide($pay_info['order_id'],1);
                    if ($pay_info['user_id']) {
                        
                        $ret=array();
                        $g_points = give_double_points($pay_info['order_id']);//多倍积分
                        if (empty($g_points['points'])) $ret['get_score']=D('Common/OrderInfo')->change_member_points($pay_info['order_id']);
                        else D('Common/OrderInfo')->change_member_points($pay_info['order_id'], 0);
                        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']=$pay_info['order_id'];
                            $savedata=array();
                            $savedata['get_score']=$ret['get_score'];
                            $savedata['get_money']=$ret['get_money'];
                            M('OrderInfo')->where($map)->save($savedata);
                        }
                        if (C('EXTENSION_SETTING')) {
                            $affiliate = affiliate($pay_info['order_id']);
                            affiliate_yes($pay_info['order_id']);
                        }
                    }
                    //增加商家未结算金额
                    $shop_unsettled = D('Common/OrderInfo')->shop_unbalance($pay_info['order_id'], 0);
                    $shop_unsettled = give_shop_balance($pay_info['order_id']);
                    if (!$shop_unsettled) {
                        $return['msg'] = "增加商户待结算金额失败";
                        return $return;
                    }
                }
            }
        }
        $return['status']=1;
        return $return;
    }
    /**
     * 实时监测是否付款成功
     */
    public function check_paysuccess($order_id){
        $return=array('status'=>1,'msg'=>'');
        if(empty($order_id)){$return['msg']='订单不存在'; $return['status']=0; return $return;}
        $map=array();
        $map['id']=intval($order_id);
        $order_info=M('OrderInfo')->where($map)->field('pay_status,pay_code,assist_code,order_sn,id,pay_amount')->find();
        $pay_code=strtoupper($order_info['pay_code']);
        if($pay_code!='MMSCAN'){
            $map=array();
            $map['order_id']=$order_info['id'];
            $map['type']=array('in','2,13');
            $order_sn=M('PayLog')->where($map)->getField('order_sn');
            if($order_info['pay_status']==1){
                if($pay_code=='HANCHAO_SWEIXIN' || $pay_code=='HANCHAO_S_WEIXIN'){$note='微信';}
                if($pay_code=='HANCHAO_SALIPAY' || $pay_code=='HANCHAO_S_ALIPAY'){$note='支付宝';}
                $return['data']['info']='扫码成功，正在'.$note.'支付';
                if($pay_code=='CHINAUMSPOS'){
                    $p_map=array();
                    $p_map['status']=1;
                    $p_map['code']=ucfirst(strtolower($pay_code));
                    $payconfig=M('Payment')->where($p_map)->field(true)->find();
                    $pay = new \Common\Vendor\Pay($p_map['code'],$payconfig);
                    $pay->check();
                    $queryResult = $pay->query($order_sn);
                    if($queryResult['errCode']=='00'){
                        if($queryResult['queryResCode']=='0'){
                            $info = $pay->getInfo();
                            $result=$this->endorder($info);
                        }
                        if($queryResult['queryResCode']=='5'){
                            $return['status']=0;
                            $return['msg']='支付失败'.json_encode($queryResult);
                            return $return;
                        }
                    }
                }
            }
        }
        if($order_info['pay_status']==3){
            $return['data']['info']='支付成功';
            $return['data']['status']=1;
            $return['data']['content']='';
            if($pay_code=='MMSCAN' || $pay_code=='CHINAUMSPOS' || $pay_code=='CHINAUMS'){
                if($order_info['assist_code']=='HANCHAO_S_WEIXIN'){
                    $return['data']['content']='微信到账'.$order_info['pay_amount'].'元';
                }
                if($order_info['assist_code']=='HANCHAO_S_ALIPAY'){
                    $return['data']['content']='支付宝到账'.$order_info['pay_amount'].'元';
                }
            }
            $return['msg']='支付成功';
            return $return;
        }else{
            $return['data']['info']='正在支付。。';
            $return['data']['status']=1;
            $return['msg']='支付成功';
            return $return;
        }
    }

    /**
     *发送配送信息
     * @param $order_id
     * @return array|bool
     */
    public function send_distribute($order_id){
        $return=array('status'=>0,'msg'=>'');
        if(empty($order_id)){return false;}
        $map=array();
        $map['id']=$order_id;
        $order_info=M('OrderInfo')->where($map)->field(true)->find();
        if(C('DIS_TRIBUTE')==1 && $order_info['distribute']){
            $disdata=$order_info;
            $disdata['order_id']=$order_id;
            $disdata['wuliu']=$order_info['distribute'];
            $req=D('Common/Distribute')->add_order($disdata);
            if($req['status'] == 1){
                $save_data=array();
                $save_data['accept_time'] = NOW_TIME;
                M('OrderInfo')->where('id='.$order_id)->save($save_data);
            }else{
                $return['status']=0;
                $return['msg'] = $req['msg'];return $return;
            }
        }
    }

    /**
     * 编辑添加收货地址
     * @param $data
     * @return bool
     */
    public function edit_address($data){
        if(empty($data['uid'])) return false;
        $map=array();
        //$map['id']=$data['address_id'];
        $map['uid']=$data['uid'];
        $map['province']=$data['province'];
        $map['city']=$data['city'];
        $map['district']=$data['district'];
        $map['consignee']=$data['consignee'];
        $map['address']=$data['address'];
        $map['mobile']=$data['mobile'];
        $map['xpoint']=$data['xpoint'];
        $map['ypoint']=$data['ypoint'];
        $count=M('MemberAddress')->where($map)->count();
        if($count<=0){
            $map=array(); $map['id']=$data['address_id'];$map['uid']=$data['uid'];
            $a_count=M('MemberAddress')->where($map)->count();
            if($a_count<=0) {
                $savedata = array();
                $savedata['uid'] = $data['uid'];
                $savedata['consignee'] = $data['consignee'];
                $savedata['province'] = $data['province'];
                $savedata['city'] = $data['city'];
                $savedata['district'] = $data['district'];
                $savedata['address'] = $data['address'];
                $savedata['house_no'] = '';
                $savedata['mobile'] = $data['mobile'];
                $savedata['updatetime'] = NOW_TIME;
                $savedata['xpoint'] = $data['xpoint'];
                $savedata['ypoint'] = $data['ypoint'];
                M('MemberAddress')->add($savedata);
            }else{
                $savedata=array();
                $savedata['consignee']=$data['consignee'];
                $savedata['province']=$data['province'];
                $savedata['city']=$data['city'];
                $savedata['district']=$data['district'];
                $savedata['address']=$data['address'];
                $savedata['mobile']=$data['mobile'];
                $savedata['updatetime']=NOW_TIME;
                $savedata['xpoint']=$data['xpoint'];
                $savedata['ypoint']=$data['ypoint'];
                M('MemberAddress')->where($map)->save($savedata);
            }
        }
    }

    /**
     * 获取商品详情
     * @param $uid
     * @param array $goods_list=
     * array (
    '245-' =>
    array (
    'goods_id' => '245',
    'goods_number' => '1',
    'goods_attr' => '',
    'active_id' => '',
    'is_sanhuo' => 0,
    ),
    '246-' =>
    array (
    'goods_id' => '246',
    'goods_number' => '1',
    'goods_attr' => '',
    'is_sanhuo' => 0,
    ),
    )
     */
    public function goods_info($goods_list,$uid=0,$shop_id){
        $return=array('status'=>0,'info'=>'');
        if(empty($goods_list)){$return['info']='商品无效!';return $return;}
        $goodsids=array();
        foreach($goods_list as $v){
            if($v['goods_id'])$goodsids[]=$v['goods_id'];
        }
        //if(empty($goodsids)){$return['info']='商品无效!';return $return;}
        $map=array();
        if(!empty($goodsids)) {//非无码商品
            $map['id'] = array('in', $goodsids);
            $map['status'] = 1;
            $map['publish_wait'] = 1;
            $map['is_delete'] = 0;
            $map['goods_type'] = 5;
            $lists = M('Goods')->where($map)->field('id,goods_sn,goods_name,suppliers_id,supply_price,shop_price,is_promote,promote_price,promote_start_time,promote_end_time,promote_id')->select();
            if (empty($lists)) {
                $return['info'] = '商品无效!';
                return $return;
            }
            
            $new_lists = array();
            foreach ($lists as $v) {
                $new_lists[$v['id']] = $v;
            }
        }      
        $uid=intval($uid);$total_price=0;$goods_amount=0;$member_discount=0;$goods_custom_discount=0;$promote_discount=$promot_money=0;
        $promat_goods=array();
        foreach($goods_list as $k=> $v){
            $promat_goods[$k]=array('discount_member'=>0,'discount_xianshi'=>0,'discount_custom'=>0);
            
            if($v['goods_id'])$goods_info=$new_lists[$v['goods_id']];
            else {
                $goods_info=$goods_list[$v['goods_sn']];
                unset($goods_list[$k]['goods_attr']);
            }
            if(empty($goods_info)){unset($goods_list[$k]);continue;}
            if($v['is_redit']){//如果是自定义编辑过的商品
                $realprice=$v['after_discount_price'];
                $goods_custom_discount+=($v['shop_price']-$realprice)*$v['goods_number'];
                $promat_goods[$k]['discount_custom']=$v['shop_price']-$realprice;
            }elseif(empty($v['goods_id']) && $v['goods_id']=='w'){
                $goods_discount = $this->count_member_discount($uid,$v['shop_price']);
                if($goods_discount['status']==1){
                    $realprice = $goods_discount['real_price'];
                    $member_discount+=$goods_discount['user_discount']*$v['goods_number'];
                    $promat_goods[$k]['discount_member']=$goods_discount['user_discount'];
                }else{
                    $realprice = $v['shop_price'];
                }
            }else{
                $memberinfo=array();
                if($uid){$memberinfo['is_tmp']=0; $memberinfo['id']=$uid;}
                else {$memberinfo['is_tmp']=1;$memberinfo['id']=0;}
                $discount_price=$this->get_min_price($shop_id,$goods_info['id'],$memberinfo,$v['attr_key']);
                if($discount_price['price_type']!=1){
                    $realprice = $discount_price['goods_price'];
                }else{
                    $realprice = $v['shop_price'];
                } 
                if($discount_price['price_type']==3){//促销价
                    $promat_goods[$k]['discount_xianshi']=$v['shop_price']-$realprice;
                    $promote_discount+=format_decimal(($v['shop_price']-$realprice))*$v['goods_number'];
                }
                if($discount_price['price_type']==2){//会员价
                    $promat_goods[$k]['discount_member']=$v['shop_price']-$realprice;
                    $member_discount+=format_decimal(($v['shop_price']-$realprice),3)*$v['goods_number'];
                }
            }
            $goods_list[$k]['goods_name']=$goods_info['goods_name'];
            $goods_list[$k]['goods_sn']=$goods_info['goods_sn'];
            $goods_list[$k]['attr_price']=$v['shop_price'];//原来价格
            $goods_list[$k]['goods_price']=$realprice;//实际价格
            $goods_list[$k]['shop_id']=$v['shop_id'];
            $goods_list[$k]['suppliers_id']=$goods_info['suppliers_id'];
            $goods_list[$k]['is_sanhuo']=$v['is_sanhuo'];
            $goods_list[$k]['promot_id'] = empty($discount_price['act_id'])?0:$discount_price['act_id'];
            $goods_list[$k]['real_price'] =format_decimal($realprice*$v['goods_number']);
            $total_price+=$goods_list[$k]['real_price'];
            $goods_amount+=format_decimal($v['shop_price']*$v['goods_number']);
        }
        //优惠活动计算开始
        $active_obj=$active_totalmoney=$promot_money_json=array();
        $active_ids=array();
        foreach($goods_list as $k=> $v){
            $goods_list[$k]['active_type']=0;
            $goods_list[$k]['active_money']=0;
            if($v['active_id']>0){
                $active_ids[]=$v['active_id'];
                $active_obj[$v['active_id']][]=$k;
                if(empty($active_totalmoney[$v['active_id']]))$active_totalmoney[$v['active_id']]=0;
                 $active_totalmoney[$v['active_id']]+=floatval($v['goods_price']*$v['goods_number']);
            }
        }
        if(!empty($active_obj) && !empty($active_ids)){ 
            $get_active=$this->get_active($active_ids);
            $active_data=$get_active['data'];
            $all_active_goods_index=array();
            foreach($active_obj as $k=>$v){//循环校验活动
                $active_min_amount=floatval($active_data[$k]['min_amount']);//活动金额下线
                $active_max_amount=floatval($active_data[$k]['max_amount']);//活动金额上线
                $active_goods_totalmoney=floatval($active_totalmoney[$k]);//当前活动内商品总金额
                $isactive=true;//满足活动标识
                $active_data[$k]['goods_index']='';//初始化活动对应商品
                $act_type=$active_data[$k]['act_type'];
               // echo "\n par:".$active_goods_totalmoney.'<'.$active_min_amount.'<'.$active_max_amount."\n";
                if($active_goods_totalmoney<$active_min_amount || ($active_goods_totalmoney>$active_max_amount && $active_max_amount>0)){//不满足活动条件
                    if($act_type==3 || $act_type==4){//当为满赠或加价购时扣掉一个商品的金额再比较一下
                        $firstgoodsid=$active_obj[$k][0];
                        $firstgoods_price=$firstgoodsid?floatval($goods_list[$firstgoodsid]['attr_price']):0;
                        $newactive_goods_totalmoney=$active_goods_totalmoney-$firstgoods_price;//扣掉第一个商品1个后的总金额
                        if($newactive_goods_totalmoney<$active_min_amount || ($newactive_goods_totalmoney>$active_max_amount && $active_max_amount>0)){//不满足活动条件
                            $isactive=false;
                        }
                    }else{$isactive=false;}
                }
                if($isactive && ($act_type==3 || $act_type==4)){//满足价格时看是否存在赠品或加价购商品
                    foreach($goods_list as $checkacti=> $val){
                        $goodsindex=$checkacti;
                        $goodsarr=explode('-',$goodsindex);
                        if(empty($goodsarr[1])){$goodsindex=$goodsarr[0];}
                        if(in_array($goodsindex,$active_data[$k]['act_good_ids']) && !in_array($goodsindex,$all_active_goods_index)){ 
                            $active_data[$k]['goods_index']=$checkacti;
                            $all_active_goods_index[]=$checkacti;
                            break;
                        }
                    }
                    if(!$active_data[$k]['goods_index'])$isactive=false;
                }
                $active_name=array();$discount_total_price=0;
                if($isactive){//满足活动条件
                    $act_type_ext=floatval($active_data[$k]['act_type_ext']);
                    $active_name[$act_type]=$active_data[$k]['act_name'];
                    //console.log('1'+that.order_param.real_price+'='+$promot_money);
                    if($act_type==1 || $act_type==2){
                        foreach($v as $goodskeyindex){
                            $goods_list[$goodskeyindex]['promot_id']=$k; 
                        }
                    }$active_price=0;
                    switch($act_type){//活动类型1满减2满折3满赠4加价购
                        case '1'://满减
                            $active_money=$act_type_ext;
                            if($active_data[$k]['is_addup']==1){//累加
                                $addup=intval($active_goods_totalmoney/$active_min_amount);
                                if($addup>1)$active_money=floatval($act_type_ext*$addup);
                            }
                            $total_price=format_decimal($total_price-$active_money);
                            $promot_money = format_decimal($promot_money+$active_money);                            
                        break;
                        case '2'://满折
                            $active_money=floatval($active_goods_totalmoney*(1-$act_type_ext/100));
                            $total_price=format_decimal($total_price-$active_money);
                            $promot_money = format_decimal($promot_money+$active_money);                   
                        break;
                        case '3'://满赠
                            $active_goods_index=$active_data[$k]['goods_index'];
                            if($active_goods_index){
                                $active_money=floatval($goods_list[$active_goods_index]['shop_price']);
                                if($goods_list[$active_goods_index]['goods_number']>1){
                                   $newkey=$active_goods_index.'-'.$act_type;
                                   $goods_list[$newkey]=$goods_list[$active_goods_index];
                                   $goods_list[$newkey]['active_type']=3;
                                   $goods_list[$newkey]['active_money']=$goods_list[$active_goods_index]['shop_price'];
                                   $goods_list[$newkey]['goods_number']=1;
                                   $goods_list[$newkey]['goods_price']=0;
                                   $goods_list[$newkey]['real_price']=0;
                                   $goods_list[$newkey]['promot_id']=$k; 
                                   $goods_list[$active_goods_index]['real_price']=$goods_list[$active_goods_index]['real_price']-$goods_list[$active_goods_index]['goods_price'];
                                   $goods_list[$active_goods_index]['goods_number']=$goods_list[$active_goods_index]['goods_number']-1;                                   
                                   if($promat_goods[$active_goods_index]['discount_member']>0){
                                       $member_discount=$member_discount-$promat_goods[$active_goods_index]['discount_member'];
                                   }
                                   if($promat_goods[$active_goods_index]['discount_xianshi']>0){
                                       $promote_discount=$promote_discount-$promat_goods[$active_goods_index]['discount_xianshi'];
                                   }
                                }else{
                                    $goods_list[$active_goods_index]['active_type']=3;
                                    $goods_list[$active_goods_index]['goods_price']=0;
                                    $goods_list[$active_goods_index]['active_money']=$goods_list[$active_goods_index]['shop_price'];
                                    $goods_list[$active_goods_index]['promot_id']=$k;
                                    $goods_list[$active_goods_index]['real_price']=0;
                                    if($promat_goods[$active_goods_index]['discount_member']>0){
                                        $member_discount=$member_discount-$promat_goods[$active_goods_index]['discount_member']*$goods_list[$active_goods_index]['goods_number'];
                                    }
                                    if($promat_goods[$active_goods_index]['discount_xianshi']>0){
                                        $promote_discount=$promote_discount-$promat_goods[$active_goods_index]['discount_xianshi']*$goods_list[$active_goods_index]['goods_number'];
                                    }
                                    $promat_goods[$active_goods_index]['discount_member']=$promat_goods[$active_goods_index]['discount_xianshi']=$promat_goods[$active_goods_index]['discount_custom']=0;
                                }
                                $total_price=format_decimal($total_price-$active_money);
                                //$goods_list[$active_goods_index]['goods_price'] =$goods_list[$active_goods_index]['goods_price']-$active_money;//重置满赠加价购商品金额
                                $promot_money = format_decimal($promot_money+$active_money);
                            }else $isactive=false;
                        break;
                        case '4'://加价购
                            $active_goods_index=$active_data[$k]['goods_index'];
                            $active_price=$act_type_ext;
                            if($active_goods_index){
                                if($goods_list[$active_goods_index]['goods_number']>1){$is_active=true;}
                                $active_money=floatval($goods_list[$active_goods_index]['shop_price']-$act_type_ext);
                                if($goods_list[$active_goods_index]['goods_number']>1){
                                   $newkey=$active_goods_index.'-'.$act_type;
                                   $goods_list[$newkey]=$goods_list[$active_goods_index];
                                   $goods_list[$newkey]['active_type']=4;
                                   $goods_list[$newkey]['active_money']=$active_money;
                                   $goods_list[$newkey]['goods_number']=1;
                                   $goods_list[$newkey]['goods_price']=$act_type_ext;
                                   $goods_list[$newkey]['promot_id']=$k; 
                                   $goods_list[$newkey]['real_price']=$act_type_ext;
                                   $goods_list[$active_goods_index]['real_price']=$goods_list[$active_goods_index]['real_price']-$active_money;
                                   $goods_list[$active_goods_index]['goods_number']=$goods_list[$active_goods_index]['goods_number']-1;
                                   if($promat_goods[$active_goods_index]['discount_member']>0){
                                       $member_discount=$member_discount-$promat_goods[$active_goods_index]['discount_member'];
                                   }
                                   if($promat_goods[$active_goods_index]['discount_xianshi']>0){
                                       $promote_discount=$promote_discount-$promat_goods[$active_goods_index]['discount_xianshi'];
                                   }
                                }else{
                                    $goods_list[$active_goods_index]['active_type']=4;
                                    $goods_list[$active_goods_index]['goods_price']=$act_type_ext;  //重置满赠加价购商品金额  
                                    $goods_list[$active_goods_index]['active_money']=$active_money;
                                    $goods_list[$active_goods_index]['promot_id']=$k;
                                    $goods_list[$active_goods_index]['real_price']=$act_type_ext;
                                    if($promat_goods[$active_goods_index]['discount_member']>0){
                                        $member_discount=$member_discount-$promat_goods[$active_goods_index]['discount_member']*$goods_list[$active_goods_index]['goods_number'];
                                    }
                                    if($promat_goods[$active_goods_index]['discount_xianshi']>0){
                                        $promote_discount=$promote_discount-$promat_goods[$active_goods_index]['discount_xianshi']*$goods_list[$active_goods_index]['goods_number'];
                                    }
                                    $promat_goods[$active_goods_index]['discount_member']=$promat_goods[$active_goods_index]['discount_xianshi']=$promat_goods[$active_goods_index]['discount_custom']=0;
                                }
                                $total_price=format_decimal($total_price-$active_money);
                                $promot_money = format_decimal($promot_money+$active_money);
                            }else $isactive=false;
                        break;
                    }
                    $promot_money_json[$k]=array('money'=>$active_money,'type'=>$act_type);
                    if($active_price>0)$promot_money_json[$k]['price']=$active_price;
                    
                    if($isactive){//均摊满减满折
                        $active_money_jt=0;                           
                        $active_goods_totalmoney=floatval($active_totalmoney[$k]);//当前活动内商品总金额
                        $active_min_amount=floatval($active_data[$k]['min_amount']);//活动金额下线
                       if($act_type==1){
                            $active_money_jt=$act_type_ext;
                            if($active_data[$k]['is_addup']==1){//累加
                                $addup=intval($active_goods_totalmoney/$active_min_amount);
                                if($addup>1)$active_money_jt=floatval($active_money_jt*$addup);
                            }
                       }
                       if($act_type==2){$active_money_jt=format_decimal($active_goods_totalmoney*(1-$act_type_ext/100));}
                      // if($active_money_jt>0){$active_rate=$active_money_jt/$active_goods_totalmoney;}
                       foreach($active_data[$k]['act_good_ids'] as $goodskeyindex){//更新活动id以及均摊满减满折商品价格
                            if(!str_exists($goodskeyindex,'-'))$goodskeyindex.='-';
                            if(!empty($goods_list[$goodskeyindex]['promot_id'])){
                                if($active_money_jt>0){
                                    //$goods_list[$goodskeyindex]['promot_id']=$k; 
                                    //$goods_list[$goodskeyindex]['goods_price']=format_decimal($goods_list[$goodskeyindex]['goods_price']*(1-$active_rate));//实际价格
                                    $goods_list[$goodskeyindex]['real_price']=format_decimal($goods_list[$goodskeyindex]['goods_price']*(1-$active_rate)*$v['goods_number']);//实际价格;
                                }
                            }
                            
                       }
                    }
                }
            }
        }
        
        //优惠活动计算结束
        
        $data=array();
        $data['goods_list'] =$goods_list;
        $data['promat_goods'] =$promat_goods;
        $data['total_price']=$total_price;//总金额
        $data['goods_amount']=$goods_amount;//商品总金额
        $data['member_discount']=$member_discount;//折扣总金额
        $data['promote_discount']=$promote_discount;//限时促销
        $data['promot_money']=$promot_money;//优惠活动优惠金额
        $data['promot_money_json']=$promot_money_json;//优惠活动优惠金额
        $data['goods_custom_discount']=$goods_custom_discount;//商品自定义折扣价格
        //print_r($data);exit;
        $return['status']=1;
        $return['info']=$data;
        return $return;
    }
    /**
     * 获取商品最小价格
     * @$memberinfo array('is_tmp'=>1,'id'=>0))
     */
    // 新 
    public function get_min_price1($shop_id,$goods_id,$memberinfo='',$attr_key=''){
        if(empty($goods_id))return false;
        if(empty($memberinfo))$memberinfo = checkuserauthtype();
        $name='Goods';
        $map=$tl_map=$return=array();$map['id']=$goods_id;
        $goods_info = M($name)->where($map)->field('id,shop_price,promote_id,promote_price,goods_type,pt_id')->find();
        var_dump($goods_info);die;
        if($attr_key){
            $map=array();
            $map['goods_id']=$goods_id;
            $map['attr_key']=$attr_key;
            $shop_price=M('GoodsAttrStock')->where($map)->getField('attr_price');
            $goods_info['shop_price']=$shop_price;
        }
        //给默认值
        $return['attr_price']=$return['goods_price']=$goods_info['shop_price'];
        $return['price_type']=1;

        if(!empty($memberinfo) && $memberinfo['is_tmp'] != 1){//判断是否有会员价
            $member_map = $memberrank_map = array();
            $member_map['id'] = $memberinfo['id'];
            $rank_id = M("Member")->where($member_map)->getField('rank_id');
            $map = array();
            $map['goods_id'] = $goods_info['id'];
            $map['user_rank'] = $rank_id;
            $user_price = M('MemberPrice')->where($map)->getField('user_price');
            if($user_price){//自定义价格
                if($user_price < $return['goods_price'])$return['goods_price'] = $user_price;
            }else{
                if($rank_id){//等级折扣
                    $memberrank_map['id'] = $rank_id;
                    $rank = M("MemberRank")->where($memberrank_map)->getField("goods_price");
                    $return['goods_price']=format_decimal($goods_info['shop_price']*$rank/100);
                }
            }
            if($goods_info['shop_price']<=$return['goods_price']){
                $return['price_type']=1;
            }else {
                $return['price_type'] = 2;
            }
        }
        $act_id=0;
        if($goods_info['promote_id']){
            $tl_map=array();
            // $tl_map['status'] = 1;
            $tl_map['id'] = $goods_info['promote_id'];
            $act_info = M('PromotAct')->where($tl_map)->order('end_time desc')->field('id,start_time,end_time,shop_id')->find();
            if(($act_info['start_time']<=NOW_TIME && $act_info['end_time']>=NOW_TIME) && ($act_info['shop_id']==0 || str_exists($act_info['shop_id'],','.$shop_id.','))){
                $act_id=$act_info['id'];
            }
        }
        
        // if($goods_info['pt_id']!=0){
        //     $tl_map=array();
        //     // $tl_map['status'] = 1;
        //     $tl_map['id'] = $goods_info['pt_id'];
        //     $ptid = M('PromotAct')->where($tl_map)->order('end_time desc')->field('id,start_time,end_time,shop_id')->find();
        //     if($ptid['end_time']>=NOW_TIME){
        //         $pt_arr=array();
        //         $pt_arr['act_id'] = $ptid['id'];
        //         $pt_arr['style_ext_id'] = $goods_id;
        //         $pt_arr['style'] = 4;
        //         $pt_money = M('PromotExt')->where($pt_arr)->getField('remarks');
        //         $pt_money = unserialize($pt_money);
        //     }
        //     if($pt_money){
        //         $return['goods_price'] = $pt_money;
        //         $return['price_type']=3;
        //         $return['act_id']=$goods_info['pt_id'];
        //     }
        // }
        if($act_id && $goods_info['promote_price']>0){//判断促销价是否有效
            if($goods_info['promote_price'] < $return['goods_price']){
                $return['goods_price'] = $goods_info['promote_price'];
                $return['price_type']=3;
                $return['act_id']=$act_id;
            }
        }
        return $return;
    }
     /**
     * 获取商品最小价格
     * @$memberinfo array('is_tmp'=>1,'id'=>0))
     */
    public function get_min_price($shop_id,$goods_id,$memberinfo='',$attr_key='',$is_online=0){
        if(empty($goods_id))return false;
        if(empty($memberinfo))$memberinfo = checkuserauthtype();
        $name='Goods';
        $map=$tl_map=$return=array();$map['id']=$goods_id;
        $goods_info = M($name)->where($map)->field('id,shop_price,promote_id,promote_price,goods_type')->find();
        if($attr_key){
            $map=array();
            $map['goods_id']=$goods_id;
            $map['attr_key']=$attr_key;
            $shop_price=M('GoodsAttrStock')->where($map)->getField('attr_price');
            $goods_info['shop_price']=$shop_price;
        }
        //给默认值
        $return['attr_price']=$return['goods_price']=$goods_info['shop_price'];
        $return['price_type']=1;
        if(empty($memberinfo) && $is_online>0){return $return;}
        if(!empty($memberinfo) && $memberinfo['is_tmp'] != 1){//判断是否有会员价
            $member_map = $memberrank_map = array();
            $member_map['id'] = $memberinfo['id'];
            $rank_id = M("Member")->where($member_map)->getField('rank_id');
            $map = array();
            $map['goods_id'] = $goods_info['id'];
            $map['user_rank'] = $rank_id;
            $user_price = M('MemberPrice')->where($map)->getField('user_price');
            if($user_price){//自定义价格
                if($user_price < $return['goods_price'])$return['goods_price'] = $user_price;
            }else{
                if($rank_id){//等级折扣
                    $memberrank_map['id'] = $rank_id;
                    $rank = M("MemberRank")->where($memberrank_map)->getField("goods_price");
                    $return['goods_price']=format_decimal($goods_info['shop_price']*$rank/100);
                }
            }
            if($goods_info['shop_price']<=$return['goods_price']){
                $return['price_type']=1;
            }else {
                $return['price_type'] = 2;
            }
        }
        $act_id=0;
        if($goods_info['promote_id']){
            $tl_map['status'] = 1;
            $tl_map['id'] = $goods_info['promote_id'];
            $act_info = M('PromotAct')->where($tl_map)->order('end_time desc')->field('id,start_time,end_time,shop_id,user_rank')->find();
            if(($act_info['start_time']<=NOW_TIME && $act_info['end_time']>=NOW_TIME) && ($act_info['shop_id']==0 || str_exists($act_info['shop_id'],','.$shop_id.','))){
                $act_id=$act_info['id'];
            }
        }
        if($act_id && $goods_info['promote_price']>0){//判断促销价是否有效
                // 19-6-25 修改
            if($is_online>0 && $memberinfo['rank_id']<$act_info['user_rank']){
                return $return;
            }
            if($goods_info['promote_price'] < $return['goods_price']){
                $return['goods_price'] = $goods_info['promote_price'];
                $return['price_type']=3;
                $return['act_id']=$act_id;
              ;
            }
        }
        return $return;
    }

    //根据优惠券id找优惠券的相关信息，计算优惠的金额
    public function count_coupon_discount($coupon_id,$coupon_code,$total_price,$code_type,$shop_id){
        $return=array('status'=>0,'msg'=>'');
        if(empty($coupon_id) && empty($coupon_code)){ $return['msg']='请选择优惠券'; return $return;}
        if($code_type==1){
            $cash_result = D('Shop/CouponsGet')->check($coupon_code,1,0,$shop_id);//获取优惠券的信息
        }else {
            $cash_result = D('Shop/CouponsGet')->check($coupon_id, 1, 1,$shop_id);//获取优惠券的信息
        }
        if($cash_result['status']==1){
            $cash_info=$cash_result['info'];
            $cash_type=$cash_info['type'];//优惠券的类型
            $cash_discount=$cash_info['discount'];//优惠券的折扣数或是满减金额
            $cash_min=$cash_info['min'];//满足优惠的最小消费金额
            $bonus_id=$cash_info['cash_id'];//优惠券的id
            if($cash_type==1 && $cash_discount>0){//满减
                if(($total_price>0 && $cash_min>0 && $total_price>$cash_min) || ($total_price>0 && $cash_min==0 && $cash_discount<$total_price)){
                    $bonu_money= $cash_discount;//满减的优惠金额
                }
            }
            if($cash_type==2 && $cash_discount>0){//满折
                $cash_discount_money=$total_price*(1-$cash_discount);//计算优惠券满折类型的优惠金额
                if(($total_price>0 && $cash_min>0 && $total_price>$cash_min) || ($total_price>0 && $cash_min==0 && $cash_discount_money<$total_price)){
                    $bonu_money=$cash_discount_money;//
                }
            }
        }
        $return['status']=1;
        if($bonu_money>0) $return['coupon_discount']['bonus_id']=$bonus_id;
        else $return['coupon_discount']['bonus_id']=0;
        $return['coupon_discount']['bonu_money']=$bonu_money;
        return $return;
    }
    //根据会员id找到折扣率，计算会员优惠金额
    public function count_member_discount($uid,$total_price){
        $return=array('status'=>0,'msg'=>'');
        if($total_price<0){$return['msg']='总金额不能小于0'; return $return;}
        if(empty($uid)){$return['msg']='请选择会员'; return $return;}
        $map=array();
        $map['id']=$uid;
        $map['status']=1;
        $map['is_tmp']=0;
        $userinfo=M('Member')->where($map)->field('id,rank_id')->find();
        if(empty($userinfo)) {$return['msg']='该会员不存在';return $return;}
        $map=array();
        $map['id']=$userinfo['rank_id'];
        $map['status']=1;
        $user_discount_rate=M('MemberRank')->where($map)->getField('goods_price');
        if(empty($user_discount_rate)) $user_discount_rate=0;
        //优惠金额
        $user_discount=$total_price*(1-$user_discount_rate/100);
        $return['user_discount']=$user_discount;
        $return['real_price']=format_decimal($total_price-$user_discount);
        $return['status']=1;        
        return $return;
    }
    public function count_custom_discount($single_type,$single_discount,$total_price){
        $return=array('status'=>1,'msg'=>'');
        if($single_discount>0){
            if($single_type==1){
                $custom_discount=$total_price*(1-$single_discount/10);
            }
            if($single_type==2){
                $custom_discount=$single_discount;
            }
        }
        $return['custom_discount']=$custom_discount;
        return $return;
    }
    /**
     * 获取订单列表
     * @param $postdata
     * @return array
     */
    public function order_list($postdata){
        $return=array('status'=>0,'msg'=>'');
        if(empty($postdata['shop_id'])) {$return['msg']='参数错误'; return $return;}
        $map=array();
        $map['shop_id']=$postdata['shop_id'];
        $map['is_delete']=0;
        if($postdata['is_offline']==1){
            $map['type']=array('IN','13,15');
            if($postdata['is_root']==0) $map['sign_building']=$postdata['sign_building'];
        }else{
            $map['pay_status']=3;
            $map['type']=array('IN','2,6,11,12,14,3');
            if($postdata['status']!=0)$map['shipping_status']=$postdata['status'];
            if($postdata['status']==1){
                $map['status']=2;
            }
            // 1110 商家中心用
            if($postdata['is_onorder']){
                unset($map['pay_status']);unset($map['status']);unset($map['shipping_status']);
                if($postdata['send_type'])$map['send_type']=$postdata['send_type'];
                if($postdata['pay_status'])$map['pay_status']=$postdata['pay_status'];
                if($postdata['status'])$map['status']=$postdata['status'];
                if($postdata['shipping_status'])$map['shipping_status']=$postdata['shipping_status'];
            }//1110 end
            unset($postdata['status']);

        }
        if($postdata['order_sn']) $map['order_sn']=$postdata['order_sn'];
        //else unset($postdata['order_sn']);
        $order_list=page_list('OrderInfo',$map,'id desc');
        if(!empty($order_list['list'])){
            foreach ($order_list['list'] as $k => $v) {
                if($v['type']==3){
                    $order_list['list'][$k]['goods_allmoney']=$v['goods_allmoney']-$v['used_score_money'];
                    $order_list['list'][$k]['order_amount']=$v['order_amount']-$v['used_score_money'];
                    $order_list['list'][$k]['goods_amount']=$v['goods_amount']-$v['used_score_money'];
                    $order_list['list'][$k]['order_money']=$v['order_money']-$v['used_score_money'];
                }
            }
        }
        if(empty($order_list['list'])){$return['status']=2;$return['msg']='暂无数据'; return $return;}
        $return['status']=1;
        $return['data']=$order_list;
        return $return;
    }

    public function order_info($postdata){
        $return=array('status'=>0,'msg'=>'');
        if(empty($postdata['shop_id'])){$return['msg']='参数错误'; return $return;}
        $map=array();
        $map['id']=$postdata['order_id'];
        $map['shop_id']=$postdata['shop_id'];
        $map['is_delete']=0;
        $order_info['infos']=M('OrderInfo')->where($map)->field(true)->find();
        if(empty($order_info['infos'])){$return['msg']='订单信息错误'; return $return;}
        if($order_info['infos'] && $order_info['infos']['type']==3){
            $order_info['infos']['goods_allmoney']=$order_info['infos']['goods_allmoney']-$order_info['infos']['used_score_money'];
            $order_info['infos']['order_amount']=$order_info['infos']['order_amount']-$order_info['infos']['used_score_money']+$order_info['infos']['delivery_fee'];
            $order_info['infos']['goods_amount']=$order_info['infos']['goods_amount']-$order_info['infos']['used_score_money']+$order_info['infos']['delivery_fee'];
            $order_info['infos']['order_money']=$order_info['infos']['order_money']-$order_info['infos']['used_score_money']+$order_info['infos']['delivery_fee'];
        }
        
        // if($order_info['infos']['promot_id']){
        //     $act_ids = explode(',', $order_info['infos']['promot_id']);
        //     $act_ids=array_filter($act_ids);
        //     $promote_arr = D('Common/Takeout')->getpromote($act_ids,$order_info['infos']['id']);
        //     $promote_money = array_sum(i_array_column($promote_arr,'money'));
        //     $order_info['infos']['promote_money']=$promote_money;
        // }else{
        //     $order_info['infos']['promote_money']=0.00;
        // }
        $map=$tui_money=array();
        $map['order_id']=$postdata['order_id'];
        $map['shop_id']=$postdata['shop_id'];
        $order_info['order_goods']=M('OrderGoods')->where($map)->field(true)->select();
        $order_info['infos']['goods_custom_discount']=0;
        foreach($order_info['order_goods'] as $k=>$vo){
            $order_info['order_goods'][$k]=$vo;
            $where=array();
            $where['org_id']=$vo['id'];
            $tuinum=$tuimoney=0;
            $return_goods = M('ReturnGoods')->where($where)->field('goods_info,money')->select();
            if($return_goods){
                foreach($return_goods as $kt=>$vt){
                    $tuimoney+=$vt['money'];
                    $tui=unserialize($vt['goods_info']);
                    $tuinum+=$tui['number'];
                }
                $tui_money[]=$tuimoney;
                $order_info['order_goods'][$k]['tui_num']=$tuinum;
            }else{
                $order_info['order_goods'][$k]['tui_num']=0;
            }
            $order_info['infos']['all_num']+=$vo['goods_number'];
            $order_info['infos']['all_num']=floatval($order_info['infos']['all_num']);
            $order_info['order_goods'][$k]['goods_number']=floatval($vo['goods_number']);
            $order_info['order_goods'][$k]['goods_price']=format_price($vo['goods_price']);
            $order_info['order_goods'][$k]['total_price']=format_decimal($vo['goods_price']*$vo['goods_number']);
            $order_info['order_goods'][$k]['goods_attr_format'] = unserialize($vo['goods_attr']);
            $order_info['order_goods'][$k]['original_num']=floatval($vo['original_num']);
            if(!empty($vo['custom_discount'])){
                $goods_custom_discount=unserialize($vo['custom_discount']);
                if($goods_custom_discount['discount_type']==1){
                    $goods_discount=format_decimal($vo['attr_price']-$goods_custom_discount['discount_num']);
                }else{
                    $goods_discount=format_decimal((1-($goods_custom_discount['discount_num']/100))*$vo['attr_price']);
                }
                $order_info['infos']['goods_custom_discount']+=$goods_discount;
            }
        }
        if($order_info['infos']['discount']>0){
            $rest_discount=$order_info['infos']['discount']-$order_info['infos']['bonus_money']-$order_info['infos']['member_discount']-$order_info['infos']['custom_discount']-$order_info['infos']['goods_custom_discount']-$order_info['infos']['moling_discount']-$order_info['infos']['used_score_money']-$order_info['infos']['first_money'];
            $order_info['infos']['promote_money']=format_decimal($rest_discount);
        }
        $order_info['infos']['tui_money']=number_format(array_sum($tui_money),2);
        if($order_info['infos']['uid']){
            $username=show_user_name($order_info['infos']['uid']);
            $shop_id=$postdata['shop_id'];
            if($shop_id && $username && strlen($username)==11){
                $is_hide_phone=idtoname($shop_id,'Shops','is_hide_phone');
                if($is_hide_phone==1){
                    $username=str_cutmobile($username);
                }
            }
            $order_info['infos']['username']=$username;
        }
        else if($order_info['infos']['type'] && $order_info['infos']['uid']==0) $order_info['infos']['username']='游客';

        if($order_info['infos']['guide']){
            $daogouname=idtoname($order_info['infos']['guide'],"ShopsAccount",'name');
            $order_info['infos']['daogouname']=$daogouname;
        }
        if($order_info['infos']){
            if($order_info['infos']['scan_money']>0 || $order_info['infos']['pay_amount']>0){
                $payname='';
                if(str_exists($order_info['infos']['assist_code'],'ALIPAY'))$payname='支付宝';
                if(str_exists($order_info['infos']['assist_code'],'WEIXIN'))$payname='微信';
                if(empty($payname) && $order_info['infos']['pay_code'])$payname=idtoname($order_info['infos']['pay_code'],'Payment','name','code');
                if(empty($payname))$payname='在线支付';
            }
            if(in_array($order_info['infos']['type'],array(13,15,2))) {
                if (floatval($order_info['infos']['cash_money']) > 0) $cash_name = '现金：' . format_price($order_info['infos']['cash_money']);
                if (floatval($order_info['infos']['card_money']) > 0) $card_name = '刷卡：' . format_price($order_info['infos']['card_money']);
                if (floatval($order_info['infos']['bank_money']) > 0) $bank_name = '台卡：' . format_price($order_info['infos']['bank_money']);
                if (floatval($order_info['infos']['scan_money']) > 0) $scan_name = $payname.'扫码：' . format_price($order_info['infos']['scan_money']);
                if (floatval($order_info['infos']['used_money']) > 0) $used_name = '余额：' . format_price($order_info['infos']['used_money']);
                $order_info['infos']['pay_name']=$cash_name.$card_name.$bank_name.$scan_name.$used_name;
            }else{
                if (floatval($order_info['infos']['pay_amount']) > 0) $cash_name = $payname.'：' . format_price($order_info['infos']['pay_amount']);
                if (floatval($order_info['infos']['used_money']) > 0) $used_name = '余额：' . format_price($order_info['infos']['used_money']);
                $order_info['infos']['pay_name']=$cash_name.$used_name;
            }
        }
        if(in_array($order_info['infos']['send_type'],array(2,3))){
            $province=idtoname($order_info['infos']['province'],'Area','name');
            $city=idtoname($order_info['infos']['city'],'Area','name');
            $district=idtoname($order_info['infos']['district'],'Area','name');
            $order_info['infos']['detail_address']=$province.$city.$district.$order_info['infos']['address'];
        }
        if($order_info['infos']['send_type']==1){
            $order_info['infos']['shop_address']=idtoname($order_info['infos']['shop_id'],'Shops','address');
        }
        if($order_info['infos']['shipping_time']!=0){$order_info['infos']['shipping_time']=time_format($order_info['infos']['shipping_time']);}
        else $order_info['infos']['shipping_time']='无';
        if($order_info['infos']['best_time']!=0){$order_info['infos']['best_time']=time_format($order_info['infos']['best_time']);}
        else $order_info['infos']['best_time']='无';
        
        $DIS_TRIBUTE=C("DIS_TRIBUTE");
        if($order_info['infos']['send_type']==2 && $DIS_TRIBUTE == 1 && $order_info['infos']['distribute']){
            $reqStatus = D('Common/Distribute')->details_order($order_info['infos']);
            
            if($reqStatus['status']){
                $reqStatus['info']['shippingname']=idtoname($order_info['infos']['distribute'],"Distribute",'name','code');
                if($reqStatus['info']['createTime'] && is_numeric($reqStatus['info']['createTime'])){$reqStatus['info']['createTime']=time_format($reqStatus['info']['createTime']);}
                if($reqStatus['info']['acceptTime'] && is_numeric($reqStatus['info']['acceptTime'])){$reqStatus['info']['acceptTime']=time_format($reqStatus['info']['acceptTime']);}
                if($reqStatus['info']['fetchTime'] && is_numeric($reqStatus['info']['fetchTime'])){$reqStatus['info']['fetchTime']=time_format($reqStatus['info']['fetchTime']);}
                if($reqStatus['info']['finishTime'] && is_numeric($reqStatus['info']['finishTime'])){$reqStatus['info']['finishTime']=time_format($reqStatus['info']['finishTime']);}
                $order_info['infos']['reqstatus']=$reqStatus['info'];
            }else{
                $order_info['infos']['reqstatuserror']=$reqStatus;
            }
        }
        if($order_info['infos']['pay_status']==3 && $order_info['infos']['shipping_status']==3 && $order_info['infos']['send_type']!=1){
            $order_info['infos']['is_tui']=1;
        }else{
            $order_info['infos']['is_tui']=0;
        }         
        $return['status']=1;
        $return['data']=$order_info;
        return $return;
    }
    /**
     * 返回某个订单可执行的操作列表，包括权限判断
     * @param   array   $order      订单信息 order_status, shipping_status, pay_status
     * @param   bool    $is_cod     支付方式是否货到付款
     * @return  array   可执行的操作  confirm, pay, unpay, prepare, ship, unship, receive, cancel, invalid, return, drop
     * 格式 array('confirm' => true, 'pay' => true)
     */
    public function operable_list($orderid){
        $return=array('status'=>0,'msg'=>'');
        if(empty($orderid)){$return['msg']='参数错误'; return $return;}
        $order=M('OrderInfo')->field('status,shipping_status,pay_status,pay_code,send_type,check_status,type')->find($orderid);
        $os = $order['status'];$ss = $order['shipping_status'];$ps = $order['pay_status'];
        $priv_list  = array('os'=> true,'ss'=>true,'ps'=>true,'edit'=>true);/* 取得订单操作权限 */ 
        if($order['pay_code']=='HANCHAObank')$is_cod= $payment = 1;   
        //return $payment; /* 取得订单支付方式是否货到付款 */
        $list = array();/* 根据状态返回可执行操作 */
        if (1 == $os){//未确认
            if ($priv_list['os']){/* 状态：未确认 => 未付款、未发货 */
                $list['confirm']= true; /*确认*/$list['invalid']= true;/* 无效*/$list['cancel']= true; /* 取消*/
                if ($is_cod){if ($priv_list['ss']){$list['prepare'] = true; }// 货到付款  配货
                }else{if ($priv_list['ps']) { $list['pay'] = true;}}  // 不是货到付款 付款
            }
        }elseif (2 == $os ){//已确认
            if (1 == $ps){/* 状态：已确认 未付款*/
                if ((1 == $ss || 2 == $ss) && $order['send_type'] !=2){$list['ship'] = true;/* 状态：已确认、未付款 未发货/备货中*/
                    if ($priv_list['os']){$list['cancel'] = true; /*取消*/$list['invalid'] = true;} // 无效                
//                  if ($is_cod){if ($priv_list['ss'] && 1 == $ss){$list['prepare'] = true;}} // 货到付款 配货
                    else if ($priv_list['ps']){$list['pay'] = true;}// 不是货到付款 付款
                }else{
                    if ($priv_list['ps']){$list['pay'] = true;} /* 状态：已确认、未付款、已发货或已收货 => 货到付款 */       
                    if ($priv_list['ss']){if (3 == $ss){$list['receive'] = true;}} /*收货确认*/
                    if ($priv_list['os']){$list['return'] = true;} /*退货*/
                    if($order['send_type'] ==0 || $order['send_type'] ==3){$list['unship'] = true;} // 设为未发货
                }
            }else{
                if (1 == $ss || 2 == $ss){
                    if($order['send_type']!=1 && $order['send_type']!=2){
                        $list['ship'] = true;
                    }/* 状态：已确认、已付款和付款中、未发货（配货中） => 不是货到付款 */
                    $list['order_take'] = true;
//                  if ($priv_list['ss'] && 1 == $ss && $order['send_type'] != 3){$list['prepare'] = true;} // 配货
                    if ($priv_list['ps']){$list['unpay'] = true; /* 设为未付款*/if ($priv_list['os']){$list['cancel'] = true;} } // 取消                    
                }else{/* 状态：已确认、已付款和付款中、已发货或已收货 */
                    if($order['send_type']==1 && 5 != $ss){
                        $list['order_take'] = true;
                    }
                    if ($priv_list['ss']){
                        if (3 == $ss){

                            if($order['send_type']==1 && $order['check_status']==0){
                                $list['receive'] = true;
                            }else{
                                $list['receive'] = true;
                            }
                        }elseif(5 == $ss && $order['send_type']==1){
                            $list['receive'] = true;
                        }
                        /*收货确认*/
                        if (!$is_cod && $order['send_type']!=1 && $order['send_type']!=2 && $priv_list['ss'] != 5){$list['unship'] = true;}
                    } // 设为未发货
                    if ($priv_list['ss'] && 5 == $ss && $order['send_type']==2){$list['prepare'] = true;} // 配货
                    if ($priv_list['ss'] && 5 == $ss && $order['send_type']==3){$list['ship'] = true;} /* 状态：已确认、已付款和付款中、未发货（配货中） => 不是货到付款 */
                    if ($priv_list['ps'] && $is_cod){$list['unpay']  = true;} // 设为未付款                
                    if ($priv_list['os'] && $priv_list['ss'] && $priv_list['ps'] && $order['send_type']!=1){$list['return'] = true;} // 退货（包括退款）
                    if ($order['send_type']==1){$list['cancel'] = true;/*取消*/$list['invalid'] = true;} // 无效
                }
            }
        }elseif(3 == $os){
            if($order['type']==13){//退货
                $list['return']=true;
            }
        }elseif (4 == $os){
//          if($priv_list['os']){$list['confirm'] = true;}
            if($priv_list['edit']){$list['remove'] = true;}
        }elseif (5 == $os){/* 状态：无效 */
            if($priv_list['os']){$list['confirm'] = true;}if($priv_list['edit']){$list['remove'] = true;}
        }elseif (6 == $os && $priv_list['os']){/*退货 */  
            $list['confirm']=true;
        }
        if($is_cod && $priv_list['ps']){$list['pay']=true;} 
        //$list['payment']= $order['pay_code'];
        $list['after_service'] = true;/* 售后 */
        $return['status']=1;
        $return['data']=$list;
        return $return;
        //return $payment;
    }

    /**
     * 店铺订单操作
     * @param $postdata
     * @return array
     */
    public function order_manage($postdata){
        $return=array('status'=>0,'msg'=>'');
        $mod=M('OrderInfo');
        if(empty($postdata['order_id']) || empty($postdata['shop_id'])){$return['msg']='参数错误'; return $return;}
        $order_id=$postdata['order_id'];
        //$content=I('post.content');
        //$order=I('post.order');
        $shop_id=$postdata['shop_id'];
        $manage_way=$postdata['manage_way'];//点击的是哪个操作按钮
        if(empty($manage_way) && empty($postdata['code'])){$return['msg']='请选择要执行的操作'; return $return;}
        //获取订单信息
        $map=array();
        $map['id']=$order_id;
        $map['shop_id']=$shop_id;
        $order_info=$mod->where($map)->field(true)->find();
        if(empty($order_info)){$return['msg']='订单信息错误'; return $return;}
        if($manage_way=='confirm') {
            $log = '确认';
            $data['confirm_time'] = NOW_TIME;
            $data['status'] = 2;
            $result = M('OrderInfo')->where('id=' . $order_id)->save($data);
            if ($result) {
                $return['status'] = 1;
                $return['msg'] = '操作成功';
                return $return;
            } else {
                $return['msg'] = '操作失败';
                return $return;
            }
        }
        if($manage_way=='pay') {
            $log = '付款';
            $data['pay_time'] = NOW_TIME;
            $data['pay_status'] = '3';
            if ($data) $mod->where('id=' . $order_id)->save($data);
            //扣库存
            $kucun_re = D('Shop/OrderInfo')->lessstock($order_id);
            if ($kucun_re['status'] == 0) {
                $return['msg'] = $kucun_re['info'];
                return $return;
            }
            //扣库存结束
            $discount = idtoname($order_id, 'OrderInfo', 'discount,first_money', 'id', false);
            D('Common/OrderInfo')->get_profit($order_id, $discount['discount'], $discount['first_money']);
            //增加营业额
            $shop_unsettled = D('Common/OrderInfo')->shop_unbalance($order_id, 0);
            if (!$shop_unsettled) {
                $return['msg'] = "增加商户待结算金额失败";
                return $return;
            }
            //分成记录，待处理分成
            $ex = C('EXTENSION_SETTING');
            if ($ex) {
                $a = affiliate($order_id);
            }

            $where_oi['id'] = $order_id;
            $orderinfo = M('OrderInfo')->where($where_oi)->find();
            if ($orderinfo['shipping_status'] == 3) {
                $where_og['order_id'] = $order_id;
                $ordergoods = M('OrderGoods')->where($where_og)->select();
                foreach ($ordergoods as $k => $v) {
                    $where_g['id'] = $v['goods_id'];
                    $old_num = M('Goods')->where($where_g)->find();
                    $con['goods_number'] = $old_num['goods_number'] - $v['goods_number'];
                    $con['sell_count'] = $old_num['sell_count'] + $v['goods_number'];
                    M('Goods')->where($where_g)->save($con);
                }
            }
            $log = $log . ' ' . $content;
            action_log('manage_order', 'OrderInfo', $order_id, UID, $log);
            $return['status'] = 1;
            $return['msg'] = '付款成功';
            return $return;
        }
        if($manage_way=='unpay') {
            $log = '设为未付款';
            $data['pay_time'] = NOW_TIME;
            $data['pay_status'] = 1;
            $result = M('OrderInfo')->where('id=' . $order_id)->save($data);
            if ($result) {
                $return['status'] = 1;
                $return['msg'] = '操作成功';
                return $return;
            } else {
                $return['msg'] = '操作失败';
                return $return;
            }
        }
        if($manage_way=='receive') {
            $log = '已收货';
            $postdata['order_id'] = $order_id;
            $postdata['admin_id'] = MID;
            $postdata['type'] == 'Admin';
            $result = D('Common/OrderInfo')->confirm_order($postdata);
            return $result;
        }
        if($manage_way=='prepare' || $postdata['code']) {
            $log = '配送';
            $param = array();
            $param['order_type'] = $postdata['order_type'];
            $param['order_id'] = $order_id;
            $param['type'] = 'Shop';//店铺发货日志
            if (I('post.code')) {
                $param['wuliu'] = $postdata['code'];
            }
            $result = D('Common/OrderInfo')->ship_goods($param);
            $return['status']=$result['status'];
            $return['msg']=$result['info'];
            return $return;
        }
        if($manage_way=='ship') {
            $log = '发货';
            $save['shipping_time'] = NOW_TIME;
            $save['pay_status'] = 3;
            $save['shop_id'] = $shop_id;
            $res = M('OrderInfo')->where('id=' . $order_id)->save($save);
            $member = M('OrderInfo')->where('id=' . $order_id)->field('uid,mobile')->find();
            if (!empty($member['uid'])) {
                $moblie = M('Member')->where('id=' . $member['uid'])->field('mobile')->find();
                $phone = $moblie['mobile'];
            } else {
                $phone = $member['mobile'];
            }
            $data['to'] = $phone;
            $result = sendbytheme($data, 'SEND_GOODS');
            if ($res) {
                $return['status'] = 1;
                $return['msg'] = '操作成功';
                return $return;
            } else {
                $return['msg'] = '操作失败';
                return $return;
            }
        }
            if($manage_way=='unship') {
                $log = '未发货';
                $data['shipping_status'] = 1;
                $result = M('OrderInfo')->where('id=' . $order_id)->save($data);
                if ($result) {
                    $return['status'] = 1;
                    $return['msg'] = '操作成功';
                    return $return;
                } else {
                    $return['msg'] = '操作失败';
                    return $return;
                }
            }            
            if($manage_way=='return') {
                $log = '退货';
                $data['status'] = 6;
                $member_info = session('member_info');
                $order_info = M("OrderInfo")->where('id=' . $order_id)->field(true)->find();
                $money = $order_info['order_amount'] - $order_info['delivery_fee'];
                $info = M("OrderGoods")->where('order_id=' . $order_id)->field('id,goods_id,goods_number')->select();
                foreach ($info as $k => $v) {
                    $goods_info[$k]['goods_id'] = $v['goods_id'];
                    $goods_info[$k]['number'] = $v['goods_number'];
                    //改变商品状态
                    $g_map['id'] = $v['id'];
                    $g_map['status'] = 1;
                    $save['status'] = 3;
                    $res = M('OrderGoods')->where($g_map)->save($save);
                    $org_id[] = $v['id'];//要生成退货单 org_id
                }

                $str_orgids = implode(',', $org_id);
                //添加退货单
                $add['org_id'] = $str_orgids;
                $add['uid'] = $member_info['id'];
                $add['shop_id'] = $order_info['shop_id'];
                $add['order_id'] = $order_id;
                $add['goods_info'] = serialize($goods_info);
                $add['reason'] = $content;
                $add['money'] = $money;
                $add['add_time'] = NOW_TIME;
                $res = M('ReturnGoods')->add($add);
                //生成退款单
                $refund_data['reason'] = $content;
                $refund_data['type'] = 0;
                $refund_data['order_goods'] = $str_orgids;
                $result = D("Common/OrderInfo")->add_refund($money, $order_id, $refund_data);
                if ($result) {
                    action_log('user_apply_return', 'Member', $res, $member_info['id']);
                    $return['status'] = 1;
                    $return['msg'] = '退货成功';
                    return $return;
                } else {
                    $return['msg'] = '退货失败';
                    return $return;
                }
            }
            if($manage_way=='cancel') {
                $log = '取消';
                $postdata = array();
                $postdata['order_id'] = $order_id;
                $postdata['admin_id'] = MID;
                $postdata['type'] == 'Admin';
                $result = D("Common/OrderInfo")->cancel_order($postdata);
                return $result;
            }
            if($manage_way=='invalid') {
                $log = '无效';
                $data['status'] = 5;
                $result = M('OrderInfo')->where('id=' . $order_id)->save($data);
                if ($result) {
                    $return['msg'] = '设置失效成功';
                    $return['status'] = 1;
                    return $return;
                } else {
                    $return['msg'] = '操作失败';
                    return $return;
                }
            }
            if($manage_way=='after_service') {
                if ($content) $log = '售后';
                $return['status']=1;
                $return['msg']='请联系客服';
                return $return;
            }
            if($manage_way=='order_take') {
                $log = '备货';
                $param = array();
                $param['type'] = $order_info['type'];
                $param['shipping_status'] = 5;
                $param['id'] = $order_id;
                $result = D('Common/OrderInfo')->order_change($param);
                if ($result['status'] == 0) {
                    $return['msg'] = $result['msg'];
                    return $return;
                }
                $return['status'] = 1;
                $return['msg'] = '备货成功';
                return $return;
            }
    }

    /**
     * 退货
     * @param $postdata
     */
    public function return_goods($postdata){
        $return=array('status'=>0,'msg'=>'');
        $money=0;
        if(empty($postdata['list'])) {$return['msg']='请选择要退款的商品'; return $return;}
        $order_add=array();
        foreach($postdata['list'] as $k => $v){
            $org_id[]=$v['id'];
            $money+=$v['all_money'];
        }
        $str_orgids=implode(',',$org_id);
        $order_add['uid']=$postdata['uid'];
        $order_add['shop_id']=$postdata['shop_id'];
        $order_add['order_id']=0;
        $order_add['cashier_name']=$postdata['cashier_name'];
        $order_add['order_goods']=$str_orgids;
        $order_add['money']=$money;
        $order_add['refund_money']=$postdata['money'];
        $order_add['refund_cash']=$postdata['cash_money'];
        $order_add['refund_scores']=0;
        $order_add['refund_web']=0;
        $order_add['payment_id']=0;
        $order_add['payment_code']='';
        $order_add['addtime']=NOW_TIME;
        $order_add['update_time']=NOW_TIME;
        $order_add['reason']=$postdata['content'];
        $order_add['status']=1;
        $order_add['type']=0;
        $order_add['order_type']=13;
        $res=M('RefundOrder')->add($order_add);
        if($res){
            $all_goods_number=0;
            foreach($postdata['list'] as $k => $v){
                $goods_list=array();$goods_info=array();
                $karr=array();$goods_attr_key='';
                $goods_list['uid']=$postdata['uid'];
                $goods_list['shop_id']=$postdata['shop_id'];
                $goods_list['cashier_name']=$postdata['cashier_name'];
                $goods_list['rorder_id']=$res;
                $karr = explode('-', $k);//得到属性值
                $goods_id = $karr[0];
                if (empty($goods_id)) continue;
                if($karr[1])$goods_attr_key = $karr[1];
                $goods_list['org_id']=$goods_id;
                $goods_info['goods_id']=$goods_id;
                $goods_info['number']=$v['goods_number'];
                if(!empty($goods_attr_key))$goods_info['goods_attr']=$goods_attr_key;
                //else{$goods_info['goods_attr']=0;}
                $goods_list['goods_info']=serialize($goods_info);
                $goods_list['reason']=$postdata['content'];
                $goods_list['money']=$v['all_money'];
                $goods_list['cash_money']=0;
                $goods_list['used_money']=0;
                $goods_list['add_time']=NOW_TIME;
                $goods_list['update_time']=NOW_TIME;
                $goods_list['status']=1;
                $goods_list['shop_status']=1;
                $goods_list['type']=0;
                $all_goods_number+=floatval($v['goods_number']);
                $result=M('ReturnGoods')->add($goods_list);
            }
            $pay_log=array();
            $pay_log['user_id']=$postdata['uid'];
            $pay_log['type']=31;
            $pay_log['order_id']=$res;
            $pay_log['shop_id']=$postdata['shop_id'];
            $pay_log['cashier_name']=$postdata['cashier_name'];
            $pay_log['in_online']=0;
            $pay_log['use_money']=$postdata['money'];
            $pay_log['cash_money']=$postdata['cash_money'];
            $pay_log['scan_money']=0;
            $pay_log['bank_money']=0;
            $pay_log['card_money']=0;
            $pay_log['card_money']=0;
            $pay_log['need_pay']=0;
            $pay_log['use_score']=0;
            $pay_log['use_score_money']=0;
            $pay_log['order_total_price']=$money;
            $pay_log['pay_amount']=0;
            $pay_log['pay_amount_type']=0;
            $pay_log['is_paid']=1;
            $pay_log['create_time']=NOW_TIME;
            $pay_log['update_time']=NOW_TIME;
            $pay_log['remarks']=$postdata['reason'];
            M('PayLog')->add($pay_log);
            if($postdata['uid'] && !empty($postdata['money'])){ account_change($postdata['uid'],$postdata['money'],1,8,'店铺线下商品退款');}
            $this->addstock($res);
            shop_balance_log($postdata['shop_id'], -$money, 1,3,'订单退款余额减少');
            shop_balance_log($postdata['shop_id'], -$money, 6,3,'订单退款,销售总额减少');
            $return['status']=1;
            $return['order_id']=$res;
            $return['msg']='退货成功';
            return $return;
        }else{
            $return['msg']='退货失败'; return $return;
        }
    }
    //加库存
    public function addstock($order_id=''){
        $return=array('status'=>0,'info'=>'');
        $order_id=intval($order_id);
        if(empty($order_id)){$return['info'] = "参数错误";return $return;}
        $map=array();
        $map['id']=$order_id;
        $map['status']=1;
        $map['order_type']=13;
        $order_info=M('RefundOrder')->where($map)->field(true)->find();
        if(empty($order_info)){$return['info'] = "订单不存在";return $return;}
        $map=array();
        $map['rorder_id'][]=$order_id;
        $map['rorder_id'][]=array('gt',0);
        $map['status']=1;
        $map['shop_status']=1;
        $map['type']=0;
        $goods=M('ReturnGoods')->where($map)->field('org_id,goods_info,shop_id')->select();
        foreach($goods as $v){
            if($v['is_sanhuo']==1)continue;
            $map=$data=$goods_info=array();
            $map['shop_id']=$v['shop_id'];
            $goods_info=unserialize($v['goods_info']);
            $map['goods_id']=empty($v['org_id'])?$goods_info['goods_id']:$v['org_id'];
            $sale_type = idtoname($v['org_id'],'Goods','sale_type');
            $v['goods_number']=$goods_info['number'];
            $v['goods_id']=$goods_info['goods_id'];
            $v['goods_attr']=$goods_info['goods_attr'];
            if($sale_type == 1){//组合商品
                $this->add_group_goods($map,$v,$order_id);
            }else{
                $this->add_stock($map,$v,$order_id);
            }
        }
        $return['status']=1;
        $return['info'] = "操作成功";
        return $return;
    }
    public function add_group_goods($map,$v,$order_id){//组合商品加库存
        $mapg=array();
        $mapg['goodsid'] = $v['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,1);
        }
    }
    public function add_stock($map,$v,$order_id,$type=0){//加库存
        if($v['goods_attr'] && ($type==0 || $type==1)){
            $map['goods_stock']=$v['goods_attr'];
        }
        $pre_num=M('ShopsGoodsStock')->where($map)->getField('goods_number');
        $data['updatetime']=NOW_TIME;
        $new_number=floatval($v['goods_number']);
        $data['goods_number']=array('exp','goods_number+'.$new_number);
        $data['sell_count']=array('exp','sell_count-'.$new_number);
        $res=M('ShopsGoodsStock')->where($map)->save($data);
        if($res){
            $desc="客户退货库存增加(".$order_id.")";
            $attr_key=empty($v['goods_attr'])?'':$v['goods_attr'];
            change_stock_log($map['shop_id'],$order_id,$pre_num,$map['goods_id'],$new_number,0,$desc,2,$attr_key);
        }
    }

    /*交接班开始*/
    /**
     * 交接班统计
     * @param $postdata
     * @return array
     */
    public function statistics($postdata){
        $return=array('status'=>0,'msg'=>'');
        if(empty($postdata['shop_id']) || empty($postdata['login_name'])){$return['msg']='参数错误'; return $return;}
        $shop_id=$postdata['shop_id'];
        $now_time=NOW_TIME;
        /*总订单数条件start*/
        if($postdata['is_root']){
            $map=array();
            $map['id']=$shop_id;
            $last_login=M('Shops')->where($map)->getField('last_login');
            if(empty($last_login) || ($now_time-$last_login)>86400){
                $map=array();
                $map['shop_id']=$shop_id;
                $map['status']=1;
                $map['is_delete']=0;
                $last_login=M('ShopsAccount')->where($map)->order('last_login desc')->getField('last_login');
            }
        }else{
            $map=array();
            $map['shop_id']=$shop_id;
            $map['login_name']=$postdata['login_name'];
            $map['status']=1;
            $map['is_delete']=0;
            $last_login=M('ShopsAccount')->where($map)->getField('last_login');
        }
        /*网上订单总数start*/
        $map=array();
        $map['type']=array('in','6,14');
        $map['status']=3;
        $map['pay_status']=3;
        $map['shop_id']=$shop_id;
        $map['pay_time'][]=array('gt',$last_login);
        $map['pay_time'][]=array('lt',$now_time);
        $on_num=M('OrderInfo')->where($map)->count('id');
        $on_price=M('OrderInfo')->where($map)->sum('order_amount');
        if(empty($on_price)) $on_price=0;
        /*网上订单总数end*/
        /*预付卡订单总数start*/
        $map=array();
        $map['type']=15;
        $map['status']=3;
        $map['pay_status']=3;
        $map['shop_id']=$shop_id;
        $map['pay_time'][]=array('gt',$last_login);
        $map['pay_time'][]=array('lt',$now_time);
        $pre_paid_num=M('OrderInfo')->where($map)->count('id');
        $pre_paid_price=M('OrderInfo')->where($map)->sum('order_amount');
        if(empty($pre_paid_price)) $pre_paid_price=0;
        /*预付卡订单总数end*/
        $map=array();
        $map['shop_id']=$shop_id;
        $map['sign_building']=$postdata['login_name'];
        $map['pay_status']=3;
        $map['status']=3;
        $map['pay_time'][]=array('gt',$last_login);
        $map['pay_time'][]=array('lt',$now_time);
        $map['type']=13;
        /*总订单数条件end*/
        $all_price=$recharge_price=$re_price=0;
        $all_num=M('OrderInfo')->where($map)->count('id');//总订单数
        $all_price=M('OrderInfo')->where($map)->sum('order_amount');//总销售金额
        if(empty($all_price)) $all_price=0;
        $cash_price=M('OrderInfo')->where($map)->sum('cash_money');//收款现金总数
        if(empty($cash_price)) $cash_price=0;
        $yue_price=M('OrderInfo')->where($map)->sum('used_money');//收款余额总数
        if(empty($yue_price)) $yue_price=0;
        $card_price=M('OrderInfo')->where($map)->sum('card_money');//刷卡总金额
        if(empty($card_price)) $card_price=0;
        $bank_price=M('OrderInfo')->where($map)->sum('bank_money');//台卡总金额
        if(empty($bank_price)) $bank_price=0;
        $score_price=M('OrderInfo')->where($map)->sum('used_score_money');//积分抵现总金额
        if(empty($score_price)) $score_price=0;
        $map['pay_code']=array('in','scanalipay,MMSCAN,CHINAUMSPOS');
        $online_price=M('OrderInfo')->where($map)->sum('pay_amount');//扫码支付总金额
        if(empty($online_price)) $online_price=0;
        $map['pay_code']='weixinpay';
        $weixin_price=M('OrderInfo')->where($map)->sum('pay_amount');//微信支付总金额
        if(empty($weixin_price)) $weixin_price=0;
        $map['pay_code']=array('in','alipay,Alipayapi,Alibarpay');
        $alipay_price=M('OrderInfo')->where($map)->sum('pay_amount');//支付宝支付总金额
        if(empty($alipay_price)) $alipay_price=0;
        unset($map['pay_code']);

        /*充值统计start*/
        $map['type']=2;
        $map['status']=3;
        $recharge_num=M('OrderInfo')->where($map)->count('id');//充值总数
        $recharge_price=M('OrderInfo')->where($map)->sum('order_amount');//充值总金额
        if(empty($recharge_price)) $recharge_price=0;
        /*充值统计end*/

        /*退款统计start*/
        $map=array();
        $map['order_type']=13;
        $map['update_time'][]=array('gt',$last_login);
        $map['update_time'][]=array('lt',$now_time);
        $map['status']=1;
        $map['shop_id']=$shop_id;
        $map['cashier_name']=$postdata['login_name'];
        $re_num=M('RefundOrder')->where($map)->count('id');//总退款数
        $re_price=M('RefundOrder')->where($map)->sum('money');//总退款金额
        if(empty($re_price)) $re_price=0;
        $re_cash_price=M('RefundOrder')->where($map)->sum('refund_cash');//退款现金总数
        if(empty($re_cash_price)) $re_cash_price=0;
        $re_yue_price=M('RefundOrder')->where($map)->sum('refund_money');//退款余额总数
        if(empty($re_yue_price)) $re_yue_price=0;
        $re_card_price=M('RefundOrder')->where($map)->sum('refund_card');//退款刷卡总数
        if(empty($re_card_price)) $re_card_price=0;
        $re_online_price=M('RefundOrder')->where($map)->sum('refund_web');//退款网银总数
        if(empty($re_online_price)) $re_online_price=0;
        $re_bank_price=M('RefundOrder')->where($map)->sum('refund_bank');//退款台卡总数
        if(empty($re_bank_price)) $re_bank_price=0;
        $re_score_price=M('RefundOrder')->where($map)->sum('refund_scores');//退款积分总数
        if(empty($re_score_price)) $re_score_price=0;
        if(empty($re_weixin_price)) $re_weixin_price=0;
        if(empty($re_alipay_price)) $re_alipay_price=0;
        /*退款统计end*/
        if($last_login) $return['data']['start_time']=time_format($last_login);
        else $return['data']['start_time']='';
        $return['data']['end_time']=time_format($now_time);
        //线上总金额统计
        $return['data']['on_num']=$on_num;
        $return['data']['on_price']=$on_price;
        //预付卡统计
        $return['data']['pre_paid_num']=$pre_paid_num;
        $return['data']['pre_paid_price']=$pre_paid_price;
        //总金额统计
        $return['data']['all_num']=$all_num;
        $return['data']['all_price']=$all_price;
        $return['data']['yue_price']=$yue_price;
        $return['data']['card_price']=$card_price;
        $return['data']['online_price']=$online_price;
        $return['data']['mmscan_price']=$online_price;//临时用
        $return['data']['weixin_price']=$weixin_price;
        $return['data']['alipay_price']=$alipay_price;
        $return['data']['cash_price']=$cash_price;
        $return['data']['bank_price']=$bank_price;
        $return['data']['score_price']=$score_price;
        //退款统计
        $return['data']['re_num']=$re_num;
        $return['data']['re_price']=$re_price;
        $return['data']['re_yue_price']=$re_yue_price;
        $return['data']['re_card_price']=$re_card_price;
        $return['data']['re_online_price']=$re_online_price;
        $return['data']['re_mmscan_price']=$re_online_price;//临时用
        $return['data']['re_weixin_price']=$re_weixin_price;
        $return['data']['re_alipay_price']=$re_alipay_price;
        $return['data']['re_cash_price']=$re_cash_price;
        $return['data']['re_bank_price']=$re_bank_price;
        $return['data']['re_score_price']=$re_score_price;
        //充值统计
        $return['data']['recharge_num']=$recharge_num;
        $return['data']['recharge_price']=$recharge_price;
        $map=array();
        $map['shop_id']=$shop_id;
        $map['cashier_name']=$postdata['login_name'];
        $turn_over=M("TurnOver")->where($map)->order('id desc')->field('id')->find();
        $return['data']['id']=$turn_over['id'];
        $return['status']=1;
        return $return;
    }

    /**
     * 添加交接班记录
     * @param $postdata
     * @return array
     */
    public function add_turnover($postdata){
        $return=array('status'=>0,'msg'=>'');
        if(empty($postdata['shop_id']) || empty($postdata['login_name'])){$return['msg']='参数错误'; return $return;}
        $add=array();
        /*2018/8/29修改*/
        $add['all_price'] = $postdata['list']['all_price'];
        $add['all_num'] = $postdata['list']['all_num'];
        $add['re_price'] = $postdata['list']['re_price'];
        $add['re_num'] = $postdata['list']['re_num'];
        $add['recharge_price'] = $postdata['list']['recharge_price'];
        $add['recharge_num'] = $postdata['list']['recharge_num'];
        $add['on_num'] = $postdata['list']['on_num'];
        $add['on_price'] = $postdata['list']['on_price'];
        $add['yue_price'] = $postdata['list']['yue_price'];
        $add['card_price'] = $postdata['list']['card_price'];
        $add['online_price'] = empty($postdata['list']['online_price'])?$postdata['list']['mmscan_price']:$postdata['list']['online_price'];
        $add['weixin_price'] = $postdata['list']['weixin_price'];
        $add['alipay_price'] = $postdata['list']['alipay_price'];
        $add['cash_price'] = $postdata['list']['cash_price'];
        $add['bank_price'] = $postdata['list']['bank_price'];
        $add['score_price'] = $postdata['list']['score_price'];
        $add['re_yue_price'] = $postdata['list']['re_yue_price'];
        $add['re_card_price'] = $postdata['list']['re_card_price'];
        $add['re_online_price'] = empty($postdata['list']['re_online_price'])?$postdata['list']['re_mmscan_price']:$postdata['list']['re_mmscan_price'];
        $add['re_weixin_price'] = $postdata['list']['re_weixin_price'];
        $add['re_alipay_price'] = $postdata['list']['re_alipay_price'];
        $add['re_cash_price'] = $postdata['list']['re_cash_price'];
        $add['re_bank_price'] = $postdata['list']['re_bank_price'];
        $add['re_score_price'] = $postdata['list']['re_score_price'];
        $add['pre_paid_num'] = $postdata['list']['pre_paid_num'];
        $add['pre_paid_price'] = $postdata['list']['pre_paid_price'];
        /*修改结束*/

        $add['shop_id'] = $postdata['shop_id'];
        $add['cashier_name'] = $postdata['login_name'];
        $add['start_time'] = strtotime($postdata['list']['start_time']);
        if(empty($add['start_time'])){
            if($postdata['is_root']){
                $map=array();
                $map['id']=$postdata['shop_id'];
                $last_login=M('Shops')->where($map)->getField('last_login');
                if(empty($last_login) || (NOW_TIME-$last_login)>86400){
                    $map=array();
                    $map['shop_id']=$postdata['shop_id'];
                    $map['status']=1;
                    $map['is_delete']=0;
                    $add['start_time']=M('ShopsAccount')->where($map)->order('last_login desc')->getField('last_login');
                }
            }else{
                $map=array();
                $map['shop_id']=$postdata['shop_id'];
                $map['login_name']=$postdata['login_name'];
                $map['status']=1;
                $map['is_delete']=0;
                $add['start_time']=M('ShopsAccount')->where($map)->getField('last_login');
            }
        }
        $add['end_time'] = strtotime($postdata['list']['end_time']);
        if(empty($add['end_time'])) $add['end_time']=NOW_TIME;
        $add['update_pre_cash'] = $postdata['update_pre_cash'];
        $add['remarks'] = $postdata['remarks'];
        $add['print_num'] = 1;
        $res=M('TurnOver')->add($add);
        if($res){$return['status']=1; $return['msg']='交接班成功'; return $return;}
        else{ $return['msg']='交接班失败'; return $return;}
    }

    /**
     * 交接班列表
     */
    public function turn_over_list($postdata){
        $return=array('status'=>0,'msg'=>'');
        if(empty($postdata['shop_id'])){$return['msg']='参数错误'; return $return;}
        $map=array();
        $map['shop_id']=$postdata['shop_id'];
        //不是登录的总管理员只能查看自己的交接班记录
        if($postdata['is_root']!=1){
            $map['cashier_name']=$postdata['cashier_name'];
        }
        $field='id,cashier_name,total_sta,all_price,all_num,start_time,end_time';
        $data=page_list('TurnOver',$map,'id desc',$field,20);
        if(empty($data['list'])){ $return['status']=2; $return['msg']='没有交接班记录'; return $return;}
        foreach($data['list'] as $k => $v){
            if(!empty($v['total_sta'])){$data['list'][$k]['total_sta'] = unserialize($v['total_sta']);}
            else{
                $data['list'][$k]['total_sta']['all_price'] = $v['all_price'];
                $data['list'][$k]['total_sta']['all_num'] = $v['all_num'];
            }
            $data['list'][$k]['start_time'] = time_format($v['start_time']);
            $data['list'][$k]['end_time'] = time_format($v['end_time']);
        }
        $return['status']=1;
        $return['data']=$data;
        return $return;
    }

    /**
     * 交接班内容
     * @param $postdata
     * @return array
     */
    public function turn_over_content($postdata){
        $return=array('status'=>0,'msg'=>'');
        if(empty($postdata['shop_id']) || empty($postdata['id'])){$return['msg']='参数错误'; return $return;}
        $map=array();
        $map['id']=$postdata['id'];
        $map['shop_id']=$postdata['shop_id'];
        if($postdata['is_root']!=1){
            $map['cashier_name']=$postdata['cashier_name'];
        }
        $data=M('TurnOver')->where($map)->field(true)->find();
        if(empty($data)){ $return['msg']='没有交接班记录'; return $return;}
        $list=$this->format_turn_over($data);
        $return['status']=1;
        $return['data']=$list;
        return $return;
    }

    /**
     * 格式化交接班数据
     * @param $data
     * @return array|bool
     */
    private function format_turn_over($data){
        if(empty($data)) return false;
        $new_data=array();
        if(!empty($data['total_sta'])){
            $total_sta=unserialize($data['total_sta']);
            $new_data['all_price']=$total_sta['all_price'];
            $new_data['all_num']=$total_sta['all_num'];
            $new_data['re_price']=$total_sta['re_price'];
            $new_data['re_num']=$total_sta['re_num'];
            $new_data['recharge_price']=$total_sta['recharge_price'];
            $new_data['recharge_num']=$total_sta['recharge_num'];
            $new_data['on_price']=$total_sta['on_price'];
            $new_data['on_num']=$total_sta['on_num'];
        }else{
            $new_data['all_price']=$data['all_price'];
            $new_data['all_num']=$data['all_num'];
            $new_data['re_price']=$data['re_price'];
            $new_data['re_num']=$data['re_num'];
            $new_data['recharge_price']=$data['recharge_price'];
            $new_data['recharge_num']=$data['recharge_num'];
            $new_data['on_price']=$data['on_price'];
            $new_data['on_num']=$data['on_num'];
            $new_data['pre_paid_num']=$data['pre_paid_num'];
            $new_data['pre_paid_price']=$data['pre_paid_price'];
        }
        if(!empty($data['received_price'])) {
            $received_price = unserialize($data['received_price']);
            $new_data['cash_price']=$received_price['cash_price'];
            $new_data['yue_price']=$received_price['yue_price'];
            $new_data['weixin_price']=$received_price['weixin_price'];
            $new_data['alipay_price']=$received_price['alipay_price'];
            $new_data['card_price']=$received_price['card_price'];
            $new_data['online_price']=$received_price['mmscan_price'];
            $new_data['mmscan_price']=$received_price['mmscan_price'];
        }else{
            $new_data['cash_price']=$data['cash_price'];
            $new_data['yue_price']=$data['yue_price'];
            $new_data['weixin_price']=$data['weixin_price'];
            $new_data['alipay_price']=$data['alipay_price'];
            $new_data['card_price']=$data['card_price'];
            $new_data['online_price']=$data['online_price'];
            $new_data['mmscan_price']=$data['online_price'];
            $new_data['bank_price']=$data['bank_price'];
            $new_data['score_price']=$data['score_price'];
        }
        if(!empty($data['return_price'])) {
            $return_price = unserialize($data['return_price']);
            $new_data['re_cash_price']=$return_price['re_cash_price'];
            $new_data['re_yue_price']=$return_price['re_yue_price'];
            if($return_price['re_card_price'])$new_data['re_card_price']=$return_price['re_card_price'];
            else $new_data['re_card_price']=0;
            if($return_price['re_online_price'])$new_data['re_online_price']=$return_price['re_online_price'];
            else $new_data['re_online_price']=0;
        }else{
            $new_data['re_cash_price']=$data['re_cash_price'];
            $new_data['re_yue_price']=$data['re_yue_price'];
            if($new_data['re_card_price'])$new_data['re_card_price']=$new_data['re_card_price'];
            else $new_data['re_card_price']=0;
            if($new_data['re_online_price'])$new_data['re_online_price']=$new_data['re_online_price'];
            else $new_data['re_online_price']=0;
        }
        $new_data['id']=$data['id'];
        $new_data['shop_id']=$data['shop_id'];
        $new_data['cashier_name']=$data['cashier_name'];
        $new_data['start_time']=time_format($data['start_time']);
        $new_data['end_time']=time_format($data['end_time']);
        $new_data['update_pre_cash']=$data['update_pre_cash'];
        $new_data['print_num'] =$data['print_num'];
        $new_data['remarks']=$data['remarks'];
        return $new_data;
    }
    /*交接班结束*/
    public function check_auth($sid,$action){
        $return=array('status'=>0,'msg'=>'');
        if(empty($sid) || empty($action)){$return['msg']='参数错误'; return $return;}
        $map=array();
        $map['account_id']=$sid;
        $role_id=M('ShopsRoleAccount')->where($map)->getField('role_id');
        $map=array();
        $map['role_id']=$role_id;
        $map['module']='Pad';
        $map['action']=$action;
        $result=M('ShopsRoleAuth')->where($map)->count();
        if(empty($result)){ $return['msg']='没有操作此模块的权限'; return $return;}
        $return['status']=1;
        return $return;
    }
    /*打印start*/
    /**
     * 交接班打印
     */
    public function exchange_print_info($param){
        $return=array('status'=>1);
        $shop_id=$param['shop_id'];
        if($param['is_content']){
            $result=D('Pad/Cashier')->turn_over_content($param);
            $map=array();
            $map['id']=$param['id'];
            $print_num = $result['data']['print_num']+1;
            $savedata=array('print_num'=>$print_num);
            M('TurnOver')->where($map)->save($savedata);
        }else {
            $result = D('Pad/Cashier')->statistics($param);
        }
        if($result['status']==0){return $result;}
        $map=array();
        $map['id']=$shop_id;
        $shop_info=M("Shops")->where($map)->field('printer_type,machine_code,print_template,print_tpl_id')->find();
        if(!empty($param['deviceId'])){
            $mod=M('PrintDevice');
            $map=array();
            $map['deviceid']=$param['deviceId'];
            $check=$mod->where($map)->count("id");
            if($check) {
                $print_arr=array();
                $print_arr=$mod->where($map)->field(true)->find();
                if(!empty($print_arr)){
                    if(!empty($print_arr['printer_type']))$shop_info['printer_type']=$print_arr['printer_type'];
                    if(!empty($print_arr['machine_code']))$shop_info['machine_code']=$print_arr['machine_code'];
                    if(!empty($print_arr['printer_ip']))$shop_info['printer_ip']=$print_arr['printer_ip'];
                    if(!empty($print_arr['port']))$shop_info['port']=$print_arr['port'];
                    if(!empty($print_arr['print_tpl_id']))$shop_info['print_tpl_id']=$print_arr['print_tpl_id'];
                    if(!empty($print_arr['print_template']))$shop_info['print_template']=$print_arr['print_template'];
                }
            }
        }else{
            if(str_exists($shop_info['printer_type'],'Jiabo')) $shop_info['printer_ip']=$shop_info['machine_code'];
        }
        $map = array();
        $map['id'] = 3;
        $info = M('TplReceipt')->where($map)->field(true)->find();
        if(empty($info)) {$return['msg']='小票模板错误';$return['status']=0; return $return;}
        $tpl = json_decode($info['tpl_info'], true);
        if($shop_info['print_template']){
            $set=json_decode($shop_info['print_template'], true);
        }else{
            $set = json_decode($info['set_info'], true);
        }
        if (!empty($set)) {
            foreach ($tpl as $k => $v) {
                if ($set['is_show'] == 0) {
                    if ($v['type'] == 'qrcode') {
                        unset($tpl[$k]);
                    }
                }
            }
        }
        if(empty($shop_info['printer_type'])){$shop_info['printer_type']='Shangmi';}//Local Yilianyun Shangmi
        if($param['type_id']==1){$set['type_id']=1;}
        $new_printer_type=explode("(", $shop_info['printer_type']);
        $printer_type=$new_printer_type[0];
        if($printer_type=='usb-Xprinter')$printer_type='Jiabo';
        $print = new \Common\Vendor\Printtpl($printer_type);//Local Yilianyun Shangmi
        $data = array(
            'shopname' => empty($set['shopname'])?idtoname($shop_id, "Shops", 'name'):$set['shopname'],
            'cashier' => $param['login_name'],
            'starttime' => $result['data']['start_time'],
            'endtime' => $result['data']['end_time'],
            'cashprice' => format_price($result['data']['cash_price']),
            'weixinprice' => format_price($result['data']['weixin_price']),
            'cardprice' => format_price($result['data']['card_price']),
            'yueprice' => format_price($result['data']['yue_price']),
            'alipayprice' => format_price($result['data']['alipay_price']),
            'mmscanprice' => format_price($result['data']['online_price']),
            're_cashprice' => format_price($result['data']['re_cashprice']),
            're_weixinprice' => format_price($result['data']['re_weixin_price']),
            're_cardprice' => format_price($result['data']['re_card_price']),
            're_yueprice' => format_price($result['data']['re_yue_price']),
            're_alipayprice' => format_price($result['data']['re_alipay_price']),
            're_mmscanprice' => format_price($result['data']['re_online_price']),
            'all_price' => format_price($result['data']['all_price']),
            'recharge_price' => format_price($result['data']['recharge_price']),
            're_price' => format_price($result['data']['re_price']),
            'on_price' => format_price($result['data']['on_price']),
            'all_num' => $result['data']['all_num'],
            'recharge_num' => $result['data']['recharge_num'],
            're_num' => $result['data']['re_num'],
            'on_num' => $result['data']['on_num'],
            'pre_paid_num' => $result['data']['pre_paid_num'],
            'pre_paid_price' => $result['data']['pre_paid_price'],
            'print_time' => time_format(NOW_TIME)
        );
        $text = $print->fetch($tpl, $data);
        if ($printer_type == 'Yilianyun') {
            if (empty($shop_info['machine_code'])) {
                $return['status'] = 0;
                $return['msg'] = '添加打印机终端号';
                return $return;
            }
            $print = doPrint($shop_info['machine_code'], $text, $result['data']['id']);
            $print['status'] = $print['status'] == 0 ? 3 : $print['status'];
            $print['msg'] = empty($print['msg']) ? $print['info'] : $print['msg'];
            return $print;
        } else {
            $return['data'] = json_decode($text,true);
        }
        return $return;
    }
    /**
     * 收银打印，线下，线上订单打印
     */
    public function order_print_info($postdata){
        $return=array('status'=>0,'msg'=>'');
        if(empty($postdata['order_id'])){$return['msg']='参数错误'; return $return;}
        $order_id=$postdata['order_id'];
        $map=array();
        $map['id']=$order_id;
        $order_info=M('OrderInfo')->where($map)->field(true)->find();
        if(empty($order_info)){$return['msg']='订单不存在'; return $return;}
        $map=array();
        $map['order_id']=$order_id;
        $order_goods=M('OrderGoods')->where($map)->field(true)->select();
        $goods_list=array();
        $discount_money=$all_promote_price=$all_money=0;
		if($order_goods){
			foreach($order_goods as $k => $v){
				$attr=array();
				$attr=unserialize($v['goods_attr']);
				$attr_name=$attr['name'];
				$promote_name=idtoname($v['promot_id'],'PromotAct','act_name');
				$goods_list[$k]=$v;
                $v['goods_name']=str_replace("•","·",$v['goods_name']);
				$goods_list[$k]['goods_name']=$v['goods_name'].$attr_name;
				if($promote_name) $goods_list[$k]['goods_name']."(".$promote_name.")";
				$goods_list[$k]['goods_number']=floatval($v['goods_number']);
				$goods_list[$k]['all_price']=format_decimal($v['goods_number']*$v['goods_price']);
                $price=format_decimal($v['goods_number']*$v['attr_price']);
				if($v['custom_discount']){
					$custom_discount=array();
					$discount_type=0;$discount=0;
					$custom_discount=unserialize($v['custom_discount']);
					$discount_type=$custom_discount['discount_type'];
					if($discount_type==2){$discount=(1-$custom_discount['discount_num']/100)*$v['attr_price']*$v['goods_number'];}
					else {$discount=$v['discount_num']*$v['goods_number'];}
					$discount_money+=$discount;
				}else{
					if($v['goods_price']!=$v['attr_price']){$promote_price=$v['attr_price']-$v['goods_price']*$v['goods_number'];}
					$all_promote_price+=$promote_price;
				}
				$all_money+=$price;
			}
		}else{
			$all_money = $order_info['order_money'];
		}
        if($order_info['uid']){
            $map=array();
            $map['id']=$order_info['uid'];
            $member_info=M('Member')->where($map)->field('card_sn,mobile,usepoints,money')->find();
            if($member_info['card_sn']) $card_num = $member_info['card_sn'];
            if($member_info['mobile']) $mobile = $member_info['mobile'];
            if($member_info['usepoints']) $usepoints = $member_info['usepoints'];
        }
        $map=array();
        $map['id']=$postdata['shop_id'];
        $shop_info=M("Shops")->where($map)->field('printer_type,machine_code,print_template,print_tpl_id')->find();
        if(!empty($postdata['deviceId'])){
            $mod=M('PrintDevice');
            $map=array();
            $map['deviceid']=$postdata['deviceId'];
            $check=$mod->where($map)->count("id");
            if($check) {
                $print_arr=array();
                $print_arr=$mod->where($map)->field(true)->find();
                if(!empty($print_arr)){
                    if(!empty($print_arr['printer_type']))$shop_info['printer_type']=$print_arr['printer_type'];
                    if(!empty($print_arr['machine_code']))$shop_info['machine_code']=$print_arr['machine_code'];
                    if(!empty($print_arr['printer_ip']))$shop_info['printer_ip']=$print_arr['printer_ip'];
                    if(!empty($print_arr['port']))$shop_info['port']=$print_arr['port'];
                    if(!empty($print_arr['print_tpl_id']))$shop_info['print_tpl_id']=$print_arr['print_tpl_id'];
                    if(!empty($print_arr['print_template']))$shop_info['print_template']=$print_arr['print_template'];
                }
            }
        }else{
            if(str_exists($shop_info['printer_type'],'Jiabo')) $shop_info['printer_ip']=$shop_info['machine_code'];
        }
        $map = array();
        if($shop_info['print_tpl_id']){
            $map['id'] = $shop_info['print_tpl_id'];
        }else{
            $map['is_select'] = 1;
        }
        $map['status'] = 1;
        $info = M('TplReceipt')->where($map)->field(true)->find();
        if(empty($info)){$return['msg']='小票模板错误!'; return $return;}
        $tpl = json_decode($info['tpl_info'], true);
        if($shop_info['print_template']){
            $set=json_decode($shop_info['print_template'], true);
        }else{
            $set = json_decode($info['set_info'], true);
        }
		$wx = new \Common\Vendor\Weixinopen;
		$res = $wx->wxconfig(C('appid'));
		if(!$res){$set['is_show'] = 0;}
        if (!empty($set)) {
            foreach ($tpl as $k => $v) {
                if ($set['is_show'] == 0) {
                    if ($v['type'] == 'qrcode') {
                        unset($tpl[$k]);
                    }
                }
            }
			$qrcode_url = '';
			//小票抽奖(判断是否有效)
			if ($set['is_show'] == 1) {
				$g_map=array();
				$g_map['status'] = 1;
				$g_map['class'] = 0;
				$g_map['start_time'] = array('lt',NOW_TIME);
				$g_map['end_time'] = array('gt',NOW_TIME);
				$count = M('ReceiptDraw')->where($g_map)->count();
				if($count){
					$cj = 'cj'.$postdata['order_id'];
                    $qr=wxqrcode($cj,1,1);
					$qrcode_url=$qr['info'];
					if(!$qrcode_url || $qrcode_url == 'null'){
						$return['status']=3;$return['is_dy']=1;
						$return['msg']='小票抽奖二维码生成中，请稍等！';
						return $return;
					}
					if(str_exists($qrcode_url,'access_token'))$qrcode_url='';
				}
				if (empty($qrcode_url)){
					if(C('WEIXIN_PUBLIC_NUMBER_URL')){
						$qrcode_url=C('WEIXIN_PUBLIC_NUMBER_URL');
					}else{
						$wx = new \Common\Vendor\Weixinopen;
						$result=$wx->get_authorizer_info();
						if(!empty($result['authorizer_info']['user_name'])){
							$qrcode=$wx->get_wxqrcode($result['authorizer_info']['user_name']);
							if(!empty($qrcode) && str_exists($qrcode,'weixin.qq.com'))$qrcode_url=$qrcode;
							if(C('WEIXIN_PUBLIC_NUMBER_URL') != $qrcode_url && strlen($qrcode_url)<=80){
								$map = $save = array();
								$map['name'] = 'WEIXIN_PUBLIC_NUMBER_URL';
								$save['value'] = $qrcode_url;
								M('Config')->where($map)->save($save);
							}
						}
					}
				}
			}
        }
        if($info['id']==2){$set['print_tpl_id']=2;}
        else $set['print_tpl_id']=1;
        if($postdata['type_id']==1){$set['type_id']=1;}
        if(empty($shop_info['printer_type'])){$shop_info['printer_type']='Shangmi';}
        $new_printer_type=explode("(", $shop_info['printer_type']);
        $printer_type=$new_printer_type[0];
        if($printer_type=='usb-Xprinter')$printer_type='Jiabo';
        $print = new \Common\Vendor\Printtpl($printer_type);//Local Yilianyun Shangmi
        $dis_way='';
        if(floatval($order_info['first_money'])>0) $dis_way.='新用户立减,';
        if(floatval($order_info['score_money'])>0) $dis_way.='积分抵现,';
        if(floatval($order_info['bonus_money'])>0) $dis_way.='优惠券,';
        //if(floatval($order_info['member_discount'])>0) $dis_way.='等级折扣,';
        if(floatval($order_info['custom_discount'])>0) $dis_way.='自定义折扣,';
        //if(floatval($all_promote_price)>0) $dis_way.='促销商品,';
        //if(floatval($discount_money)>0) $dis_way.='单品优惠,';
        $dis_way=rtrim($dis_way,',');
        $line="";
        if(!empty($goods_list)) $line="--------------------------------";
        $zero=0;$zero_type='';
        if($order_info['moling_discount']){
            $moling_discount=unserialize($order_info['moling_discount']);
            $zero=$moling_discount['moling_money'];
            if($moling_discount['moling_type']==1){$zero_type='抹分';}
            if($moling_discount['moling_type']==2){$zero_type='抹角';}
            if($moling_discount['moling_type']==3){$zero_type='四舍五入抹角';}
        }
        /*支付方式支付金额统计start*/
        if($order_info['cash_money']>0){
            $cash_in_hand=$order_info['cash_in_hand'];
            $cash_money=$order_info['cash_money'];
            $back_money=$order_info['back_money'];
        }
        if($order_info['scan_money']>0){
            if($order_info['assist_code']=='HANCHAO_S_WEIXIN') $weixin_money=$order_info['scan_money'];
            if($order_info['assist_code']=='HANCHAO_S_ALIPAY') $alipay_money=$order_info['scan_money'];
        }
        if($order_info['bank_money']>0) $bank_money=$order_info['bank_money'];
        if($order_info['card_money']>0) $card_money=$order_info['card_money'];
        if($order_info['used_money']>0) $used_money=$order_info['used_money'];
        $user_money='';
        if($set['is_yue']==1 && $order_info['uid']) $user_money=$member_info['money']?$member_info['money']:'0.00';
        if($set['is_show']==0) $set['description']='';
        /*支付方式支付金额统计end*/
        $data = array(
            'shopname' => empty($set['shopname'])?idtoname($postdata['shop_id'], "Shops", 'name'):$set['shopname'],//店铺名称
            'ordersn' => $order_info['order_sn'],
            'cashier' => $order_info['sign_building'],//收银员名字
            'goodslist' => $goods_list,//商品列表
            'zongji' => $all_money,//总计
            'dis_way' => $dis_way,//优惠方式
            //'discount' => $order_info['discount'],//优惠金额
            'firstmoney'=>$order_info['first_money'],
            'scoremoney'=>$order_info['used_score_money'],
            'bonusmoney' => $order_info['bonus_money'],//代金券优惠金额
            //'memberdiscount'=>$order_info['member_discount'],
            'customdiscount'=>$order_info['custom_discount'],
            //'promoteprice'=>$all_promote_price,
            //'discountmoney'=>$discount_money,
            'zero' => $zero,//抹零
            //'zerotype' => $zero_type,//抹零方式
            'w_money' => $order_info['order_amount'],//应付款金额
            'cashinhand' => $cash_in_hand,//现金实际支付金额
            'cashmoney' => $cash_money,//现金应支付金额
            'backmoney' => $back_money,//找零
            'weixinmoney' => $weixin_money,//微信支付金额
            'alipaymoney' => $alipay_money,//支付宝支付金额
            'bankmoney' => $bank_money,//台卡支付金额
            'cardmoney' => $card_money,//刷卡支付金额
            'usedmoney' => $used_money,//余额支付金额
            'temp' => $order_info['temp'] ? $order_info['temp'] : "",
            'addtime' => time_format(empty($order_info['confirm_time'])?$order_info['addtime']:$order_info['confirm_time']),
            'mobile' => $mobile ? $mobile : "",
            'card_num' => $card_num ? $card_num : "",
            'usermoney' => empty($user_money)?"":$user_money,
            'lunch_box_price' => $order_info['lunch_box_price'],
            'delivery_fee' => $order_info['delivery_fee'],
            'integral' => $order_info['get_score'],
            'sum_integral' => $usepoints ? $usepoints :"",
            'bottom_temp' => $set['temp'] ? $set['temp'] : '',
            'qrcode_url'=>$qrcode_url,
            'description'=>$set['description'],
            'line'=>$line,
        );
        $print->setConfig($set);
        $text = $print->fetch($tpl, $data);
        if ($printer_type == 'Yilianyun') {
            if (empty($shop_info['machine_code'])) {
                $return['msg'] = '添加打印机终端号'; return $return;
            }
            $print = doPrint($shop_info['machine_code'], $text, $order_info['order_sn']);
            $print['status'] = $print['status'] == 0 ? 3 : $print['status'];
            $print['msg'] = empty($print['msg']) ? $print['info'] : $print['msg'];
            return $print;
        } else {
            $return['status']=1;
            $return['data'] = json_decode($text,true);
            return $return;
        }
    }
    /**
     * 充值小票打印
     */
    public function print_recharge_info($postdata){
        $return=array('status'=>0,'msg'=>'');
        if(empty($postdata['order_id'])){$return['msg']='参数错误'; return $return;}
        $order_id=$postdata['order_id'];
        $map=array();
        $map['id']=$order_id;
        $map['type']=2;
        $order_info=M('OrderInfo')->where($map)->field(true)->find();//充值订单信息
        if(empty($order_info)){$return['msg']='订单不存在'; return $return;}
        //会员信息
        if($order_info['uid']){
            $map=array();
            $map['id']=$order_info['uid'];
            $member_info=M('Member')->where($map)->field('card_sn,mobile,usepoints')->find();
            if($member_info['card_sn']) $card_num = $member_info['card_sn'];
            if($member_info['mobile']) $mobile = $member_info['mobile'];
            if($member_info['usepoints']) $usepoints = $member_info['usepoints'];
        }
        $map=array();
        $map['id']=$postdata['shop_id'];
        $shop_info=M("Shops")->where($map)->field('printer_type,machine_code,print_template,print_tpl_id')->find();
        if(!empty($postdata['deviceId'])){
            $mod=M('PrintDevice');
            $map=array();
            $map['deviceid']=$postdata['deviceId'];
            $check=$mod->where($map)->count("id");
            if($check) {
                $print_arr=array();
                $print_arr=$mod->where($map)->field(true)->find();
                if(!empty($print_arr)){
                    if(!empty($print_arr['printer_type']))$shop_info['printer_type']=$print_arr['printer_type'];
                    if(!empty($print_arr['machine_code']))$shop_info['machine_code']=$print_arr['machine_code'];
                    if(!empty($print_arr['printer_ip']))$shop_info['printer_ip']=$print_arr['printer_ip'];
                    if(!empty($print_arr['port']))$shop_info['port']=$print_arr['port'];
                    if(!empty($print_arr['print_tpl_id']))$shop_info['print_tpl_id']=$print_arr['print_tpl_id'];
                    if(!empty($print_arr['print_template']))$shop_info['print_template']=$print_arr['print_template'];
                }
            }
        }else{
            if(str_exists($shop_info['printer_type'],'Jiabo')) $shop_info['printer_ip']=$shop_info['machine_code'];
        }
        $map = array();
        $map['id'] = 4;
        $info = M('TplReceipt')->where($map)->field(true)->find();//获取充值订单的打印模板
        if(empty($info)) {$return['msg']='小票模板错误'; return $return;}
        $tpl = json_decode($info['tpl_info'], true);
        if($shop_info['print_template']){
            $set=json_decode($shop_info['print_template'], true);
        }else{
            $set = json_decode($info['set_info'], true);
        }
        if (!empty($set)) {
            foreach ($tpl as $k => $v) {
                if ($set['is_show'] == 0) {
                    if ($v['type'] == 'qrcode') {
                        unset($tpl[$k]);
                    }
                }
            }
        }
        if($postdata['type_id']==1){$set['type_id']=1;}
        if(empty($shop_info['printer_type'])){$shop_info['printer_type']='Shangmi';}//Local Yilianyun Shangmi
        $new_printer_type=explode("(", $shop_info['printer_type']);
        $printer_type=$new_printer_type[0];
        if($printer_type=='usb-Xprinter')$printer_type='Jiabo';
        $print = new \Common\Vendor\Printtpl($printer_type);//Local Yilianyun Shangmi
        if(C('WEIXIN_PUBLIC_NUMBER_URL')){
            $qrcode_url=C('WEIXIN_PUBLIC_NUMBER_URL');
        }else{
            $wx = new \Common\Vendor\Weixinopen;
            $result=$wx->get_authorizer_info();
            if(!empty($result['authorizer_info']['user_name'])){
                $qrcode=$wx->get_wxqrcode($result['authorizer_info']['user_name']);
                if(!empty($qrcode) && str_exists($qrcode,'weixin.qq.com'))$qrcode_url=$qrcode;
                if(C('WEIXIN_PUBLIC_NUMBER_URL') != $qrcode_url && strlen($qrcode_url)<=80){
                    $map = $save = array();
                    $map['name'] = 'WEIXIN_PUBLIC_NUMBER_URL';
                    $save['value'] = $qrcode_url;
                    M('Config')->where($map)->save($save);
                }
            }
        }
        $dis_way='';
        if($order_info['get_money']) $dis_way.='储值赠余额';
        if($order_info['get_score']) $dis_way.='储值赠积分';
        if($set['is_show']==0) $set['description']='';
        $data = array(
            'shopname' => empty($set['shopname'])?idtoname($postdata['shop_id'], "Shops", 'name'):$set['shopname'],//店铺名称
            'ordersn' => $order_info['order_sn'],//订单号
            'addtime' => time_format($order_info['confirm_time']),//交易时间
            'cashier' => $order_info['sign_building'],//收银员名称
            'zongji' => $order_info['goods_amount'],//总计
            'dis_way' => $dis_way,//优惠方式
            'get_money'=> $order_info['get_money'],
            'mobile' => $mobile ? $mobile : "",//会员手机号
            'card_num' => $card_num ? $card_num : "",//会员卡号
            'integral' => $order_info['get_score'] ? $order_info['get_score'] :"",
            'sum_integral' => $usepoints ? $usepoints :"",
            'bottom_temp' => $set['temp'] ? $set['temp'] : '',//底部文案
            'qrcode_url'=>$qrcode_url,//二维码
            'temp' => $order_info['temp'] ? $order_info['temp'] : "",//备注
            'description' => $set['description'],//备注
        );
        $print->setConfig($set);
        $text = $print->fetch($tpl, $data);
        if ($printer_type == 'Yilianyun') {
            if (empty($shop_info['machine_code'])) {
                $return['msg'] = '添加打印机终端号'; return $return;
            }
            $print = doPrint($shop_info['machine_code'], $text, $order_info['order_sn']);
            $print['status'] = $print['status'] == 0 ? 3 : $print['status'];
            $print['msg'] = empty($print['msg']) ? $print['info'] : $print['msg'];
            return $print;
            //$return['data'] = $text;
        } else {
            $return['status']=1;
            $return['data'] = json_decode($text,true);
            return $return;
        }
    }
    /*打印end*/
    /*退货*/
    public function tui_goods($postdata){
        $return=array('status'=>0,'msg'=>'');
        if(empty($postdata['order_id']) || empty($postdata['shop_id']) || empty($postdata['og_id'])){$return['msg']='参数错误'; return $return;}
        $order_id=intval($postdata['order_id']);
        $tui_money=floatval($postdata['money']);
        $tui_number=floatval($postdata['goods_num']);
        $og_id=intval($postdata['og_id']);
        $where=array();
        $where['id']=$order_id;
        $order_info=M("OrderInfo")->where($where)->field(true)->find();
        $money=$postdata['money'];
        if($postdata['pay_type']==2 && $order_info['uid']==0){
            $return['msg']='该订单无会员，请选择其他方式退款';
            return $return;
        }
        if($postdata['pay_type']==3 && $money>$order_info['scan_money']){
            $return['msg']='退款金额必须小于实际扫码支付金额';
            return $return;
        }
        $param=$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(true)->find();
        if(!$order_goods){
            $return['msg']='无此商品订单';
            return $return;
        }
        if($tui_number > $order_goods['goods_number']){
            $return['msg']='退货数量不得大于购买量';
            return $return;
        }
        if($tui_number == $order_goods['goods_number']){
            $data['status']=4;
        }else{
            $data['status']=6;
        }
        if($order_goods['original_num']==0){
            $data['original_num']=$order_goods['goods_number'];
        }
        $data['goods_number']=$order_goods['goods_number']-$tui_number;
        if($data['status']==4){
            $data['profit']=0;
            $data['money']=0;
            $kou_money=$order_goods['money'];
            $profit=$order_goods['profit'];
        }else{
            $profit = ($order_goods['profit']/$data['original_num'])*$tui_number;
            $money = ($order_goods['money']/$data['original_num'])*$tui_number;
            $data['profit']=round($order_goods['profit']-$profit,2);
            $data['money']=round($order_goods['money']-$money,2);
            $kou_money=$money;
        }
        // 修改订单
        M("OrderGoods")->where($map)->save($data);
        $map_og['order_id']=$order_id;
        $allgoodsnum = M("OrderGoods")->where($map_og)->sum('goods_number');
        if(floatval($allgoodsnum)==0 || floatval($allgoodsnum)=='0.00'){
            $data_oi['status']=7;
        }
        $data_oi['goods_amount']=$order_info['goods_amount']-$money;
        $data_oi['goods_allmoney']=$order_info['goods_allmoney']-$order_goods['attr_price']*$tui_number;
        $data_oi['order_amount']=$order_info['order_amount']-$money;
        $data_oi['order_money']=$order_info['order_money']-$money;
        $data_oi['profit']=$order_info['profit']-$profit;
        $data_oi['sales_maid']=$order_info['sales_maid']-$kou_money;
        M('OrderInfo')->where($where)->save($data_oi);
        if($postdata['pay_type']==3){
            $res=D('Common/OrderInfo')->refund($order_info['uid'],$tui_money,$order_info['order_sn'],2);
            if($res['status']==0){
                $return['msg']=$res['msg'];
            }

            return $return;
        }
        $log='订单'.$order_info['order_sn'].'退货'.$tui_number.'件，佣金扣除'.$kou_money.'元';
        account_change($order_info['guide'],-$kou_money,1,10,$log,'','',5);
         //添加退货单
        $tuigoods['goods_id']=$goods_info['goods_id']=$order_goods['goods_id'];
        $tuigoods['goods_number']=$goods_info['number']=$tui_number;
        if($order_goods['goods_attr']){
            $attr = unserialize($order_goods['goods_attr']);
            $tuigoods['goods_attr']=$goods_info['goods_attr']=$attr['key'];
        }
        
        //生成退款单
        $refund_data['reason']=$postdata['content'];
        $refund_data['type']=0;
        $refund_data['cashier_name']=$postdata['login_name'];
        $refund_data['order_goods']=$og_id;
        $refund_data['order_id']=$order_id;
        $refund_data['shop_id']=$postdata['shop_id'];
        $refund_data['money']=$tui_money;
        switch ($postdata['pay_type']) {
            case 1:
                $param['payment_id']=$refund_data['payment_id']=2;
                $param['pay_code']=$refund_data['payment_code']='HANCHAO_XIANJIN';
                $param['cash_money']=$refund_data['refund_cash']=$tui_money;
                break;
            case 2:
                $param['payment_id']=$refund_data['payment_id']=1;
                $param['pay_code']=$refund_data['payment_code']='HANCHAO';
                $param['use_money']=$refund_data['refund_money']=$tui_money;
                if($tui_money > 0){
                    account_change($order_info['uid'],$tui_money,1,8,'退货,订单'.$order_info['order_sn']);
                }
                break;
            case 3:
                $param['payment_id']=$refund_data['payment_id']=23;
                $param['pay_code']=$refund_data['payment_code']='CHINAUMSPOS';
                $param['scan_money']=$refund_data['refund_web']=$tui_money;
                break;
            case 5:
                $param['payment_id']=$refund_data['payment_id']=19;
                $param['pay_code']=$refund_data['payment_code']='HANCHAO_CARD';
                $param['card_money']=$refund_data['refund_card']=$tui_money;
                break;
        }
        $refund_data['addtime']=NOW_TIME;
        $refund_data['update_time']=NOW_TIME;
        $refund_data['cashier_name']=$postdata['login_name'];
        $refund_data['status']=1;
        $refund_data['uid']=$order_info['uid'];
        $refund_data['order_type']=$order_info['type'];
        $refund_data['type']=1;
        $rorder_id= M("RefundOrder")->add($refund_data);
       
        $add['rorder_id']=$rorder_id;
        $add['org_id']=$og_id;
        $add['uid']=$order_info['uid'];
        $add['cashier_name']=$postdata['login_name'];
        $add['shop_id']=$postdata['shop_id'];
        $add['order_id']=$order_id;
        $add['goods_info']=serialize($goods_info);
        $add['reason']=$postdata['content'];
        $add['money']=$tui_money;
        $add['add_time']=NOW_TIME;
        $add['status']=1;
        $add['shop_status']=1;
        $add['type']=1;
        $res=M('ReturnGoods')->add($add);
        switch ($postdata['pay_type']) {
            case 1:
                // 退货退款营业额减少
                shop_balance_log($order_info['shop_id'], $tui_money, 6,3,'订单'.$order_info['order_sn'].'退货退款,销售总额减少', $order_info);
                break;
            case 2:
               // 退货退款营业额减少
                shop_balance_log($order_info['shop_id'], $tui_money, 6,3,'订单'.$order_info['order_sn'].'退货退款,销售总额减少', $order_info);
                // 退货退款余额减少
                shop_balance_log($order_info['shop_id'], $tui_money, 1,3,'订单'.$order_info['order_sn'].'退货退款,余额减少', $order_info);
                    break;
            case 3:

                // 退货退款营业额减少
                shop_balance_log($order_info['shop_id'], $tui_money, 6,3,'订单'.$order_info['order_sn'].'退货退款,销售总额减少', $order_info);
                // 退货退款余额减少
                shop_balance_log($order_info['shop_id'], $tui_money, 1,3,'订单'.$order_info['order_sn'].'退货退款,余额减少', $order_info);
                break;
            case 5:
                // 退货退款营业额减少
                shop_balance_log($order_info['shop_id'], $tui_money, 6,3,'订单'.$order_info['order_sn'].'退货退款,销售总额减少', $order_info);
                break;
        }
        // 增加退款流水
        $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']=$order_info['pay_amount'];$param['use_score']=$order_info['used_score'];
        $param['order_total_price']=$order_info['order_money'];
        $param['in_online']=$order_info['in_online'];
        $param['shop_id']=$order_info['shop_id'];
        D('Common/OrderInfo')->return_goods_log($param);
        // 加库存
        $map=array();
        $map['shop_id']=$order_goods['shop_id'];
        $map['goods_id']=$order_goods['goods_id'];
        $sale_type = idtoname($order_goods['goods_id'],'Goods','sale_type');
        if($sale_type == 1){//组合商品
            D('Shop/OrderInfo')->add_group_goods($map,$tuigoods,$order_id,1);
        }else{
            D('Shop/OrderInfo')->add_stock($map,$tuigoods,$order_id,1,1);
        }
       
        $return['status']=1;
        $return['msg']='退货成功';
        return $return;
    }
    //获取现有所有有效的优惠活动
    public function get_active($ids=''){
        $map=$data=array();
        $map['is_offline']=1;
        $map['start_time']=array('elt',NOW_TIME);
        $map['end_time']=array('egt',NOW_TIME);
        if($ids)$map['id']=array('in',$ids);
        $list=M('PromotAct')->where($map)->field('id,act_name,min_amount,max_amount,act_type,act_type_ext,act_good_ids,is_addup')->select();
        foreach($list as $v){
            if($v['act_good_ids'])$v['act_good_ids']=array_values(array_filter(explode(',',$v['act_good_ids'])));
            $data[$v['id']]=$v;
        }
        $return['status']=1;
        $return['data']=$data;
        return $return;
    }
    //获取现有所有有效的优惠活动
    public function get_goods_activeid($goodsid,$shop_id=0){
        if(empty($goodsid))return 0;
        if(empty($shop_id))$shop_id=I('shop_id');
        $map=array();
        $map['style_ext_id']=$goodsid;
        $map['style']=3;
        $check=M('PromotExt')->where($map)->cache(true)->count('id');
        if(empty($check))return 0;
        $map=array();
        $map['id']=$shop_id;
        $shop_type=M("Shops")->where($map)->getField('shop_type');
        $map=array();
        $map['a.is_offline']=1;
        $map['a.start_time']=array('elt',NOW_TIME);
        $map['a.end_time']=array('egt',NOW_TIME);
        $map['e.style_ext_id']=$goodsid;
        if($shop_type==2){
            $map['a.shop_id']=$shop_id;
        }else {
            $map['_string'] = "a.shop_id=" . $shop_id . "  OR a.shop_id=0";
        }
        $id=M('PromotAct')->alias('a')->join('__PROMOT_EXT__ e on a.id=e.act_id')->cache(true)->where($map)->getField('a.id');
        return $id?$id:0;
    }
    /**
     * 导出PLU
     * @param $list商品数组
     * @type 0 大华 1顶尖
     */
    public function export_plu($list,$type=0){
        $data=array();$i=1;
        $shop_id=I('shop_id');
        $jizhong_config=D('Common/InvoicingOrder')->get_jizhong($shop_id);
        foreach($list as $k=>$v){
            $v['plu']=$v['goods_plu']?$v['goods_plu']:$i;
            if($type==1){
                $data[]=$this->dingjianplu($v);
            }else{
                $v['cashier_code']=$jizhong_config['code'];
                $data[]=$this->dahuaplu($v);
            }$i++;
        }
        $filename='plu_data'.time_format(NOW_TIME,'Ymd');
        if($type==1){
            export_csv($filename.'.csv','',$data);
        }else{        
            echo implode("\r\n",$data); //这里是文件的内容
        }
    }
    /* 1.plu编号4        0-4000
        2.商品代码6       0-999999
        3.单价6             0-999999  无小数点, 单位为分
        4.单位1             0-9     0-称重状态 1-非计重状态（计件）2-定重
        5.有效期3           0-999     无小数点, 单位为克
        6.条码店名标识符2   00-99
        7.皮重/定重5         0-15000   无小数点, 单位为克
        8.特殊信息号1        0-9
        9.商品名称        最多汉字9个    
        10.配料            最多汉字13个*/
    private function dahuaplu($data){
        $is_auto=I('auto');$goods_name=str_cut($data['goods_name'],25,'');
        $str=($is_auto?'!0V':'1P').str_pad($data['plu'],4, "0", STR_PAD_LEFT).'A';
        $str.=$data['cashier_code'].str_pad(substr(intval($data['goods_sn']),0,5),5, "0", STR_PAD_LEFT);
        $str.=str_pad(($data['shop_price']*100),6,"0", STR_PAD_LEFT);
        $str.='0';
        $str.='00';//特殊信息1
        $str.='00';//特殊信息2
        $str.='00';//特殊信息3
        $str.='000';//有效期
        $str.=$data['cashier_code'];//店名号
        $str.='00';//部门号
        $str.='0000000000000';//13位数字代号
        $str.='00000';//皮重
        $str.='00';//标签号
        $str.='00';//是否打折
        $str.='00';//是否打折
        $str.='00';
        $str.='00';
        $str.='00';
        $str.='00';
        $str.='00';
        $str.='00';
        $str.='00';
        $str.='00';
        $str.='00';
        $str.='00';
        $str.='00';
        $str.=$is_auto?'B':'##';
        $str.=$is_auto?quweima($goods_name):iconv('utf-8','gb2312',$goods_name);
        $str.=$is_auto?'00C00D00E':'####';
        return $str;
    }
    private function dingjianplu($data){
        $str=array();
        $str[]=$data['plu'];
        $str[]=str_cut($data['goods_name'],25,'');
        $str[]=str_pad(substr(intval($data['goods_sn']),0,6),6, "0", STR_PAD_LEFT);
        $str[]='';//货号10位以内的数字
        $str[]='12';//条形码型号(0-99)
        $str[]=($data['shop_price']*100);//输入单价
        $str[]='4';//重量单位
        $str[]='0';//数量单位
        $str[]='0';//部门
        $str[]='0.000';//去皮重量
        $str[]='0';//保质时间
        $str[]='0';//包装类型
        $str[]='0.000';//包装重量
        $str[]='0';//包装误差
        $str[]='0';//
        $str[]='0';//
        $str[]='0';//
        return $str;
    }
	// 修改礼品卡信息
	private function change_gift_code($order_id){
		$return=array('status'=>0,'msg'=>'');
		if(empty($order_id)){$return['msg']='参数错误！';return $return;}
		$o_map = array();$o_map['id'] = $order_id;$o_map['type'] = 15;
		$order_info = M('OrderInfo')->where($o_map)->field('uid,guide,sign_building,shop_id')->find();
		
		if($order_info){
			$map = $save_data = array();
			$save_data['sell_time'] = NOW_TIME;
			$save_data['buy_uid'] 	= $order_info['uid'];
			$save_data['daogou'] 	= $order_info['guide'];
			$save_data['shop_id'] 	= $order_info['shop_id'];
			$save_data['cashier'] 	= $order_info['sign_building'];
			
			$map['order_id'] = $order_id;$map['status'] = 0;
			M('GiftCard')->where($map)->save($save_data);
		}
	}
	/**
     * 根据商品编号进行唯一查询
     * @param $id
     * @return array
     */
	public function search_by_id($id){
        $return=array('status'=>0,'msg'=>'');
        $id=intval(trim($id));
        if(empty($id)){$return['msg']='请输入礼品卡id';return $return;}
		
		$map = array();$map['id'] = $id;
        $gift_card_info = M('GiftCard')->where($map)->field(true)->find();
		if($gift_card_info){
			if($gift_card_info['end_time'] != 0 && $gift_card_info['end_time'] < NOW_TIME){
				$return['msg'] = '该礼品卡已过期';
			}else if($gift_card_info['status'] == 1){
				$return['msg'] = '该礼品卡已激活';
			}else if($gift_card_info['status'] == 2){
				$return['msg'] = '该礼品卡已作废';
			}else if($gift_card_info['sell_time'] != 0){
				$return['msg'] = '该礼品卡已售出';
			}else{
				$return['status']=1;
			}
		}else{
			$return['msg'] = '没有查到相应的礼品卡';
		}
		return $return;
    }

    /**
     * 退货打印小票
     * @param $postdata
     * @return array|\Common\Vendor\Printtpl
     */
    public function return_goods_print($postdata){
        $return=array('status'=>0,'msg'=>'');
        if(empty($postdata['order_id'])){$return['msg']='参数错误'; return $return;}
        $order_id=$postdata['order_id'];
        $map=array();
        $map['id']=$order_id;
        $order_info=M('RefundOrder')->where($map)->field(true)->find();
        if(empty($order_info)){$return['msg']='订单不存在'; return $return;}
        $map=array();
        $map['_string']= "(rorder_id > 0 AND rorder_id =".$order_info['id'].") OR (rorder_id = 0 AND order_id > 0  AND order_id =".$order_info['order_id'].")";
        //$map['type']=$order_info['type'];
        $order_goods=M('ReturnGoods')->where($map)->field(true)->select();
        $goods_list=array();
        if($order_goods){
            foreach($order_goods as $k => $v){
                $attr=$goods_info=$goods_attr=array();
                $attr=unserialize($v['goods_info']);
                $attr_name=attr_key2name($attr['goods_attr'],$attr['goods_id']);
                $goods_list[$k]=$v;
                $goods_list[$k]['goods_number']=floatval($attr['number']);//退款数量
                if($order_info['type']==0) {//线下直接退
                    //有属性的商品价格
                    if ($attr['goods_attr']) {
                        $map = array();
                        $map['goods_id'] = $attr['goods_id'];
                        $map['attr_key'] = $attr['goods_attr'];
                        $goods_attr=M('GoodsAttrStock')->where($map)->field('attr_price,goods_attr_sn')->find();
                        $goods_list[$k]['goods_price'] = $goods_attr['attr_price'];
                        $goods_list[$k]['goods_sn'] = $goods_attr['goods_attr_sn'];
                    }
                    $map = array();
                    $map['id'] = $attr['goods_id'];
                    $goods_info=M('Goods')->where($map)->field('goods_name,shop_price,goods_sn')->find();
                    if (empty($goods_list[$k]['goods_price'])) {
                        $goods_list[$k]['goods_price'] = $goods_info['shop_price'];
                    }
                    if(empty($goods_list[$k]['goods_sn'])) $goods_list[$k]['goods_sn']=$goods_info['goods_sn'];
                    $goods_list[$k]['goods_name']=$goods_info['goods_name'];
                }else{//线上、线下订单退
                    $map=array();
                    $map['id']=$v['org_id'];
                    $map['order_id']=$order_info['order_id'];
                    $goods_info=M('OrderGoods')->where($map)->field('goods_name,goods_sn,attr_price,goods_price')->find();
                    $goods_list[$k]['goods_sn']=$goods_info['goods_sn'];
                    $goods_list[$k]['goods_name']=$goods_info['goods_name'];
                    $goods_list[$k]['goods_price']=$goods_info['goods_price'];
                    $map=array('id'=>$order_info['order_id']);
                    $order_sn=M('OrderInfo')->where($map)->getField('order_sn');
                }
                $goods_list[$k]['goods_name']=str_replace("•","·",$goods_list[$k]['goods_name']);
                $goods_list[$k]['goods_name']=$goods_list[$k]['goods_name'].$attr_name;
                $goods_list[$k]['all_price']=format_decimal($attr['number']*$goods_list[$k]['goods_price']);
            }
        }
        if($order_info['uid']){
            $map=array();
            $map['id']=$order_info['uid'];
            $member_info=M('Member')->where($map)->field('card_sn,mobile')->find();
            if($member_info['card_sn']) $card_num = $member_info['card_sn'];
            if($member_info['mobile']) $mobile = $member_info['mobile'];
        }
        /*打印模板start*/
        $map=array();
        $map['id']=$postdata['shop_id'];
        $shop_info=M("Shops")->where($map)->field('printer_type,machine_code,print_template,print_tpl_id')->find();
        if(!empty($postdata['deviceId'])){
            $mod=M('PrintDevice');
            $map=array();
            $map['deviceid']=$postdata['deviceId'];
            $check=$mod->where($map)->count("id");
            if($check) {
                $print_arr=array();
                $print_arr=$mod->where($map)->field(true)->find();
                if(!empty($print_arr)){
                    if(!empty($print_arr['printer_type']))$shop_info['printer_type']=$print_arr['printer_type'];
                    if(!empty($print_arr['machine_code']))$shop_info['machine_code']=$print_arr['machine_code'];
                    if(!empty($print_arr['printer_ip']))$shop_info['printer_ip']=$print_arr['printer_ip'];
                    if(!empty($print_arr['port']))$shop_info['port']=$print_arr['port'];
                    if(!empty($print_arr['print_tpl_id']))$shop_info['print_tpl_id']=$print_arr['print_tpl_id'];
                    if(!empty($print_arr['print_template']))$shop_info['print_template']=$print_arr['print_template'];
                }
            }
        }else{
            if(str_exists($shop_info['printer_type'],'Jiabo')) $shop_info['printer_ip']=$shop_info['machine_code'];
        }
        $map = array();
        $map['id']=6;
        $map['status'] = 0;
        $info = M('TplReceipt')->where($map)->field(true)->find();
        if(empty($info)){$return['msg']='小票模板错误!'; return $return;}
        $tpl = json_decode($info['tpl_info'], true);
        if($shop_info['print_template']){
            $set=json_decode($shop_info['print_template'], true);
        }else{
            $set = json_decode($info['set_info'], true);
        }
        if($info['id']==2){$set['print_tpl_id']=2;}
        else $set['print_tpl_id']=1;
        if($postdata['type_id']==1){$set['type_id']=1;}
        if(empty($shop_info['printer_type'])){$shop_info['printer_type']='Shangmi';}
        /*打印模板end*/
        $new_printer_type=explode("(", $shop_info['printer_type']);
        $printer_type=$new_printer_type[0];
        if($printer_type=='usb-Xprinter')$printer_type='Jiabo';
        $print = new \Common\Vendor\Printtpl($printer_type);//Local Yilianyun Shangmi
        $line="";
        if(!empty($goods_list)) $line="--------------------------------";
        $data = array(
            'shopname' => empty($set['shopname'])?idtoname($postdata['shop_id'], "Shops", 'name'):$set['shopname'],//店铺名称
            'ordersn' => $order_sn,
            'addtime' => time_format(empty($order_info['update_time'])?$order_info['addtime']:$order_info['update_time']),
            'cashier' => $order_info['cashier_name'],//收银员名字
            'goodslist' => $goods_list,//商品列表
            'zongji' => format_decimal($order_info['money']),
            'mobile' => $mobile ? $mobile : "",
            'card_num' => $card_num ? $card_num : "",
            'temp' => $order_info['reason'] ? $order_info['reason'] : "",
            'bottom_temp' => $set['temp'] ? $set['temp'] : '',
            'line'=>$line,
        );
        $print->setConfig($set);
        $text = $print->fetch($tpl, $data);
        if ($printer_type == 'Yilianyun') {
            if (empty($shop_info['machine_code'])) {
                $return['msg'] = '添加打印机终端号'; return $return;
            }
            $print = doPrint($shop_info['machine_code'], $text, $order_info['id']);
            $print['status'] = $print['status'] == 0 ? 3 : $print['status'];
            $print['msg'] = empty($print['msg']) ? $print['info'] : $print['msg'];
            return $print;
        } else {
            $return['status']=1;
            $return['data'] = json_decode($text,true);
            return $return;
        }
    }
}
?>