<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model as BaseModel;

class Bouns extends Model
{
    protected $dates = ['date'];
    protected $casts = [
        'source' => 'array',
    ];
    const ONE_STAR   = 1;
    const TWO_STAR   = 2;
    const THREE_STAR = 3;
    const FOUR_STAR  = 4;
    const FIVE_STAR  = 5;
    const TYPES      = [
        self::ONE_STAR   => '一星分红',
        self::TWO_STAR   => '二星分红',
        self::THREE_STAR => '三星分红',
        self::FOUR_STAR  => '四星分红',
        self::FIVE_STAR  => '五星分红',
    ];

    const TYPEARRAY = [self::ONE_STAR, self::TWO_STAR, self::THREE_STAR, self::FOUR_STAR, self::FIVE_STAR];

    const STATUS_INIT    = 0;
    const STATUS_SENDING = 1;
    const STATUS_SENDED  = 2;
    const STATUS_REJECT  = 8;
    const STATUS_ERROR   = 9;
    const STATUS         = [
        self::STATUS_INIT    => '待发放',
        self::STATUS_SENDING => '发放中',
        self::STATUS_SENDED  => '发放完毕',
        self::STATUS_REJECT  => '停发',
        self::STATUS_ERROR   => '错误',
    ];

    protected function orders()
    {
        return $this->hasMany(BounsOrder::class);
    }

    /**
     * 增加累计额度，增加对应订单记录
     * @param  BaseModel  $order
     * @param  float      $total
     * @param  float      $rate
     * @return void
     */
    protected function addAmount(BaseModel $order, float $total, float $rate)
    {
        $amount = bcmul($total, bcdiv($rate, 100, 4), 2);
        if ($this->orders()->create([
            'order_type' => $order->getMorphClass(),
            'order_id'   => $order->id,
            'type'       => $this->type,
            'total'      => $total,
            'amount'     => $amount,
        ])) {
            $this->increment('total', $amount);
        }
    }

    /**
     * 获取分红模型
     * @param  int   $type  类别
     * @param  bool  $last  是否上一期
     * @return mixed
     */
    public static function getBouns(int $type, bool $last = false)
    {
        $time = now()->startOfMonth();
        if ($last) {
            $time = now()->subMonth()->startOfMonth();
        }
        return Bouns::firstOrCreate([
            'type' => $type,
            'date' => $time->toDateTimeString(),
        ], [
            'total'  => 0,
            'status' => self::STATUS_INIT,
        ]);
    }

    /**
     * 增加分红
     * @param  BaseModel  $order  订单
     * @param  float      $total  订单金额（未计算前）
     * @return void
     */
    public static function addBouns(BaseModel $order, float $total)
    {
        $rateArray = [
            self::ONE_STAR   => app('Conf_user')['one_star_balance_rate'] ?? 0,
            self::TWO_STAR   => app('Conf_user')['two_star_balance_rate'] ?? 0,
            self::THREE_STAR => app('Conf_user')['three_star_balance_rate'] ?? 0,
            self::FOUR_STAR  => app('Conf_user')['four_star_balance_rate'] ?? 0,
            self::FIVE_STAR  => app('Conf_user')['five_star_balance_rate'] ?? 0,
        ];
        foreach ($rateArray as $key => $rate) {
            if ($rate > 0) {
                $model = Bouns::getBouns($key);
                $model->addAmount($order, $total, $rate);
            }
        }
    }

    public function doIng()
    {
        $this->status = self::STATUS_SENDING;
        $this->save();
    }

    public function doEnd()
    {
        $this->status = self::STATUS_SENDED;
        $this->save();
    }

    public function doError()
    {
        $this->status = self::STATUS_ERROR;
        $this->save();
    }
}
