<?php

namespace BYDAuto\Models;

use BYDAuto\Observers\TestdriveObserver;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
use Illuminate\Database\Eloquent\Model;

/**
 * 销售线索.
 *
 * @property int $id
 * @property Carbon $date_created
 * @property Carbon $date_updated
 */
#[ObservedBy([TestdriveObserver::class])]
class Testdrive extends Model
{
    public const STATUS_UNKNOWN = 'unknown';

    public const STATUS_DRAFT = 'draft';

    public const STATUS_PUBLISHED = 'published';

    public const STATUS_ARCHIVED = 'archived';

    public const STATUS_REJECTED = 'rejected';

    public const CREATED_AT = 'date_created';

    public const UPDATED_AT = 'date_updated';

    protected $table = 'bydauto_testdrive';

    protected $fillable = ['status', 'name', 'mobile', 'platform', 'source', 'meta', 'rawdata', 'request_id', 'external_id'];

    protected $casts = ['meta' => 'json', 'rawdata' => 'json'];

    // 行业运SPI接口数据处理
    public static function isaas($data)
    {
        // {
        //     "alipayUserId": "2088002970810315",
        //     "extInfo": "",
        //     "formName": "预约试驾",
        //     "formResultBizCode": "formResult_a91a68a38acc49f1adf202ea15676909",
        //     "gmtCreate": "2024-09-04 17:38:48",
        //     "merchantAppId": "2021004170670447",
        //     "merchantPid": "2088511783986035",
        //     "propertyList": [
        //         { "key": "CID_20240904111701423264", "name": "您的姓名", "outCode": "", "value": "张伊琳" },
        //         { "key": "CID_20240904111701378536", "name": "联系电话", "outCode": "", "value": "13585623001" },
        //         { "key": "CID_20240904111701273727", "name": "意向车型", "outCode": "QR100", "value": "探索06 都市版" },
        //         { "key": "CID_20240904111701876422", "name": "选择门店", "outCode": "22486", "propertyExt": { "address": { "cityCode": "310100", "cityName": "上海城区", "provinceCode": "310000", "provinceName": "上海市" } }, "value": "上海远程汽车维修有限公司" }
        //     ],
        //     "responseClass": "com.alipay.adc.proxyopsplatform.biz.model.ecospi.response.FormDataQuerySpiResponse"
        // }

        // $externalId = $data['formResultBizCode'];
        // $model = static::query()->where('external_id', $externalId)->first();
        // if ($model) {
        //     info('===== isaas exists', $data);
        //     return $model;
        // }
        $model = new static(['source' => 'isaas', 'rawdata' => $data]);
        foreach ($data['propertyList'] as $prop) {
            // 手机号
            if ($prop['name'] === '联系电话') {
                $model->mobile = $prop['value'];
            }
            // 姓名
            if ($prop['name'] === '您的姓名') {
                $model->name = $prop['value'];
            }
            // // 意向车型
            // if ($prop['name'] === '意向车型') {
            //     $model->vehicle = $prop['value'];
            // }
            // // 门店
            // if ($prop['name'] === '选择门店') {
            //     $model->province = $prop['propertyExt']['address']['provinceName'] ?? '';
            //     $model->city = $prop['propertyExt']['address']['cityName'] ?? '';
            //     $model->dealer = $prop['value'] ?? '';
            //     $model->dealer_code = $prop['outCode'];
            // }
        }
        $model->save();
        return $model;
    }

