using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XYY.Data.Standard.OrderAddressCheck;
using XYY.Model.Standard.OrderAddressCheck;

namespace XYY.Service.Standard.AddressCheck
{
    public class GFSFRLineAddressService : IAdderssService
    {
        private IFRSLAreasRepository _frSLAreasRepository;
        private const string CacheKey = "FRSLAreas";
        private IDistributedCache _cache;

        public int ChannelId { get => 99; }

        public string CountryCode { get => "FR"; }

        public GFSFRLineAddressService(IFRSLAreasRepository frSLAreasRepository, IDistributedCache cache)
        {
            _frSLAreasRepository = frSLAreasRepository;
            _cache = cache;
        }

        public async Task<AddressGroup> Verify(OrderAddress address)
        {
            throw new Exception("暂未实现");
            //非紧急，暂不实现
            //return AddressGroup.Normal;
        }

        public async Task<RecommendedAddress> GetRecommendedAddresses(OrderAddress address)
        {
            var all = await GetCacheData();
            var RecommendedAddress = new RecommendedAddress
            {
                CityRecommendedAddress = new List<RecommendedAddressItem>(),
                ZipCodeRecommendedAddress = new List<RecommendedAddressItem>()
            };
            address.City = address.City.ToUpper();
            RecommendedAddress.CityRecommendedAddress = all.Where(x => x.AreaName.Contains(address.City))
                .Select(x => ConvertAddress(x)).ToList();
            RecommendedAddress.ZipCodeRecommendedAddress = all.Where(x => x.ZipCode.Equals(address.ZipCode, StringComparison.InvariantCultureIgnoreCase))
                .Select(x => ConvertAddress(x)).ToList();
            return RecommendedAddress;

        }

        private RecommendedAddressItem ConvertAddress(FRSLAreas area)
        {
            return new RecommendedAddressItem { City = area.AreaName, ZipCode = area.ZipCode };
        }

        private async Task<List<FRSLAreas>> GetCacheData()
        {
            var areas = await _cache.GetStringAsync(CacheKey);
            if (areas == null || string.IsNullOrEmpty(areas))
            {
                var list = await _frSLAreasRepository.GetAll();
                areas = Newtonsoft.Json.JsonConvert.SerializeObject(list);
                await _cache.SetStringAsync(CacheKey, areas);
            }
            var data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<FRSLAreas>>(areas);
            return data;
        }
    }
}
