<?php

namespace Modules\User\Models;

use App\Models\Model;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\DB;
use Modules\User\Traits\BelongsToUser;

class Account extends Model
{

    use BelongsToUser;

    protected $table      = 'user_accounts';

    protected $primaryKey = 'user_id';

    const TYPES = [
        'balance' => '现金余额',
        'score'   => '水滴',
        'coins'   => '未使用',
        'other'   => '其他',
    ];

    /**
     * Notes   : 账户日志
     *
     * @Date   : 2021/4/27 11:22 上午
     * @Author : < Jason.C >
     * @return HasMany
     */
    public function logs(): HasMany
    {
        return $this->hasMany(AccountLog::class, 'account_id', 'user_id');
    }

    /**
     * Notes: 执行账户规则
     *
     * @Author: <C.Jason>
     * @Date  : 2019/11/28 1:24 下午
     * @param         $rule string|int
     * @param  float  $variable
     * @param  bool  $frozen
     * @param  array  $source
     * @return bool
     * @throws Exception
     */
    public function rule($rule, float $variable = 0, bool $frozen = true, array $source = []): bool
    {
        if (is_numeric($rule)) {
            $rule = AccountRule::findOrFail($rule);
        } else {
            $rule = AccountRule::where('name', $rule)->firstOrFail();
        }

        if ($rule->trigger == 0) {
            // 不限制执行的
            return $this->accountExecute($rule, $variable, $frozen, $source);
        } elseif ($rule->trigger > $this->logs()
                ->where('rule_id', $rule->id)
                ->whereDate('created_at', Carbon::today())
                ->count()) {
            // 每日执行 trigger 次
            return $this->accountExecute($rule, $variable, $frozen, $source);
        } elseif ($rule->trigger < 0 && ! $this->logs()->where('rule_id', $rule->id)->first()) {
            // 终身只能执行一次
            return $this->accountExecute($rule, $variable, $frozen, $source);
        }

        throw new Exception('达到最大可执行次数');
    }

    /**
     * Notes: 增加账户余额
     *
     * @Author: <C.Jason>
     * @Date  : 2019/11/28 1:25 下午
     * @param $type
     * @param $variable
     * @return bool
     */
    public function increase($type, $variable): bool
    {
        DB::transaction(function () use ($type, $variable) {
            $this->increment($type, $variable);
            $log = [
                'rule_id'  => 0,
                'type'     => $type,
                'variable' => $variable,
                'frozen'   => 0,
                'balance'  => $this->{$type},
                'source'   => ['type' => 'increase'],
            ];
            $this->logs()->create($log);
        });

        return true;
    }

    /**
     * Notes: 扣除账户金额
     *
     * @Author: <C.Jason>
     * @Date  : 2019/11/28 1:25 下午
     * @param $type
     * @param $variable
     * @return bool
     * @throws Exception
     */
    public function decrease($type, $variable): bool
    {

        DB::transaction(function () use ($type, $variable) {
            $this->decrement($type, $variable);
            $log = [
                'rule_id'  => 0,
                'type'     => $type,
                'variable' => -$variable,
                'frozen'   => 0,
                'balance'  => $this->{$type},
                'source'   => ['type' => 'deduct'],
            ];
            $this->logs()->create($log);
        });

        return true;
    }

    /**
     * Notes: 执行账户规则
     *
     * @Author: <C.Jason>
     * @Date  : 2019/11/28 1:41 下午
     * @param  AccountRule  $rule
     * @param               $variable
     * @param               $frozen
     * @param               $source
     * @return bool
     * @throws Exception
     */
    protected function accountExecute(AccountRule $rule, $variable, $frozen, $source): bool
    {
        if ($variable != 0) {
            $rule->variable = $variable;
        }

        DB::transaction(function () use ($rule, $frozen, $source) {
            // 如果是扣款，立即执行，如果非冻结，也立即执行
            if ($rule->variable < 0 || $rule->deductions == 1 || $frozen === false) {
                $this->increment($rule->type, $rule->variable);
                $frozen = false;
            }
            $log = [
                'rule_id'   => $rule->id,
                'type'      => $rule->type,
                'amount'    => $rule->variable,
                'frozen'    => $frozen,
                'balance'   => $this->{$rule->type},
                'source'    => $source ?: [],
                'remark'    => $source['remark'] ?? $rule->remark,
                'settle_at' => $source['settle_at'] ?? null,
                'frozen_at' => $source['frozen_at'] ?? null,
            ];
            // 写入记录
            $this->logs()->create($log);
        });

        return true;
    }

}
