<?php

namespace app\shared\logic\pay;
use app\shared\model\RechargeOrder;
use think\exception\ValidateException;
use app\shared\model\User;
use app\shared\model\Bill;
use app\shared\model\Card;
use app\shared\model\CardUser;
use app\shared\model\Coupon;
use app\BaseController;
use think\facade\Db;
class RechargeOrderForm{
	//支付回调
	public function saveOrder($order_no=null,$xml_array=[]){
		      $order=RechargeOrder::where('order_no',$order_no)->find();
          if(!$order){
            echo "success";
            exit();
          }
          if($order->is_pay==1){
            echo "success";
            exit();
          }
          $order->is_pay=1;
          $order->pay_time=time();
          $order->xml_array=json_encode($xml_array);
          $order->status=1;
          $order->save();
          $user=User::where('id',$order->user_id)->find();
          $money=$order->money+$order->give_price;
          $user->money=$user->money+$money;
          $user->save();
          (new Bill())->save([
              'acid'=>$order->acid,
              'type'=>Bill::TYPE_RECHARGE,
              'account_type'=>Bill::ACCOUNT_TYPE_USER,
              'form_id'=>$order->user_id,
              'order_id'=>$order->id,
              'price'=>$money,
              'price_type'=>1,
              'balance'=>$user->money,
              'status'=>1,
              'des'=>"用户:【{$user['nickname']}】充值金额"
          ]);
          
          $card_list=Card::where('id','in',$order->card_ids)->where(['acid'=>$order->acid,'is_delete'=>0])->select();
           foreach ($card_list as $card){
              $cardUser=CardUser::where([
                  'card_id'=>$card->id,
                  'user_id'=>$order->user_id,
                  'acid'=>$order->acid
              ])->find();
              if($card->month<=0){
                  $card->month=1;
              }
              if(!$cardUser){
                  $cardUser=new CardUser();
                  $cardUser->card_id=$card->id;
                  $cardUser->user_id=$order->user_id;
                  $cardUser->acid=$order->acid;
                  $cardUser->start_time=time();
                  $cardUser->end_time=strtotime(date("Y-m-d",strtotime("+{$card->month} month")));
                  $cardUser->status=1;
                  $cardUser->hour=$card->hour;
              }else{
                  $time=strtotime(date("Y-m-d",strtotime("+{$card->month} month")))-strtotime(date("Y-m-d",time()));
                  if($cardUser->status==0){
                      $cardUser->end_time=time()+$time;
                  }else{
                      $cardUser->end_time+=$time;
                  }
                  $cardUser->hour+=$card->hour;
              }
              $cardUser->level=$card->level;
              $cardUser->save();
           }
           Coupon::giveUserCoupon($order->user_id,4,$order->acid,$order->coupon_ids);
           echo "success";
	}
}