<?php

namespace Modules\Mall\Models;

use App\Models\Model;
use App\Traits\OrderByIdDesc;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Modules\Mall\Models\Traits\BelongsToOrder;
use Modules\Mall\Models\Traits\BelongsToShop;
use Modules\Mall\Models\Traits\RefundActions;
use Modules\Mall\Traits\WithWorkflow;
use Modules\User\Traits\BelongsToUser;
use Overtrue\LaravelVersionable\Versionable;

class Refund extends Model
{

    use BelongsToOrder,
        BelongsToShop,
        BelongsToUser,
        OrderByIdDesc,
        Versionable,
        WithWorkflow,
        RefundActions,
        SoftDeletes;

    protected $table = 'mall_refunds';

    /**
     * 不参与版本记录的字段
     * @var array|string[]
     */
    protected array $dontVersionable = ['updated_at'];

    const REFUND_APPLY     = 'REFUND_APPLY';        // 申请退款
    const REFUND_AGREE     = 'REFUND_AGREE';        // 同意退款
    const REFUND_REFUSE    = 'REFUND_REFUSE';       // 拒绝退款
    const REFUND_PROCESS   = 'REFUND_PROCESS';      // 退款中
    const REFUND_DELIVER   = 'REFUND_DELIVER';      // 客户退货，等待签收
    const REFUND_DELIVERED = 'REFUND_DELIVERED';    // 客户退货，等待签收
    const REFUND_SIGNED    = 'REFUND_SIGNED';       // 已签收
    const REFUND_COMPLETED = 'REFUND_COMPLETED';    // 退款完成

    const STATUS_MAP = [
        self::REFUND_APPLY     => '申请退款',
        self::REFUND_AGREE     => '同意退款',
        self::REFUND_REFUSE    => '拒绝退款',
        self::REFUND_DELIVER   => '等待客户退货',
        self::REFUND_DELIVERED => '客户退货，等待签收',
        self::REFUND_SIGNED    => '已签收',
        self::REFUND_PROCESS   => '退款中',
        self::REFUND_COMPLETED => '退款完成',
    ];

    /**
     * @var array
     */
    protected $dates = [
        'refunded_at',
    ];

    public static function boot()
    {
        parent::boot();

        self::creating(function ($model) {
            $model->state = self::REFUND_APPLY;

            $time = explode(' ', microtime());

            $counter = $model->whereDate('created_at', Carbon::today())->count() + 1;

            $len    = config('mall.refund_no_counter_length');
            $prefix = config('refund_no_counter_prefix');

            $len = $len < 6 ? 6 : $len;
            $len = $len > 16 ? 16 : $len;

            $model->refund_no = $prefix . date('YmdHis') .
                                sprintf('%06d', $time[0] * 1e6) .
                                sprintf('%0' . $len . 'd', $counter);
        });
    }

    /**
     * 获取该模型的路由的自定义键名
     * @return string
     */
    public function getRouteKeyName(): string
    {
        return 'refund_no';
    }

    /**
     * Notes: 退款单详情
     * @Author: <C.Jason>
     * @Date  : 2019/11/22 4:25 下午
     * @return HasMany
     */
    public function items(): HasMany
    {
        return $this->hasMany(RefundItem::class);
    }

    /**
     * Notes: 退款单物流
     * @Author: <C.Jason>
     * @Date  : 2019/11/22 4:25 下午
     * @return HasOne
     */
    public function express(): HasOne
    {
        return $this->hasOne(RefundExpress::class);
    }

    /***
     * Notes: 获取状态
     * @Author: 玄尘
     * @Date  : 2021/5/18 11:50
     */
    public function getStatusTextAttribute(): string
    {
        return self::STATUS_MAP[$this->state] ?? '---';
    }

    /**
     * Notes: 获取退款状态
     * @Author: <C.Jason>
     * @Date  : 2019/11/22 4:25 下午
     * @return string
     */
    protected function getStateTextAttribute(): string
    {
        switch ($this->state) {
            case self::REFUND_APPLY:
                $state = '退款申请中';
                break;
            case self::REFUND_AGREE:
                $state = '同意退款';
                break;
            case self::REFUND_PROCESS:
                $state = '退款中，请等待商家打款';
                break;
            case self::REFUND_COMPLETED:
                $state = '退款完毕';
                break;
            case self::REFUND_REFUSE:
                $state = '拒绝退款';
                break;
            case self::REFUND_DELIVER:
                $state = '您的申请已经通过，请将商品退回给商家';
                break;
            case self::REFUND_DELIVERED:
                $state = '客户退货，等待签收';
                break;
            case self::REFUND_SIGNED:
                $state = '店家已签收，等待打款';
                break;
            default:
                $state = '未知状态';
                break;
        }

        return $state;
    }

    /**
     * Notes   : 关联店铺
     * @Date   : 2021/5/7 1:46 下午
     * @Author : < Jason.C >
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function shop(): BelongsTo
    {
        return $this->belongsTo(Shop::class);
    }

    /**
     * Notes: 关联日志
     * @Author: 玄尘
     * @Date  : 2021/5/17 11:38
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function logs(): HasMany
    {
        return $this->hasMany(RefundLog::class);
    }

    /**
     * Notes   : 工作流获取状态
     * @Date   : 2021/5/8 3:52 下午
     * @Author : < Jason.C >
     * @return string
     */
    public function getCurrentState(): string
    {
        return $this->state;
    }

    /**
     * Notes   : 工作流设置状态
     * @Date   : 2021/5/8 4:01 下午
     * @Author : < Jason.C >
     * @param $state
     */
    public function setCurrentState($state)
    {
        $this->state = $state;
        $this->save();
    }

}
