<?php

namespace App\Models;


use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;
use Modules\Mall\Models\Traits\HasRegion;
use Modules\User\Models\User;
use Modules\User\Models\UserInvite;
use Modules\User\Traits\BelongsToUser;

class Area extends Model
{
    use BelongsToUser,
        HasRegion;

    const STATUS_DOWN = 0;
    const STATUS_UP   = 1;

    const STATUS = [
        self::STATUS_DOWN => '下架',
        self::STATUS_UP   => '上架',
    ];

    protected static function boot()
    {
        parent::boot();
        self::created(function ($model) {
            self::addStock($model, $model->stock, true);
        });
    }

    /**
     * Notes: 操作员
     *
     * @Author: 玄尘
     * @Date: 2023/1/11 13:57
     * @return BelongsToMany
     */
    public function clerks(): BelongsToMany
    {
        return $this->belongsToMany(
            User::class,
            (new AreaClerk())->getTable())->using(AreaClerk::class
        );
    }

    /**
     * Notes: 操作员
     *
     * @Author: 玄尘
     * @Date: 2023/1/11 15:53
     * @return HasMany
     */
    public function areaClerks(): HasMany
    {
        return $this->hasMany(AreaClerk::class);
    }

    /**
     * Notes: 关联库存变动表
     *
     * @Author: 玄尘
     * @Date: 2023/1/11 14:54
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function stocks(): HasMany
    {
        return $this->hasMany(AreaStock::class);
    }

    /**
     * Notes: 关联提货券
     *
     * @Author: 玄尘
     * @Date: 2023/1/11 15:43
     * @return HasMany
     */
    public function areaCodes(): HasMany
    {
        return $this->hasMany(AreaCode::class);
    }

    /**
     * Notes: 增加库存
     *
     * @Author: 玄尘
     * @Date: 2023/1/11 14:50
     * @param $number
     */
    public static function addStock($area, $number, $isCreate = false)
    {
        $stock = $area->stock;

        if ($isCreate) {
            $all = $number;
        } else {
            $area->increment('stock', $number);
            $all = bcadd($number, $stock);
        }
        $area->stocks()->create([
            'amount' => $number,
            'stock'  => $all,
        ]);

        return true;
    }

    /**
     * Notes: 生成提货码
     *
     * @Author: 玄尘
     * @Date: 2023/1/11 16:00
     * @param $num
     */
    public function generate($user_id, $num)
    {
        try {
            if (! $num) {
                throw new \Exception('缺少数量');
            }

            $canStockNum = bcsub($this->stock, $this->areaCodes()->count());

            if ($canStockNum < $num) {
                throw new \Exception('可生成数量不足，您还可以释放'.$canStockNum);
            }

            while ($num > 0) {
                $data[] = [
                    'area_id'    => $this->id,
                    'manage_id'  => $user_id,
                    'code'       => Str::random(14),
                    'status'     => AreaCode::STATUS_INIT,
                    'created_at' => now(),
                    'updated_at' => now(),
                ];
                --$num;
            }

            AreaCode::insert($data);

            return true;
        } catch (\Exception $exception) {
            return $exception->getMessage();
        }
    }
}
