using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using _Combo;
using _Combo.Events;
using _Core;
using Seayoo.ComboSDK.Windows.Store.Networking;
using Seayoo.ComboSDK.Windows.Store.Tools;
using UnityEngine;
using UnityEngine.UI;

namespace Seayoo.ComboSDK.Windows.Store.View
{
    public class QRCodePayView : MonoBehaviour
    {
        public Button cancelBtn;
        public Button backBtn;
        public Text titleText;
        public Text productNameText;
        public Text productValueText;
        public Text payTipText;
        public Text expiredText;
        public HyperlinkText reorderText;
        public Image expiredImage;
        public Image titleImage;
        public RawImage QRCodeImg;
        public Sprite weixinSprite;
        public Sprite alipaySprite;
        public GameObject expiredPanel;
        public RectTransform titleTransform;
        private bool stopPolling = false;
        private long targetTime;
        private string url;

        private Order order;
        private string orderToken;

        private QRCodeTool codeTool = new QRCodeTool();
        private string method = SeayooStoreManager.Instance.GetPaymentMethodName(PaymentMethods.WEIXIN_NATIVE);
        void Awake()
        {
            EventSystem.Register(this);
            gameObject.SetActive(false);
        }

        void Start()
        {
            expiredText.text = I18n.T("payment_qrcode_expired_text_above_qrcode");
            reorderText.text = I18n.T("payment_qrcode_expired_text");
            cancelBtn.onClick.AddListener(OnClose);
            backBtn.onClick.AddListener(OnBackPayView);
        }

        void OnDestroy()
        {
            EventSystem.UnRegister(this);
            cancelBtn.onClick.RemoveListener(OnClose);
            backBtn.onClick.RemoveListener(OnBackPayView);
        }

        public void OnClose()
        {
            stopPolling = true;
            SeayooStoreClient.QueryPayment(orderToken, method, result =>
            {
                if (result.Data.paymentStatus == "pending")
                {
                    PurchaseCancelEvent.Invoke();
                }
                else if (result.Data.paymentStatus == "paid")
                {
                    PurchaseSuccessEvent.Invoke(new PurchaseSuccessEvent
                    {
                        orderId = order.orderId
                    });
                }
                else
                {
                    var ie = new InternalError(I18n.T("iap_payment_failed"), new StoreError(order, "seayoo_store"));
                    PurchaseFailedEvent.Invoke(new PurchaseFailedEvent { error = ie });
                }
                ClosePayViewCommand.Invoke(new ClosePayViewCommand());
            }, (err) =>
            {
                PurchaseFailedEvent.Invoke(new PurchaseFailedEvent { error = err });
                ClosePayViewCommand.Invoke(new ClosePayViewCommand());
            });
        }

        public void OnBackPayView()
        {
            GoToViewCommand.Invoke(new GoToViewCommand
            {
                type = PayViewType.PAY,
                order = order,
                orderToken = orderToken,
                productName = productNameText.text,
                productValue = productValueText.text
            });
        }

        public void OnNewOrder()
        {
            var error = new InternalError(I18n.T("order_expired_toast"), new StoreError(order, "seayoo_store", enableTracking: false));
            PurchaseFailedEvent.Invoke(new PurchaseFailedEvent { error = error });
            ClosePayViewCommand.Invoke(new ClosePayViewCommand());
            stopPolling = true;
        }

        [EventSystem.BindEvent]
        public void OnQueryResult(QueryPaymentResultsCommand action)
        {
            if (action.method == PaymentMethods.SEAYOO_SANDBOX)
            {
                return;
            }
            if (action.status == PaymentStatus.PAID)
            {
                GoToViewCommand.Invoke(new GoToViewCommand
                {
                    type = PayViewType.PAY_SUCCESS,
                    order = order,
                    productName = productNameText.text,
                    productValue = productValueText.text,
                    paymentMethod = action.method
                });
            }
        }

        [EventSystem.BindEvent]
        public void ShowPayView(GoToViewCommand action)
        {
            if (action.type != PayViewType.PAY_QR)
            {
                gameObject.SetActive(false);
                return;
            }
            gameObject.SetActive(true);
            QRCodeImg.gameObject.SetActive(false);
            url = action.url;
            targetTime = action.timeExpire;
            ShowQRCode(url);
            orderToken = action.orderToken;
            order = action.order;
            method = SeayooStoreManager.Instance.GetPaymentMethodName(action.paymentMethod);
            StartCoroutine("Polling");
            productNameText.text = action.productName;
            productValueText.text = action.productValue;
            Refresh();
            if (action.paymentMethod == PaymentMethods.WEIXIN_NATIVE)
            {
                titleText.text = I18n.T("weixin_pay_qrcode_text");
                titleImage.sprite = weixinSprite;
                titleImage.rectTransform.sizeDelta = new Vector2(36, 32);
                payTipText.text = I18n.T("weixin_pay_qrcode_tip_text");
                LayoutRebuilder.ForceRebuildLayoutImmediate(titleTransform);
            }
            else if (action.paymentMethod == PaymentMethods.ALIPAY_QR_CODE)
            {
                titleText.text = I18n.T("alipay_qrcode_text");
                titleImage.sprite = alipaySprite;
                titleImage.rectTransform.sizeDelta = new Vector2(30, 30);
                payTipText.text = I18n.T("alipay_pay_qrcode_tip_text");
                LayoutRebuilder.ForceRebuildLayoutImmediate(titleTransform);
            }
        }

        private void Refresh()
        {
            stopPolling = false;
            expiredImage.gameObject.SetActive(false);
            expiredText.gameObject.SetActive(false);
            payTipText.gameObject.SetActive(true);
            expiredPanel.SetActive(false);
        }

        private void ShowQRCode(string url)
        {
            if (codeTool.isEncodeing() == false)
            {
                codeTool.EncodeQRCode(url, new Vector2Int(268, 268));
                StartCoroutine(getQRCode());
            }
        }

        IEnumerator getQRCode()
        {
            while (true)
            {
                if (codeTool.GetQRimage() != null)
                {
                    QRCodeImg.gameObject.SetActive(true);
                    QRCodeImg.texture = codeTool.GetQRimage();
                    break;
                }
                yield return 0;
            }
        }

        private IEnumerator Polling()
        {
            while (!stopPolling)
            {
                long currentTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds();

                // 判断是否到达指定时间戳的1分钟后，如果到达则停止轮询
                if (currentTimestamp >= targetTime + 60)
                {
                    stopPolling = true;
                }
                if (currentTimestamp >= targetTime)
                {
                    // 二维码过期
                    expiredImage.gameObject.SetActive(true);
                    expiredText.gameObject.SetActive(true);
                    payTipText.gameObject.SetActive(false);
                    expiredPanel.SetActive(true);
                    StartCoroutine(SetHyperlinkActionsDelayed());
                }
                SeayooStoreManager.Instance.QueryPayment(orderToken, method);
                yield return new WaitForSeconds(2f);
            }
        }

        private IEnumerator SetHyperlinkActionsDelayed()
        {
            // 等待一帧，确保 OnPopulateMesh 执行
            yield return null;

            reorderText.SetHyperlinkClickActions(new Dictionary<string, System.Action<string>>{
                {"reorder", (link)=>{OnNewOrder();}}
            });
        }

    }
}