<?php
// app/service/BaseService.php
namespace app\service;

use app\model\ThirdUser;
use think\db\exception\BindParamException;
use think\facade\Db as ThinkDb;
use app\model\Campaign as CampaignModel;

class BaseService
{
    /**
     * 更新广告系列状态
     *
     * @param int $campaignId 广告系列ID
     * @param int $status 新的状态值
     * @return bool
     */
    public function modifyDbCampaignStatus(int $campaignId, int $status)
    {
        // 确保状态值是有效的(例如可以是 ENABLED、PAUSED 等)
        if (!in_array($status, [2, 3, 4])) {  // 这里 1、2、3 是示例状态码,按需替换
            throw new \think\exception\ValidateException('Invalid status');
        }

        // 使用原始 SQL 更新状态
        $sql = "UPDATE bps.bps_google_ads_campaign SET status = :status, update_at = CURRENT_TIMESTAMP WHERE campaign_id = :campaign_id";

        // 执行 SQL 更新
        $result = ThinkDb::execute($sql, ['status' => $status, 'campaign_id' => $campaignId]);

        return $result > 0;  // 如果更新成功,返回 true,否则返回 false
    }

    /**
     * 更新广告组状态
     *
     * @param int $groupId 广告组ID
     * @param int $status 新的状态值
     * @return bool
     * @throws BindParamException
     */
    public function modifyDbGroupStatus(int $groupId, int $status)
    {
        // 确保状态值是有效的(例如可以是 ENABLED、PAUSED 等)
        if (!in_array($status, [2, 3, 4])) {  // 这里 1、2、3 是示例状态码,按需替换
//            throw new \think\exception\ValidateException('Invalid status');
        }

        // 使用原始 SQL 更新状态
        $sql = "UPDATE bps.bps_google_ads_ad_group SET status = :status, update_at = CURRENT_TIMESTAMP WHERE ad_group_id = :ad_group_id";

        // 执行 SQL 更新
        $result = ThinkDb::execute($sql, ['status' => $status, 'ad_group_id' => $groupId]);

        return $result > 0;  // 如果更新成功,返回 true,否则返回 false
    }

    /**
     * 更新广告组状态
     *
     * @param int $groupId 广告组ID
     * @param int $status 新的状态值
     * @return bool
     * @throws BindParamException
     */
    public function modifyDbAdStatus(int $adId, int $status)
    {
        // 确保状态值是有效的(例如可以是 ENABLED、PAUSED 等)
        if (!in_array($status, [2, 3, 4])) {  // 这里 1、2、3 是示例状态码,按需替换
//            throw new \think\exception\ValidateException('Invalid status');
        }

        // 使用原始 SQL 更新状态
        $sql = "UPDATE bps.bps_google_ads_ad SET status = :status, update_at = CURRENT_TIMESTAMP WHERE ad_id = :ad_id";

        // 执行 SQL 更新
        $result = ThinkDb::execute($sql, ['status' => $status, 'ad_id' => $adId]);

        return $result > 0;  // 如果更新成功,返回 true,否则返回 false
    }


    /**
     * 从数据库获取 refreshToken
     *
     * @param string $thirdUserId 广告主ID
     * @return string|null
     */
    public function getRefreshTokenFromDatabase($thirdUserId)
    {
        // 通过 advertiser_id 查询 ThirdUserAdvertiser,联表查询 ThirdUser 数据
        $thirdUser = ThirdUser::find($thirdUserId);
//dump($thirdUser);

        // 如果找到广告主数据
        if ($thirdUser) {
            return $thirdUser->access_token;  // 返回 access_token
        }

        return null;  // 如果没有找到,返回 null
    }
}