<?php


namespace App\Services;

use App\Constants\HttpStatus;
use App\Services\BaseService;
use App\Models\Config;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
 * 配置
 */
class ConfigService extends BaseService
{
    public static string $MODEL = Config::class;


    /**
     * @description: 模型
     * @return {string}
     */
    public static function model(): string
    {
        return Config::class;
    }

    /**
     * @description: 枚举
     * @return {*}
     */
    public static function enum(): string
    {
        return '';
    }

    /**
     * @description: 获取查询条件
     * @param {array} $search 查询内容
     * @return {array}
     */
    public static function getWhere(array $search = []): array
    {
        $where = [];
        if (isset($search['field']) && !empty($search['field'])) {
            $where[] = ['field', '=', $search['field']];
        }

        if (isset($search['group_id']) && !empty($search['group_id'])) {
            if (!is_array($search['group_id'])) {
                $where[] = ['group_id', '=', $search['group_id']];
            }
        }

        if (isset($search['id']) && !empty($search['id'])) {
            $where[] = ['id', '=', $search['id']];
        }
        return $where;
    }

    public static function getWhereIn(array $search = []): array
    {
        $where = [];
        if (isset($search['in_group_id']) && is_array($search['in_group_id'])) {
            $where['group_id'] = $search['in_group_id'];
        }
        return $where;
    }


    /**
     * @description: 查询单条数据
     * @param array $search
     * @return \App\Models\Coin|null
     */
    public static function findOne(array $search): ?Config
    {
        return self::model()::where(self::getWhere($search))->first();
    }

    /**
     * @description: 查询所有数据
     * @param array $search
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function findAll(array $search = [])
    {
        return self::model()::where(self::getWhere($search))->get();
    }

    /**
     * @description: 分页查询
     * @param array $search
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public static function paginate(array $search = [])
    {
        $limit = isset($search['limit']) ? $search['limit'] : 15;
        $query = self::model()::where(self::getWhere($search));
        $where = self::getWhereIn($search);
        foreach ($where as $key => $value) {
            $query = $query->whereIn($key, $search['in_group_id']);
        }
        $paginator = $query->paginate($limit);
        return ['total' => $paginator->total(), 'data' => $paginator->items()];
    }

    /**
     * @description:
     * @param {*} $params
     * @return {*}
     */
    public static function submit($params = [])
    {
        $result = false;
        $msg['code'] = self::NOT;
        $msg['msg'] = '';

        // 2. 判断是否是更新
        if (!empty($params['id'])) {
            // 更新
            $info = self::findOne(['id' => $params['id']]);
            if (!$info) {
                $msg['msg'] = '配置不存在！';
            } else {
                unset($params['field']);
                $result = $info->update($params);
                $id = $params['id'];
            }
        } else {
            // 创建
            $result = $info = self::model()::create($params);
            $id = $result->id;
        }


        if ($result) {
            $msg['code'] = self::YES;
            $msg['msg'] = '设置成功';
        } else {
            $msg['msg'] = empty($msg['msg']) ? '操作失败' : $msg['msg'];
        }

        return $msg;
    }


    public static function syncExchangeRate()
    {
        $url = "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/usd.json";

        $result = file_get_contents($url, false, stream_context_create([
            'http' => [
                'method' => 'GET',
                'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3\r\n"
            ]
        ]));
        $result = json_decode($result, true);
        $rate = number_format($result['usd']['cnh'], 2);
        $info = self::findOne(['field' => 'exchange_rate_rmb']);
        $info->val = $rate;
        $info->save();
        return $result;
    }

    public static function getRemark(string $field)
    {
        $config = static::$MODEL::where('field', $field)->first();
        if ($config) return $config->remark;
        throw new Exception("参数不存在", HttpStatus::CUSTOM_ERROR);
    }

    public static function getVal(string $field)
    {
        $config = static::$MODEL::where('field', $field)->first();
        if ($config) return $config->val;
        throw new Exception("参数不存在", HttpStatus::CUSTOM_ERROR);
    }

    /**
     * 每天把19:56–20:30这段时间的开奖切换成 极速PC28
     */
    public function autoSwitchGameType(): void
    {
        $day = date('Y-m-d');
        $start = strtotime("$day 19:56:00");
        $end = strtotime("$day 20:30:00");
        $now = time();
        if ($start <= $now && $now <= $end) {
            Cache::put('pc28_switch', 1);
        } else {
            Cache::put('pc28_switch', 0);
        }
    }
}