<?php

namespace App\Controller\api\expose\v1;

use App\Controller\AbstractController;
use App\Model\AppDropLog;
use App\Model\AppKeywordsMonitor;
use App\Model\AppKeywordsMonitorResult;
use App\Model\AppKeywordsMonitorTask;
use Hyperf\Context\ApplicationContext;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;

#[Controller(prefix: "/api/expose/v1/tools")]
class ToolsController extends AbstractController
{
    /**
     * 获取关键词监控的关键词
     * @url /api/expose/v1/tools/get-query-keyword
     * @return \Psr\Http\Message\ResponseInterface
     */
    #[RequestMapping(path:'get-query-keyword', methods:'get')]
    public function getQueryKeyword(): \Psr\Http\Message\ResponseInterface
    {
        $keyword = AppKeywordsMonitorTask::query()
//            ->where('id', 23)
            ->where('queried_at', '<=', strtotime('-10 hours'))
            ->where('is_delete', 0);

        if ($keyword) {
            $query = $keyword->first()?->toArray();
            if ($query) {
                $ignoreUrl = AppKeywordsMonitor::formatQuery([])->where('id', $query['aid'])->first()?->toArray()['ignore_url'] ?? '[]';
                $query['ignore_url'] = $ignoreUrl ?: '[]';
            }
            return $this->response->json([
                'code' => 0,
                'data' => $query
            ]);
        }

        return $this->response->json([
            'code' => 0,
            'data' => ''
        ]);
    }

    /**
     * 提交监控数据
     * @url /api/expose/v1/tools/submit-query-keyword
     * @return \Psr\Http\Message\ResponseInterface
     */
    #[RequestMapping(path:'submit-query-keyword', methods:'post')]
    public function submitQueryKeyword(): \Psr\Http\Message\ResponseInterface
    {
//        Db::beginTransaction();
        try {
            $requestData = $this->request->post();
var_dump($requestData);
            if (!isset($requestData['length']) || $requestData['length'] < 2 || !isset($requestData['keyword_id']) || !$requestData['keyword_id'] || !$requestData['image_name'] || !$requestData['ip_info']) {
                return $this->response->json([
                    'code' => 400,
                    'msg' => '缺少参数'
                ]);
            }

            // 被查的关键词id
            $aid = $requestData['keyword_id'];

            foreach ($requestData['items'] ?? [] as $key => $value) {
                // 非负面不存储
                if (!$value['matched'] || !$value['mu']) {
                    continue;
                }

                $query = AppKeywordsMonitorResult::query()->where([
                    ['aid', $aid],
                    ['url', $value['mu']],
                    ['is_delete', 0],
                    ['platform', $requestData['platform']],
                    ['created_at', '>', strtotime('today')]
                ])->first()?->toArray();

                // 如果这个负面存过了就不管了
                if ($query) {
                    echo '????@@@';
                    continue;
                }

                list($title, $desc) = call_user_func(function () use ($value, $requestData) {
                    $content = $value['content'];

                    // 头条pc 和 wap
                    if (in_array($requestData['platform'], [3, 4])) {
                        $de = PHP_EOL;
                    } else {
                        $de = PHP_EOL . PHP_EOL;
                    }
                    $ex = explode($de, $content);
                    if (count($ex) > 1) {
                        return [$ex[0], $ex[1]];
                    }

                    return ['', ''];
                });

                if (!$title || !$desc) {
                    echo '??????';
                    continue;
                }

                $query = new AppKeywordsMonitorResult();

                $query->aid = $aid;
                $query->title = $title;
                $query->description = $desc;
                $query->url = $value['mu'];
                // 百度wap, 头条pc 特殊处理
                if (in_array($requestData['platform'], [2, 3, 4])) {
                    $value['id'] = (intval(AppKeywordsMonitorTask::find($aid)?->page) - 1) * 10 + $value['id'];
                }
                $query->order = $value['id'];
                $ipInfo = json_decode($requestData['ip_info'], true);
                $query->ip_address = $ipInfo['ip'];
                $query->ip_source =  "{$ipInfo['country']}{$ipInfo['province']}{$ipInfo['city']}";
                $query->screen_path = $requestData['image_name'];
                $query->platform = $requestData['platform'];
                $query->save();
            }

            // 更新关键词最后查询时间
            $query = AppKeywordsMonitorTask::find($aid);
            $query->queried_at = time();
            $query->length = $requestData['length'] - 1; // 去掉相关搜索
            $query->save();

            // 更新关键词最后查询时间
            $query = AppKeywordsMonitor::query()->where('id', $query->aid)->first();
            $query->queried_at = time();
            $query->save();

            Db::commit();
        }catch (\Throwable $e) {
            var_dump($e->getMessage());
//            Db::rollBack();
        }
        return $this->response->json([
            'code' => 0,
            'msg' => 'ok'
        ]);
    }

    /**
     * 刷下拉数据上报
     * @url /api/expose/v1/tools/succ
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[RequestMapping(path:'succ', methods:'post')]
    public function success(): \Psr\Http\Message\ResponseInterface
    {
        $keyword = $this->request->post('Keyword');
        $dropKeyword = $this->request->post('DropKeyword');
        $op = $this->request->post('Op');
        $vps = $this->request->post('Vps');
        $model = new AppDropLog();
        $model->keyword = $keyword;
        $model->op = $op;
        $model->drop_keyword = $dropKeyword;
        $model->save();

        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\Redis::class);

        $redis->sAdd('vps', $vps);
        // 十分钟不上报数据就算掉线
        $redis->set('vps:app' . $vps, 1, 60 * 10);

        return $this->response->json([]);
    }
}