using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine;

namespace RedHotRoast
{
    public class BIManager : MonoBehaviour
    {
        private static BIManager _instance;
        public static BIManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    var go = new GameObject("BIManager");
                    DontDestroyOnLoad(go);
                    _instance = go.AddComponent<BIManager>();
                }

                return _instance;
            }
        }
        // ================= 通用埋点 =================
        public void TrackEvent(string eventName, Dictionary<string, object> properties = null)
        {
            if (properties == null)
                properties = new Dictionary<string, object>();

            // DataEyeAnalyticsAPI.Track(eventName, properties);
            // DataEyeAnalyticsAPI.Flush();
#if UNITY_IOS&&!UNITY_EDITOR
            BrigdeIOS.TrackProduct(eventName, JsonConvert.SerializeObject(properties));
#endif
            Debug.Log($"[BI] 事件上报: {eventName}, 属性={JsonConvert.SerializeObject(properties)}");
        }

        // ================= 预制事件封装 =================

        /// <summary>
        ///     上报广告事件
        /// </summary>
        /// <param name="eventName"></param>
        /// <param name="adType">Native，RewardedVideo，Banner，Interstitial，Splash</param>
        /// <param name="placementId">聚合广告位id</param>
        /// <param name="networkFirmId">广告网络ID</param>
        public void TrackAdEvent(string eventName, string adType, string placementId = null,
            string networkFirmId = null, double revenue = 0, string scene = null, string currency = "USD")
        {
            var props = new Dictionary<string, object>
            {
                { "ad_type", adType }
            };

            if (!string.IsNullOrEmpty(placementId))
                props["PlacementId"] = placementId;

            if (!string.IsNullOrEmpty(networkFirmId))
                props["NetworkFirmId"] = networkFirmId;

            if (revenue > 0)
            {
                props["Revenue"] = revenue;
                props["Ecpm"] = revenue * 1000;
            }

            if (!string.IsNullOrEmpty(scene))
                props["scene"] = scene;

            if (!string.IsNullOrEmpty(currency))
                props["Currency"] = currency;


            TrackEvent(eventName, props);
        }

        /// <summary>
        ///     上报内购事件
        /// </summary>
        /// <param name="revenue">收入</param>
        /// <param name="currency">币种</param>
        /// <param name="payType">支付方式  0=商店支付，1=三方支付</param>
        /// <param name="itemId">sku</param>
        /// <param name="status">order:下单 paid:付费成功 paid_err:扣款失败</param>
        /// <param name="itemName">商品名称</param>
        /// <param name="msg">如果遇到异常或相关情况，将err_msg进行上报</param>
        public void TrackPurchase(double revenue, string currency, string payType, string itemId,
            string status, string itemName = null, string msg = null)
        {
            var props = new Dictionary<string, object>
            {
                { "Revenue", revenue },
                { "Currency", currency },
                { "type", payType },
                { "item_id", itemId },
                { "purchase_status", status }
            };

            if (!string.IsNullOrEmpty(itemName))
                props["item_name"] = itemName;
            if (!string.IsNullOrEmpty(msg))
                props["msg"] = msg;

            TrackEvent(BIEvent.PURCHASE, props);
        }

        /// <summary>
        ///     上报页面浏览
        /// </summary>
        public void TrackPageView(string pageName)
        {
            var props = new Dictionary<string, object>
            {
                { "page_name", pageName } // 例如 "loading"、"game"
            };

            TrackEvent(BIEvent.PAGE_VIEW, props);
        }

        /// <summary>
        ///     AB 分组埋点
        /// </summary>
        public void TrackABConfig(int responseTime)
        {
            var props = new Dictionary<string, object>
            {
                { "response_time", responseTime }
            };

            TrackEvent(BIEvent.AB_CONFIG, props);
        }
    }
}

public static class BIEvent
{
    // 自动采集（SDK 开启自动采集即可，不需要手动埋点）
    public const string APP_INSTALL = "app_install";
    public const string APP_START = "app_start";
    public const string APP_END = "app_end";
    public const string APP_VIEW = "app_view";
    public const string APP_CRASH = "app_crash";

    // 内部预制事件
    public const string AD_REQUEST = "ad_request"; // 广告请求
    public const string AD_INVENTORY = "ad_inventory"; // 广告填充的时候
    public const string AD_IMP = "ad_imp"; // 广告展示
    public const string AD_CLICK = "ad_click"; // 广告点击

    public const string PURCHASE = "purchase"; // 内购

    // 页面相关
    public const string PAGE_VIEW = "page_view_customize";

    // 其他业务事件（AB 测试等）
    public const string AB_CONFIG = "config"; // AB 
}