<?php

namespace Modules\User\Models;

use App\Models\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Modules\Payment\Traits\WithPayments;
use Modules\User\Events\UserOrderPaid;
use Modules\User\Models\Traits\OrderActions;
use Modules\User\Traits\BelongsToUser;

class Order extends Model
{

    use WithPayments,
        OrderActions,
        BelongsToUser;

    protected $table = 'user_orders';

    const STATE_INIT    = 'INIT';
    const STATE_SUCCESS = 'SUCCESS';
    const STATE_REFUND  = 'refund';

    const  STATES = [
        self::STATE_INIT    => '待审核',
        self::STATE_SUCCESS => '已支付',
        self::STATE_REFUND  => '已退款',
    ];

    const TYPE_OPEN  = 1;
    const TYPE_RENEW = 2;

    const  TYPES = [
        self::TYPE_OPEN  => '开通',
        self::TYPE_RENEW => '续费',
    ];

    const CHANNEL_IDENTITY   = 1;
    const CHANNEL_EXPERIENCE = 2;
    const CHANNEL_PARTNER    = 3;

    const  CHANNELS = [
        self::CHANNEL_IDENTITY   => '开通身份',
        self::CHANNEL_EXPERIENCE => '开通体验官',
        self::CHANNEL_PARTNER    => '开通合伙人',
    ];

    public $casts = [
        'source' => 'json'
    ];

    public function identity(): BelongsTo
    {
        return $this->belongsTo(Identity::class, 'identity_id');
    }

    /**
     * Notes: 设置订单支付
     * @Author: 玄尘
     * @Date  : 2020/11/12 11:19
     */
    public function pay()
    {
        $this->state = self::STATE_SUCCESS;
        $this->save();

        event(new UserOrderPaid($this));
    }

    /**
     * Notes: 是否可以支付
     * @Author: 玄尘
     * @Date  : 2021/6/4 10:19
     * @return bool
     */
    public function canPay(): bool
    {
        return $this->state == self::STATE_INIT;
    }

    /**
     * Notes: 是否可以退款
     *
     * @Author: 玄尘
     * @Date: 2022/8/22 13:18
     * @return bool
     */
    public function canRefund(): bool
    {
        return $this->isPay();
    }

  


}
