<?php

namespace App\Distributor\Repositories;

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

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

    /**
     * 插入新的社媒账号（仅在找到对应社媒时插入）
     *
     * @param string $mediaName    要查找的社媒名称
     * @param string $accountName 要插入的账号名称
     * @param string $accessToken 访问令牌
     * @return Model|null         新创建的模型实例或null
     */
    public static function createAccountIfMediaExists($mediaName, $accountId,$accountName, $accessToken,$expiresAt,$refreshToken = '',$backupField1 = '')
    {
        $model = new Model();
        // 查找匹配的社媒记录
        $mediaRecord = $model->where('name', $mediaName)->first();
        if (!$mediaRecord) {
            return null;
        }
        // 查找是否存在相同的账号
        $userRow = $model->where('account_id', $accountId)->first();
        if ($userRow) {
            $userRow->access_token = $accessToken;
            $userRow->expires_at = $expiresAt;
            $userRow->name = $accountName;
            $userRow->refresh_token = $refreshToken;
            $userRow->backup_field1 = $backupField1;
            $userRow->save();
        } else {
            // 创建新账号并关联父级
            $data = [
                'account_id'   => $accountId,
                'name'        => $accountName,
                'access_token' => $accessToken,
                'expires_at'   => $expiresAt,
                'parent_id'    => $mediaRecord->id,
                'dist_id'      => getDistributorId(),
                'created_at'   => Carbon::now(),  // 自动生成时间戳
                'updated_at'   => Carbon::now(),
                'refresh_token' => $refreshToken,
                'backup_field1' => $backupField1, //备用字段
            ];
            $model->insert($data);
        }
        return true;
    }


    /*
     * 查出dist_id=0和parent_id=0的账号
     */
    public static function getRootAccounts()
    {
        $model = new Model();
        $accounts = $model->where('dist_id', 0)->where('parent_id', 0)->get();
        return $accounts;
    }


    /*
     * 查找当前用户下所有用户账号(只显示有效的账号)
     */
    public static function getUserAccounts()
    {
        $model = new Model();
        $accounts = $model->where('dist_id','=', getDistributorId())->where('parent_id','>',0)->where('expires_at','>', Carbon::now())->orderBy('parent_id', 'asc')->get();
        return $accounts;
    }

    /*
     *  查找所有用户账号 (全站账号)
     */
    public static function getAllYouTubeUserAccounts()
    {
        $model = new Model();
        $youTube = $model->where('name', 'YouTube')->first();
        $twitter = $model->where('name', 'Twitter')->first();
        $parentIds = [$youTube->id,$twitter->id];
        //15分钟前
        $time = Carbon::now()->addMinutes(15);
        $accounts = $model->whereIn('parent_id',$parentIds)->where('expires_at','<', $time)->where('expires_at','>', Carbon::now())->orderBy('id', 'asc')->get();
        //dd($accounts->toArray());
        return $accounts;
    }

    /*
     *  查找所有用户账号
     */
    public static function getAccountsByIds($ids)
    {
        $model = new Model();
        $accounts = $model->whereIn('id', $ids)->get();
        return $accounts;
    }

    public static function getAccountById($id)
    {
        $model = new Model();
        $account = $model->find($id);
        return $account;
    }

    /*
     * 返回子账号数量
     */
    public static function returnChildCount($id, $distId)
    {
        $model = new Model();
        $count = $model->where('parent_id', $id)->where('dist_id', $distId)->where('expires_at','>', Carbon::now())->count();
        return $count;
    }



    public static function getYoutubeCategory()
    {
        $model = new Model();
        $categories = $model->where('name', 'YouTube')->first();
        $categories = json_decode($categories->backup_field1,true);
        return $categories;
    }



    public static function deleteAccount($id, $distId)
    {
        $model = new Model();
        $account = $model->find($id);
        if ($account && $account->dist_id == $distId && $account->parent_id > 0) {
            $account->delete();
            return true;
        }
        return false;
    }

     /*
      * 查找用户IDS中有无YouTube的帐号
      */
    public static function findYoutubeAccount($ids, $distId)
    {
        $model = new Model();
        $youTubeRs = $model->where('name', 'YouTube')->first();
        $result = $model->where('parent_id', $youTubeRs->id)->whereIn('id', $ids)->where('dist_id', $distId)->get();
        return $result;
    }

    /*
     * 判断用户是否可以发送POST
     * 根据IDS查找用户账号，找到是否超
     */

    public static function checkAccountCanSendPost($ids, $distId) {
        $model = new Model();
        $result = $model->whereIn('id', $ids)->where('dist_id', $distId)->get();
        $youTubeCount = 0;
        $twitterCount = 0;
        foreach ($result as $row) {
            if ($row->getParent->name == 'YouTube') {
                $youTubeCount++;
            }
            if ($row->getParent->name == 'Twitter') {
                $twitterCount++;
            }
        }
        if (SmmPostLog::getPostQuota('YouTube') < $youTubeCount) {
            return ['status'=>false,'mediaName'=>'YouTube'];
        }
        if (SmmPostLog::getPostQuota('Twitter') < $twitterCount) {
            return ['status'=>false,'mediaName'=>'Twitter'];
        }
        return ['status'=>true];
    }

}
