<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Builder;

trait WithPosition
{

    /**
     * Notes   : 获取定位的数组
     * @Date   : 2021/7/2 11:31 上午
     * @Author : < Jason.C >
     */
    protected function getPositionMap(): array
    {
        return $this->position_map ?? [];
    }

    /**
     * Notes: 定位查询作用域
     * @Author: Mr.wang
     * @Date  : 2021/5/11 10:48
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  int                                    $pos
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeOfPosition(Builder $query, int $pos): Builder
    {
        return $query->whereRaw('position & ' . $pos);
    }

    /**
     * Notes: 设置定位
     * @Author: Mr.wang
     * @Date  : 2020/5/11 10:48
     * @param  int  $value
     */
    protected function setPositionAttribute($value): void
    {
        if (is_array($value) && !blank($value)) {
            $this->attributes['position'] = array_sum($value);
        }
    }

    /**
     * Notes: 获取定位数据
     * @Author:  Mr.wang
     * @Date  : 2020/5/11 10:48
     * @param  int  $value
     * @return array
     */
    protected function getPositionAttribute(int $value): array
    {
        $position = [];
        foreach ($this->getPositionMap() as $k => $v) {
            if ($k & $value) {
                array_push($position, $k);
            }
        }

        return $position;
    }

}
