<?php
namespace app\task\controller;
use think\facade\Cache;
use app\shared\model\WxSubscription;
use app\shared\model\HouseOrder;
use app\shared\model\House;
use app\shared\model\HouseOrderContinue;
use app\shared\model\Store;
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\StoreCleaning;
use app\shared\model\Bill;
use app\shared\model\User;
use app\shared\model\WeixinUser;
use app\shared\model\Option;
use app\shared\model\ShareOrder;
use app\shared\model\TeaSpecialistOrder;
use app\shared\model\TeaSpecialist;
use app\shared\model\App;
use wechatpay\WechatPay;
use app\shared\model\Electricity;
use think\facade\Db;
use app\shared\controller\Task;
use app\shared\model\WxpayAccounting;
use app\shared\model\PartnerOrder;
use app\shared\model\PartnerUser;
use app\shared\model\Partner;
use app\shared\model\PartnerUserBill;
use app\shared\model\HouseStock;

//门锁回调
class Wechat
{
  //发送订阅消息
    public function sendSubscribe(){      
      $list=Cache::get('subscribeOrder');
      $list=json_decode($list,1);
      if(!$list){
         echo"no";
         //关闭绿米
         self::offLvmiEle();
         self::updteOrderStatus();
         self::updateSql();
         self::updataMeituan();
         //绿米复位
         self::updateLvmiReset();
         exit();
      }
      $listArray=[];
      $time=time();
      $start_time=$time;
      foreach ($list as $key => $value) {
          if($value['start_time']-900<=$start_time&&$value['end_time']+300>$time){
                 $order=Cache::get('subscribeOrder'.$value['order_id']);
                 $order=json_decode($order,1);
                 if($order){
                    $form=new WxSubscription();
                  //提前15分钟发送消息
                  if($order['order']['start_time']-900<$time&&$order['book_inform']==0){
                     $res=$form->sendMsg($order['app'],'shared','wx_subscibe_book_inform',$order['order']['openid'],$order['order']);
                     $order['book_inform']=1;
                  }
                  if($order['order']['end_time']-900<$time&&$order['book_overtime']==0){
                     $order['book_overtime']=1;
                     $res=$form->sendMsg($order['app'],'shared','wx_subscibe_book_overtime',$order['order']['openid'],$order['order']);
                     self::couldSoundPlayTxt($value['order_id'],1);
                  }
                  if($order['order']['end_time']-300<$time&&$order['book_finish']==0){
                     $order['book_finish']=1;
                     $res=$form->sendMsg($order['app'],'shared','wx_subscibe_book_finish',$order['order']['openid'],$order['order']);
                     self::couldSoundPlayTxt($value['order_id'],2);
                  }
                  if($order['order']['end_time']<$time){
                  }else{
                    $order=Cache::set('subscribeOrder'.$value['order_id'],json_encode($order));
                    $listArray[]=$value;
                  }
                 }
            }else{
              $listArray[]=$value;
            }
      }
      Cache::set('subscribeOrder',json_encode($listArray));
      //关闭绿米
      self::offLvmiEle();
      self::updteOrderStatus();
      echo"success";
      self::updateSql();
      self::updataMeituan();
      //绿米复位
      self::updateLvmiReset();
    }
    //播放云喇叭
    public function couldSoundPlayTxt($order_id=0,$type=1){
       $house_id=HouseOrder::where('id',$order_id)->value('house_id');
       $could_sound=House::where('id',$house_id)->value('could_sound');
       $could_sound=json_decode($could_sound,1);
       if(!$could_sound) return 0;
       if(isset($could_sound['could_sound_id'])){
           $could_sound_id=$could_sound['could_sound_id'];
           $could_sound_token=$could_sound['could_sound_token'];
           $could_sound_version=$could_sound['could_sound_version'];
       }else{
          return 0;
       }
       if($type==1){
          $could_sound_content=$could_sound['could_sound_repeat_content'];
       }else{
          $could_sound_content=$could_sound['could_sound_finish_content'];
       }
       $url="https://speaker.17laimai.cn/notify.php?id={$could_sound_id}&token={$could_sound_token}&version={$could_sound_version}&message={$could_sound_content}";
       httpRequest($url);
    }
    //绿米复位
    public function updateLvmiReset(){
      $list=Electricity::where(['status'=>2])->where('reset_time',">",0)->where('reset_time',"<",time())->column('id,line,mac,order_id,config');
      foreach ($list as $value){
           $data['electronic_id']=$value['id'];
           $form=new Task();
            //绿米
           $form->lvmiotherele($value['mac'],$value['config'],-1);
           Electricity::where(['id'=>$value['id']])->update(['status'=>3]);
       }
    }
    public function updataMeituan(){
       $find=Option::get_data(1,'platform','app_meituan_dianping');
       $find=json_decode($find,1);
       if(isset($find['alldata'])&&isset($find['create_time'])){
          if(isset($find['alldata']['expires_in'])&&isset($find['create_time'])){
               $create_time=$find['create_time'];
               $expires_in=$find['alldata']['expires_in'];
               $time=$create_time+$expires_in-7200;
               $remain_refresh_count=$find['alldata']['remain_refresh_count'];
               //进入刷新access_token
               if(time()>$time&&$remain_refresh_count>0){
                    $refresh_token=$find['alldata']['refresh_token'];
                    $form=new \app\meituan\controller\Index();
                    $res=$form->refreshToken($refresh_token);
                    if($res['code']==0){
                        //保存session了
                        $find['create_time']=time();
                        $find['alldata']['remain_refresh_count']=$res['data']['remain_refresh_count'];
                        $find['alldata']['refresh_token']=$res['data']['refresh_token'];
                        $find['bid']=$res['data']['bid'];
                        $find['session']=$res['data']['access_token'];
                        $find['alldata']['remain_refresh_count']=$res['data']['remain_refresh_count'];
                        Option::set_data(1,'platform','app_meituan_dianping',json_encode($find));
                    }
               }
          }
            
       }
    }
    //绿米关电
    private function offLvmiEle(){
       $list=Electricity::where(['status'=>1])->where('end_time',"<",time())->column('id,line,mac,order_id');
       foreach ($list as $value){
           $data['electronic_id']=$value['id'];
           $form=new Task();
           if($value['line']==''||$value['line']=='-1'){
                //绿米
               $form->lvreceiveOn($data);
               sleep(1);
            }else{
               //曼顿
               $form->receiveOn($data);
               sleep(1);
            }
       }
    }
    private function sendTplMsg($orderInfo){
            $order=Cache::get('subscribeOrder'.$orderInfo['id']);
            $order=json_decode($order,1);
             //发送保洁人员
            $weixin=new \weixin\Wechat();
            $data=[
                "first"    =>[
                  "value"  =>"打扫提醒",
                  "color"  =>"#173177"
                ],
                "keyword1" =>[
                  "value"  =>$order['order']['title'],//房间名称：
                  "color"  =>"#173177"
                ],
                "keyword2" =>[
                  "value"  =>$order['order']['store_name'],//保洁员：
                  "color"  =>"#173177"
                ],
                "keyword3" =>[
                  "value"  =>"共享茶室",//保洁类型：
                  "color"  =>"#173177"
                ],
                "keyword4" =>[
                  "value"  =>date('Y-m-d H:i:s',$order['order']['end_time']), //保洁时间：
                  "color"  =>"#173177"
                ],
                "remark"   =>[
                  "value"  =>"辛苦了~",
                  "color"  =>"#173177"
                ]
            ];
            if(isset($order['order']['cleaning_openid'])){
                $openidArr=explode(',',$order['order']['cleaning_openid']);
                //$order['order']['page']
                foreach ($openidArr as $openid) {
                  $res=$weixin->sendWxopenTemplate($order['app'],$order['wx_template']['cleaning_inform'],$openid,"storeManager/cleaner/index",$data);

                }
            }
            self::sendCleaning($order,$orderInfo);
            Cache::set('subscribeOrder'.$orderInfo->id,0,1);
    }
    //保存订单状态
    public function updteOrderStatus(){
         $list=HouseOrder::where(['is_pay'=>1])->where('status','in','1,2')->where('end_time','<',time())->column('id,start_time,end_time');
         foreach ($list as $value){
              $end_time=HouseOrderContinue::where(['order_id'=>$value['id'],'is_pay'=>1])->order('id DESC')->value('end_time');
              if($end_time<time()){
                $order=HouseOrder::where(['id'=>$value['id']])->find();
                self::addStoreBill($order);
                self::teaSpecialistcomplete($order);
                self::sendTplMsg($order);
              }
         }
    }
    //提前结束订单
    public function endOrdersEarly($order=[]){
        if($order->is_pay==1){
            self::addStoreBill($order);
            self::teaSpecialistcomplete($order);
            self::sendTplMsg($order);
            HouseStock::where(['order_id'=>$order->id])->update(['status'=>1,'order_id'=>0]);
            $list=Electricity::where(['status'=>1,'order_id'=>$order->id])->column('id,line,mac,order_id');
            foreach ($list as $value){
               $data['electronic_id']=$value['id'];
               $form=new Task();
               if($value['line']==''||$value['line']=='-1'){
                    //绿米
                   $form->lvreceiveOn($data,1);
                   sleep(1);
                }else{
                   //曼顿
                   $form->receiveOn($data,1);
                   sleep(1);
                }
            }
            self::couldSoundPlayTxt($order->id,2);
        }
    }
    //发送保洁员信息
    public function sendCleaning($order=[],$orderInfo=[]){
       $form=new WxSubscription();
       $snapshoot=json_decode($orderInfo['snapshoot'],1);
       $order['order']['address']=$snapshoot['address'];
       $order['order']['page']='storeManager/cleaner/index';
       $accounts=StoreCleaning::where(['store_id'=>$orderInfo['store_id'],'is_delete'=>0,'status'=>1])->column('account');
       // $list=WeixinUser::where('mobile','in',$accounts)->column('wxapp_open_id');
       // if(!isset($order['app']))return false;
       // foreach ($list as $openid){
       //    $form->sendMsg($order['app'],'shared','wx_subscibe_book_sweep',$openid,$order['order']);
       // }
       self::sendCleaningTpl($orderInfo);
       //发送手机短信
       $config=Option::get_data($orderInfo['acid'],'shared','cloudSheetConfig');
       $res=[];
       if($config){
          $config=json_decode($config,1);
          $could=new  \CloudSheet\CloudSheet($config['title'],$config['apiKey']);
          $title="保洁工作人员您好，有新的茶室结束订单,请前往：{$order['order']['address']}进行打扫";
          foreach ($accounts as $phone){
             $could->SendMsg($title,$phone);
          }
      }             
    }
    //保洁端用户下单提醒
    public function sendCleaningTpl($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"  =>'请前往打扫~',
              "color"  =>"#173177"
            ]
        ];
        $app=App::find($order->acid);
        $tpl=Option::get_data($order->acid,'platform','wx_template_cleaning_port_inform');
        foreach($cleaning as $value){
            $res=$weixin->sendWxopenTemplate($app,$tpl,$value['openid'],"storeManager/cleaner/index",$data);
            \app\shared\model\MessageLog::pushMsg($order->acid,$value['account'],$order->order_no,json_encode($data,JSON_UNESCAPED_UNICODE),json_encode($res));
        }
    }
    //增加商户账单
    private function addStoreBill($order=[]){
        if($order->status==3){
          return false;
        }
        $order->status=3;
        $order->save();
        $store=Store::where('id',$order->store_id)->find();
        if($order->pay_type==3){
            (new Bill())->save([
                'acid'=>$order['acid'],
                'type'=>Bill::TYPE_STORE_USER_HOUSE,
                'account_type'=>Bill::ACCOUNT_TYPE_STORE,
                'form_id'=>$order->store_id,
                'order_id'=>$order->id,
                'price'=>$order->price,
                'price_type'=>$order->pay_type,
                'status'=>1,
                'balance'=>$store->money,
                'fee'=>0,
                'des'=>'商户: 【'.$store->name.'】茶室用户商户储值卡支付收入'
            ]);
            return false;
        }
        if($order->meituan_price>0){
            $order->price=$order->meituan_price;
        }  
        $fee=($store->fee*0.01)*$order->price;
        $fee=$fee>0?$fee:0;//手续费
        $orderPrice=$order->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();
        $wxpayAccounting=self::WxpayAccounting($store,$order,$order->pay_price);
        if($wxpayAccounting['code']==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'=>$wxpayAccounting['data']->total_fee,
                'price_type'=>$order->pay_type,
                'balance'=>$store->money,
                'status'=>1,
                'fee'=>$fee,
                'des'=>'商户: 【'.$store->name.'】茶室收入'.$wxpayAccounting['data']->total_fee.'分账金额'.$wxpayAccounting['data']->sub_price
            ]);
           //进行了分账
           return false;
        }     
        //分红金额
        $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('id,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,
                'balance'=>$store->money,
                'status'=>1,
                'fee'=>$fee,
                'des'=>'商户: 【'.$store->name.'】茶室收入其中股东分红扣除'.$sharePrice.'元'
            ]);
            $store->money+=$orderPrice-$sharePrice;
        }else{
            //
            //if($wx)
            (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,
                'balance'=>$store->money,
                'status'=>1,
                'fee'=>$fee,
                'des'=>'商户: 【'.$store->name.'】茶室收入'
            ]);
            $store->money+=$orderPrice-$sharePrice;
        }        
        $store->save();
        $user_parent_id=User::where(['id'=>$order->user_id])->value('parent_id');
        $parent=PartnerUser::where(['user_id'=>$user_parent_id,'status'=>1])->find();
        if($parent){
            self::partnerShareBill($order,$parent);
        }else{
            self::shareOrder($order);
        }
    }
    //合伙人分销订单
    public function partnerShareBill($order=[],$parent1=[]){
        $nickname=User::where(['id'=>$order->user_id])->value('nickname');
        $partner1=Partner::where(['id'=>$parent1->partner_id])->find();
        $price=$order->pay_price*$partner1->one_level*0.01;
        $parent1->total_price+=$price;
        $parent1->price+=$price;
        $parent1->save();

        //一级分销佣金
        if($price>0){
            (new PartnerUserBill())->save([
                'acid'=>$order->acid,
                'user_id'=>$parent1->id,
                'order_id'=>$order->id,
                'title'=>$nickname.'预定茶室一级佣金',
                'lngot'=>0,
                'price'=>$price,
                'type'=>2,
                'status'=>1
            ]);
        }
        //二级分销佣金
        $parent2=PartnerUser::where(['user_id'=>$parent1->parent_id])->find();
        if($parent2){
            $partner2=Partner::where(['id'=>$parent2->partner_id])->find();
            $price2=$order->pay_price*$partner2->two_level*0.01;
            $parent2->total_price+=$price2;
            $parent2->price+=$price2;
            $parent2->save();
            if($price2>0){
                (new PartnerUserBill())->save([
                    'acid'=>$order->acid,
                    'user_id'=>$parent2->id,
                    'order_id'=>$order->id,
                    'title'=>$nickname.'预定茶室二级佣金',
                    'lngot'=>0,
                    'price'=>$price2,
                    'type'=>2,
                    'status'=>1
                ]);
            }
        }
    }
    //微信分账
    public function WxpayAccounting($store,$order,$total_fee=1){
        
       if(!$order){
          return ['code'=>1];
       }
       if($order['pay_type']==2){
          return ['code'=>1];
       }
       if($order['pay_type']==3){
          return ['code'=>1];
       }
       $app=App::find($order->acid);
       if($app->wx_profit_sharing==0){
          return ['code'=>1];
       }
       if($app->wx_pay_type==1){
           $wx_config=[
              'appid'=>$app->wxapp_app_id,
              'mchid'=>$store['wx_mch_id'],
              'appsecret'=>$app->wxapp_app_secret,
              'key'=>$store['wx_key'],
              'sslcert'=>$store['wx_sslcert'],//$app->wx_cert_pem,
              'sslkey'=>$store['wx_sslkey'],//$app->wx_key_pem,
              'sub_mch_id'=>$app->wx_mch_id,
              'wx_pay_type'=>$app->wx_pay_type,
           ];
       }else{
           $wx_config=[
              'appid'=>$app->wxapp_app_id,
              'mchid'=>$app->wx_mch_id,
              'wx_server_appid'=>$app->wx_server_appid,
              'appsecret'=>$app->wxapp_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'=>$app->wxapp_app_id,
              'sub_mch_id'=>$app->wx_mch_id,
              'wx_pay_type'=>$app->wx_pay_type,
           ];
       }
      
       $is_server=$app->wx_pay_type==2?1:0;
       $xml_array=json_decode($order['xml_array'],1);
       $order_no=WxpayAccounting::crateOrderNo("FZ".$order->store_id."S");
       $store_fee=Store::where('id',$order->store_id)->value('fee');
       if($store_fee>30){
          //根据分账要求最多只能分账微信的百分之30
          $store_fee=29;
       }
       if($store_fee<=0){
          return ['code'=>1];
       }
       $form=new WechatPay($wx_config);
       $account=$app->wx_mch_id;
       $companyName=$app->wx_mch_name;
       $amount=$total_fee*$store_fee;//分账金额（分）
       $out_trade_no=$xml_array['out_trade_no'];//订单号
       $transaction_id=$xml_array['transaction_id'];//微信交易订单号
       $res=$form->profitsharingaddreceiver($account,$companyName,$is_server);
       if($res['code']==1){
          return ['code'=>1];
        //return fetchJson([],$res['msg'],1);
       }
       $res=$form->profitsharing($order_no,$transaction_id,$account,$amount,$companyName,$is_server);
       if($res['code']==0){
        if($res['data']['result_code']=="SUCCESS"){
          $form=new WxpayAccounting();
          $form->acid=$order->acid;
          $form->store_id=$order->store_id;
          $form->order_id=$order->id;
          $form->appid=$xml_array['appid'];
          $form->mch_id=$xml_array['mch_id'];
          $form->openid=$xml_array['openid'];
          $form->order_no=$order_no;
          $form->out_trade_no=$xml_array['out_trade_no'];
          $form->transaction_id=$xml_array['transaction_id'];
          $form->total_fee=$xml_array['total_fee']*0.01;
          $form->sub_price=$amount*0.01;
          $form->sub_account=$account;
          $form->sub_type=1;
          $form->save();
          return ['code'=>0,'data'=>$form];
          //return fetchJson($res,"分账成功");
        }else{
          return ['code'=>1];
          //return fetchJson([],$res['data']['err_code_des'],1);
        }
       }else{
         return ['code'=>1];
         //return fetchJson("",$res['msg'],1);
         }

    }
    //分销订单
    private function  shareOrder($order=[]){
        $share_setting=Option::get_data($order->acid,'platform','app_share_setting');
        $share_setting=json_decode($share_setting,1);
        $xorderPrice=HouseOrderContinue::where(['status'=>1,'order_id'=>$order->id])->sum('pay_price');
        if($xorderPrice<0||empty($xorderPrice)){
          $xorderPrice=0;
        }
        if(isset($share_setting['status'])){
             if($share_setting['status']){
                //一级
                $parent1_id=User::where('id',$order->user_id)->value('parent_id');
                if($share_setting['one']>0){
                    if($parent1_id){
                        $price=$share_setting['one']*0.01*($order->pay_price+$xorderPrice);
                        self::shareUserMoney($order,$parent1_id,$price,$order->user_id);
                    }
                }
                //二级
                if($share_setting['two']>0){
                    if($parent1_id){
                        $parent2_id=User::where('id',$parent1_id)->value('parent_id');
                        $price=$share_setting['one']*0.01*($order->pay_price+$xorderPrice);
                        if($parent2_id){
                            self::shareUserMoney($order,$parent2_id,$price,$parent1_id);
                        }
                    }
                }
             }
        }
    }
    private function shareUserMoney($order=[],$user_id=0,$price=0,$child_userid=0){
        if($price>0){
            $user=User::where('id',$user_id)->find();
            if(!$user){
                return false;
            }
            $user->price+=$price;
            $user->total_price+=$price;
            $user->save();
            $shareOrder=new ShareOrder();
            $shareOrder->save([
                'acid'=>$order->acid,
                'user_id'=>$user_id,
                'form_user_id'=>$child_userid,
                'user_type'=>ShareOrder::USER_TYPE_USER,
                'type'=>ShareOrder::TYPE_HOUSE,
                'order_id'=>$order->id,
                'price'=>$price,
                'status'=>2,
                'pay_time'=>time()
            ]);
            (new Bill())->save([
                'acid'=>$order->acid,
                'type'=>Bill::TYPE_SHARE,
                'account_type'=>Bill::ACCOUNT_TYPE_USER,
                'form_id'=>$user_id,
                'order_id'=>$shareOrder->id,
                'price'=>$price,
                'price_type'=>$order['pay_type'],
                'status'=>1,
                'des'=>'分销佣金:茶室预订'
            ]);
        }
    }
    //茶艺师完成订单
    public function teaSpecialistcomplete($orderInfo){
        $order=TeaSpecialistOrder::where(['house_order_id'=>$orderInfo['id'],'is_pay'=>1])->where('status','in','1,2')->find();
        if(!$order){
            return false;
        }
         $app=App::where('id',$order->acid)->find();
        if($order->status==1){
            //退款
            $user=User::where('id',$order['user_id'])->find();
            if($order['pay_type']==2){
                 $user->money+=$order['pay_price'];
                 $user->save();
            }else{
                 $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,
                 ];
                 $wechatPay=new WechatPay($wx_config);
                 $notify_url='https://chashi-demo.youdiy.cn';
                 $order->out_order_no=TeaSpecialistOrder::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,//全额退款
                    'notify_url' => $notify_url,
                ];
                $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->refund_time=time();
            }
            (new Bill())->save([
                'acid'=>$order->acid,
                'type'=>Bill::TYPE_TEASPECIALIST,
                'account_type'=>Bill::ACCOUNT_TYPE_USER,
                'form_id'=>$order['user_id'],
                'order_id'=>$order['id'],
                'price'=>$order['pay_price'],
                'price_type'=>$order['pay_type'],
                'status'=>1,
                'des'=>'用户: '.$user->nickname.'茶艺师预约'
            ]);
            $order->status=4;
            $order->save();
            return false;
        }
        $teaSpecialist=TeaSpecialist::where(['id'=>$order['tea_specialist_id']])->find();
        $order->status=3;
        $teaSpecialist->status=1;
        $order->save();
        $fee=($teaSpecialist->fee*0.01)*$order['price'];
        $fee=$fee>0?$fee:0;
        $teaSpecialist->total_price+=$order['price']-$fee;
        $teaSpecialist->price+=$order['price']-$fee;
        $teaSpecialist->stay_price-=$order['price']-$fee;
        $teaSpecialist->save();
        (new Bill())->save([
            'acid'=>$order->acid,
            'type'=>Bill::TYPE_TEASPECIALIST,
            'account_type'=>Bill::ACCOUNT_TYPE_TEASPECIALIST,
            'form_id'=>$order['tea_specialist_id'],
            'order_id'=>$order['id'],
            'price'=>$order['price']-$fee,
            'price_type'=>$order['pay_type'],
            'fee'=>$fee,
            'status'=>1,
            'des'=>'茶艺师: 【'.$teaSpecialist->nickname.'】收入'
        ]);
        //通知用户
       
        $app['wx_subscibe_tea_specia_order_finish']=Option::get_data($order->acid,'platform','wx_subscibe_tea_specia_order_finish');
        $openid=WeixinUser::where(['mobile'=>$teaSpecialist['binding']])->value('wxapp_open_id');
        $houseOrder=HouseOrder::where(['id'=>$order['house_order_id']])->find();
        $snapshoot=json_decode($houseOrder['snapshoot'],1);
        $address=$snapshoot['address'];
        $msg=[
            'page'=>"teaOrder/orderDetail?id={$order['id']}",
            'username'=>$houseOrder['username'],
            'time'=>date('Y-m-d H:i',$order['start_t2ime']),
            'dec'=>"感谢您的服务~"
        ];
        $form=new WxSubscription();
        $res=$form->sendMsg($app,'shared','wx_subscibe_tea_specia_order_finish',$openid,$msg);
    }
    //更新数据库
    private function updateSql(){
        if(Cache::get('system_version')){
            return false;
         }else{
             Cache::set('system_version',1,120);
         }
        $version= Option::get_data('-1','admin','system_version');
        if(!$version){
            Option::set_data('-1','admin','system_version','1.0.0');
            $version="1.0.0";
        }
        $path_version=[];
        foreach(explode('.',$version) as $version_v_index=>$version_v){
          if($version_v_index<2){
            $path_version[]=$version_v;
          }else{
            break;
          }
        }
        $path_version=implode($path_version,'.');
        $path_version=(string)$path_version;
        $path=app()->getRootPath().'sql/'.$path_version.'/';
        if(!is_dir($path)){
            return 0;
        }
        $data = scandir($path);
        $array=[];
        foreach ($data as $key => $value) {
            if(strpos($value,'.sql') !== false){
                $updSql=$path.$value;
                $val=str_replace('.sql','',$value);
                $array[]=$val;
            }
        }
        $array=sortVersion($array);
        foreach ($array as $k => $vl) {
             $version= Option::get_data('-1','admin','system_version');
             $updata=version_compare($version,$vl);
             if($updata==-1||$updata==0){
                $newversion=QyVersionsInc($vl);
                //处理SQL
                 Option::set_data('-1','admin','system_version',$newversion);
                 $sql = Sql::getSqlFromFile($path.$vl.'.sql');  
                 foreach ($sql as $v) {  
                    @Db::execute($v);
                 }
            }else{
                continue;
            }
        }
    }
}
class Sql
{
    /**
     * 从sql文件获取纯sql语句
     * @param  string $sql_file sql文件路径
     * @param  bool $string 如果为真，则只返回一条sql语句，默认以数组形式返回
     * @param  array $replace 替换前缀，如：['my_' => 'me_']，表示将表前缀"my_"替换成"me_"
     *         这种前缀替换方法不一定准确，比如正常内容内有跟前缀相同的字符，也会被替换
     * @return mixed
     */
   static public function getSqlFromFile($sql_file = '', $string = false, $replace = [])
    {
        if (!file_exists($sql_file)) {
            return false;
        }

        // 读取sql文件内容
        $handle = self::read_file($sql_file);

        // 分割语句
        $handle = self::parseSql($handle, $string, $replace);

        return $handle;
    }

