<?php

namespace App\Http\Controllers\Open;

use Carbon\Carbon;
use App\Models\Tag;
use App\Models\News;
use App\Models\CollectTitle;
use App\Models\CollectMedia;
use App\Models\CollectTag;
use App\Models\Setting;
use App\Models\TagDescription;
use App\Models\NewsDescription;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\CollectSearch;
use App\Traits\JsonResponseTrait;
use App\Models\Lang;

class AiNewsController extends Controller
{
    use JsonResponseTrait;

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function index(Request $request)
    {
        if (Setting::get('apptoken') == $request->header('token')) {
            $title = CollectTitle::where('status', 0)->orderByRaw("RAND()")->take(1)->first();

            if ($title) {
                try {
                    $lang = Lang::flag()->where('enabled', 1)->where('buy', 1)->where('slug', config('setting.lang'))->first();

                    if (!$lang) {
                        throw new \Exception('主语言不存在');
                    }

                    $client = new \GuzzleHttp\Client([
                        'headers' => [
                            'Authorization' => 'gsvfKSKk7EX1IO6yNs9Ut8cYE'
                        ],
                        'timeout' => 600
                    ]);

                    $response = $client->request('GET', config('setting.chat_url'). '?wd=' . $title->name . ' 请用'.$lang->name.'写2000字，不要出现公司名称' . '&source=' . $request->input('domain'));

                    if ($response->getStatusCode() >= 400) {
                        throw new \Exception('新闻采集异常');
                    }

                    $result = json_decode($response->getBody()->getContents(), true);
                    $content = str_replace("\n\n", "#", $result['text']);
                    $content = str_replace("\n", "#", $content);
                    $contents = explode("#", "$content");
                    $contentArr = [];

                    foreach ($contents as $key => $value) {
                        $contentArr[$key] = '<p style="text-indent: 2em;">'.$value.'</p>';
                    }

                    $content = implode('#', $contentArr);
                    $content = str_replace(["#", "*"], "", $content);
                    $media = CollectMedia::orderByRaw("RAND()")->take(1)->first();

                    if ($media) {
                        $content = '<div style="text-align: center;"><img src="' . $media->path . '" alt="' . $title->name . '"></div><p>&nbsp;</p>' . $content;
                    }

                    $data = [
                        'pid' => $title->cid,
                        'description' => [
                            $lang->slug => [
                                'title' => $title->name,
                                'content' => $content,
                            ]
                        ],
                        'flag' => Setting::get('ai_publish_flag') ? 1 : 0
                    ];

                    $order = News::max('orders');
                    $data['orders'] = $order + 1;
                    $tags = CollectTag::orderByRaw("RAND()")->take(3)->get(['name'])->toArray();

                    if (!empty($tags)) {
                        foreach ($tags as $tag) {
                            if (!Tag::where('name', $tag['name'])->first()) {
                                $result = Tag::create($tag);
                                if ($result) {
                                    Tag::attachSlug($result, $tag['name'], 'tag_id');
                                    $description = [
                                        $lang->slug => $tag
                                    ];
                                    TagDescription::attachDescription($description, $result->tag_id, 'tag_id', true);
                                }
                            }
                        }
                    }

                    $res  = News::create($data);
                    $res->tag(array_column($tags, 'name'));

                    if ($res) {
                        News::attachSlug($res, $title->name);
                        NewsDescription::attachDescription($data['description'], $res->id, 'news_id', true);
                    }

                    $title->update(['status' => 1]);

                } catch (\Exception $e) {
                    file_put_contents(
                        storage_path('logs/ai_publish_' . date('Ymd') . '.txt'),
                        "{$e->getMessage()} Fail" . PHP_EOL,
                        FILE_APPEND
                    );
                }
            }
        }
    }

    public function search(Request $request)
    {
        $data = file_get_contents('php://input');
        $data = urldecode($data);

        if ($data) {
            parse_str($data, $output);
            $token	= $output['token'];
            $content	= $output['content'];

            $content = str_replace(["\n\n", "\n"], "<br/>", $content);

            CollectSearch::where('token', $token)->update([
                'content' => $content,
                'created_at' => Carbon::now(),
                'flag' => 1
            ]);

            return $this->success();
        }

        return $this->error('保存失败！');
    }
}