    public static function cluepackage($data)
    {
        // {
        //     "id": "5100421",
        //     "sign": "M9XNP7B49mldvBqGkASL/PFp/0HITi7zwShy78FzArS9H+3WuUTNewy3QIIwMhWXS5sEaePjw5BtC0A7xYO4pYP2HVCcospiOTXO5boz/Ki03xeY7OhbY1YrhI5fhYqgQOj6Efn2mM44ijtXzMh4phDMgcu0e1HcgQFTDvIgAZZ5D6IvXyLR245WGMjSDnyqtMJj87MCrTj6ZmkfiLKvGH8mSWtKd0WFS6UgfQIs/Rruw0ZQNT5+mawTT8CZE1Va3Wt0xGc6CegeNtI4f/eFNHsqgppwXO0dtKPcWRZeNvNYUqQT1G9M1epC6lvxdPD+rr8i6SEVaBkxmQVF+eN8Iw==",
        //     "method": "spi.alipay.data.dataservice.ad.cluepackage.send",
        //     "charset": "UTF-8",
        //     "version": "1.0",
        //     "clue_time": "2024-08-26 22:11:59",
        //     "sign_type": "RSA2",
        //     "user_city": "河北省",
        //     "user_name": "滏",
        //     "extend_info": "{\"brandName\":\"奇瑞\",\"merchantId\":\"23408\",\"seriesName\":\"瑞虎8L\",\"merchantName\":\"唐山荣泽\"}",
        //     "user_province": "唐山市",
        //     "utc_timestamp": "1724681530",
        //     "user_mobile_no": "15318418738"
        // }

        // $externalId = $data['id'];
        // $model = static::query()->where('external_id', $externalId)->first();
        // if ($model) {
        //     info('===== cluepackage exists', $data);
        //     return $model;
        // }
        $model = new static(['source' => 'cluepackage', 'rawdata' => $data]);
        $model->name = $data['user_name'] ?? '';
        $model->mobile = $data['user_mobile_no'] ?? '';
        $model->meta = $data['extend_info'] ?? [];
        $model->save();

        return $model;
    }

    public static function syncFromAliPromote($data, $pageId)
    {
        // {
        //     "biz_no":"PROMOTE_PAGE#COLLECT_INFO#99800024#22f01c68c22e0572dbbf48e5abddce9f_1200811224",
        //     "encrypt_uid":"g0uZivSfdAauU6JcY6qU5zUYbPJAZusYEhYlBjWoD10=",
        //     "property_list":[
        //         {"key":"phone", "name":"手机号", "value":"13823496047"},
        //         {"key":"name", "name":"姓名", "value":"罗"},
        //         {"key":"tree_option_1", "name":"意向车型", "value":"瑞虎8L"},
        //         {"key":"tree_option_2", "name":"所在城市", "value":"黑龙江省-佳木斯市"},
        //         {"key":"principal_name", "name":"商家名称", "value":"安徽奇瑞汽车销售有限公司"},
        //         {"key":"market_target_name", "name":"营销目标", "value":"销售线索搜集"},
        //         {"key":"plan_name", "name":"计划名称", "value":"cpa-瑞虎8L-0823-1"},
        //         {"key":"plan_id", "name":"计划ID", "value":"131702876"},
        //         {"key":"group_name", "name":"单元名称", "value":"cpa-瑞虎8L-0823-1"},
        //         {"key":"group_id", "name":"单元ID", "value":"144611104"},
        //         {"key":"ad_name", "name":"创意名称", "value":"cpa-瑞虎8L-0823-1"},
        //         {"key":"creative_id", "name":"创意ID", "value":"170187992"},
        //         {"key":"interested_desc", "name":"意向线索", "value":"空白"},
        //         {"key":"click_id", "name":"点击ID", "value":"7f9685e2edf3a48996fbc444473035a4"}
        //     ]
        // }

        $externalId = $data['biz_no'];
        $model = static::query()->where('external_id', $externalId)->first();
        if ($model) {
            return $model;
        }
        $model = new static(['source' => 'alipromote:' . $pageId, 'rawdata' => $data, 'external_id' => $externalId]);
        foreach ($data['property_list'] as $prop) {
            // 手机号
            if ($prop['key'] === 'phone') {
                $model->mobile = $prop['value'];
            }
            // 姓名
            if ($prop['key'] === 'name') {
                $model->name = $prop['value'];
            }
            // // 意向车型
            // if (Str::contains($prop['name'], '车型')) {
            //     $model->vehicle = $prop['value'];
            // }
            // // 城市: 黑龙江省-哈尔滨市
            // if (Str::contains($prop['name'], '城市')) {
            //     if (Str::contains($prop['value'], '-')) {
            //         [$model->province, $model->city] = explode('-', $prop['value']);
            //     } else {
            //         $model->city = $prop['value'];
            //     }
            // }
            // // 门店：黑龙江省-哈尔滨市-哈尔滨若冲
            // if (Str::contains($prop['name'], '门店')) {
            //     if (Str::contains($prop['value'], '-')) {
            //         $value = explode('-', $prop['value']);
            //         $model->province = $value[0] ?? '';
            //         $model->city = $value[1] ?? '';
            //         $model->dealer = $value[2] ?? '';
            //     } else {
            //         $model->dealer = $prop['value'];
            //     }
            // }
        }
        $model->save();
        return $model;
    }
}