    /**
     * 分割sql语句
     * @param  string $content sql内容
     * @param  bool $string 如果为真，则只返回一条sql语句，默认以数组形式返回
     * @param  array $replace 替换前缀，如：['my_' => 'me_']，表示将表前缀my_替换成me_
     * @return array|string 除去注释之后的sql语句数组或一条语句
     */
    public static function parseSql($content = '', $string = false, $replace = [])
    {
        // 被替换的前缀
        $from = '';
        // 要替换的前缀
        $to = '';

        // 替换表前缀
        if (!empty($replace)) {
            $to   = current($replace);
            $from = current(array_flip($replace));
        }

        if ($content != '') {
            // 纯sql内容
            $pure_sql = [];

            // 多行注释标记
            $comment = false;

            // 按行分割，兼容多个平台
            $content = str_replace(["\r\n", "\r"], "\n", $content);
            $content = explode("\n", trim($content));

            // 循环处理每一行
            foreach ($content as $key => $line) {
                // 跳过空行
                if ($line == '') {
                    continue;
                }

                // 跳过以#或者--开头的单行注释
                if (preg_match("/^(#|--)/", $line)) {
                    continue;
                }

                // 跳过以/**/包裹起来的单行注释
                if (preg_match("/^\/\*(.*?)\*\//", $line)) {
                    continue;
                }

                // 多行注释开始
                if (substr($line, 0, 2) == '/*') {
                    $comment = true;
                    continue;
                }

                // 多行注释结束
                if (substr($line, -2) == '*/') {
                    $comment = false;
                    continue;
                }

                // 多行注释没有结束，继续跳过
                if ($comment) {
                    continue;
                }

                // 替换表前缀
                if ($from != '') {
                    $line = str_replace('`'.$from, '`'.$to, $line);
                }

                // sql语句
                array_push($pure_sql, $line);
            }

            // 只返回一条语句
            if ($string) {
                return implode($pure_sql, "");
            }

            // 以数组形式返回sql语句
            $pure_sql = implode($pure_sql, "\n");
            $pure_sql = explode(";\n", $pure_sql);
            return $pure_sql;
        } else {
            return $string == true ? '' : [];
        }
    }

    /**
     * 读取文件内容
     * @param $filename  文件名
     * @return string 文件内容
     */
    public static function read_file($filename) {
        $content = '';
        if(function_exists('file_get_contents')) {
            @$content = file_get_contents($filename);
        } else {
            if(@$fp = fopen($filename, 'r')) {
                @$content = fread($fp, filesize($filename));
                @fclose($fp);
            }
        }
        return $content;
    }
}