<?php

namespace app\event;

use app\service\BpsAdAccountService;
use app\service\GoogleAdsCampaignService;
use app\service\GoogleOAuthService;
use Google\ApiCore\ApiException;
use support\Response;
use DI\Annotation\Inject;
use Webman\RedisQueue\Redis;
use Webman\RedisQueue\Client;

//use QL\QueryList;


class GoogleAdsDateDatas
{

    /**
     * @Inject
     * @var GoogleOAuthService
     */

    private $googleOAuthService;


    /**
     * @Inject
     * @var BpsAdAccountService
     */

    private $bpsAdAccountService;

    const event = 'googleads:datedatas:event';
    const queue = 'googleads:datedatas:queue';
    const task = 'googleads:datedatas:task';

    //同步某段时间成效(默认新绑定用户触发7天历史数据)
    public function syncDateRangeDatas($options = [])
    {
        // 获取 startDate 和 endDate
        $startDate = $options['startDate'];
        $endDate   = $options['endDate'];

        // 验证日期格式
        if (!strtotime($startDate) || !strtotime($endDate)) {
            throw new \InvalidArgumentException('Invalid date format for startDate or endDate');
        }

        // 将日期转换为 DateTime 对象
        $startDate = new \DateTime($startDate);
        $endDate   = new \DateTime($endDate);

        // 获取队列名称
        $queue = self::queue;

        // 获取客户数据
//        $customers = $this->googleOAuthService->getGoogleAdCustomers($options);
        $customers = $this->bpsAdAccountService->getGoogleAdAccounts($options);

        // 遍历每一天的日期
        $interval  = new \DateInterval('P1D'); // 1天间隔
        $dateRange = new \DatePeriod($startDate, $interval, $endDate->modify('+1 day')); // 包含 endDate

        foreach ($dateRange as $date) {
            $currentDate = $date->format('Y-m-d'); // 格式化日期为 Y-m-d            // 遍历每个客户
            foreach ($customers as $customer) {
                if ($customer['login_customer_id'] > 0) {
                    $customer['date'] = $currentDate; // 设置当前日期
                    Redis::send($queue, $customer, rand(1, 10)); // 发送到 Redis 队列
                }
            }
        }
        //同步消息到同步任务表
//        $queueTask = self::task;
//        $taskInfo  = [
//            'ecommerce' => 1001,
//            'ecommerce_shop_id' => $options['date'],
//            'task_type' => 'InsightsMerge',
//            'remain' => 1
//        ];
//        Client::send($queueTask, $taskInfo, 30);


        return self::event . ' send queue ok';
    }

    //同步某天成效 废弃2025-2-13,改用syncDateRangeDatas
    public function syncDateDatas($options = [])
    {
        $queue     = self::queue;
//        $customers = $this->googleOAuthService->getGoogleAdCustomers($options);
        $customers = $this->bpsAdAccountService->getGoogleAdAccounts($options);
        foreach ($customers as $customer) {
            if ($customer['login_customer_id'] > 0) {
                $customer['date'] = $options['date'];
                Redis::send($queue, $customer, rand(1, 10));
            }
        }
        //同步消息到同步任务表
//        $queueTask = self::task;
//        $taskInfo  = [
//            'ecommerce' => 1001,
//            'ecommerce_shop_id' => $options['date'],
//            'task_type' => 'InsightsMerge',
//            'remain' => 1
//        ];
//        Client::send($queueTask, $taskInfo, 30);


        return self::event . ' send queue ok';
    }

    /**
     * get date datas
     * @throws ApiException
     */
    public function getDateDatas($customer)
    {
        //新客户表不用检查manager了
//        if ($customer['login_customer_id'] > 0 && ((isset($customer['manager']) && $customer['manager'] === false))) {
        if ($customer['login_customer_id'] > 0) {
//                dump($customer);
            $googleAdsCampaignService = new googleAdsCampaignService($customer['account_id']);
//                dump($customer['customer_id'],$customer, $options['date']);
            $googleAdsCampaignService->runListDateDatas($customer['account_id'], $customer, $customer['date']);
        }

//        $this->googleAdsCampaignService->runListDateDatas($options['customer_id'], $options['date']);
//        return $this->successResponse(['data' => $resourceName]);
    }

    /**
     * 通知到同步task todo
     * @throws ApiException
     */
    public function noticeDateDatas($taskInfo)
    {


    }


    // 可以加入一些公共方法
    protected function successResponse($data): Response
    {
        return Json([
            'code' => 0,
            'msg' => 'ok',
            'data' => $data,
        ]);
    }

    protected function errorResponse($code, $message, $data = []): Response
    {
        return Json([
            'code' => $code,
            'msg' => $message ?: 'error',
            'data' => $data
        ]);
    }
}