using System;
using System.Collections.Generic;
using GameMessage;
using MessagePack;
using Server.Core;

namespace Server.Config
{
    public partial class DiamondMallConfigCategory
    {
        /// <summary>
        /// AppStoreType 商品数据 Response
        /// </summary>
        private Dictionary<int, DiamondMallDataResponse> _diamondMallDataResponsesMap =
            new Dictionary<int, DiamondMallDataResponse>();

        /// <summary>
        /// AppStoreType 序列化后的数据
        /// </summary>
        private Dictionary<int, byte[]> _diamondMallDataMap =
            new Dictionary<int, byte[]>();

        /// <summary>
        /// 配置版本
        /// </summary>
        private long Ver;

        partial void PostInit()
        {
            _diamondMallDataMap.Clear();
            _diamondMallDataResponsesMap.Clear();

            Ver = DateTimeHelper.DateTime2TimeStamp(DateTime.Now);

            // 对数据排序：Sort 大的在前，Sort 相同时保持原列表顺序（稳定排序：选择排序变体）
            var sortedList = new List<DiamondMallConfig>(_dataList);
            for (int i = 0; i < sortedList.Count; i++)
            {
                int maxSortIdx = i;
                for (int j = i + 1; j < sortedList.Count; j++)
                {
                    if (sortedList[j].Sort > sortedList[maxSortIdx].Sort)
                    {
                        maxSortIdx = j;
                    }
                }

                if (i != maxSortIdx)
                {
                    DiamondMallConfig temp = sortedList[maxSortIdx];
                    sortedList.RemoveAt(maxSortIdx);
                    sortedList.Insert(i, temp);
                }
            }

            // 第一步：填充 _diamondMallDataResponsesMap（按 AppStoreType 聚合）
            foreach (var config in sortedList)
            {
                AddDiamondMallData(config);
            }

            // 第二步：填充 _diamondMallDataMap（按 AppStoreType 序列化 Response）
            foreach (var kv in _diamondMallDataResponsesMap)
            {
                _diamondMallDataMap[kv.Key] = MessagePackHelper.Serialize(kv.Value);
            }
        }

        private void AddDiamondMallData(DiamondMallConfig data)
        {
            if (data.NotShelved)
                return;

            DiamondProduct product = new DiamondProduct
            {
                Id = data.Id,
                PlatProductId = data.PlatProductId,
                Name = data.Name,
                Price = data.Price,
                Packages = GameResHelper.Convert(data.Packages),
                Gift = GameResHelper.Convert(data.Gift),
                Desc = data.Desc
            };

            if (!_diamondMallDataResponsesMap.TryGetValue(data.AppStoreType, out DiamondMallDataResponse storeResponse))
            {
                storeResponse = new DiamondMallDataResponse { Products = new List<DiamondProduct>() };
                storeResponse.Ver = Ver;
                _diamondMallDataResponsesMap[data.AppStoreType] = storeResponse;
            }

            storeResponse.Products.Add(product);
        }

        /// <summary>
        /// 获取版本号
        /// </summary>
        public long GetVer() => Ver;

        /// <summary>
        /// 根据 AppStoreType 获取商品数据 Response
        /// </summary>
        public bool TryGetResponse(int appStoreType, out DiamondMallDataResponse response)
        {
            return _diamondMallDataResponsesMap.TryGetValue(appStoreType, out response);
        }

        /// <summary>
        /// 根据 AppStoreType 获取序列化后的数据
        /// </summary>
        public bool TryGetSerializedData(int appStoreType, out byte[] data)
        {
            return _diamondMallDataMap.TryGetValue(appStoreType, out data);
        }

        /// <summary>
        /// 根据 Title 获取商品配置
        /// </summary>
        /// <param name="title"></param>
        /// <param name="appStoreType"></param>
        /// <returns></returns>
        public DiamondProduct GetMallConfigByTitle(string title, int appStoreType)
        {
            DiamondMallDataResponse response = null;
            if (_diamondMallDataResponsesMap.TryGetValue(appStoreType, out response))
            {
                foreach (var product in response.Products)
                {
                    if (product.Name == title)
                    {
                        return product;
                    }
                }
            }

            if (_diamondMallDataResponsesMap.TryGetValue(0, out response))
            {
                foreach (var product in response.Products)
                {
                    if (product.Name == title)
                    {
                        return product;
                    }
                }
            }

            return null;
        }
    }
}