<?php

namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * @description 产品属性
 * @author  system;
 * @version    1.0
 * @date 2018-07-03 16:51:48
 *
 */
class AlbumProductAttrModel extends BaseModel
{
    use SoftDeletes;
    /**
     * 数据表名
     *
     * @var string
     *
     */
    protected $table = 'album_product_attr';
    /**
     * 主键
     */
    protected $primaryKey = 'id';

    //分页
    protected $perPage = PAGE_NUMS;

    /**
     * 可以被集体附值的表的字段
     *
     * @var string
     */
    protected $fillable = [
        'name',
        'pid',
        'attr_type',
        'sort',
        'store_id'
    ];

    public static function _tree($items, $pid = 0, $level = 0, $layer = 3) {
        if ($level > $layer) {
            return [];
        }
        $result = [];
        foreach ($items as $item) {
            if ($item->pid == $pid) {
                $node = [
                    'id'     => $item->id,
                    'name'   => $item->name,
                    'created_at'   => $item->created_at,
                    'updated_at'   => $item->updated_at,
                    'pid'   => $item->pid,
                    'children'  => self::_tree($items, $item->id, $level + 1),
                ];
                if ($level === 1) {
                    $result[$item->id] = $node;
                } else {
                    $result[] = $node;
                }
            }
        }
        return $result;
    }

    public static function genAreaTree($storeid,$layer = 3) {
        if ($layer <= 1) {
            return [];
        }
        $items = self::whereBetween('attr_type', [0, $layer])->where('store_id',$storeid)->orderBy('attr_type', 'desc')->orderBy('updated_at','desc')->get();
        $result = self::_tree($items, 0, 0, $layer);
        ksort($result);
        return $result;
    }

    public function pid(){
        if($this->pid){
            return self::find($this->pid)?self::find($this->pid)->name:$this->pid;
        }else{
            return '';
        }

    }
    public function attr_type(){
        switch ($this->attr_type){
            case 1:
                return '型号';
                break;
            case 2:
                return '颜色';
                break;
            default:
                return '品类';
                break;
        }
    }

}