<?php

namespace App\Distributor\Repositories;

use App\Models\SmmPost as Model;
use Carbon\Carbon;
use Dcat\Admin\Repositories\EloquentRepository;

class SmmPost extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;


    /*
     * 插入数据
     */
    public static function create($post,$sendTime,$imageVideoUrl,$distId)
    {
        $model = new Model();
    //    $model->send_type = $post['send_type'];
        $model->send_time = $sendTime;
        $model->message = $post['message'];
        $model->post_type = $post['post_type'];
        $model->account_ids = implode(',',$post['account_ids']);
        $model->image_video_url = $imageVideoUrl;
        $model->status = 0;
        $model->dist_id = $distId;
        $model->backup_field1 = json_encode([
            'youtube_category' => $post['youtube_category'],
            'yutube_title' => $post['yutube_title'],
        ]);
        $model->save();
        return $model->id;
    }

    /*
     * 找出状态 0 的数据
     */
    public static function getWaitPost()
    {
        $model = new Model();
        $model = $model->where('status',0)->get();
        return $model;
    }

    public static function getOssUploadPost()
    {
        $model = new Model();
        $model = $model->where('oss_upload',0)->get();
        return $model;
    }

    public static function hasOssUploadingPost()
    {
        $model = new Model();
        $result = $model->where('oss_upload',1)->first();
        if($result){
            //updated_at到现在时间大于10分钟，则认为已经上传失败
            $now = Carbon::now();
            $diff = $now->diffInMinutes($result->updated_at);
            if($diff > 10){
                $result->oss_upload = 0;//改为0，重新发送
                $result->updated_at = $now;
                $result->save();
                return true;
            }
            return true;
        } else {
            return false;
        }
    }


    public static function getPostById($id)
    {
        $model = new Model();
        $model = $model->where('id',$id)->first();
        return $model;
    }


}
