using System;
using System.Collections.Generic;
using System.Linq;
using GameMessage;
using MessagePack;
using MrWu.Debug;
using Server.Core;

namespace Server.Config
{
    public partial class ExchangeMallConfigCategory
    {
        /// <summary>
        /// MallType 序列化后的数据
        /// </summary>
        private Dictionary<string, byte[]> _exchangeMallDataMap =
            new Dictionary<string, byte[]>();

        private List<ExchangeMallConfig> _sortDataList = null;
        
        /// <summary>
        /// 配置版本
        /// </summary>
        private long Ver;

        partial void PostInit()
        {
            _exchangeMallDataMap.Clear();

            Ver = DateTimeHelper.DateTime2TimeStamp(DateTime.Now);

            // 对数据排序：Sort 大的在前，Sort 相同时保持原列表顺序（稳定排序：选择排序变体）
            _sortDataList = new List<ExchangeMallConfig>(_dataList);
            for (int i = 0; i < _sortDataList.Count; i++)
            {
                int maxSortIdx = i;
                for (int j = i+1; j < _sortDataList.Count; j++)
                {
                    if (_sortDataList[j].Sort > _sortDataList[maxSortIdx].Sort)
                    {
                        maxSortIdx = j;
                    }
                }
                
                //不是简单的交换，是插入到第一个位置，为的是不打乱顺序
                if (maxSortIdx != i)
                {
                    ExchangeMallConfig temp = _sortDataList[maxSortIdx];
                    _sortDataList.RemoveAt(maxSortIdx);
                    _sortDataList.Insert(i, temp);
                }
            }
        }

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

        /// <summary>
        /// 根据 MallType 获取序列化后的数据
        /// </summary>
        public bool TryGetSerializedData(int mallType,int appStoreType,out byte[] data)
        {
            string key = $"{mallType}_{appStoreType}";

            if (!_exchangeMallDataMap.ContainsKey(key))
            {
                //去处理数据
                _exchangeMallDataMap.Add(key,DataInit(mallType, appStoreType));
            }
            
            return _exchangeMallDataMap.TryGetValue(key, out data);
        }

        /// <summary>
        /// 缓存初始化
        /// </summary>
        /// <param name="mallType">0表示全部 商城类型</param>
        /// <param name="appStoreType">APP 商城类型 0表示获取全部</param>
        private byte[] DataInit(int mallType,int appStoreType)
        {
            ExchangeMallDataResponse response = new ExchangeMallDataResponse();
            response.Ver = Ver;
            response.Products = new List<ExchangeProduct>();
            
            //Debug.Info($"DataInit mallType:{mallType} appStoreType:{appStoreType} count:{_sortDataList.Count}");
            
            for (int i = 0; i < _sortDataList.Count; i++)
            {
                ExchangeMallConfig data = _sortDataList[i];

                if (data.NotShelved)
                {
                    continue;
                }

                if (mallType != 0 && data.MallType != mallType)
                {
                    //Debug.Info($"跳过:{data.MallType}");
                    continue;
                }

                if (appStoreType != 0 && data.AppStore.Length > 0 && !data.AppStore.Contains(appStoreType))
                {
                    //Debug.Info($"appStore跳过:{appStoreType}");
                    continue;
                }

                //Debug.Info($"添加商品:{data.Name}");
                
                ExchangeProduct product = new ExchangeProduct
                {
                    Id = data.Id,
                    Name = data.Name,
                    MallType = data.MallType,
                    SourceItems = GameResHelper.Convert(data.SourceItems),
                    TargetItems = GameResHelper.Convert(data.TargetItems),
                    Desc = data.Desc,
                };
                
                response.Products.Add(product);
            }
            
            return MessagePackHelper.Serialize(response);
        }
    }
}