<?php

namespace App\Distributor\Repositories;

use App\Models\SmmPostLog as Model;
use Carbon\Carbon;
use Dcat\Admin\Repositories\EloquentRepository;
use Illuminate\Support\Facades\Log;

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



    /*
     * 创建日志
     */
    public static function createLog($data)
    {
        $log = new Model();
        $log->post_id = $data['post_id'];
        $log->account_id = $data['account_id'];
        $log->account_name = $data['account_name'];
        $log->status = $data['status'];
        $log->remark = $data['remark'];
        $log->created_at = $data['created_at'];
        $log->updated_at = $data['updated_at'];
        $log->dist_id = $data['dist_id'];
        $log->media_name = $data['media_name'];
        $log->response_ids = $data['response_ids'];
        $log->send_time = $data['send_time'];
        $log->save();
    }

    /*
     * 找状态为0并且发送时间小于当前时间的日志
     */
    public static function getSendLog($limit = 5)
    {
        $log = new Model();
        $result = $log->where('status', 1)->first();//查找状态为1的日志,发送中的日志
        if ($result) {
            //updated_at与当前时间差距30分钟以上，则更新日志状态为3
            $nowTime = Carbon::now();
            $diffTime = $nowTime->diffInMinutes($result->updated_at);
            if ($diffTime >= 30) {
                Log::info('发送中的帖子超过30分钟，更新状态为3，发送失败');
                $result->status = 3;
                $result->save();
            }
            Log::info('有正在发送中的帖子，返回[]');
            return [];
        }
        //找出是否有帖子正在上传到Oss如果有，则不发送
        $ossUploadPost = SmmPost::getOssUploadPost();

        if ($ossUploadPost->isNotEmpty())  {
            Log::info('有帖子正在上传到oss，不发送帖子');
            return [];
        }

        //找出待发送与发送失败的日志,重试2次
        $result = $log->wherein('status', [0,3])->where('request_count', '<=', 2)->where('send_time', '<', Carbon::now())->limit($limit)->get();
        return $result;
    }


    /*
     * 计算Twitter月配额，每月只能发送100个帖子，（只限发送帖子，其他接口，每个用户1个请求，15分钟内只允许发送一次）
     * 全站统计
     */
    public static function getPostQuota($mediaName = 'Twitter')
    {
        $log = new Model();

        if ($mediaName === 'Twitter') {
            // 获取当月第一天 00:00:00 的时间戳
            $startOfMonth = Carbon::now()->startOfMonth();

            $rows = $log->where('media_name', 'Twitter')
                ->where('created_at', '>=', $startOfMonth->format('Y-m-d H:i:s'))
                ->get();
            $count = 0;
            foreach ($rows as $row) {
                if ($row->status == 0) {
                    $count++;
                } else {
                    $count = $count + $row->request_count;
                }
            }
            return 100 - $count;

        } elseif ($mediaName === 'YouTube') {
            // 获取当天 00:00:00 的时间戳
            $startOfDay = Carbon::now()->startOfDay();

            $rows = $log->where('media_name', 'YouTube')
                ->where('created_at', '>=', $startOfDay->format('Y-m-d H:i:s'))
                ->get();

            $count = 0;
            foreach ($rows as $row) {
                if ($row->status == 0) {
                    $count++;
                } else {
                    $count = $count + $row->request_count;
                }
            }

            // 计算可用配额（向下取整）
            $quota = floor((10000 - 1600 * $count) / 1600);
            return max($quota, 0); // 保证最小返回0

        } else {
            return 999;
        }
    }



    /*
     * 返回Twitter可以发送的时间
     */
    public static function getTwitterSendTime()
    {
        // 将字符串转换为Carbon实例
        $sendTimeCarbon = Carbon::now();

        $log = new Model();
        $query = $log->where('status', 0)
            ->where('media_name', 'Twitter')
            ->where('send_time', '>=',$sendTimeCarbon->copy()->subMinutes(15))
            ->orderByDesc('id')
            ->first();

        if ($query) {
            // 返回格式化的时间字符串（与原输入格式保持一致）
            $query_send_time = Carbon::parse($query->send_time);
            return $query_send_time
                ->addMinutes(16)
                ->toDateTimeString();
        }

        // 没有记录时返回原始字符串
        return Carbon::now();
    }

    /*
     * 判断是否可以发送
     *
     */
    public static function twitterCanSend()
    {
        $log = new Model();
        //查找最后一条发送记录
        $lastSendLog = $log->wherein('status', [2,3])->where('media_name', 'Twitter')->orderByDesc('send_time')->first();
        //如果时间间隔小于15分钟，则不允许发送
        if ($lastSendLog) {
            $lastSendTime = Carbon::parse($lastSendLog->send_time);
            $nowTime = Carbon::now();
            $diffTime = $nowTime->diffInMinutes($lastSendTime);
            if ($diffTime <= 15) {
                return false;
            }
        }
        return true;
    }

}
