<?php

namespace App\Controller\admin\api;

use App\Controller\AbstractController;
use App\Enums\ArticlePublishedStatusEnum;
use App\FormModel\admin\articles\ModifyModel;
use App\FormModel\admin\news\NewsFormModel;
use App\Helpers\AppHelper;
use App\Helpers\ArticleHelper;
use App\Model\AppArticle;
use App\Model\AppBrand;
use App\Model\AppNews;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use function Hyperf\Support\env;

#[Controller(prefix: 'admin/api/news')]
class NewsController extends AbstractController
{
    /**
     * 文章列表
     * @url /admin/api/news
     * @return array
     */
    #[RequestMapping(path:'', methods: 'get')]
    public function index(): array
    {
        $createdFilter = $this->request->query('created_at', [date('Y-m-d', strtotime('-1 month')), date('Y-m-d', time())]);
        $title = $this->request->input('title', '');
        foreach ($createdFilter as $index => &$item) {
            if ($index == 0) {
                $item = strtotime($item . ' 00:00:00');
            }

            if ($index == 1) {
                $item = strtotime($item . ' 23:59:59');
            }
        }

        $ids = [];
        $query = AppNews::query()
            ->where('is_delete', 0)
            ->select(['id'])
            ->when($title, fn($q) => $q->where('title', 'like', "%{$title}%"))
            ->whereBetween('created_at', $createdFilter)
            ->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 = AppNews::query()->whereIn('id', $ids)->orderBy('id', 'desc')->get()->toArray();
        // $value = AppNews::find($ids, ['title', 'is_record'])->toArray();
        return ['code' => 0, 'msg' => 'ok', 'count' => $pagination->total(), 'data' => $value];
    }

    /**
     * 查看文章详情信息
     * @url /admin/api/news/view
     */
    #[RequestMapping(path:'view', methods: 'get')]
    public function view(): \Psr\Http\Message\ResponseInterface
    {
        $query = AppNews::query()
            ->where('id', $this->request->query('id'));

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

    /**
     * 更新文章内容
     * @url /admin/api/news/update
     */
    #[RequestMapping(path:'update', methods: 'post')]
    public function update()
    {
        $model = new NewsFormModel();
        $model->setAttributes($this->request->post());
        $model->update();
        return $this->response->json(['code' => 0, 'msg' => 'ok']);
    }

    /**
     * 新增新新闻接口
     * @url /admin/api/news/insert
     */
    #[RequestMapping(path:'insert', methods: 'post')]
    public function insert()
    {
        $model = new NewsFormModel();
        $model->setAttributes($this->request->post(), ['title', 'keywords', 'description', 'cover', 'content', 'platform', 'column1', 'column2']);
        $model->insert();
        return $this->response->json(['code' => 0, 'msg' => 'ok']);
    }

    /**
     * 导入
     * [{title:'',desc:'',keywords:'',content:''}]
     * @url /admin/api/news/insert
     */
    #[RequestMapping(path:'import', methods: 'post')]
    public function import()
    {
        $content = $this->request->post('content', null);
        $platform = $this->request->post('platform', 0);
        $column = $this->request->post('column', 0);
        $column2 = $this->request->post('column2', 0);
        $cover = $this->request->post('cover', '');

        $imagesArr = [];
        // 自动选封面
        if (!$cover) {
            // 随机图片
            $directory = env('COVER_ROOT');  // 文件夹路径
            $images = glob($directory . '/*.{jpg,jpeg,png,gif,bmp}', GLOB_BRACE);  // 获取图片文件

            if (count($images) > 0) {
                foreach ($images as $image) {
                    $imagesArr[] =  basename($image);
                }
            }

            if (!$imagesArr) {
                return $this->response->json(['code' => 400, 'msg' => 'not content.']);
            }
        }

        if (!$content) {
            return $this->response->json(['code' => 400, 'msg' => 'not content.']);
        }

        $content = json_decode($content, true);
        foreach ($content as $item) {
            if ($imagesArr) {
                $randIndex = mt_rand(1,count($imagesArr));
                $cover = env('APP_DOMAIN') . '/uploads/cover/' . $imagesArr[$randIndex];
            }

            $model = new AppNews();
            $model->title = is_array($item['title']) ? current($item['title']) : $item['title'];
            $model->description = $item['desc'];
            $model->keywords = $item['keywords'];
            $model->platform = $platform;
            $model->cover = $cover;
            $model->content = strtr($item['content'], [
                '<imageSlot>' => <<<EOF
<p style="text-align:center"><img style="aspect-ratio: 4 / 3;max-width: 56%;" class="ue-image" src="$model->cover"></p>
EOF
            ]);

            $model->content = ArticleHelper::saveImagesFromArticle($model->content, srcPrefix: env('APP_DOMAIN') . '/uploads/');
            $model->column_tag = $column;
            $model->second_column = $column2;
            $model->save();
        }
        return $this->response->json(['code' => 0, 'msg' => 'ok']);
    }

    /**
     * 删除新新闻接口
     * @url /admin/api/news/delete
     */
    #[RequestMapping(path:'delete', methods: 'post')]
    public function delete(): \Psr\Http\Message\ResponseInterface
    {
        $id = $this->request->post('id');
        $query = AppNews::find($id);
        $query->is_delete = 1;
        $query->deleted_at = time();
        $query->save();
        return $this->response->json(['code' => 0, 'msg' => 'ok']);
    }
}