<?php

namespace app\common\model\server;

use app\common\model\ServerCategory;
use app\common\model\UploadFile;
use cores\BaseModel;
use think\db\exception\DbException;
use think\model\concern\SoftDelete;
use think\model\relation\HasOne;
use think\Paginator;

class Server extends BaseModel
{

    // 定义表名
    protected $name = 'server';

    // 定义主键
    protected $pk = 'server_id';

    use SoftDelete;

    protected string $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;

    /**
     * 图片
     * @return HasOne
     */
    public function image(): HasOne
    {
        return $this->hasOne(UploadFile::class, 'file_id', 'image_id')
            ->bind(['server_image' => 'preview_url']);
    }

    public function category(): HasOne
    {
        return $this->hasOne(ServerCategory::class, 'category_id', 'category_id')
            ->bind(['server_category' => 'name']);
    }

    /**
     * @notes:服务详情
     * @param $where
     * @param array $with
     * @return static|array|null
     * @author: wanghousheng
     */
    public static function detail($where, array $with = [])
    {
        return static::get($where, $with);
    }


    /**
     * @notes:获取全部记录
     * @param array $where
     * @param int $listRows
     * @param string $sort
     * @param string $sort_type
     * @return Paginator
     * @throws DbException
     * @author: wanghousheng
     */
    public function getList(array $where = [], int $listRows = 15, string $sort = '', string $sort_type = 'desc'): Paginator
    {
        $where = $this->setQueryDefaultValue($where);
        $sort_arr = ['sort' => $sort_type, 'create_time' => $sort_type];
        if ($sort) {
            $sort_arr = [$sort => $sort_type, 'create_time' => $sort_type];
        }
        return $this->with(['image'])->withJoin(['category' => ['category_id', 'name']])
            ->where($where)
            ->order($sort_arr)
            ->paginate($listRows);
    }

    /**
     * 根据商品id集获取服务列表
     * @param array $serverIds
     * @param null $status
     * @return mixed
     */
    public function getListByIds(array $serverIds, $status = null)
    {
        // 筛选条件
        $filter = [['server_id', 'in', $serverIds]];
        // 商品状态
        $status > 0 && $filter[] = ['status', '=', $status];
        // 获取商品列表数据
        $result = $this->withoutField(['content'])
            ->with(['image'])
            ->withJoin(['category' => ['category_id', 'name']])
            ->where($filter)
            ->orderRaw('field(server_id, ' . implode(',', $serverIds) . ')')
            ->select();
        if (!empty($result)) {
            return $result->toArray();
        }
        return [];
    }

    /**
     * 文章详情:HTML实体转换回普通字符
     * @param $value
     * @return string
     */
    public function getContentAttr($value): string
    {
        return htmlspecialchars_decode($value);
    }

}