<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */

namespace app\api\logic;

use app\api\lists\ArticleLists;
use app\common\enum\FootprintEnum;
use app\common\enum\UserTerminalEnum;
use app\common\logic\BaseLogic;
use app\common\model\IndexVisit;
use app\common\model\User;
use weather\Weather;

class IndexLogic extends BaseLogic
{

    /**
     * 首页
     */
    public static function home( ){

        // 获取文章列表
        $lists = (new ArticleLists());

        return [
            'article' => $lists
        ];

    }

    // 获取天气接口
    public static function weather($params){
        $info = Weather::getWeather($params['district_id']);
        return $info;
    }
    /**
     * @notes 首页访客记录
     * @return bool
     */
    public static function visit($params)
    {
        try {
            if (!isset($params['terminal']) || !in_array($params['terminal'], UserTerminalEnum::ALL_TERMINAL)) {
                throw new \Exception('终端参数缺失或有误');
            }
            $ip =  request()->ip();
            // 一个ip一个终端一天只生成一条记录
            $record = IndexVisit::where([
                'ip' => $ip,
                'terminal' => $params['terminal']
            ])->whereDay('create_time')->findOrEmpty();
            if (!$record->isEmpty()) {
                // 增加访客在终端的浏览量
                $record->visit += 1;
                $record->save();
                return true;
            }
            // 生成访客记录
            IndexVisit::create([
                'ip' => $ip,
                'terminal' => $params['terminal'],
                'visit' => 1
            ]);

            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * 用户搜索,仅搜索相似的3条记录
     */
    public static function search_user($params){

        if( !$params['keyword'] ){
            return [];
        }
        
        $data = User::with(['user_level'])
                ->where('nickname' ,'like' ,'%'.$params['keyword'].'%')
                ->field('id,nickname,level,user_integral,avatar')
                ->orderRaw("LOCATE('nickname', nickname) ASC")
                ->select();

        // --- 实时校准搜索结果等级开始 ---
        $levelThresholds = \think\facade\Db::name('user_level')->order('rank asc')->select()->toArray();
        foreach ($data as &$u) {
            $integral = (int)($u->user_integral ?? 0);
            $correctLevelData = $levelThresholds[0] ?? null;
            if (!empty($levelThresholds)) {
                foreach ($levelThresholds as $lt) {
                    if ($integral >= (int)$lt['experience']) {
                        $correctLevelData = $lt;
                    } else {
                        break;
                    }
                }
            }
            if ($correctLevelData && $u->level != $correctLevelData['id']) {
                $u->level = $correctLevelData['id'];
                $u->setRelation('user_level', new \app\common\model\UserLevel($correctLevelData));
            }
        }
        // --- 实时校准搜索结果等级结束 ---

        return $data->toArray();
    }
}
