<?php
namespace app\traits\order;

use app\model\Express;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;
use think\Paginator;

/**
 * 物流相关
 *
 * Trait ShoppingCartTrait
 * @package app\traits\order
 */
trait ExpressTrait
{
    /**
     * 添加快递公司
     *
     * @param  array  $data
     * @return Model
     */
    public function addExpress(array $data): Model
    {
        return Express::create($data);
    }

    /**
     * 删除快递
     *
     * @param  array  $where
     * @return bool
     */
    public function delExpress(array $where): bool
    {
        return Express::where($where)->delete();
    }

    /**
     * 快递公司列表 [带分页]
     *
     * @param  array  $where
     * @param  array  $pageParams
     * @param  callable|null  $callable  $callable
     * @return Paginator
     * @throws DbException
     */
    public function express(array $where = [], array $pageParams = [], callable $callable = null): Paginator
    {
        return Express::findListWithPaginate($where, $pageParams, $callable);
    }

    /**
     * 物流信息
     *
     * @param  int  $id
     * @return array|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function expressInfo(int $id)
    {
        return Express::findById($id);
    }

    /**
     * 获取所有快递公司
     *
     * @param array $where
     * @return Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function allExpress(array $where = []): Collection
    {
        return Express::where($where)->order('is_default', 'desc')->select();
    }

    /**
     * 获取默认快递
     *
     * @return Express|array|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getDefaultExpress()
    {
        return Express::where('is_default', Express::COMMON_ON)->find();
    }
}