using Dapper;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Wicture.DbRESTFul.Infrastructure.Repository;

namespace JiaZhiQuan.Common.Region
{
    public class RegionHelper
    {
        private readonly IConnectionManager _connectionManager;
        private readonly ILogger _logger;

        public List<RegionModel> Regions { get; private set; }

        public Dictionary<string, string> CodeNameMap = new Dictionary<string, string>();

        /// <summary>
        /// 匹配省市区的正则对象
        /// </summary>
        public Regex AreaMatchRegex { get; private set; }

        public RegionHelper(IConnectionManager manager, ILoggerFactory loggerFactory)
        {
            _connectionManager = manager;
            _logger = loggerFactory.CreateLogger("DbRESTFul");
            try
            {
                Resolve();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Region 读取失败");
            }
        }

        public RegionHelper Resolve()
        {
            using (var conn = _connectionManager.GetConnection())
            {
                conn.Open();
                Init(SqlMapper.Query(conn, "select * from n_region where code<'700000' order by code asc"));
            }
            return this;
        }

        private void Init(IEnumerable<dynamic> regions)
        {
            var arr = new RegionModel[2];
            var root = new List<RegionModel>();
            foreach (var item in regions)
            {
                CodeNameMap[item.code] = item.name;

                var ritem = new RegionModel { Code = item.code, Name = item.name, Alias = item.alias, PY = item.py };
                if (arr[0] != null && arr[0].Code.StartsWith(ritem.Code.Substring(0, 2)))
                {
                    if (arr[1] != null && arr[1].Code.StartsWith(ritem.Code.Substring(0, 4)) && arr[1].Code.EndsWith("00"))
                    {
                        arr[1].Children.Add(ritem);
                    }
                    else
                    {

                        arr[0].Children.Add(ritem);
                        arr[1] = ritem;

                        //if (ritem.Code.EndsWith("00"))
                        //{
                        //    arr[0].Children.Add(ritem);
                        //    arr[1] = ritem;
                        //}
                        //else
                        //{
                        //    arr[1] = new RegionModel { Code = arr[0].Code, Name = arr[0].Name, Alias = arr[0].Alias };
                        //    arr[0].Children.Add(arr[1]);
                        //}
                    }
                }
                else
                {
                    root.Add(ritem);
                    arr[0] = ritem;
                    arr[1] = null;
                }
            }
            Regions = root;
        }

    }
}
