<?php

namespace App\Models;

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use DateTimeInterface;

class Course extends Model
{
    use SoftDeletes;
    use HasFactory;
    protected $table='course';
    protected $guarded=[];

    public static $courseLevel = [
        '1' =>'1',
        '2' =>'2',
        '3' =>'3',
        '4' =>'1,2',
        '5' =>'1,3',
        '6' =>'2,3',
        '7' =>'1,2,3',
    ];

    public static $levelCourse = [
        '1' =>[1,4,5,7],
        '2' =>[2,4,6,7],
        '3' =>[3,5,6,7],
    ];

    protected function serializeDate(DateTimeInterface $date): string
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function setPermissionAttribute($value)
    {
        sort($value);
        $this->attributes['permission'] = array_search(implode(',',$value),self::$courseLevel);
    }

    public function setImgAttribute($value)
    {
        $this->attributes['img'] = json_encode($value);
    }
    public function setAudioAttribute($value)
    {
        $this->attributes['audio'] = json_encode($value);
    }
    public function setVideoAttribute($value)
    {
        $this->attributes['video'] = json_encode($value);
    }

    public function getPermissionAttribute($value)
    {
        return explode(',',self::$courseLevel[$value]);
    }
    public function getImgAttribute($value)
    {
        return json_decode($value,'true');
    }
    public function getAudioAttribute($value)
    {
        return json_decode($value,'true');
    }
    public function getVideoAttribute($value)
    {
        return json_decode($value,'true');
    }

    public static function setField()
    {
        return self::query()
            ->select('id',
            'title',
            'is_share',
            'cate',
            'perface',
            'img',
            'audio',
            'video',
            'c_id',
            'author',
            'permission',
            'is_top',
            'top_at',
            'state',
            'collection',
            'share',
            'read',
            'comms',
            'created_at',
            'updated_at'
        );
    }

    public function p_cate()
    {
        return $this->hasOneThrough(
            'App\Models\Cate',//战区
            'App\Models\Cate',//代理
            'id', // 代理表外键...
            'id', // 战区表外键...
            'c_id', // 店铺表本地键...
            'p_id' // 代理表本地键...
        );
    }

//    public function posts()
//    {
//        return $this->hasManyThrough(
//            'App\Models\OrderDetail',
//            'App\Models\Order',
//            'store_id', // 国家表外键...
//            'order_id', // 用户表外键...
//            'id', // 国家表本地键...
//            'id' // 用户表本地键...
//        );
//    }
}
