<?php

namespace App\Modules\Trade\Pay;

use App\Modules\Subscribe\Models\Order;
use App\Modules\Subscribe\Models\YearOrder;


class QuarterOrderPaySuccess extends PaySuccessAbstract
{
    private $year_order;

    public function __construct(Order $order)
    {
        parent::__construct($order);
        $this->year_order = [];
        $this->year_order['uid'] = $order->uid;
        $this->year_order['distribution_channel_id'] = $order->distribution_channel_id;
        $this->year_order['fee'] = $order->price;
        $this->year_order['send_order_id'] = $order->send_order_id;
    }

    protected function handlePayProcess()
    {
        $this->year_order['begin_time'] = date('Y-m-d H:i:s');
        $this->year_order['end_time'] = date('Y-m-d H:i:s', strtotime('+92 day'));
        $old = YearOrder::where('uid', $this->year_order['uid'])->select('id', 'uid', 'u', 'begin_time', 'end_time', 'fee')->first();
        if ($old) {
            //如果包过年
            if (strtotime($old->end_time) > time()) {
                //旧的包年没过期
                $old->end_time = date('Y-m-d H:i:s', strtotime($old->end_time) + 86400 * 92);
                $old->fee = $old->fee + $this->year_order['fee'];
                $old->save();
            } else {
                //旧的包年过期了
                $old->end_time = date('Y-m-d H:i:s', strtotime('+92 day'));
                $old->fee = $old->fee + $this->year_order['fee'];
                $old->save();
            }
            return $old;
        } else {
            return YearOrder::firstOrCreate($this->year_order);
        }
    }
}
