<?php

namespace App\Controller\admin\api;

use App\Constants\Config;
use App\Controller\AbstractController;
use App\Helpers\ExcelHelper;
use App\Model\AppKeywordsMonitor;
use App\Model\AppKeywordsMonitorResult;
use App\Model\AppKeywordsMonitorTask;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\View\RenderInterface;
use Laminas\Stdlib\ArrayUtils;

#[Controller(prefix: 'admin/api/keywords')]
class KeywordsController extends AbstractController
{

    // pc前三页
    // wap 前两页
    private function getPage($platform): array
    {
        return match ($platform) {
            '1', '3' => [1, 2, 3],
            default => [1, 2],
        };
    }

    /**
     * 列表数据
     * @url /admin/api/keywords/monitor
     * @return \Psr\Http\Message\ResponseInterface
     */
    #[RequestMapping(path: 'monitor', methods: 'get')]
    public function monitor(): \Psr\Http\Message\ResponseInterface
    {
        $ids = [];
        $query = AppKeywordsMonitor::query()
            ->select(['id'])
            ->where('is_delete', 0)
            ->orderBy('id', 'desc');
        $pagination = $query->paginate($this->request->input('limit', 10), page: $this->request->input('page'));
        foreach ($pagination->items() as $item) {
            $ids[] = $item->id;
        }

        $value = AppKeywordsMonitor::query()->whereIn('id', $ids)->orderBy('id', 'desc')->get()->toArray();
        return $this->response->json(['code' => 0, 'msg' => 'ok', 'count' => $pagination->total(), 'data' => $value]);
    }

