<?php
namespace app\shared\logic\user;
use app\shared\model\User;
use app\shared\model\HouseOrder;
use app\shared\model\House;
use app\shared\model\TeaSpecialistOrder;
use app\shared\model\TeaSpecialist;
use app\shared\model\App;
use app\shared\model\Bill;
use app\shared\model\Coupon;
use app\shared\model\CouponUser;
use app\shared\model\WeixinUser;
use app\shared\model\WxSubscription;
use wechatpay\WechatPay;
use app\shared\model\Option;
use app\shared\model\Store;
use slock\Slock;
use think\exception\ValidateException;
use app\BaseController;
use think\facade\Db;
class TeaSpecialistOrderForm extends  UserForm
{
    //列表
	  public function list(){
        $query=TeaSpecialistOrder::alias('tso')
              ->leftJoin([TeaSpecialist::getTable()=>'ts'],'tso.tea_specialist_id=ts.id')
              ->leftJoin([HouseOrder::getTable()=>'ho'],'tso.house_order_id=ho.id')
              ->leftJoin([House::getTable()=>'h'],'ho.house_id=h.id')
              ->where(['tso.acid'=>$this->acid,'tso.user_id'=>$this->user_id]);
        $status=input('status');
        switch ($status) {
          case '0':
            $query->where('tso.status',$status);
            break;
          case '1':
            $query->where('tso.status',$status);
            break;
          case '2':
            $query->where('tso.status',$status);
            break;
          case '3':
            $query->where('tso.status',$status);
            break;
          case '4':
            $query->where('tso.status',$status);
          default:
            break;
        }
        $list=$query->limit(10)->page($this->page)->order('tso.id DESC')->field('tso.*,ts.nickname,ts.avatar_url,h.address')->select();
        $statusArray=[0=>'待支付',1=>'待接单',2=>'已接单',3=>'已完成',4=>'已取消'];
        foreach ($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']);
            $value['status_name']=isset($statusArray[$value['status']])?$statusArray[$value['status']]:'未知状态';
        }
        return fetchJson($list);
    }
    //提交预览
    public function submit_preview(){
          try {
            $data=request()->post();
            $rule = [
                 'house_order_id|订单ID' => 'require|number',
                 'tea_specialist_id|茶艺师ID' => 'require|number',
                 'start_time|开始时间'=>'require',
                 'end_time|结束时间'=>'require',
             ];
               $this->validate($data,$rule);
          }catch (ValidateException $e){
             return fetchJson([],$e->getError(),1);
         }
  	     $start_time=strtotime($data['start_time']);
  	     $end_time=strtotime($data['end_time']);
  	     if($start_time<time()){
  	         return fetchJson([],'预订时间已过',1);
  	     }
  	     if($end_time<time()){
  	          return fetchJson([],'预订时间已过',1);
  	     }
         $houseOrder=HouseOrder::where(['id'=>$data['house_order_id'],'is_pay'=>1,'user_id'=>$this->user_id])->where('status','in','1,2')->find();
         if(!$houseOrder){
         	 return fetchJson([],'暂无订单',1);
         }
         $teaSpecialist=TeaSpecialist::where(['id'=>$data['tea_specialist_id']])->where('status','in','1,2')->find();
         if(!$teaSpecialist){
         	  return fetchJson([],'暂无茶艺师',1);
         }
         if($teaSpecialist['status']==2){
            return fetchJson([],'茶艺师已在服务中，暂时不可预约呦',1);
         }
         $house=House::where('id',$houseOrder['house_id'])->field('address,lng,lat')->find();
         $hour=($end_time-$start_time)/3600;
         $pay_price=$teaSpecialist['service_price']*$hour;
         $coupon_user_id=input('coupon_user_id');
         if($coupon_user_id){
            $coupon_id=CouponUser::where(['id'=>$coupon_user_id,'is_use'=>0,'type'=>Coupon::TYPE_HOTEL,'user_id'=>$this->user_id])->value('coupon_id');
            $coupon=Coupon::where('id',$coupon_id)->find();
            if($coupon){
                if($coupon['full_price']<=$pay_price){
                  $pay_price-=$coupon['price'];
                }
            }
         }
         
         return fetchJson([
         	'pay_price'=>$pay_price,
         	'username'=>$houseOrder['username'],
         	'tel'=>$houseOrder['tel'],
         	'start_time'=>date('Y-m-d H:i',$start_time),
         	'end_time'=>date('Y-m-d H:i',$end_time),
         	'address'=>$house['address'],
         	'lng'=>$house['lng'],
         	'lat'=>$house['lat'],
          'service_price'=>$teaSpecialist['service_price'],
         	'nickname'=>$teaSpecialist['nickname'],
         	'avatar_url'=>$teaSpecialist['avatar_url'],
          'order_inform'=>Option::get_data($this->acid,'platform','wx_subscibe_tea_specia_order_inform')
         ]);
    }
    //提交订单
    public function submit(){
         try {
          $data=request()->post();
          $rule = [
               'house_order_id|订单ID' => 'require|number',
               'tea_specialist_id|茶艺师ID' => 'require|number',
               'start_time|开始时间'=>'require',
               'end_time|结束时间'=>'require',
           ];
             $this->validate($data,$rule);
         }catch (ValidateException $e){
             return fetchJson([],$e->getError(),1);
         }
  	     $start_time=strtotime($data['start_time']);
  	     $end_time=strtotime($data['end_time']);
  	     if($start_time<time()){
  	         return fetchJson([],'预订时间已过',1);
  	     }
  	     if($end_time<time()){
  	          return fetchJson([],'预订时间已过',1);
  	     }
         $houseOrder=HouseOrder::where(['id'=>$data['house_order_id'],'is_pay'=>1,'user_id'=>$this->user_id])->where('status','<>',4)->find();
         if(!$houseOrder){
         	 return fetchJson([],'暂无订单',1);
         }
         if($houseOrder->tea_specialist_id!=0){
             if(TeaSpecialistOrder::where(['house_order_id'=>$data['house_order_id'],'user_id'=>$this->user_id,'is_pay'=>1,'status'=>2])->count()){
                 return fetchJson([],'茶艺师已接单,您已预约过了。',1);
             }
             if(TeaSpecialistOrder::where(['house_order_id'=>$data['house_order_id'],'user_id'=>$this->user_id,'is_pay'=>1,'tea_specialist_id'=>$data['tea_specialist_id'],'status'=>1])->count()){
                 return fetchJson([],'您已预约了该茶艺师。',1);
             }
         }
         $teaSpecialist=TeaSpecialist::where(['id'=>$data['tea_specialist_id']])->where('status','in','1,2')->find();
         if(!$teaSpecialist){
            return fetchJson([],'暂无茶艺师',1);
         }
         if($teaSpecialist['status']==2){
            return fetchJson([],'茶艺师已在服务中，暂时不可预约呦',1);
         }
         $hour=($end_time-$start_time)/3600;
         $pay_price=$teaSpecialist['service_price']*$hour;
         $order=new TeaSpecialistOrder();
         $order->order_no=TeaSpecialistOrder::crateOrderNo();
         $order->acid=$this->acid;
         $order->user_id=$this->user_id;
         $order->tea_specialist_id=$data['tea_specialist_id'];
         $order->house_order_id=$data['house_order_id'];
         $order->start_time=$start_time;
         $order->end_time=$end_time;
         $order->price=$pay_price;
         $order->pay_price=$pay_price;
         $coupon_user_id=input('coupon_user_id');
         if($coupon_user_id){
            $couponUser=CouponUser::where(['id'=>$coupon_user_id,'is_use'=>0,'type'=>Coupon::TYPE_TEASPECIALIST,'user_id'=>$this->user_id])->find();
            $coupon=Coupon::where('id',$couponUser->coupon_id)->find();
            if($coupon){
                if($coupon->full_price<=$order->price){
                  $order->pay_price-=$coupon->price;
                  if($order->pay_price<0){
                    $order->pay_price=0;
                  }else{
                     $order->coupon_user_id=$coupon_user_id;
                     $couponUser->discounts_price=$coupon->price;
                     $couponUser->save();
                  }
                }
            }
         }
       	 $order->save();
         return fetchJson($order);
    }
    //支付订单
    public function orderPay(){
       $order_id=input('order_id');
       $order=TeaSpecialistOrder::where(['id'=>$order_id,'user_id'=>$this->user_id,'is_pay'=>0])->find();
       if(!$order){
          return fetchJson([],'暂无订单',1);
       }
       if(TeaSpecialistOrder::where(['house_order_id'=>$order->house_order_id,'user_id'=>$this->user_id,'is_pay'=>1,'status'=>2])->count()){
           return fetchJson([],'茶艺师已接单,您已预约过了。',1);
       }
       if(TeaSpecialistOrder::where(['house_order_id'=>$order->house_order_id,'user_id'=>$this->user_id,'is_pay'=>1,'tea_specialist_id'=>$order->tea_specialist_id,'status'=>1])->count()){
           return fetchJson([],'您已预约了该茶艺师。',1);
       }
       $order->order_no=TeaSpecialistOrder::crateOrderNo();
       $pay_type=input('pay_type')?input('pay_type'):1;
       $order->pay_type=$pay_type;
       $order->save();
        //判断是否用余额支付
       if($pay_type==2){
           $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,
       ];
       $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();
         if($user->money<$order->pay_price){
            return [
              'msg'=>'余额不足',
              'code'=>1
            ];
         }
         $form=new \app\shared\logic\pay\TeaSpecialistOrderForm();
         $res=$form->saveOrder($order->order_no);
         if($res=='success'){
            return [
              'msg'=>'支付成功',
              'code'=>0
            ];
         }
        return [
          'msg'=>'余额支付错误',
          'code'=>1
        ];
    }
    //详情
    public function details(){
        $order_id=input('order_id');
        $order=TeaSpecialistOrder::where(['id'=>$order_id,'user_id'=>$this->user_id])->find();
        if(!$order){
            return fetchJson([],'暂无订单',1);
        }
        $order['start_time']=date('Y-m-d H:s',$order['start_time']);
        $order['end_time']=date('Y-m-d H:s',$order['end_time']);
        $houseOrder=HouseOrder::where('id',$order['house_order_id'])->field('order_no,username,tel,house_id')->find();
        $order['house_order']=$houseOrder;
        $order['tea_specialist']=TeaSpecialist::where('id',$order['tea_specialist_id'])->field('nickname,avatar_url,binding tel,lng,lat')->find();
        $order['address']=House::where('id',$houseOrder['house_id'])->value('address');
        $statusArray=[0=>'待支付',1=>'待接单',2=>'已接单',3=>'已完成',4=>'已取消'];
        $order['status_name']=isset($statusArray[$order['status']])?$statusArray[$order['status']]:'未知状态';
        $couponUser=CouponUser::alias('a')
            ->leftJoin([Coupon::getTable()=>'b'],'a.coupon_id=b.id')
            ->where(['a.id'=>$order['coupon_user_id'],'a.type'=>Coupon::TYPE_TEASPECIALIST])
            ->field('a.discounts_price,b.name')->find();
        $order['discounts_name']=$couponUser['name'];
        $order['discounts_price']=$couponUser['discounts_price']>0?$couponUser['discounts_price']:0;
        return fetchJson($order,'获取成功');
    }
    //取消订单
    public function cancel(){
         $order_id=input('order_id');
         $order=TeaSpecialistOrder::where(['id'=>$order_id,'user_id'=>$this->user_id,'status'=>1,'is_pay'=>1])->find();
         if(!$order){
            return fetchJson([],'暂无订单',1);
         }
         if($order->refund_time>0){
            return fetchJson([],'已经退过了',1);
         }
         $user=User::where('id',$order->user_id)->find();
         $app=App::find($order->acid);
         if($order->pay_type==1){
             $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' => $order->pay_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);
            }
            $des="微信退款";
         }else{
            $des="余额退款";
            $user->money+=$order->pay_type;
            $user->save();
         }
        $order->refund_time=time();
        CouponUser::where(['id'=>$order->coupon_user_id])->update(['is_use'=>0,'use_time'=>0]);
        (new Bill())->save([
            'acid'=>$order->acid,
            'type'=>Bill::TYPE_TEASPECIALIST,
            'account_type'=>Bill::ACCOUNT_TYPE_TEASPECIALIST,
            'form_id'=>$order->user_id,
            'order_id'=>$order->id,
            'price'=>$order->pay_price,
            'price_type'=>$order->pay_type,
            'status'=>-1,
            'fee'=>0,
            'des'=>'用户: 【'.$user->nickname.'】茶艺师预约'
        ]);
        $order->status=4;
        $order->save();
        return fetchJson([],'退款成功');
    }
    //完成订单
    public function complete(){
    	  $order_id=input('order_id');
        $order=TeaSpecialistOrder::where(['id'=>$order_id,'user_id'=>$this->user_id,'status'=>2,'is_pay'=>1])->find();
        if(!$order){
            return fetchJson([],'暂无订单',1);
        }
        $teaSpecialist=TeaSpecialist::where(['id'=>$order->tea_specialist_id])->find();
        $order->status=3;
        $order->save();
        $teaSpecialist->status=1;
        $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=App::where('id',$this->acid)->find();
        $app['wx_subscibe_tea_specia_order_finish']=Option::get_data($this->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);
        return fetchJson([],'订单已完成');
    }
}
