<?php

namespace app\command;

use app\model\GoogleAdsAsset;
use app\model\GoogleAdsAd;
use app\model\GoogleAdsAssetRelations;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class SyncGoogleAdsAsset extends Command
{
    protected function configure()
    {
        $this->setName('sync:google_ads_asset')
            ->setDescription('Synchronize Google Ads Asset relations');
    }

    protected function execute(Input $input, Output $output)
    {
        // 获取所有素材
        $assets = GoogleAdsAsset::where('status', 1)->select();

        foreach ($assets as $asset) {
            // 获取广告表中的所有广告
            $ads = GoogleAdsAd::where('status', 1)->select();

            foreach ($ads as $ad) {
                // 检查广告的 metadata 是否包含素材的 resource_name
                if (isset($ad->metadata) && strpos($ad->metadata, $asset->resource_name) !== false) {
                    // 插入关联记录
                    $existingRelation = GoogleAdsAssetRelations::where('asset_id', $asset->asset_id)
                        ->where('ad_id', $ad->ad_id)
                        ->where('date', date('Y-m-d'))
                        ->find();

                    if (!$existingRelation) {
                        // 如果没有现有记录,则插入新的关联
                        GoogleAdsAssetRelations::create([
                            'asset_id' => $asset->asset_id,
                            'ad_id' => $ad->ad_id,
                            'ad_group_id' => $ad->ad_group_id,
                            'campaign_id' => $ad->campaign_id,
                            'date' => date('Y-m-d')
                        ]);

                        $output->writeln("Inserted relation for Asset ID: {$asset->asset_id} and Ad ID: {$ad->ad_id}");
                    } else {
                        $output->writeln("Relation already exists for Asset ID: {$asset->asset_id} and Ad ID: {$ad->ad_id}");
                    }
                }
            }
        }

        $output->writeln('Google Ads Asset synchronization completed.');
    }
}