    /**
     * 新增关键词
     * @url /admin/api/keywords/monitor/insert
     * @return \Psr\Http\Message\ResponseInterface
     */
    #[RequestMapping(path: 'monitor/insert', methods: 'post')]
    public function monitorInsert(): \Psr\Http\Message\ResponseInterface
    {
        $keyword = $this->request->post('keyword');
        $ignoreUrl = $this->request->post('ignore_url');

        $query = AppKeywordsMonitor::query()->where([
            ['keyword', $keyword],
            ['is_delete', 0]
        ])->get()->toArray();
        if ($query) {
            return $this->response->json(['code' => 400, 'msg' => '已重复添加']);
        }

        $query = new AppKeywordsMonitor();

        $query->keyword = $keyword;

        $ignoreUrl = array_filter(array_unique(explode(PHP_EOL, $ignoreUrl ?: '')));
        $query->ignore_url = json_encode($ignoreUrl);
        $query->save();

        foreach ($this->request->post('platform', []) as $platform) {
            foreach ($this->getPage($platform) as $page) {
                $task = new AppKeywordsMonitorTask();
                $task->keyword = $keyword;
                $task->aid = $query->id;
                $task->platform = $platform;
                $task->page = $page;
                $task->save();
            }
        }

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

    /**
     * 查看关键词
     * @url /admin/api/keywords/monitor/view
     * @return \Psr\Http\Message\ResponseInterface
     */
    #[RequestMapping(path: 'monitor/view', methods: 'get')]
    public function monitorView(): \Psr\Http\Message\ResponseInterface
    {
        $id = $this->request->input('id');

        $query = AppKeywordsMonitor::formatQuery(['ignore_url'])->where(['id' => $id])->first()->toArray();
        if (!$query) {
            return $this->response->json(['code' => 400, 'msg' => 'id 有误']);
        }

        if ($query['ignore_url']) {
            $query['ignore_url'] = implode(PHP_EOL, $query['ignore_url']);
        }
        $query['platform'] = AppKeywordsMonitorTask::query()->select(['platform'])
            ->where([
                ['aid', $query['id']],
                ['is_delete', 0],
            ])
            ->get()?->pluck('platform');

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

    /**
     * 编辑关键词
     * @url /admin/api/keywords/monitor/save
     * @return \Psr\Http\Message\ResponseInterface
     */
    #[RequestMapping(path: 'monitor/save', methods: 'post')]
    public function monitorSave(): \Psr\Http\Message\ResponseInterface
    {
        $id = $this->request->post('id');
        $keyword = $this->request->post('keyword');
        $platform = $this->request->post('platform', []);
        $ignoreUrl = $this->request->post('ignore_url');

        $query = AppKeywordsMonitor::find($id);
        if (!$query) {
            return $this->response->json(['code' => 400, 'msg' => 'id 有误']);
        }

        $query->keyword = $keyword;
        $ignoreUrl = array_filter(array_unique(explode(PHP_EOL, $ignoreUrl)));

        $query->ignore_url = json_encode($ignoreUrl);
        $query->save();

        // 先全部删掉
        AppKeywordsMonitorTask::query()->where(['aid' => $id])->update(['is_delete' => 1]);
        foreach ($platform as $platformItem) {
            foreach ($this->getPage($platformItem) as $page) {
                $taskQuery = AppKeywordsMonitorTask::query()->where([
                    ['aid', $id], ['platform', $platformItem], ['page', $page]
                ])->first();
                if ($taskQuery) {
                    $taskQuery->is_delete = 0;
                    $taskQuery->save();
                } else {
                    $task = new AppKeywordsMonitorTask();
                    $task->keyword = $keyword;
                    $task->aid = $query->id;
                    $task->platform = $platformItem;
                    $task->page = $page;
                    $task->save();
                }
            }
        }

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

    // /admin/api/keywords/monitor/research

    /**
     * 重查关键词
     * @url /admin/api/keywords/monitor/research
     * @return \Psr\Http\Message\ResponseInterface
     */
    #[RequestMapping(path: 'monitor/research', methods: 'post')]
    public function monitorResearch(): \Psr\Http\Message\ResponseInterface
    {
        $id = $this->request->input('id');

        $query = AppKeywordsMonitorTask::query()->where('aid', $id)->update(['queried_at' => 0]);

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

    /**
     * 删除关键词
     * @url /admin/api/keywords/monitor/delete
     * @return \Psr\Http\Message\ResponseInterface
     */
    #[RequestMapping(path: 'monitor/delete', methods: 'post')]
    public function monitorDelete(): \Psr\Http\Message\ResponseInterface
    {
        $id = $this->request->post('id');

        $query = AppKeywordsMonitor::find($id);
        if (!$query) {
            return $this->response->json(['code' => 400, 'msg' => 'id 有误']);
        }

        $query->is_delete = 1;
        $query->save();

        AppKeywordsMonitorTask::query()->where(['aid' => $id])->update(['is_delete' => 1]);

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

    /**
     * 导出关键词报表
     * @url /admin/api/keywords/monitor/export-all
     */
    #[RequestMapping(path: 'monitor/export-all', methods: 'get')]
    public function monitorExportAll()
    {
        $baiduPCRes = AppKeywordsMonitorResult::query()
            ->where('is_delete', 0)
            ->where('platform', 1)
            ->where('created_at', '>', strtotime('today'))
            ->orderBy('aid', 'desc')
            ->get()
            ->toArray();

        foreach ($baiduPCRes as &$v) {
            $v['keyword'] = AppKeywordsMonitorTask::find($v['aid'])->keyword;
            $v['screen_path'] = Config::getDomain() . $v['screen_path'];
            $v['created_at'] = date('Y-m-d H:i:s', $v['created_at']);
        }

        $baiduWAPRes = AppKeywordsMonitorResult::query()
            ->where('is_delete', 0)
            ->where('platform', 2)
            ->where('created_at', '>', strtotime('today'))
            ->orderBy('aid', 'desc')
            ->get()
            ->toArray();

        foreach ($baiduWAPRes as &$v) {
            $v['keyword'] = AppKeywordsMonitorTask::find($v['aid'])->keyword;
            $v['screen_path'] = Config::getDomain() . $v['screen_path'];
            $v['created_at'] = date('Y-m-d H:i:s', $v['created_at']);
        }

        $toutiaoPC = AppKeywordsMonitorResult::query()
            ->where('is_delete', 0)
            ->where('platform', 3)
            ->where('created_at', '>', strtotime('today'))
            ->orderBy('aid', 'desc')
            ->get()
            ->toArray();

        foreach ($toutiaoPC as &$v) {
            $v['keyword'] = AppKeywordsMonitorTask::find($v['aid'])->keyword;
            $v['screen_path'] = Config::getDomain() . $v['screen_path'];
            $v['created_at'] = date('Y-m-d H:i:s', $v['created_at']);
        }

        $toutiaoWAP = AppKeywordsMonitorResult::query()
            ->where('is_delete', 0)
            ->where('platform', 4)
            ->where('created_at', '>', strtotime('today'))
            ->orderBy('aid', 'desc')
            ->get()
            ->toArray();

        foreach ($toutiaoWAP as &$v) {
            $v['keyword'] = AppKeywordsMonitorTask::find($v['aid'])->keyword;
            $v['screen_path'] = Config::getDomain() . $v['screen_path'];
            $v['created_at'] = date('Y-m-d H:i:s', $v['created_at']);
        }

        $fileName = date('Y-m-d') . '关键词监控结果';
        $exportList = [];
        // 百度PC负面率
        $total = AppKeywordsMonitorTask::query()->where('is_delete', 0)->where('platform', 1)->sum('length') ?: 1;
//        $percent = round(count($baiduPCRes) / $total, 2) * 100;
        $exportList["百度PC端"] = $baiduPCRes;

        // 百度WAP负面率
        $total = AppKeywordsMonitorTask::query()->where('is_delete', 0)->where('platform', 2)->sum('length') ?: 1;
//        $percent = round(count($baiduWAPRes) / $total, 2) * 100;
        $exportList["百度WAP端"] = $baiduWAPRes;

        // 头条PC端负面率
        $total = AppKeywordsMonitorTask::query()->where('is_delete', 0)->where('platform', 3)->sum('length') ?: 1;
//        $percent = round(count($toutiaoPC) / $total, 2) * 100;
        $exportList["头条PC端"] = $toutiaoPC;

        // 头条WAP端负面率
        $total = AppKeywordsMonitorTask::query()->where('is_delete', 0)->where('platform', 4)->sum('length') ?: 1;
//        $percent = round(count($toutiaoWAP) / $total, 2) * 100;
        $exportList["头条WAP端"] = $toutiaoWAP;

        return ExcelHelper::exportData($this->response, list: $exportList, header: [
            ['关键词', 'keyword', 'text'],
            ['标题', 'title', 'text'],
            ['排名', 'order', 'text'],
            ['链接地址', 'url', 'text'],
            ['ip归属地', 'ip_source', 'text'],
            ['截图地址', 'screen_path', 'text'],
            ['查询时间', 'created_at', 'text'],
        ], filename:$fileName);

        return [];
    }
}