<?php

namespace app\admin\model;

use support\Db;
use support\Model;

/**
 * 角色模型
 * Class Users
 * @package app\admin\model
 */
class Package extends Model
{
    const PACKAGE_PUT_SHELVES = '1';
    const PACKAGE_LOWER_SHELF = '2';
    const PACKAGE_STATUS = [
        self::PACKAGE_PUT_SHELVES => '上架',
        self::PACKAGE_LOWER_SHELF => '下架'
    ];
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'package';

    public $timestamps = false;

    /**
     * Notes:获取角色列表
     * @param string $keywords
     * @param int $page
     * @param int $limit
     * @return array
     * User: QJF
     * Date: 2022/9/19
     */
    public static function getPackageList(int $page, int $limit, $keywords)
    {
        $list = static::select('*')
            ->where(['package_is_del'=>0])
            ->when($keywords != '', function ($query) use ($keywords){
                $query->where('package_name', 'like', '%' . $keywords . '%');
            })
            ->orderBy('package_update_time','DESC')
            ->forPage($page, $limit)
            ->get();
        $count = static::where(['package_is_del'=>0])
            ->when($keywords != '', function ($query) use ($keywords){
                $query->where('package_name', 'like', '%' . $keywords . '%');
            })->count();
        return [$list, $count];
    }

    public function getPackageCreateTimeAttribute($value)
    {
        return date('Y-m-d H:i:s', $value);
    }


    public function getPackageUpdateTimeAttribute($value)
    {
        return date('Y-m-d H:i:s', $value);
    }
    public function setPackageUpdateTimeAttribute($value)
    {
        return strtotime($value);
    }
    public function getPackagePriceAttribute($value)
    {
        $id  = json_decode($this->package_product_ids);
        $price = PackageGoods::whereIn('goods_id',$id)->sum('goods_price');
        return $price;
    }

    /**
     * Notes:获取单个套餐包详情
     * @param int $package_id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * User: yym
     * Date: 2022/9/22
     */
    public static function getInfo(int $package_id)
    {
        $info = static::where(['package_id' => $package_id])->first();
        $info['goods'] = PackageGoods::getPackageGoodsListNew(json_decode($info['package_product_ids'], true));
        return $info;
    }
}
