<?php
namespace app\shared\logic\pay;
use app\shared\model\CardOrder;
use app\shared\model\CardUser;
use app\shared\model\Card;
use app\shared\model\User;
use app\shared\model\Bill;
class CardOrderForm
{
    //获取数据
    public  function saveOrder($order_no='',$xml_array=[]){
        $order=CardOrder::where('order_no',$order_no)->find();
        if(!$order)return '';
        if($order->is_pay==1){
           if($order->pay_type==1){
                echo "success";
                exit();
            }else{
                return "success";
            }
        }
        $order->is_pay=1;
        $order->status=1;
        $order->xml_array=json_encode($xml_array);
        $order->pay_time=time();
        $order->save();
        //
        $cardUser=CardUser::where([
            'card_id'=>$order->card_id,
            'user_id'=>$order->user_id,
            'acid'=>$order->acid
        ])->find();
        $card=Card::find($order->card_id);
        if($card->month<=0){
            $card->month=1;
        }
        if(!$cardUser){
            $cardUser=new CardUser();
            $cardUser->card_id=$order->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->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->status=1;
        $cardUser->level=$card->level;
        $cardUser->save();
        $user=User::where('id',$order->user_id)->find();
        $user->level=$card->level;
        $user->save();
        $card->num-=1;
        $card->save();
        self::decUserBill($order);
        if($order->pay_type==1){
            echo "success";
            exit();
        }else{
            return "success";
        }
    }
     //减少用户账单
    public function decUserBill($order=[]){
        $user=User::where('id',$order['user_id'])->find();
        if($order->pay_type==2){
            $user->money-=$order['price'];
            $user->save();
        }
        $balance=$user->money;
        (new Bill())->save([
            'acid'=>$order->acid,
            'type'=>Bill::TYPE_CARD,
            'account_type'=>Bill::ACCOUNT_TYPE_USER,
            'form_id'=>$order['user_id'],
            'order_id'=>$order['id'],
            'price'=>$order['price'],
            'price_type'=>$order['pay_type'],
            'balance'=>$balance,
            'status'=>-1,
            'des'=>'用户: '.$user['nickname'].'购买会员卡'
        ]);
    }

}