<?php

namespace App\FormModel\spiderArticle;

use App\Enums\SpiderArticlePublishedStatusEnum;
use App\Helpers\AppHelper;
use App\Model\AppArticle;
use App\Model\AppSpiderArticle;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;

class ReviewModel
{
    #[Inject]
    private readonly RequestInterface $_request;

    /**
     * 爬虫文章预发布
     * @param $spiderArticleId
     * @return void
     * @throws \Exception
     */
    public function prePublish($spiderArticleId)
    {
        try {
            Db::beginTransaction();

            $query = AppSpiderArticle::find($spiderArticleId);

            $model = new AppArticle();
            $model->title = $query->title;
            $model->aid = AppHelper::generateAid();
            $model->cover = $query->cover;
            $model->images = $query->images;
            $model->year = $query->year;
            $model->module = $query->module;
            $model->brand = $query->brand;
            $model->spider_article_id = $spiderArticleId;
            $model->published_status = 0;
            $model->save();

            $query->published_status = SpiderArticlePublishedStatusEnum::TRUE->value;
            $query->published_at = time();
            $query->save();

            Db::commit();
        } catch (\Throwable $throwable) {
            Db::rollBack();
            throw new \Exception($throwable->getMessage());
        }
    }

    public function delete($spiderArticleId)
    {
        try {
            Db::beginTransaction();

            $query = AppSpiderArticle::find($spiderArticleId);
            $query->deleted_at = SpiderArticlePublishedStatusEnum::DELETE;
            $query->deleted_at = time();
            $query->save();
            Db::commit();
        } catch (\Throwable $throwable) {
            Db::rollBack();
            throw new \Exception($throwable->getMessage());
        }
    }
}