<?php

namespace app\model;

use think\Model;

class BpsAdInsight extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'bps.bps_ads_insights';

    // 设置复合主键
    protected $pk = ['id'];

    // 设置自动时间戳
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段
    protected $createTime = 'create_at';
    protected $updateTime = 'update_at';

    // 设置字段类型和默认值
    protected $casts = [
        'ad_id' => 'int',
        'account_id' => 'int',
        'clicks' => 'int',
        'spend' => 'int',
        'purchases_value' => 'int',
        'revenue' => 'int',
        'impressions' => 'int',
        'date' => 'date',
    ];

    // 默认值设置
    protected $defaults = [
        'clicks' => 0,
        'spend' => 0,
        'purchases_value' => 0,
        'revenue ' => 0,
        'impressions' => 0,
        'ad_name' => '',
    ];

        // 检查唯一键
    protected function checkUniqueKey()
    {
        $exists = $this->where('ad_id', $this->ad_id)
            ->where('date', $this->date)
            ->where('platform', $this->platform)
            ->find();

        if ($exists && $exists->id != $this->id) {
            throw new \Exception('数据已存在,ad_id、date 和 platform 必须唯一');
        }
    }

    // 在保存数据前调用
    protected static function onBeforeWrite($model)
    {
        $model->checkUniqueKey();
    }


    // 关联 Campaign 模型(报告数据属于广告活动)
    public function campaign()
    {
        return $this->belongsTo(BpsAdCampaign::class, 'campaign_id', 'campaign_id');
    }

    // 关联 AdGroup 模型(报告数据属于广告组)
    public function adSet()
    {
        return $this->belongsTo(BpsAdSet::class, 'ad_set_id', 'ad_set_id');
    }

    // 关联 Ad 模型(报告数据属于广告)
    public function ad()
    {
        return $this->belongsTo(BpsAdAd::class, 'ad_id', 'ad_id');
    }

    // 关联 Customer 模型(报告数据与客户相关)
//    public function customer()
//    {
//        return $this->belongsTo(GoogleAdsCustomer::class, 'account_id', 'account_id');
//    }

    // 关联 Budget 模型(报告数据与预算相关)
//    public function budget()
//    {
//        return $this->belongsTo(CampaignBudget::class, 'budget_id', 'budget_id');
//    }
}