<?php
namespace app\shared\logic\user;
use app\shared\model\User;
use app\shared\model\HouseOrder;
use app\shared\model\HouseOrderContinue;
use app\shared\model\House;
use app\shared\model\Coupon;
use app\shared\model\CouponUser;
use app\shared\model\StoreCoupon;
use app\shared\model\StoreCouponUser;
use app\shared\model\HouseStock;
use app\shared\model\Electricity;
use app\shared\model\App;
use app\shared\model\Option;
use app\shared\model\StoreCleaning;
use app\shared\model\Card;
use app\shared\model\CardUser;
use app\shared\model\CardUserOrder;
use wechatpay\WechatPay;
use app\shared\model\Store;
use app\shared\model\Bill;
use app\shared\model\ElectricityLine;
use app\plugin\model\stock\User as StockUser;
use app\plugin\model\stock\House as StockHouse;
use app\plugin\model\stock\HouseUser as StockHouseUser;
use app\plugin\model\stock\HouseUserOrder as StockHouseUserOrder;
use app\shared\model\CardCoupon;
use app\shared\model\StoreUserMoney;
use app\shared\model\Partner;
use app\shared\model\PartnerUser;
use app\shared\model\PartnerUserOrder;
use app\shared\model\CardCouponOrder;
use slock\Slock;
use think\facade\Cache;
use think\exception\ValidateException;
use app\BaseController;
use think\facade\Db;
class HouseOrderForm extends  UserForm
{
    //列表
    public function list(){
        $query=HouseOrder::where(['acid'=>$this->acid,'user_id'=>$this->user_id]);
        $status=input('status');
        if($is_tea_specialist=input('is_tea_specialist')){
           $query=$query->where('tea_specialist_id',0)->where('status','in','1,2');
        }else{
           switch ($status) {
              case '-2':
                $query->where('status',-2);
                break;
              case '-1':
                $query->where('status',-1);
                break;  
              case '0':
                $query->where('status',0);
                break;
              case '1':
                $query->where('status',1);
                break;
              case '2':
                $query->where('status',2);
                break;
              case '3':
                $query->where('status',3);
                break;      
              default:
              
                break;
            }
        }
        $list=$query->limit(10)->page($this->page)->order('id DESC')->select();
        $time=time()-90;
        foreach ($list as $key => &$value) {
            if($value->book_type==3){
                 $house=House::where('id',$value->house_id)->find();
                 $endOrderTime=$value->start_time+$house['limit_time']*3600;
                 if(time()>$endOrderTime){
                    $value->end_time=$endOrderTime;
                    $value->save();
                 }
            }else{
                $startTime=strtotime($value->create_time);
                if($startTime<$time&&$value->status==0&&$value->is_pay==0){
                   $value->status=-1;
                   //优惠券还原
                   $userCoupon=CouponUser::where(['id'=>$value->coupon_user_id])->find();
                   if($userCoupon){
                       $value->pay_price+=$userCoupon['discounts_price'];
                       $value->price=$value->pay_price;
                       $value->coupon_user_id=0;
                       $userCoupon->is_use=0;
                       $userCoupon->order_id=0;
                       $userCoupon->discounts_price=0;
                       $userCoupon->use_time=0;
                       $userCoupon->save();
                   }
                   //商家优惠券还原
                   $storeUserCoupon=StoreCouponUser::where(['id'=>$value->store_coupon_user_id])->find();
                   if($storeUserCoupon){
                       $value->pay_price+=$storeUserCoupon['discounts_price'];
                       $value->price=$value->pay_price;
                       $value->store_coupon_user_id=0;
                       $storeUserCoupon->is_use=0;
                       $storeUserCoupon->use_time=0;
                       $storeUserCoupon->save();
                   }
                   $value->save();
                }
                if($value->start_time<time()&&$value->status==1){
                  $value->status=2;

                  $value->save();
                }
            }
            $start_time=HouseOrderContinue::where(['status'=>1,'order_id'=>$value->id])->order('id ASC')->value('start_time');
            if($start_time){
              //续单
              if($start_time>$value->start_time){
                  $end_time=HouseOrderContinue::where(['status'=>1,'order_id'=>$value->id])->order('id DESC')->value('end_time');
                  $value->end_time=$end_time;
              }else{
                //向前续单
                   $value->start_time=$start_time;
              }
              $value->is_reorder=1;
            }else{
              $value->is_reorder=0;
            }
            $value->start_time=date('Y-m-d H:i',$value->start_time);
            $value->end_time=date('Y-m-d H:i',$value->end_time);
            $store=Store::where('id',$value->store_id)->field('address,lng,lat')->find();
            $snapshoot=json_decode($value->snapshoot,1);
            $snapshoot['address']=$store['address'];
            $snapshoot['lng']=$store['lng'];
            $snapshoot['lat']=$store['lat'];
            $value->snapshoot=$snapshoot;
            $value->price+=HouseOrderContinue::where(['status'=>1,'order_id'=>$value->id])->sum('price');
            $value->pay_price+=HouseOrderContinue::where(['status'=>1,'order_id'=>$value->id])->sum('pay_price');
        }
        return fetchJson($list);
    }
    //获取时间价格
    private function getTimePirce($house,$starttime,$endtime,$feeHour=0){
        $price_list=json_decode($house['price_list'],1);

        $halfDay=($endtime-$starttime)/1800;
        $priceArr=[];
        $timePirce=0;
        //每个小时的钱
        if($feeHour>0){
         
          $feeHour=(int)($feeHour*2);
          if(empty($price_list)){
             return ($feeHour)*$house['price']/2;
          }
          $feeHour-=1;
          $priceData=array_column($price_list,'price','time');
          for ($j=0;$j<($halfDay);$j++){
              $key=date('H',$starttime+1800*$j); 
              $timePirce+=$priceData[$key]/2;
              if($j>=$feeHour){
                break;
              }
          }
          if($timePirce<=0){
            return $halfDay*$house['price']/2;
          }
          return $timePirce;
        }
        if(empty($price_list)){
           return $halfDay*$house['price']/2;
        }
        $priceData=array_column($price_list,'price','time');
        for ($j=0;$j<($halfDay);$j++){
            $key=date('H',$starttime+1800*$j); 
            $timePirce+=$priceData[$key]/2;
        }
        if($timePirce<=0){
          return $halfDay*$house['price']/2;
        }
        return $timePirce;
    }
    //提交预览
    public function submit_preview(){
      try {
          $data=request()->post();
          $rule = [
               'house_id|房间ID' => 'require|number',
               'start_time|开始时间'=>'require',
           ];
          $this->validate($data,$rule);
       }catch (ValidateException $e){
          return fetchJson([],$e->getError(),1);
       }
       $house=House::where('id',$data['house_id'])->find();
       if(!$house){
          return fetchJson([],'暂无茶室',1);
       }
       $order_id=input('order_id');
       $book_type=input('book_type');
       $pay_type=input('pay_type');

       $start_time=strtotime($data['start_time']);
       if($book_type!=2&&$book_type!=3){
          if($start_time<time()){
              return fetchJson([],'预订时间已过',1);
          }
       }
       $end_time=strtotime(input('end_time'));
       if(!$order_id){
           if($end_time<time()){
                return fetchJson([],'预订时间已过',1);
           }
           if(HouseOrder::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'book_type'=>3,'status'=>0])->count()){
               return fetchJson([],'您有即到即用订单，请支付后进行预订',1);
           }
       }else{
           $endOrderTime=$start_time+$house['limit_time']*3600;
           $end_time=time();
           if($end_time>$endOrderTime){
              $end_time=$endOrderTime;
           }
       }
       $starttime=strtotime(date('Y-m-d H:i',$start_time));
       $endtime=strtotime(date('Y-m-d H:i',$end_time));
       $halfDay=($endtime-$starttime)/1800;
       $dayArr=[];
       for ($j=0;$j<($halfDay+1);$j++){ 
          $dayArr[]=$starttime+1800*$j;
       }
       if(!$order_id){
           $is_booKtime=HouseStock::where(['acid'=>$house['acid'],'store_id'=>$house['store_id'],'house_id'=>$data['house_id'],'status'=>0])->where('hour','in',$dayArr)->count();
           if($is_booKtime){
              return fetchJson([],'该时间段已预订',1);
           }
           foreach ($dayArr as $dV){
               $is_booKtime=HouseStock::where(['acid'=>$house['acid'],'store_id'=>$house['store_id'],'house_id'=>$data['house_id'],'status'=>0])->where('hour','>=',$dV)->where('hour','<=',$end_time)->column('id,hour');
               if($is_booKtime){
                  return fetchJson([],date('Y-m-d H:i:s',$dV).'该时间段已预订',1);
               }
           }
       }
       $num=($endtime-$start_time)/3600;
       $booktime=$house['booktime']>0?$house['booktime']:1;
       if($num<$booktime){
          if(!$order_id){
             return fetchJson([],'预订时间请大于等于'.$booktime.'小时',1);
          }
       }
       $orderPrice=self::getTimePirce($house,$start_time,$end_time);
       $package_price=json_decode($house['package_price'],1);
       if($package_price){
          foreach ($package_price as $package){
              if(isset($package['num'])&&isset($package['price'])){
                if($package['num']==$num){
                  $orderPrice=$package['price'];
                  break;
                }
              }
          }
       }
       $subscibe['book_inform']=Option::get_data($this->acid,'platform','wx_subscibe_book_inform');
       //预约结束提醒
       $subscibe['book_finish']=Option::get_data($this->acid,'platform','wx_subscibe_book_finish');
       //预约提醒加时
       $subscibe['book_overtime']=Option::get_data($this->acid,'platform','wx_subscibe_book_overtime');
       $time=time();
       $cardUser=CardUser::where(['status'=>1,'user_id'=>$this->user_id])->where('start_time','<',$time)->where('end_time','>',strtotime(date('Y-m-d',$time))-86399);
       $card_user_id=input('card_user_id');
       if($card_user_id){
          $cardUser=$cardUser->where('id',$card_user_id);
       }
       $cardUser=$cardUser->order('level DESC')->find();
       $payPrice=$orderPrice;
       $discount=-1;
       $hour=0;
       $partnerUser=PartnerUser::where([
          'user_id'=>$this->user_id,
          'acid'=>$this->acid,
          'status'=>1
        ])->find();
       $feeHour=0;

       $card_coupon_id=input('card_coupon_id'); 
       if($partnerUser&&$pay_type!=3){
          if($partnerUser->end_time<-1){
            $partnerUser->end_time=-1;
            $partnerUser->save();
          }
          if($partnerUser->end_time>time()&&$partnerUser->start_time<time()||$partnerUser->end_time==-1){
              $partner=Partner::where([
                'id'=>$partnerUser->partner_id,
                'acid'=>$this->acid
              ])->find();
              $everyday_hour=$partner->everyday_hour;
              $hour=PartnerUserOrder::where(['user_partner_id'=>$partnerUser->id,'user_id'=>$this->user_id,'acid'=>$this->acid,'status'=>1])->whereDay('create_time','today')->sum('hour');
              $useHour=$everyday_hour-$hour;
              if($useHour>0){
                if($useHour>$num){
                   $feeHour=$num;
                }else{
                   $feeHour=$useHour;
                }
              }
              //免费金额
              $feehourPirce=self::getTimePirce($house,$start_time,$end_time,$feeHour);
              if($feeHour>0){
                if($feehourPirce>$partnerUser->money){
                  $payPrice-=$partnerUser->money;
                }else{
                  $payPrice-=$feehourPirce;
                }
                
              }              
          }
       }else{

          if($cardUser&&$pay_type!=3){
              if($pay_type==2){
                 $card=Card::where(['id'=>$cardUser['card_id'],'is_delete'=>0,'is_balance'=>1])->find();
              }else{
                 $card=Card::where(['id'=>$cardUser['card_id'],'is_delete'=>0])->find();
              }

              if($card&&empty($card_coupon_id)){
                  $discount=$card['discount'];

                  if($card['type']==2){
                      $hour=0;
                      $hour=$cardUser['hour'];
                      $coutHour=$num;
                      $cardHouseIds=explode(',',$card['house_ids']);
                      $feePirce=0;
                      if($card['house_ids']=='-1'||in_array($data['house_id'],$cardHouseIds)){
                        if($coutHour<=$hour){
                         $hour=$coutHour;
                         $feePirce=self::getTimePirce($house,$start_time,$end_time,$hour);
                         if($payPrice<$feePirce){
                             $feePirce=$payPrice;
                         }
                         $payPrice-=$feePirce;
                        }
                        if($coutHour>$hour&&$hour>0){
                          $feePirce=self::getTimePirce($house,$start_time,$end_time,$hour);
                          if($payPrice<$feePirce){
                             $feePirce=$payPrice;
                          }
                          $payPrice-=$feePirce;
                        }
                      }
                      $payPrice=$payPrice*$discount/10;
                  }else{
                    if($house['member_price']>0){
                      $bookNum=($endtime-$start_time)/1800;
                      $booknum1=ceil($bookNum)/2;
                      $payPrice=$house['member_price']*$booknum1;
                    }else{
                      $house_price=$card['house_price'];
                      $hour=0;
                      if($house_price>0){
                          $hour=$cardUser['hour'];
                          $coutHour=(int)($orderPrice/$house_price);
                          if($coutHour<=$hour){
                            $hour=$coutHour;
                          }
                      }
                      $payPrice=($orderPrice-$hour*$house_price)*$discount/10;
                    }
                  }

                  
              }
           }
       }

       if($card_coupon_id&&$pay_type!=3){
          $cardCoupon=CardCoupon::where(['id'=>$card_coupon_id,'acid'=>$this->acid,'user_id'=>$this->user_id,'status'=>1])->field('id,name,discounts_price')->find();
          if($cardCoupon){
              if($house['original_price']>=$house['price']){
                $payPrice=$num*$house['original_price'];
              }
              if($payPrice>=$cardCoupon->discounts_price){
                  $orderPrice=$payPrice;
                  $payPrice-=$cardCoupon->discounts_price;
              }else{
                return fetchJson([],'支付价格必须大于等于美团兑换券价格',1);
              }
          }
       }
       $coupon_user_id=input('coupon_user_id');
       if($coupon_user_id&&$pay_type!=3){
          $userCoupon=CouponUser::where(['id'=>$coupon_user_id,'is_use'=>0,'type'=>Coupon::TYPE_HOTEL,'user_id'=>$this->user_id])->find();
          $coupon=Coupon::where('id',$userCoupon['coupon_id'])->find();
          if($coupon){
              if($coupon['full_price']<=$payPrice){
                $payPrice-=$coupon['price'];
                $userCoupon->discounts_price=$coupon['price'];
                $userCoupon->save();
              }
          }
       }
       $store_coupon_user_id=input('store_coupon_user_id');
       if($store_coupon_user_id){
          $storeUserCoupon=StoreCouponUser::where(['id'=>$store_coupon_user_id,'is_use'=>0,'type'=>StoreCoupon::TYPE_HOTEL,'user_id'=>$this->user_id])->find();
          $storeCoupon=StoreCoupon::where('id',$storeUserCoupon['coupon_id'])->find();
          if($storeCoupon){
              if($storeCoupon['full_price']<=$payPrice){
                $payPrice-=$storeCoupon['price'];
                $storeUserCoupon->discounts_price=$storeCoupon['price'];
                $storeUserCoupon->save();
              }
          }
       }

       return fetchJson([
          'price'=>round($orderPrice,2),
          'pay_price'=>round($payPrice,2),
          'discount'=>$discount,
          'subscibe'=>$subscibe,
          'hour'=>$hour,
          'feeHour'=>$feeHour,
          'user_money'=>$this->user->money,
          'user_store_money'=>StoreUserMoney::where(['store_id'=>$house['store_id'],'user_id'=>$this->user_id])->value('money'),
       ]);

    }
    //提交订单
    public function submit(){
        try {
          $data=request()->post();
          $rule = [
               'house_id|房间ID' => 'require|number',
               'start_time|入住时间'=>'require',
               'tel|电话'=>'require',
           ];
          $this->validate($data,$rule);
       }catch (ValidateException $e){
          return fetchJson([],$e->getError(),1);
       }

       $house=House::where('id',$data['house_id'])->find();
       if(!$house){
          return fetchJson([],'暂无茶室',1);
       }
       $pay_type=input('pay_type');
       if($order_id=input('order_id')){
           $order=HouseOrder::where('id',$order_id)->find();
           if(!$order){
              return fetchJson([],'暂无订单',1);
           }
           $starttime=$order->start_time;
           $start_time=$order->start_time;
           $endtime=strtotime(date('Y-m-d H:i',time()));
           $endOrderTime=$starttime+$house['limit_time']*3600;
           if($endtime>$endOrderTime){
              $endtime=$endOrderTime;
           }
           $order->end_time=$endtime;
           $end_time=$endtime;
       }else{
           $book_type=input('book_type');

           if(HouseOrder::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'book_type'=>3,'status'=>0])->count()){
               return fetchJson([],'您有即到即用订单，请支付后进行预订',1);
           }
           $start_time=strtotime($data['start_time']);
           if($book_type!=2){
              if($start_time<time()){
                  return fetchJson([],'预订时间已过',1);
              }
           }
           
           $end_time=strtotime($data['end_time']);
           if($end_time<time()){
              return fetchJson([],'预订时间已过',1);
           }
           if($start_time>$end_time){
              return fetchJson([],'预订时间错误',1);
           }
           $starttime=strtotime(date('Y-m-d H:i',$start_time));
           $endtime=strtotime(date('Y-m-d H:i',$end_time));
           $halfDay=($endtime-$starttime)/3600;
           $booktime=$house['booktime']>0?$house['booktime']:1;
           if($halfDay<$booktime){
              return fetchJson([],'预订时间请大于等于'.$booktime.'小时',1);
           }
           $dayArr=[];
           for ($j=0;$j<($halfDay+1);$j++){ 
              $dayArr[]=$starttime+1800*$j;
           }
           $is_booKtime=HouseStock::where(['acid'=>$house['acid'],'store_id'=>$house['store_id'],'house_id'=>$data['house_id'],'status'=>0])->where('hour','in',$dayArr)->count();
           if($is_booKtime){
              return fetchJson([],'该时间段已预订',1);
           }
           foreach ($dayArr as $dV){
               $is_booKtime=HouseStock::where(['acid'=>$house['acid'],'store_id'=>$house['store_id'],'house_id'=>$data['house_id'],'status'=>0])->where('hour','>=',$dV)->where('hour','<=',$end_time)->count();
               if($is_booKtime){
                  return fetchJson([],date('Y-m-d H:i:s',$dV).'该时间段已预订',1);
               }
           }
           $repetition_submint=Cache::get("repetition".$this->user_id);
           if($repetition_submint){
               return fetchJson([],'请勿重复提交',1);
           }else{
               Cache::set("repetition".$this->user_id,1,10);
           }
           $order=new HouseOrder();
           $order->acid=$this->acid;
           $order->user_id=$this->user_id;
           $order->order_no=HouseOrder::crateOrderNo();
           $order->username=$this->user->nickname;
           $order->tel=$data['tel'];
           $order->house_id=$data['house_id'];
           $order->store_id=$house['store_id'];
           $order->start_time=$starttime;
           $order->end_time=$endtime;
           $order->is_verifier=$house['is_verifier'];
       }
       $num=($endtime-$start_time)/3600;
       $num=round($num,2);
       $num1=explode(".",$num);
       if(isset($num1[1])){
           $x=$num1[0];
           $y=$num1[1];
           if($y>=50){
             $x+=1;
             $y=0;
           }
           if($y>0&&$y<50){
             $y=50;
           }
           $num=$x.".".$y;
           $num=$num*1;
       }
       $order->price=self::getTimePirce($house,$start_time,$end_time);
       $package_price=json_decode($house['package_price'],1);
       if($package_price){
          foreach ($package_price as $package){
              if(isset($package['num'])&&isset($package['price'])&&isset($package['title'])){
                if($package['num']==$num){
                  $order->price=$package['price'];
                  $order->package_price=$package['title'];
                  break;
                }
              }
          }
       }
       $time=time();
       $cardUser=CardUser::where(['status'=>1,'user_id'=>$this->user_id])->where('start_time','<',$time)->where('end_time','>',strtotime(date('Y-m-d',$time))-86399);
       $card_user_id=input('card_user_id');
       if($card_user_id){
          $cardUser=$cardUser->where('id',$card_user_id);
       }
       $orderPrice=$order->price;
       $orderPayPrice=$order->price;
       //$order->save();
       //使用合伙人支付
       $partnerUser=PartnerUser::where([
          'user_id'=>$this->user_id,
          'acid'=>$this->acid,
           'status'=>1
        ])->find();
       $order->save();
       $feeHour=0;
       if($partnerUser&&$pay_type!=3){
          if($partnerUser->end_time<-1){
            $partnerUser->end_time=-1;
            $partnerUser->save();
          }
          if($partnerUser->end_time>time()&&$partnerUser->start_time<time()||$partnerUser->end_time==-1){
              $partner=Partner::where([
                'id'=>$partnerUser->partner_id,
                'acid'=>$this->acid
              ])->find();
              $everyday_hour=$partner->everyday_hour;
              $hour=PartnerUserOrder::where(['user_partner_id'=>$partnerUser->id,'user_id'=>$this->user_id,'acid'=>$this->acid,'status'=>1])->whereDay('create_time','today')->sum('hour');
              $useHour=$everyday_hour-$hour;
              if($useHour>0){
                if($useHour>$num){
                   $feeHour=$num;
                }else{
                   $feeHour=$useHour;
                }
                //免费金额
                $feehourPirce=self::getTimePirce($house,$start_time,$end_time,$feeHour);
                if($feeHour==0){
                  $feehourPirce=0;
                }
                if($feehourPirce>$partnerUser->money){
                  $feehourPirce=$partnerUser->money;
                }
                $order->pay_price=$orderPayPrice-$feehourPirce;  
                $order->snapshoot=json_encode($house);
                $order->store_id=$house['store_id'];
                $order->save();
                //插入订单记录
                if($feehourPirce){
                  (new PartnerUserOrder())->save([
                    'acid'=>$this->acid,
                    'type'=>1,
                    'user_id'=>$this->user_id,
                    'user_partner_id'=>$partnerUser->id,
                    'order_id'=>$order->id,
                    'hour'=>$feeHour,
                    'price'=>$feehourPirce
                  ]);
                }
                return fetchJson($order);
              }
          }
       }else{
          $card_coupon_id=input('card_coupon_id');
         $cardUser=$cardUser->order('level DESC')->find();
         if($cardUser&&$pay_type!=3){
            if($pay_type==2){
               $card=Card::where(['id'=>$cardUser['card_id'],'is_delete'=>0,'is_balance'=>1])->find();
            }else{
               $card=Card::where(['id'=>$cardUser['card_id'],'is_delete'=>0])->find();
            }
            if($card&&empty($card_coupon_id)){
                 $discount=$card['discount'];
                 if($card['type']==2){
                      $hour=0;
                      $hour=$cardUser['hour'];
                      $order->card_type=$card['type'];
                      $coutHour=$num;
                      $cardHouseIds=explode(',',$card['house_ids']);
                      $feePirce=0;
                      if($card['house_ids']=='-1'||in_array($order->house_id,$cardHouseIds)){
                         if($coutHour<=$hour){
                           $hour=$coutHour;
                           $feePirce=self::getTimePirce($house,$start_time,$end_time,$hour);
                           if($orderPayPrice<$feePirce){
                               $feePirce=$orderPayPrice;
                           }
                           $orderPayPrice-=$feePirce;
                         }
                         if($coutHour>$hour&&$hour>0){
                           $feePirce=self::getTimePirce($house,$start_time,$end_time,$hour);
                           if($orderPayPrice<$feePirce){
                               $feePirce=$orderPayPrice;
                           }
                           $orderPayPrice-=$feePirce;
                         }
                      }
                      $orderPayPrice=$orderPayPrice*$discount/10;
                      (new CardUserOrder())->save([
                        'acid'=>$this->acid,
                        'order_id'=>$order->id,
                        'user_id'=>$this->user_id,
                        'card_user_id'=>$cardUser->id,
                        'order_id'=>$order->id,
                        'price'=>($orderPrice-$orderPayPrice)<=0?$feePirce:$orderPrice-$orderPayPrice,
                        'hour'=>$hour,
                        'discount'=>$discount
                      ]);
                  }else{
                      if($house['member_price']>0){
                        $bookNum=($endtime-$start_time)/1800;
                        $booknum1=ceil($bookNum)/2;
                        $orderPayPrice=$house['member_price']*$booknum1;
                        (new CardUserOrder())->save([
                          'acid'=>$this->acid,
                          'order_id'=>$order->id,
                          'user_id'=>$this->user_id,
                          'card_user_id'=>$cardUser->id,
                          'order_id'=>$order->id,
                          'price'=>$orderPrice-$orderPayPrice,
                          'hour'=>0,
                          'discount'=>10
                        ]);
                      }else{
                        $house_price=$card['house_price'];
                        
                        $hour=0;
                        if($house_price>0){
                            $hour=$cardUser['hour'];
                            $coutHour=(int)($orderPrice/$house_price);
                            if($coutHour<=$hour){
                              $hour=$coutHour;
                            }
                        }
                        $orderPayPrice=($orderPrice-$hour*$house_price)*$discount/10;
                        (new CardUserOrder())->save([
                          'acid'=>$this->acid,
                          'order_id'=>$order->id,
                          'user_id'=>$this->user_id,
                          'card_user_id'=>$cardUser->id,
                          'order_id'=>$order->id,
                          'price'=>$orderPrice-$orderPayPrice,
                          'hour'=>$hour,
                          'discount'=>$discount
                        ]);
                      }
                 }
            }
         }
       }
       //使用卡券
       if($card_coupon_id=input('card_coupon_id')){
          $cardCoupon=CardCoupon::where(['id'=>$card_coupon_id,'acid'=>$this->acid,'user_id'=>$this->user_id,'status'=>1])->field('id,name,discounts_price')->find();
          if($cardCoupon&&$pay_type!=3){
              if($house['original_price']>=$house['price']){
                $orderPayPrice=$num*$house['original_price'];
                $orderMeituanPrice=$num*$house['price'];
              }else{
                $orderPayPrice=$num*$house['price'];
                $orderMeituanPrice=$num*$house['price'];
              }
              if($orderPayPrice>=$cardCoupon->discounts_price){
                  $order->price=$orderPayPrice;
                  $order->meituan_price=$orderMeituanPrice;
                  $orderPayPrice-=$cardCoupon->discounts_price;
                  (new CardCouponOrder())->save([
                    'card_coupon_id'=>$card_coupon_id,
                    'order_id'=>$order->id,
                    'user_id'=>$order->user_id,
                  ]);
                  $order->card_coupon_id=$card_coupon_id;
              }else{
                return fetchJson([],'支付价格必须大于等于美团兑换券价格',1);
              }
          }
       }
       //优惠券使用
       $coupon_user_id=input('coupon_user_id');
       if($coupon_user_id&&$pay_type!=3){
          $userCoupon=CouponUser::where(['id'=>$coupon_user_id,'is_use'=>0,'type'=>Coupon::TYPE_HOTEL,'user_id'=>$this->user_id])->field('coupon_id,discounts_price')->find();
          $coupon=Coupon::where('id',$userCoupon->coupon_id)->find();
          if($coupon){
              if($coupon['full_price']<=$orderPayPrice){
                $userCoupon->discounts_price=$coupon['price'];
                $userCoupon->save();
                if($order->price<0){
                  $order->price=0;
                }else{
                  $order->coupon_user_id=$coupon_user_id;
                }
              }
          }
       }
       //优惠券使用
       $store_coupon_user_id=input('store_coupon_user_id');
       if($store_coupon_user_id){
          $userCoupon=StoreCouponUser::where(['id'=>$store_coupon_user_id,'is_use'=>0,'type'=>StoreCoupon::TYPE_HOTEL,'user_id'=>$this->user_id])->field('coupon_id,discounts_price')->find();

          $storeCoupon=StoreCoupon::where('id',$userCoupon->coupon_id)->find();
          if($storeCoupon){
              if($storeCoupon['full_price']<=$orderPayPrice){
                $userCoupon->discounts_price=$storeCoupon['price'];
                $userCoupon->save();
                if($order->price<0){
                  $order->price=0;
                }else{
                  $order->store_coupon_user_id=$store_coupon_user_id;
                }
              }
          }
       }
       $order->pay_price=$orderPayPrice>0?$orderPayPrice:0;
       $store=Store::where('id',$house['store_id'])->find();
       $house['is_wallet']=$store['is_wallet'];
       $house['store_info']=$store;
       $order->snapshoot=json_encode($house);
       $order->store_id=$house['store_id'];
       $order->book_type=input('book_type');
       $order->save();
       return fetchJson($order);
    }
    //即到即用提交
    public function thatIsSubmit(){
       try {
          $data=request()->post();
          $rule = [
               'house_id|房间ID' => 'require|number',
               'tel|电话'=>'require',
           ];
          $this->validate($data,$rule);
       }catch (ValidateException $e){
          return fetchJson([],$e->getError(),1);
       }
       $house=House::where('id',$data['house_id'])->find();
       if(!$house){
          return fetchJson([],'暂无茶室',1);
       }
       $start_time=time();
       
       $starttime=strtotime(date('Y-m-d H:i',$start_time));
       $minute=date('i',$starttime);
       $hour=date('Y-m-d H',$starttime).":00";
       if($minute<=30&&$minute>0){
          $hour=strtotime($hour);
       }
       if($minute>30){
          $hour=strtotime($hour)+1800;
       }
       
       $end_time=$hour+$house['limit_time']*3600;
       $endtime=$end_time;
       $halfDay=$house['limit_time'];
       $dayArr=[];
       for ($j=0;$j<($halfDay+1);$j++){ 
          $dayArr[]=$starttime+1800*$j;
       }
       $is_booKtime=HouseStock::where(['acid'=>$house['acid'],'store_id'=>$house['store_id'],'house_id'=>$data['house_id'],'status'=>0])->where('hour','in',$dayArr)->count();
       if($is_booKtime){
          return fetchJson([],'该时间段已预订',1);
       }
       foreach ($dayArr as $dV){
           $is_booKtime=HouseStock::where(['acid'=>$house['acid'],'store_id'=>$house['store_id'],'house_id'=>$data['house_id'],'status'=>0])->where('hour','>=',$dV)->where('hour','<=',$end_time)->find();
           if($is_booKtime){
              return fetchJson($is_booKtime,date('Y-m-d H:i:s',$dV).'该时间段已预订',1);
           }
       }
       $repetition_submint=Cache::get("repetitionthatIsSubmit".$this->user_id);
       if($repetition_submint){
           return fetchJson([],'请勿重复提交',1);
       }else{
           Cache::set("repetitionthatIsSubmit".$this->user_id,1,10);
       }
       if(HouseOrder::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'book_type'=>3,'status'=>0])->count()){
           return fetchJson([],'您有即到即用订单，请支付后进行预订',1);
       }
       $order=new HouseOrder();
       $order->acid=$this->acid;
       $order->user_id=$this->user_id;
       $order->order_no=HouseOrder::crateOrderNo();
       $order->username=$this->user->nickname;
       $order->tel=$data['tel'];
       $order->house_id=$data['house_id'];
       $order->store_id=$house['store_id'];
       $order->start_time=$starttime;
       $order->is_verifier=$house['is_verifier'];
       $order->book_type=3;
       $house['is_wallet']=Store::where('id',$house['store_id'])->value('is_wallet');
       $order->snapshoot=json_encode($house);
       $order->save();
       $num=$house['limit_time']*2;
       $stockInsert=[];
       for($i=0; $i <$num+2; $i++) {
            $time=$hour+(1800*$i); 
            if(!HouseStock::where([
                'acid'=>$order->acid,
                'date'=>strtotime(date('Y-m-d',$time)),
                'house_id'=>$order->house_id,
                'hour'=>$time,
                'order_id'=>$order->id,
                'store_id'=>$order->store_id,
            ])->count()){
                $stockInsert[]=[
                    'acid'=>$order->acid,
                    'date'=>strtotime(date('Y-m-d',$time)),
                    'house_id'=>$order->house_id,
                    'hour'=>$time,
                    'order_id'=>$order->id,
                    'store_id'=>$order->store_id,
                    'create_time'=>time(),
                    'update_time'=>time()
                ];
            } 
        }
        HouseStock::insertAll($stockInsert);
        return fetchJson($order,'预订成功');
    }
    //支付订单
    public function orderPay(){

       $order_id=input('order_id');
       $order=HouseOrder::where(['id'=>$order_id,'user_id'=>$this->user_id,'is_pay'=>0])->find();
       if(!$order){
          return fetchJson([],'暂无订单',1);
       }
       $starttime=$order->start_time;
       $endtime=$order->end_time;
       $halfDay=($endtime-$starttime)/3600;
       $house=House::where('id',$order->house_id)->find();
       $booktime=$house['booktime']>0?$house['booktime']:1;
       if($halfDay<$booktime){
          return fetchJson([],'预订时间请大于等于'.$booktime.'小时',1);
       }
       $dayArr=[];
       for ($j=0;$j<($halfDay+1);$j++){ 
          $dayArr[]=$starttime+1800*$j;
       }
       $is_booKtime=HouseStock::where(['acid'=>$house['acid'],'store_id'=>$house['store_id'],'house_id'=>$order->house_id,'status'=>0])->where('hour','in',$dayArr)->count();
       if($is_booKtime){
          return fetchJson([],'该时间段已预订',1);
       }
       foreach ($dayArr as $dV){
           $is_booKtime=HouseStock::where(['acid'=>$house['acid'],'store_id'=>$house['store_id'],'house_id'=>$order->house_id,'status'=>0])->where('hour','>=',$dV)->where('hour','<=',$endtime)->count();
           if($is_booKtime){
              return fetchJson([],date('Y-m-d H:i:s',$dV).'该时间段已预订',1);
           }
       }
       $order->order_no=HouseOrder::crateOrderNo();
       $pay_type=input('pay_type')?input('pay_type'):1;
       //使用优惠券
       $couponUser=CouponUser::where(['id'=>$order->coupon_user_id,'is_use'=>0,'type'=>Coupon::TYPE_HOTEL,'user_id'=>$this->user_id])->find();
       if($couponUser&&$pay_type!=3){
          $order->pay_price=$order->pay_price-$couponUser->discounts_price;
          $couponUser->is_use=1;
          $couponUser->save();
       }else{
          $order->coupon_user_id=0;
       }

       //使用优惠券
       $storeCouponUser=StoreCouponUser::where(['id'=>$order->store_coupon_user_id,'is_use'=>0,'type'=>Coupon::TYPE_HOTEL,'user_id'=>$this->user_id])->find();
       if($storeCouponUser){
          $order->pay_price=$order->pay_price-$storeCouponUser->discounts_price;
          $storeCouponUser->is_use=1;
          $storeCouponUser->save();
       }else{
          $order->store_coupon_user_id=0;
       }
       $order->pay_type=$pay_type;
       $order->save();
        //判断是否用余额支付
       if($pay_type==2){
           $res=self::balancePayment($order);
           return fetchJson([],$res['msg'],$res['code']);
       }
        //判断是否用店铺余额支付
       if($pay_type==3){
           $res=self::storeBalancePayment($order);
           return fetchJson([],$res['msg'],$res['code']);
       }
       //钱不够的时候
       if($order->pay_price<=0){
           if($order->pay_price<0){
               return fetchJson([],'支付价格'.$order->pay_price,1);
           }
           $order->pay_price=0;
           $order->pay_type=2;
           $order->save();
           $res=self::balancePayment($order);
           return fetchJson([],$res['msg'],$res['code']);
       }
       $app=App::find($this->acid);
       $appid=$app->wxapp_app_id;
       $app_secret=$app->wxapp_app_secret;
       $openid=$this->user->wxapp_open_id;
       if(input('is_weixin')==1){
          $appid=$app->wx_app_id;
          $app_secret=$app->wx_app_secret;
          $openid=$this->user->wx_open_id;
       }
       if($this->platform=='app'||$this->platform=='ios'||$this->platform=='android'){
            $appConfig=Option::get_data($this->acid,'platform','app_config');
            $appConfig=json_decode($appConfig);
            $appid=isset($appConfig->appid)?$appConfig->appid:'';
            $app_secret=isset($appConfig->app_secret)?$appConfig->app_secret:'';
       }
       $wx_config=[
            'appid'=>$appid,
            'appsecret'=>$app_secret,
            'mchid'=>$app->wx_mch_id,
            'key'=>$app->wx_key,
            'sslcert'=>$app->wx_cert_pem,
            'sslkey'=>$app->wx_key_pem,
       ];
       if(isset($app->wx_pay_type)){
          $storeWx=Store::where('id',$order->store_id)->field('wx_mch_id,wx_key,wx_sslcert,wx_sslkey')->find();
          //服务商模式
          if($app->wx_pay_type==2){
             $wx_config=[
                  'appid'=>$appid,
                  'mchid'=>$storeWx['wx_mch_id']!=0?$storeWx['wx_mch_id']:$app->wx_mch_id,
                  'wx_server_appid'=>$app->wx_server_appid,
                  'appsecret'=>$app_secret,
                  'wx_server_mch_id'=>$app->wx_server_mch_id,
                  'key'=>$app->wx_server_key,
                  'sslcert'=>$app->wx_server_cert_pem,
                  'sslkey'=>$app->wx_server_key_pem,
                  'sub_appid'=>$appid,
                  'sub_mch_id'=>$app->wx_mch_id,
                  'wx_pay_type'=>$app->wx_pay_type,
                  'wx_profit_sharing'=>$app->wx_profit_sharing
             ];
          }else{
             if($storeWx['wx_mch_id']){
                $wx_config=[
                      'appid'=>$appid,
                      'appsecret'=>$app_secret,
                      'mchid'=>$storeWx['wx_mch_id']!=0?$storeWx['wx_mch_id']:$app->wx_mch_id,
                      'key'=>$storeWx['wx_key']?$storeWx['wx_key']:$app->wx_key,
                      'sslcert'=>$storeWx['wx_sslcert']!=0?$storeWx['wx_sslcert']:$app->wx_cert_pem,
                      'sslkey'=>$storeWx['wx_sslkey']!=0?$storeWx['wx_sslkey']:$app->wx_key_pem,
                      'wx_profit_sharing'=>$app->wx_profit_sharing
                 ];
             }
          }
       }
       $wechatPay=new WechatPay($wx_config);
       $notify_url=request()->domain().str_replace('index.php', 'pay_shared.php',request()->baseFile());
       $paydata = [
            'body' =>$order->house_title.'购买商品',
            'out_trade_no' => $order->order_no,
            'total_fee' => round($order->pay_price,2)* 100,
            'notify_url' =>$notify_url ,
            'trade_type' => 'JSAPI',
            'openid' => $openid,
        ];
       //字节跳动支付
       if($this->platform=='ttapp'){
             $paydata=[
                'body' =>$order->house_title.'购买商品',
                'appid'=>$app->wx_app_id,
                'attach'=>'购买商品',
                'mch_id'=>$app->mch_id,
                'notify_url' =>$notify_url ,
                'out_trade_no' => $order->order_no,
                'total_fee' => round($order->pay_price,2)* 100,
                'trade_type' => 'MWEB',
                'openid' => $openid,
                'scene_info'=>'{"h5_info":{"type":"Wap","wap_url":"'.request()->domain().'","wap_name":"测试支付"}}'
            ];
            $ttapp=Option::get_data($this->acid,'platform','ttapp_config');
            $ttapp=json_decode($ttapp);
            $res=$wechatPay->toutiaoh5pay($paydata,$ttapp);
            if($res['code']==0){
              return fetchJson($res);
            }else{
              return fetchJson([],$res['msg'],1);
            }
       }
        //微信外部支付
       if($this->platform=='h5'&&input('is_weixin')==0){
            $paydata=[
              'body' =>$order->house_title.'购买商品',
              'appid'=>$app->wx_app_id,
              'attach'=>'购买商品',
              'mch_id'=>$app->mch_id,
              'notify_url' =>$notify_url ,
              'out_trade_no' => $order->order_no,
              'total_fee' => round($order->pay_price,2)* 100,
              'trade_type' => 'MWEB',
              'openid' => $openid,
              'scene_info'=>'{"h5_info":{"type":"Wap","wap_url":"'.request()->domain().'","wap_name":"测试支付"}}'
            ];
            $rest['order_id']=$order->id;
            $res=$wechatPay->h5pay($paydata);
            if($res['code']==0){
              $rest['mweb_url']=$res['data'];
              return fetchJson($rest);
            }else{
              return fetchJson([],$res['msg'],1);
            }
       }
       if($this->platform=='app'||$this->platform=='ios'||$this->platform=='android'){
            unset($paydata['openid']);
            $paydata['trade_type']="APP";
            $res=$wechatPay->appPay($paydata);
       }else{
          $res=$wechatPay->pay($paydata);
       }
       $res['order_id']=$order->id;
       return fetchJson($res);
    }
   //余额支付
    private function balancePayment($order=[]){
         $user=User::where('id',$order['user_id'])->find();
         $cardUserOrder=CardUserOrder::where(['order_id'=>$order->id,'type'=>1])->find();
         if($cardUserOrder){
            $cardUser=CardUser::where('id',$cardUserOrder->card_user_id)->find();
            if($cardUser){
              $card=Card::where(['id'=>$cardUser->card_id,'is_balance'=>0])->count();
              if($card){
                 $order->pay_price-=$cardUserOrder['price'];
                 $order->save();
                 $cardUserOrder->is_delete=1;
                 $cardUserOrder->save();
              }
            }
         }
         if($user->money<$order->pay_price){
            return [
              'msg'=>'余额不足',
              'code'=>1
            ];
         }
         
         $form=new \app\shared\logic\pay\HouseOrderForm();
         $res=$form->saveOrder($order->order_no);
         if($res=='success'){
            return [
              'msg'=>'支付成功',
              'code'=>0
            ];
         }
        return [
          'msg'=>'余额支付错误',
          'code'=>1
        ];
    }
    private function storeBalancePayment($order=[]){
         $user=StoreUserMoney::where(['user_id'=>$order['user_id'],'store_id'=>$order['store_id']])->find();
         if(!$user){
            return [
              'msg'=>'用户商户余额不足',
              'code'=>1
            ];
         }
         if($user->money<$order->pay_price){
            return [
              'msg'=>'用户商户余额不足',
              'code'=>1
            ];
         }
         $form=new \app\shared\logic\pay\HouseOrderForm();
         $res=$form->saveOrder($order->order_no);
         if($res=='success'){
            return [
              'msg'=>'支付成功',
              'code'=>0
            ];
         }
        return [
          'msg'=>'用户商户余额支付错误',
          'code'=>1
        ];
    }
    //取消订单
    public function cancelOrder(){
        $order_id=input('order_id');
        $order=HouseOrder::where(['id'=>$order_id,'user_id'=>$this->user_id])->where('status','in','0,1')->find();
        if(!$order){
           return fetchJson([],'暂无订单',1);
        }
        if($order->status==0){
           $order->status=-1;
           //优惠券还原
           $userCoupon=CouponUser::where(['id'=>$order->coupon_user_id])->find();
           if($userCoupon){
               $order->pay_price+=$userCoupon['discounts_price'];
               $order->price=$order->pay_price;
               $order->coupon_user_id=0;
               $userCoupon->is_use=0;
               $userCoupon->order_id=0;
               $userCoupon->discounts_price=0;
               $userCoupon->use_time=0;
               $userCoupon->save();
           }
           //商家优惠券还原
           $storeUserCoupon=StoreCouponUser::where(['id'=>$order->store_coupon_user_id])->find();
           if($storeUserCoupon){
               $order->pay_price+=$storeUserCoupon['discounts_price'];
               $order->price=$order->pay_price;
               $order->store_coupon_user_id=0;
               $storeUserCoupon->is_use=0;
               $storeUserCoupon->use_time=0;
               $storeUserCoupon->save();
           }
           $order->save();
           return fetchJson([],'取消成功');
        }

        //已支付
        if($order->status==1){
              $refund_rate=Store::where('id',$order->store_id)->value('refund_rate');
              if(!$refund_rate){
                 $refund_rate=0;
              }
              $refund_price=$order->pay_price*(100-$refund_rate)*0.01;
              $refund_price=filter_money($refund_price);
              $refund_fee_price=$order->pay_price-$refund_price;
              //微信支付
              $user=User::where('id',$order->user_id)->find();
              $app=App::find($order->acid);
              if($order->pay_type==1){
                 if($order->out_order_time>0){
                    return ['code' => 0, 'info' => '已经退过了','data' =>''];
                 }
                 $appid=$app->wxapp_app_id;
                 $app_secret=$app->wxapp_app_secret;
                 $wx_config=[
                      'appid'=>$appid,
                      'appsecret'=>$app_secret,
                      'mchid'=>$app->wx_mch_id,
                      'key'=>$app->wx_key,
                      'sslcert'=>$app->wx_cert_pem,
                      'sslkey'=>$app->wx_key_pem,
                 ];
                 if(isset($app->wx_pay_type)){
                    $storeWx=Store::where('id',$order->store_id)->field('wx_mch_id,wx_key,wx_sslcert,wx_sslkey')->find();
                    //服务商模式
                    if($app->wx_pay_type==2){
                       $wx_config=[
                            'appid'=>$appid,
                            'mchid'=>$storeWx['wx_mch_id']!=0?$storeWx['wx_mch_id']:$app->wx_mch_id,
                            'wx_server_appid'=>$app->wx_server_appid,
                            'appsecret'=>$app_secret,
                            'wx_server_mch_id'=>$app->wx_server_mch_id,
                            'key'=>$app->wx_server_key,
                            'sslcert'=>$app->wx_server_cert_pem,
                            'sslkey'=>$app->wx_server_key_pem,
                            'sub_appid'=>$appid,
                            'sub_mch_id'=>$app->wx_mch_id,
                            'wx_pay_type'=>$app->wx_pay_type,
                            'wx_profit_sharing'=>$app->wx_profit_sharing
                       ];
                    }else{
                       if($storeWx['wx_mch_id']){
                          $wx_config=[
                                'appid'=>$appid,
                                'appsecret'=>$app_secret,
                                'mchid'=>$storeWx['wx_mch_id']!=0?$storeWx['wx_mch_id']:$app->wx_mch_id,
                                'key'=>$storeWx['wx_key']?$storeWx['wx_key']:$app->wx_key,
                                'sslcert'=>$storeWx['wx_sslcert']!=0?$storeWx['wx_sslcert']:$app->wx_cert_pem,
                                'sslkey'=>$storeWx['wx_sslkey']!=0?$storeWx['wx_sslkey']:$app->wx_key_pem,
                                'wx_profit_sharing'=>$app->wx_profit_sharing
                           ];
                       }
                    }

                 }
                 $wechatPay=new WechatPay($wx_config);
                 $notify_url='https://chashi-demo.youdiy.cn';
                 $order->out_order_no=HouseOrder::crateOutOrderNo();
                 $data = [
                    'out_refund_no' => $order->out_order_no,//订单号码
                    'out_trade_no' =>$order->order_no,//退款单号
                    'total_fee' =>  $order->pay_price * 100,//支付金额
                    'refund_fee' => $refund_price * 100,//全额退款
                ];
                if(isset($order->xml_array)){
                    $xml_array=json_decode($order->xml_array,1);
                    if(isset($xml_array['transaction_id'])){
                      $data['transaction_id']=$xml_array['transaction_id'];
                    }
                }
                $payResult = $wechatPay->refund($data);
                if (!isset($payResult['return_code']) || $payResult['return_code'] != 'SUCCESS') {
                    $info='退款失败，' . (isset($payResult['return_msg']) ? $payResult['return_msg'] : '');
                    return fetchJson([],$info,1);
                }
                if (!isset($payResult['result_code']) || $payResult['result_code'] != 'SUCCESS') {
                    $info='提交业务失败，'. (isset($payResult['err_code_des']) ? $payResult['err_code_des'] : '');
                    return fetchJson([],$info,1);
                }
                $order->out_order_time=time();
                (new Bill())->save([
                    'acid'=>$order->acid,
                    'type'=>Bill::TYPE_HOUSE_REFUND,
                    'account_type'=>Bill::ACCOUNT_TYPE_USER,
                    'form_id'=>$order->user_id,
                    'order_id'=>$order->id,
                    'price'=>$refund_price,
                    'price_type'=>$order->pay_type,
                    'status'=>1,
                    'fee'=>$refund_fee_price,
                    'balance'=>$user->money,
                    'des'=>'用户: 【'.$user->nickname.'】茶室预订微信退款'
                ]);
             }
             //余额支付退款
             if($order->pay_type==2){
                $user->money+=$refund_price;
                $user->save();
                (new Bill())->save([
                    'acid'=>$order->acid,
                    'type'=>Bill::TYPE_HOUSE_REFUND,
                    'account_type'=>Bill::ACCOUNT_TYPE_USER,
                    'form_id'=>$order->user_id,
                    'order_id'=>$order->id,
                    'price'=>$refund_price,
                    'price_type'=>$order->pay_type,
                    'status'=>1,
                    'fee'=>$refund_fee_price,
                    'balance'=>$user->money,
                    'des'=>'用户: 【'.$user->nickname.'】茶室预订余额退款'
                ]);
                
             }
             if($refund_price>0){
                self::addStoreBill($order,$refund_fee_price);
             }
             //还原库存
             HouseStock::where([
                'acid'=>$order->acid,
                'house_id'=>$order->house_id,
                'order_id'=>$order->id,
                'store_id'=>$order->store_id,
             ])->update(['status'=>1,'order_id'=>0]);
             //优惠券还原
             $userCoupon=CouponUser::where(['id'=>$order->coupon_user_id])->find();
             if($userCoupon){
                 $order->pay_price+=$userCoupon['discounts_price'];
                 $order->price=$order->pay_price;
                 $order->coupon_user_id=0;
                 $order->save();
                 
                 $userCoupon->is_use=0;
                 $userCoupon->order_id=0;
                 $userCoupon->discounts_price=0;
                 $userCoupon->use_time=0;
                 $userCoupon->save();
             }
             //商家优惠券还原
             $storeUserCoupon=StoreCouponUser::where(['id'=>$order->store_coupon_user_id])->find();
             if($storeUserCoupon){
                 $order->pay_price+=$storeUserCoupon['discounts_price'];
                 $order->price=$order->pay_price;
                 $order->store_coupon_user_id=0;
                 $order->save();
                 $storeUserCoupon->is_use=0;
                 $storeUserCoupon->use_time=0;
                 $storeUserCoupon->save();
             }
             //会员卡免费时长还原
             $cardUserOrder=CardUserOrder::where(['acid'=>$this->acid,'order_id'=>$order->id,'user_id'=>$this->user_id,'type'=>1])->find();
             if($cardUserOrder){
                 $cardUser=CardUser::where(['id'=>$cardUserOrder->card_user_id])->find();
                 $cardUser->hour+=$cardUserOrder->hour;
                 $cardUser->save();
                 $cardUserOrder->status=0;
                 $cardUserOrder->save();
             }
             //美团卡券
             $cardCoupon=CardCoupon::where(['id'=>$order->card_coupon_id])->find();
             if($cardCoupon){
                $cardCoupon->num+=1;
                $cardCoupon->status=1;
                $cardCoupon->save();
                CardCouponOrder::where(['order_id'=>$order->id])->update(['status'=>-1,'use_time'=>time()]);
             }
             $order->status=-2;
             $order->save();
             Cache::set('subscribeOrder'.$order_id,0,1);
             //发送保洁人员
             $weixin=new \weixin\Wechat();
             $snapshoot=json_decode($order->snapshoot,1);
             $data=[
                "first"    =>[
                  "value"  =>"取消订单",
                  "color"  =>"#173177"
                ],
                "keyword1" =>[
                  "value"  =>date("Y-m-d H:i",$order->start_time).' 至 '.date("Y-m-d H:i",$order->end_time),//取消时间
                  "color"  =>"#173177"
                ],
                "keyword2" =>[
                  "value"  =>$snapshoot['name'],//标签
                  "color"  =>"#173177"
                ],
                "remark"   =>[
                  "value"  =>"顾客取消订单~ :(",
                  "color"  =>"#173177"
                ]
            ];
            $openids=Store::where('id',$order->store_id)->value('openid');
            if($openids){
                $openidArr=explode(',',$openids);
                $tpl=Option::get_data($this->acid,'platform','wx_template_cancel_order_inform');
                foreach ($openidArr as $openid) {
                  $res=$weixin->sendWxopenTemplate($app,$tpl,$openid,'pages/index/index',$data);
                }
            }
            self::sendCleaningTpl($app,$order);
        }
        return fetchJson([],'退款成功');
    }
    //保洁端用户下单提醒
    public function sendCleaningTpl($app,$order){
        set_time_limit(0);
        $cleaning= StoreCleaning::where(['acid'=>$order->acid,'store_id'=>$order->store_id,'is_delete'=>0,'status'=>1])->where('openid','<>','')->column('openid,account');
        $snapshoot=json_decode($order->snapshoot,1);
        $store=Store::where('id',$order->store_id)->field('address,name')->find();
        //发送保洁人员
        $weixin=new \weixin\Wechat();
        $data=[
            "first"    =>[
              "value"  =>"用户在店【{$store['name']}】"."取消订单",
              "color"  =>"#173177"
            ],
            "keyword1" =>[
              "value"  =>$snapshoot['name'],//房间名称：
              "color"  =>"#173177"
            ],
            "keyword2" =>[
              "value"  =>$store['address'],//房间地址：
              "color"  =>"#173177"
            ],
            "keyword3" =>[
              "value"  =>date('Y-m-d H:i:s',$order->end_time).'之后', //保洁时间：
              "color"  =>"#173177"
            ],
            "remark"   =>[
              "value"  =>'用户取消订单时间'.date('Y-m-d H:i:s',$order->start_time).'至'.date('Y-m-d H:i:s',$order->end_time),
              "color"  =>"#173177"
            ]
        ];
        $tpl=Option::get_data($order->acid,'platform','wx_template_cleaning_port_inform');
        foreach($cleaning as $value){
            $res=$weixin->sendWxopenTemplate($app,$tpl,$value['openid'],"pages/index/index",$data);
            \app\shared\model\MessageLog::pushMsg($order->acid,$value['account'],$order->order_no,json_encode($data,JSON_UNESCAPED_UNICODE),json_encode($res));
        }
    }
    //增加商户账单
    public function addStoreBill($order=[],$price=0){
        $store=Store::where('id',$order['store_id'])->find();
        $fee=($store->fee*0.01)*$price;
        $fee=$fee>0?$fee:0;//手续费
        $orderPrice=$price-$fee; //总金额   
        $stockHouse=StockHouseUser::alias('h_u')
               ->leftJoin([StockHouse::getTable()=>'h'],'h_u.stock_house_id=h.id')
               ->where(['h_u.acid'=>$order->acid,'h.house_id'=>$order->house_id,'h_u.is_delete'=>0,'h.is_delete'=>0])
               ->field('h_u.stock_user_id,h_u.ratio,h.house_id,h_u.stock_house_id')
               ->select()
               ->toArray();
        //分红金额
        $sharePrice=0;           
        foreach($stockHouse as $hu){
           (new StockHouseUserOrder())->save([
              'acid'=>$order->acid,
              'type'=>1,
              'order_id'=>$order->id,
              'stock_house_id'=>$hu['stock_house_id'],
              'stock_user_id'=>$hu['stock_user_id'],
              'ratio'=>$hu['ratio'],
              'price'=>$hu['ratio']*$orderPrice*0.01, 
            ]);
           $user=StockUser::where('id',$hu['stock_user_id'])->field('money,total_price')->find();
           if($user){
             $user->money+=$hu['ratio']*$orderPrice*0.01;
             $user->total_price+=$hu['ratio']*$orderPrice*0.01;
             $user->save();
           }
           $sharePrice+=$hu['ratio']*$orderPrice*0.01;
        }  
        if($sharePrice>0){
            (new Bill())->save([
                'acid'=>$order['acid'],
                'type'=>Bill::TYPE_HOUSE,
                'account_type'=>Bill::ACCOUNT_TYPE_STORE,
                'form_id'=>$order['store_id'],
                'order_id'=>$order['id'],
                'price'=>$orderPrice-$sharePrice,
                'price_type'=>$order['pay_type'],
                'status'=>1,
                'fee'=>$fee,
                'des'=>'商户: 【'.$store->name.'】茶室用户退款手续费收入其中股东分红扣除'.$sharePrice.'元'
            ]);
            $store->money+=$orderPrice-$sharePrice;
        }else{
            (new Bill())->save([
                'acid'=>$order['acid'],
                'type'=>Bill::TYPE_HOUSE,
                'account_type'=>Bill::ACCOUNT_TYPE_STORE,
                'form_id'=>$order['store_id'],
                'order_id'=>$order['id'],
                'price'=>$orderPrice-$sharePrice,
                'price_type'=>$order['pay_type'],
                'status'=>1,
                'fee'=>$fee,
                'des'=>'商户: 【'.$store->name.'】茶室用户退款手续费收入'
            ]);
            $store->money+=$orderPrice-$sharePrice;
        }        
        $store->save();
    } 
    //详情
    public function details(){
        $order_id=input('order_id');
        $order=HouseOrder::where(['id'=>$order_id])->find();
        if(!$order){
            return fetchJson([],'暂无订单',1);
        }
        $order['snapshoot']=json_decode($order['snapshoot'],1);
        $order['store']=Store::where('id',$order['store_id'])->field('tel,name')->find();
        if($order['book_type']==3&&$order['is_pay']==0){
           $order['start_time']=date("Y-m-d H:i:s",$order['start_time']);
           $order['end_time']=$order['end_time']>0?date("Y-m-d H:i:s",$order['end_time']):'';
           return fetchJson($order,'获取成功');
        }
        $order_continue_list=HouseOrderContinue::where(['status'=>1,'order_id'=>$order->id])->order('id DESC')->column('id,start_time,pay_price,price,end_time');
        $price=0;
        foreach ($order_continue_list as $key => &$value) {
          $value['start_time']=date('Y-m-d H:i',$value['start_time']);
          $value['end_time']=date('Y-m-d H:i',$value['end_time']);
          $price+=$value['pay_price'];
          $value['discounts_price']=$value['price']-$value['pay_price'];
        }
        $end_time=$order->end_time;
        $start_time=$order->start_time;
        $xdstart_time=HouseOrderContinue::where(['status'=>1,'order_id'=>$order->id])->order('id ASC')->value('start_time');
        $start_time=$order['start_time'];
        if($xdstart_time){
          //续单
          if($xdstart_time>$order['start_time']){
              $xdend_time=HouseOrderContinue::where(['status'=>1,'order_id'=>$order->id])->order('id DESC')->value('end_time');
              $end_time=$xdend_time;
          }else{
            //向前续单
              $start_time=$xdstart_time;
          }
        }
        $order['start_time']=date("Y-m-d H:i:s",$start_time);
        $order['end_time']=date("Y-m-d H:i:s",$end_time);

        if($start_time<time()&&$order['status']==1){
           HouseOrder::where(['id'=>$order_id,'user_id'=>$this->user_id])->update(['status'=>2]);
        }
        $order['pay_price']+=$price;
        $order['order_continue_list']=$order_continue_list;
        $card_user_order=CardUserOrder::alias('cuo')
            ->leftJoin([CardUser::getTable()=>'cu'],'cuo.card_user_id=cu.id')
            ->leftJoin([Card::getTable()=>'c'],'cu.card_id=c.id')
            ->where(['cuo.type'=>1,'cuo.order_id'=>$order->id,'cuo.user_id'=>$this->user_id,'cuo.is_delete'=>0])
            ->field('cuo.price,cuo.hour,cuo.discount,cuo.status,cuo.type,c.title')
            ->find();
        if($card_user_order){
           $card_user_order['discounts_price']=0;
        }
        //判断是否使用合伙人
        $is_table = Db::query('show tables like "'.PartnerUserOrder::getTable().'"');
        if($is_table){
          $partner_order=PartnerUserOrder::alias('puo')
          ->leftJoin([PartnerUser::getTable()=>'pu'],'puo.user_partner_id=pu.id')
          ->leftJoin([Partner::getTable()=>'p'],'pu.partner_id')
          ->where(['puo.order_id'=>$order->id,'puo.status'=>1])
          ->field("puo.*,p.title")->find();
          $order['partner_user_order']=$partner_order;
        }else{
          $order['partner_user_order']=[];
        }
        $order['card_user_order']=$card_user_order;
        $discounts_price=CouponUser::where(['id'=>$order->coupon_user_id,'type'=>Coupon::TYPE_HOTEL,'user_id'=>$this->user_id])->value('discounts_price');
        $order['discounts_price']=$discounts_price>0?$discounts_price:0;
        $store_discounts_price=StoreCouponUser::where(['id'=>$order->store_coupon_user_id,'type'=>StoreCoupon::TYPE_HOTEL,'user_id'=>$this->user_id])->value('discounts_price');
        $order['store_discounts_price']=$store_discounts_price>0?$store_discounts_price:0;
        $order['card_coupon']=CardCouponOrder::alias('cco')->leftJoin([CardCoupon::getTable()=>'cc'],'cco.card_coupon_id=cc.id')->where(['cco.order_id'=>$order_id])->field('cc.discounts_price,cc.name,cco.id')->find();
        $order['cancel_time']=House::where('id',$order['house_id'])->value('cancel_time');
        return fetchJson($order,'获取成功');
    }
    //最新详情
    public function newDetails(){
        $order=HouseOrder::where(['user_id'=>$this->user_id])->order('id DESC')->find();
        if(!$order){
            return fetchJson([],'暂无订单',0);
        }
        if($order['book_type']!=3&&$order['is_pay']!=1){
            return fetchJson([],'暂无订单',0);
        }
        if($order->status==3){
          return fetchJson([],'订单已过期，无法开锁',0);
        }
        if($order->is_verifier==-1){
           return fetchJson($order,'开房成功');
        }
        $smart_device=Store::where('id',$order->store_id)->value('smart_device');

        $smart_device=json_decode($smart_device,1);
        $house=House::where('id',$order->house_id)->find();
        $ahead_time=$house['ahead_time']*60;
        $forward_time=$house['forward_time']*60;
        $continueOrder=HouseOrderContinue::where(['order_id'=>$order->id])->where('status','>',0)->order('id DESC')->field('start_time,end_time')->find();
        $end_time=$order->end_time;
        $start_time=$order->start_time;
        if($continueOrder){
            if($continueOrder->end_time>time()&&$order->end_time<time()){
                $start_time=time();
            }
            $end_time=$continueOrder->end_time;
        }
        $order['snapshoot']=json_decode($order['snapshoot'],1);
        $order['store']=Store::where('id',$order['store_id'])->field('tel,name')->find();
        $order['end_time']=$end_time;
        return fetchJson($order,'开房成功');
    }
    //订单续单预览
    public function orderContinuePreview(){
         try {
            $data=request()->post();
            $rule = [
                 'order_id|订单ID' => 'require|number',
                 'time|入住时间'=>'require|in:0.5,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5,8,8.5,9,9.5,10',
             ];
            $this->validate($data,$rule);
         }catch (ValidateException $e){
            return fetchJson([],$e->getError(),1);
         }
         $order=HouseOrder::where(['id'=>$data['order_id'],'is_pay'=>1])->where('status','in','1,2')->find();
         if(!$order){
            return fetchJson([],'订单',1);
         }
         $pay_type=input('pay_type');
         //向前续单
         if($type=input('type')){
              $start_time=HouseOrderContinue::where(['status'=>1,'order_id'=>$order->id])->order('start_time ASC')->value('start_time');
              if($start_time){
                $start_time=$start_time-$data['time']*3600;
                if($start_time<time()){
                   $start_time=time();
                }
                $end_time=HouseOrderContinue::where(['status'=>1,'order_id'=>$order->id])->order('start_time ASC')->value('start_time');
              }else{
                $start_time=$order->start_time-$data['time']*3600;
                if($start_time<time()){
                   $start_time=time();
                }
                $end_time=$order->end_time;
              }
         }else{
           // 向后续单
           $end_time=HouseOrderContinue::where(['status'=>1,'order_id'=>$order->id])->order('end_time DESC')->value('end_time');
           if($end_time){
              $start_time=HouseOrderContinue::where(['status'=>1,'order_id'=>$order->id])->order('end_time DESC')->value('end_time');
              $end_time=$end_time+$data['time']*3600;

           }else{
              $start_time=$order->end_time;
              $end_time=$order->end_time+$data['time']*3600;
           }
         }
         if($end_time<time()){
            return fetchJson([],'预订时间已过',1);
         }
         if($start_time>$end_time){
            return fetchJson([],'预订时间错误',1);
         }
         $starttime=strtotime(date('Y-m-d H:i',$start_time));
         $endtime=strtotime(date('Y-m-d H:i',$end_time));
         $halfDay=($endtime-$starttime)/3600;
         $num=$halfDay;
         $dayArr=[];
         for ($j=1;$j<($halfDay+1);$j++){ 
            $dayArr[]=$starttime+1800*$j;
         }
         $is_booKtime=HouseStock::where(['acid'=>$order['acid'],'store_id'=>$order['store_id'],'house_id'=>$order['house_id'],'status'=>0])->where('hour','in',$dayArr)->where('order_id','<>',$data['order_id'])->count();
         if($is_booKtime){
            return fetchJson([],'该时间段已被预订，请重新预约茶室',1);
         }
         foreach ($dayArr as $dV){
             $is_booKtime=HouseStock::where(['acid'=>$order['acid'],'store_id'=>$order['store_id'],'house_id'=>$order->house_id,'status'=>0])->where('hour','>=',$dV)->where('hour','<=',$endtime)->count();
             if($is_booKtime){
                return fetchJson([],date('Y-m-d H:i:s',$dV).'该时间段已预订',1);
             }
         }
         $house=House::where('id',$order['house_id'])->find();
         $xdOrderPrice=self::getTimePirce($house,$start_time,$end_time);
         $xdOrderPayPrice=$xdOrderPrice;
         $time=time();
         $cardUser=CardUser::where(['status'=>1,'user_id'=>$this->user_id])->where('start_time','<',$time)->where('end_time','>',strtotime(date('Y-m-d',$time+86400)));
         $card_user_id=input('card_user_id');
         if($card_user_id){
            $cardUser=$cardUser->where('id',$card_user_id);
         }
         $orderPrice=$xdOrderPrice;
         $orderPayPrice=$orderPrice;
         $cardUser=$cardUser->order('level DESC')->find();
         $cardUserArr=[];
         $cardUserArr['title']='普通会员';
         $cardUserArr['price']=0;
         $is_repeat_order_original=0;
         $store=Store::where('id',$house['store_id'])->find();
         if(isset($store['is_repeat_order_original'])){
            $is_repeat_order_original=$store['is_repeat_order_original']==1?1:0;
         }
         if($cardUser&&$pay_type!=3&&$is_repeat_order_original==0){
            if($pay_type==2){
               $card=Card::where(['id'=>$cardUser['card_id'],'is_delete'=>0,'is_balance'=>1])->find();
            }else{
               $card=Card::where(['id'=>$cardUser['card_id'],'is_delete'=>0])->find();
            }
            if($card){
                $discount=$card['discount'];
                if($card['type']==2){
                    $hour=0;
                    $hour=$cardUser['hour'];
                    $order->card_type=$card['type'];
                    $coutHour=$num;
                    $cardHouseIds=explode(',',$card['house_ids']);
                    $feePirce=0;
                    if($card['house_ids']=='-1'||in_array($order->house_id,$cardHouseIds)){
                       if($coutHour<=$hour){
                         $hour=$coutHour;
                         $feePirce=self::getTimePirce($house,$start_time,$end_time,$hour);
                         $orderPayPrice-=$feePirce;
                       }
                       if($coutHour>$hour&&$hour>0){
                         $feePirce=self::getTimePirce($house,$start_time,$end_time,$hour);
                         $orderPayPrice-=$feePirce;
                       }
                    }
                    $orderPayPrice=$orderPayPrice*$discount/10;
                }else{
                   if($house['member_price']>0){
                    $bookNum=($endtime-$start_time)/1800;
                    $booknum1=ceil($bookNum)/2;
                    $orderPayPrice=$house['member_price']*$booknum1;
                    $cardUserArr['title']='会员价减免';
                    $cardUserArr['price']=$orderPrice-$orderPayPrice;
                  }else{
                    $house_price=$card['house_price'];
                    if($house_price>0){
                        $discount=$card['discount'];
                        $hour=$cardUser['hour'];
                        $coutHour=(int)($orderPrice/$house_price);
                        if($coutHour<=$hour){
                          $hour=$coutHour;
                          $cardUserArr['title']='会员优惠时长&折扣减免';
                        }else{
                          $cardUserArr['title']='会员折扣减免';
                        }
                        $orderPayPrice=($orderPrice-$hour*$house_price)*$discount/10;
                        $cardUserArr['price']=$orderPrice-$orderPayPrice;
                    }
                  }
                }
                
                $xdOrderPayPrice=$orderPayPrice;
            }
         }
         return fetchJson([
          'card_user'=>$cardUserArr,
          'price'=>$orderPrice,
          'pay_price'=>$orderPayPrice
         ]);
    }
    //订单续单提交
    public function orderContinueSubmit(){
         try {
            $data=request()->post();
            $rule = [
                 'order_id|订单ID' => 'require|number',
                 'time|入住时间'=>'require|in:0.5,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5,8,8.5,9,9.5,10',
             ];
            $this->validate($data,$rule);
         }catch (ValidateException $e){
            return fetchJson([],$e->getError(),1);
         }
         $order=HouseOrder::where(['id'=>$data['order_id'],'is_pay'=>1])->where('status','in','1,2')->find();
         if(!$order){
            return fetchJson([],'订单',1);
         }
         $pay_type=input('pay_type');
         //向前续单
         if($type=input('type')){
              $start_time=HouseOrderContinue::where(['status'=>1,'order_id'=>$order->id])->order('start_time ASC')->value('start_time');
              if($start_time){
                $start_time=$start_time-$data['time']*3600;
                if($start_time<time()){
                   $start_time=time();
                }
                $end_time=HouseOrderContinue::where(['status'=>1,'order_id'=>$order->id])->order('start_time ASC')->value('start_time');
              }else{
                $start_time=$order->start_time-$data['time']*3600;
                if($start_time<time()){
                   $start_time=time();
                }
                $end_time=$order->end_time;
              }
         }else{
           // 向后续单
           $end_time=HouseOrderContinue::where(['status'=>1,'order_id'=>$order->id])->order('end_time DESC')->value('end_time');
           if($end_time){
              $start_time=HouseOrderContinue::where(['status'=>1,'order_id'=>$order->id])->order('end_time DESC')->value('end_time');
              $end_time=$end_time+$data['time']*3600;

           }else{
              $start_time=$order->end_time;
              $end_time=$order->end_time+$data['time']*3600;
           }
         }
         if($end_time<time()){
            return fetchJson([],'预订时间已过',1);
         }
         if($start_time>$end_time){
            return fetchJson([],'预订时间错误',1);
         }
         
         if($end_time<time()){
            return fetchJson([],'预订时间已过',1);
         }
         if($start_time>$end_time){
            return fetchJson([],'预订时间错误',1);
         }
         $starttime=strtotime(date('Y-m-d H:i',$start_time));
         $endtime=strtotime(date('Y-m-d H:i',$end_time));
         $halfDay=($endtime-$starttime)/3600;
         $num=$halfDay;
         $dayArr=[];
         for ($j=1;$j<($halfDay+1);$j++){ 
            $dayArr[]=$starttime+1800*$j;
         }
         $is_booKtime=HouseStock::where(['acid'=>$order['acid'],'store_id'=>$order['store_id'],'house_id'=>$order['house_id'],'status'=>0])->where('hour','in',$dayArr)->where('order_id','<>',$data['order_id'])->count();
         if($is_booKtime){
            return fetchJson([],'该时间段已被预订，请重新预约茶室',1);
         }
         foreach ($dayArr as $dV){
             $is_booKtime=HouseStock::where(['acid'=>$order['acid'],'store_id'=>$order['store_id'],'house_id'=>$order->house_id,'status'=>0])->where('hour','>=',$dV)->where('hour','<=',$endtime)->count();
             if($is_booKtime){
                return fetchJson([],date('Y-m-d H:i:s',$dV).'该时间段已预订',1);
             }
         }
         $house=House::where('id',$order['house_id'])->find();
         $xdOrder=new HouseOrderContinue();
         $xdOrder->save([
            'order_no'=>HouseOrderContinue::crateOrderNo(),
            'start_time'=>$start_time,
            'end_time'=>$end_time,
            'order_id'=>$order->id,
            'user_id'=>$this->user_id,
            'acid'=>$order->acid,
            'house_id'=>$order->house_id,
            'store_id'=>$order->store_id,

         ]);
         $xdOrder->price=self::getTimePirce($house,$start_time,$end_time);
         $xdOrder->pay_price=$xdOrder->price;
         $time=time();
         $cardUser=CardUser::where(['status'=>1,'user_id'=>$this->user_id])->where('start_time','<',$time)->where('end_time','>',strtotime(date('Y-m-d',$time+86400)));
         $card_user_id=input('card_user_id');
         if($card_user_id){
            $cardUser=$cardUser->where('id',$card_user_id);
         }
         $orderPrice=$xdOrder->price;
         $orderPayPrice=$orderPrice;
         $cardUser=$cardUser->order('level DESC')->find();

         $is_repeat_order_original=0;
         $store=Store::where('id',$order->store_id)->find();
         if(isset($store['is_repeat_order_original'])){
            $is_repeat_order_original=$store['is_repeat_order_original']==1?1:0;
         }
         if($cardUser&&$pay_type!=3&&$is_repeat_order_original==0){
            if($pay_type==2){
               $card=Card::where(['id'=>$cardUser['card_id'],'is_delete'=>0,'is_balance'=>1])->find();
            }else{
               $card=Card::where(['id'=>$cardUser['card_id'],'is_delete'=>0])->find();
            }
            if($card){
                $discount=$card['discount'];
                if($card['type']==2){
                    $hour=0;
                    $hour=$cardUser['hour'];
                    $order->card_type=$card['type'];
                    $coutHour=$num;
                    $cardHouseIds=explode(',',$card['house_ids']);
                    $feePirce=0;
                    if($card['house_ids']=='-1'||in_array($order->house_id,$cardHouseIds)){
                       if($coutHour<=$hour){
                         $hour=$coutHour;
                         $feePirce=self::getTimePirce($house,$start_time,$end_time,$hour);
                         $orderPayPrice-=$feePirce;
                       }
                       if($coutHour>$hour&&$hour>0){
                         $feePirce=self::getTimePirce($house,$start_time,$end_time,$hour);
                         $orderPayPrice-=$feePirce;
                       }
                    }
                    $orderPayPrice=$orderPayPrice*$discount/10;
                    (new CardUserOrder())->save([
                      'acid'=>$this->acid,
                      'order_id'=>$xdOrder->id,
                      'user_id'=>$this->user_id,
                      'card_user_id'=>$cardUser->id,
                      'price'=>($orderPrice-$orderPayPrice)<=0?$feePirce:$orderPrice-$orderPayPrice,
                      'hour'=>$hour,
                      'type'=>10,
                      'discount'=>$discount
                    ]);
                }else{
                   if($house['member_price']>0){
                      $bookNum=($endtime-$start_time)/1800;
                      $booknum1=ceil($bookNum)/2;
                      $orderPayPrice=$house['member_price']*$booknum1;

                    }else{
                      $house_price=$card['house_price'];
                      if($house_price>0){
                          $discount=$card['discount'];
                          $hour=$cardUser['hour'];
                          $coutHour=(int)($orderPrice/$house_price);
                          if($coutHour<=$hour){
                            $hour=$coutHour;
                          }
                          $orderPayPrice=($orderPrice-$hour*$house_price)*$discount/10;

                          (new CardUserOrder())->save([
                            'acid'=>$this->acid,
                            'order_id'=>$xdOrder->id,
                            'user_id'=>$this->user_id,
                            'card_user_id'=>$cardUser->id,
                            'price'=>$hour*$house_price,
                            'type'=>10,
                            'hour'=>$hour,
                            'discount'=>$discount
                          ]);
                      }
                    }
                }
                
                $xdOrder->pay_price=$orderPayPrice;
            }
         }
         $xdOrder->save();
         return fetchJson($xdOrder);
    }
    //订单续单支付
    public function orderContinuePay(){
       $order_id=input('order_id');
       $order=HouseOrderContinue::where(['id'=>$order_id,'user_id'=>$this->user_id,'is_pay'=>0])->find();
       if(!$order){
          return fetchJson([],'暂无订单',1);
       }
       $order->order_no=HouseOrderContinue::crateOrderNo();
       $pay_type=input('pay_type')?input('pay_type'):1;
       $order->pay_type=$pay_type;
       $order->save();
        //判断是否用余额支付
       if($pay_type==2){
           $res=self::balancePaymentContinue($order);
           return fetchJson([],$res['msg'],$res['code']);
       }
       if($pay_type==3){
           $res=self::storeBalancePaymentContinue($order);
           return fetchJson([],$res['msg'],$res['code']);
       }
       $app=App::find($this->acid);
       $appid=$app->wxapp_app_id;
       $app_secret=$app->wxapp_app_secret;
       $openid=$this->user->wxapp_open_id;
       if(input('is_weixin')==1){
          $appid=$app->wx_app_id;
          $app_secret=$app->wx_app_secret;
          $openid=$this->user->wx_open_id;
       }
       if($this->platform=='app'||$this->platform=='ios'||$this->platform=='android'){
            $appConfig=Option::get_data($this->acid,'platform','app_config');
            $appConfig=json_decode($appConfig);
            $appid=isset($appConfig->appid)?$appConfig->appid:'';
            $app_secret=isset($appConfig->app_secret)?$appConfig->app_secret:'';
       }
       $wx_config=[
            'appid'=>$appid,
            'appsecret'=>$app_secret,
            'mchid'=>$app->wx_mch_id,
            'key'=>$app->wx_key,
            'sslcert'=>$app->wx_cert_pem,
            'sslkey'=>$app->wx_key_pem,
       ];
       if(isset($app->wx_pay_type)){
          $storeWx=Store::where('id',$order->store_id)->field('wx_mch_id,wx_key,wx_sslcert,wx_sslkey')->find();
          //服务商模式
          if($app->wx_pay_type==2){
             $wx_config=[
                  'appid'=>$appid,
                  'mchid'=>$storeWx['wx_mch_id']!=0?$storeWx['wx_mch_id']:$app->wx_mch_id,
                  'wx_server_appid'=>$app->wx_server_appid,
                  'appsecret'=>$app_secret,
                  'wx_server_mch_id'=>$app->wx_server_mch_id,
                  'key'=>$app->wx_server_key,
                  'sslcert'=>$app->wx_server_cert_pem,
                  'sslkey'=>$app->wx_server_key_pem,
                  'sub_appid'=>$appid,
                  'sub_mch_id'=>$app->wx_mch_id,
                  'wx_pay_type'=>$app->wx_pay_type,
                  'wx_profit_sharing'=>$app->wx_profit_sharing
             ];
          }else{
             if($storeWx['wx_mch_id']){
                $wx_config=[
                      'appid'=>$appid,
                      'appsecret'=>$app_secret,
                      'mchid'=>$storeWx['wx_mch_id']!=0?$storeWx['wx_mch_id']:$app->wx_mch_id,
                      'key'=>$storeWx['wx_key']?$storeWx['wx_key']:$app->wx_key,
                      'sslcert'=>$storeWx['wx_sslcert']!=0?$storeWx['wx_sslcert']:$app->wx_cert_pem,
                      'sslkey'=>$storeWx['wx_sslkey']!=0?$storeWx['wx_sslkey']:$app->wx_key_pem,
                      'wx_profit_sharing'=>$app->wx_profit_sharing
                 ];
             }
          }
       }
       
       $wechatPay=new WechatPay($wx_config);
       $notify_url=request()->domain().str_replace('index.php', 'pay_shared.php',request()->baseFile());
       $paydata = [
            'body' =>$order->house_title.'购买商品',
            'out_trade_no' => $order->order_no,
            'total_fee' => round($order->pay_price,2)* 100,
            'notify_url' =>$notify_url ,
            'trade_type' => 'JSAPI',
            'openid' => $openid,
        ];
       //字节跳动支付
       if($this->platform=='ttapp'){
             $paydata=[
                'body' =>$order->house_title.'购买商品',
                'appid'=>$app->wx_app_id,
                'attach'=>'购买商品',
                'mch_id'=>$app->mch_id,
                'notify_url' =>$notify_url ,
                'out_trade_no' => $order->order_no,
                'total_fee' => round($order->pay_price,2)* 100,
                'trade_type' => 'MWEB',
                'openid' => $openid,
                'scene_info'=>'{"h5_info":{"type":"Wap","wap_url":"'.request()->domain().'","wap_name":"测试支付"}}'
            ];
            $ttapp=Option::get_data($this->acid,'platform','ttapp_config');
            $ttapp=json_decode($ttapp);
            $res=$wechatPay->toutiaoh5pay($paydata,$ttapp);
            if($res['code']==0){
              return fetchJson($res);
            }else{
              return fetchJson([],$res['msg'],1);
            }
       }
        //微信外部支付
       if($this->platform=='h5'&&input('is_weixin')==0){
            $paydata=[
              'body' =>$order->house_title.'购买商品',
              'appid'=>$app->wx_app_id,
              'attach'=>'购买商品',
              'mch_id'=>$app->mch_id,
              'notify_url' =>$notify_url ,
              'out_trade_no' => $order->order_no,
              'total_fee' => round($order->pay_price,2)* 100,
              'trade_type' => 'MWEB',
              'openid' => $openid,
              'scene_info'=>'{"h5_info":{"type":"Wap","wap_url":"'.request()->domain().'","wap_name":"测试支付"}}'
            ];
            $rest['order_id']=$order->id;
            $res=$wechatPay->h5pay($paydata);
            if($res['code']==0){
              $rest['mweb_url']=$res['data'];
              return fetchJson($rest);
            }else{
              return fetchJson([],$res['msg'],1);
            }
       }
       if($this->platform=='app'||$this->platform=='ios'||$this->platform=='android'){
            unset($paydata['openid']);
            $paydata['trade_type']="APP";
            $res=$wechatPay->appPay($paydata);
       }else{
          $res=$wechatPay->pay($paydata);
       }
       $res['order_id']=$order->id;
       return fetchJson($res);
    }
    //续单
    private function balancePaymentContinue($order=[]){
         $user=User::where('id',$order['user_id'])->find();
         $cardUserOrder=CardUserOrder::where(['order_id'=>$order->id,'type'=>10])->find();
         if($cardUserOrder){
            $cardUser=CardUser::where('id',$cardUserOrder->card_user_id)->find();
            if($cardUser){
              $card=Card::where(['id'=>$cardUser->card_id,'is_balance'=>0])->count();
              if($card){
                 $order->pay_price-=$cardUserOrder['price'];
                 $order->save();
                 $cardUserOrder->is_delete=1;
                 $cardUserOrder->save();
              }
            }
         }
         if($user->money<$order->pay_price){
            return [
              'msg'=>'余额不足',
              'code'=>1
            ];
         }
         $form=new \app\shared\logic\pay\HouseOrderContinueForm();
         $res=$form->saveOrder($order->order_no);
         if($res=='success'){
            return [
              'msg'=>'支付成功',
              'code'=>0
            ];
         }
        return [
          'msg'=>'余额支付错误',
          'code'=>1
        ];
    }
    //续单商家储值卡支付
    private function storeBalancePaymentContinue($order=[]){
         $user=StoreUserMoney::where(['user_id'=>$order['user_id'],'store_id'=>$order['store_id']])->find();
         if($user->money<$order->pay_price){
            return [
              'msg'=>'用户商户余额不足',
              'code'=>1
            ];
         }
         $form=new \app\shared\logic\pay\HouseOrderContinueForm();
         $res=$form->saveOrder($order->order_no);
         if($res=='success'){
            return [
              'msg'=>'支付成功',
              'code'=>0
            ];
         }
        return [
          'msg'=>'用户商户余额支付错误',
          'code'=>1
        ];
    }
    //提前结束订单
    public function endOrdersEarly(){
        $order=HouseOrder::where(['id'=>input('order_id'),'is_pay'=>1])->where('status','in','1,2')->find();
        if(!$order){
            return fetchJson([],'暂无订单',1);
        }
        $form= new \app\task\controller\Wechat();
        $form->endOrdersEarly($order);
        return fetchJson([],'提前结束订单');
    }
    //提前使用订单
    public function useOrdersEarly(){
        $order=HouseOrder::where(['id'=>input('order_id'),'is_pay'=>1,'status'=>1])->find();
        if(!$order){
            return fetchJson([],'暂无订单',1);
        }
        $start_time=time();
        $start_time1=$start_time;
        $numB=($order->end_time-$order->start_time)/1800;
        $end_time=$start_time+$numB*1800;
        $is_booKtime=HouseStock::where(['acid'=>$order->acid,'store_id'=>$order->store_id,'house_id'=>$order->house_id,'status'=>0])
        ->where('order_id','<>',$order->id)
        ->whereTime('hour', '<=', $end_time+1800)
        ->whereTime('hour', '>=', $start_time)
        ->count();
        if($is_booKtime){
          return fetchJson([],'提前失败现在时间段已预订',1);
        }
        // $start_time=strtotime("2020-01-18 10:45");
        // $end_time=strtotime("2020-01-18 11:35");
        $num=($end_time-$start_time)/1800;
        $newStart_time=date("Y-m-d",$start_time).' '.date("H",$start_time).':00';
        $newStart_time=strtotime($newStart_time);
        $dateArray=[];
        $stockInsert=[];
        if($start_time%1800!=0){
           $minute=date('i',$start_time);
           $hour=date('Y-m-d H',$start_time).":00";
           if($minute<=30&&$minute>0){
              $hour=strtotime($hour);
           }
           if($minute>30){
              $hour=strtotime($hour)+1800;
           }
           $start_time=$hour;
        }
         $stockInsert=[];
         for ($j=0;$j<$num+2;$j++){
           $time=$start_time+(1800*$j);
           if($time>($start_time-1800)&&$time<($end_time+1800)){
               $stockInsert[]=[
                    'acid'=>$order->acid,
                    'date'=>strtotime(date('Y-m-d',$time)),
                    'house_id'=>$order->house_id,
                    'hour'=>$time,
                    'order_id'=>$order->id,
                    'store_id'=>$order->store_id,
                    'create_time'=>time(),
                    'update_time'=>time(),
                ];
           }
         }
        HouseStock::where(['order_id'=>$order->id])->update(['status'=>1,'order_id'=>0]);
        for ($i=0; $i <$num ; $i++) { 
          $time=$newStart_time+1800*$i;
          if($time>$end_time+1799){
            break;
          }
          $stockOrder=HouseStock::where([
                      'acid'=>$order->acid,
                      'date'=>strtotime(date('Y-m-d',$time)),
                      'house_id'=>$order->house_id,
                      'hour'=>$time,
                      'store_id'=>$order->store_id,
                  ])->find(); 
          if(!$stockOrder){
               $stockInsert[]=[
                    'acid'=>$order->acid,
                    'date'=>strtotime(date('Y-m-d',$time)),
                    'house_id'=>$order->house_id,
                    'hour'=>$time,
                    'order_id'=>$order->id,
                    'store_id'=>$order->store_id,
                    'create_time'=>time(),
                    'update_time'=>time(),
                ];
            }else{
                $stockOrder->order_id=$order->id;
                $stockOrder->status=0;
                $stockOrder->save();
            }
        }
        HouseStock::insertAll($stockInsert);
        $order->start_time=$start_time1;
        $order->end_time=$end_time;
        $order->save();
        $form=new HouseOrderDoorForm();
        $form->openRoom($order);
        return fetchJson([],'提前成功');
    }

}


