using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RFrameGenerate.Model;
using RFramework.SQLQuery;

namespace RFrameGenerate.BLL
{
    public class AreasManage
    {
        private const string treeKey = "RFrameGenerate.BLL.AreasManage.AreaTree";

        #region List<T_BAS_Areas> GetAreaData
        /// <summary>
        /// get area list
        /// </summary>
        /// <returns></returns>
        public static List<T_BAS_Areas> GetAreaData()
        {
            using (var querys = Factory.CreateT_BAS_Areas())
            {
                return querys.GetList();
            }

        }
        #endregion

        #region List<T_BAS_Areas> GetAreaList(string rootID)
        /// <summary>
        /// get area list by root id
        /// </summary>
        /// <param name="rootID"></param>
        /// <returns></returns>
        public static List<T_BAS_Areas> GetAreaList(string rootID)
        {
            List<T_BAS_Areas> areaList;
            using (var querys = Factory.CreateT_BAS_Areas())
            {
                areaList = querys.GetList(p => p.ParentAreaCode == rootID);
            }

            var jqData = (from s in areaList.OrderBy(s => s.AreaCode).ToList()
                          select new
                          {
                              Text = s.AreaName,
                              Value = s.AreaCode,
                          }).ToArray();
            return areaList;
        }
        #endregion

        /// <summary>
        /// 获取地区树结构
        /// </summary>
        public static string GetAreaTree()
        {
            if (System.Web.HttpContext.Current.Cache[treeKey] != null)
            {
                var strTree = System.Web.HttpContext.Current.Cache[treeKey] as string;

                if (!string.IsNullOrEmpty(strTree)) return strTree;
            }
            StringBuilder tree = new StringBuilder();
            tree.Append("[");
            using (var query = Factory.CreateT_BAS_Areas())
            {
                var list = query.GetList(p => p.ParentAreaCode == "0", false, v => v.AreaCode);

                foreach (var item in list)
                {
                    tree.Append("{ id:" + item.AreaCode + ", pId:" + item.ParentAreaCode + ", name:\"" + item.AreaName + "\",iconOpen:\"../../Images/open.png\",iconClose:\"../../Images/close.png\",checked:false , open:false },");

                    foreach (var subItem in query.GetList(m => m.ParentAreaCode == item.AreaCode, false, v => v.AreaCode))
                    {
                        tree.Append("{ id:" + subItem.AreaCode + ", pId:" + subItem.ParentAreaCode + ", name:\"" + subItem.AreaName + "\",iconOpen:\"../../Images/open.png\",iconClose:\"../../Images/close.png\",checked:false , open:true },");
                    }
                }
            }
            tree.Remove(tree.Length - 1, 1);
            tree.Append("]");

            string result = tree.ToString();

            System.Web.HttpContext.Current.Cache[treeKey] = result;

            return result;
        }

        public static T_BAS_Areas GetAreas(string code)
        {
            using (var query = Factory.CreateT_BAS_Areas())
            {
                var area = query.GetFirstData(m => m.AreaCode == code);

                if (area == null) return new T_BAS_Areas();

                return area;
            }
        }

        public static T_BAS_Areas GetAreas(string code, Dictionary<string, T_BAS_Areas> cache)
        {
            if (cache == null) cache = new Dictionary<string, T_BAS_Areas>();

            if (cache.ContainsKey(code)) return cache[code];

            var area = GetAreas(code);

            cache.Add(code, area);

            return area;
        }

        /// <summary>
        /// 获取名称列表
        /// </summary>
        public static string GetAreasName(string codes)
        {
            if (string.IsNullOrEmpty(codes)) return string.Empty;

            var array = codes.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            if (array == null || array.Length <= 0) return string.Empty;

            List<T_BAS_Areas> list = null;
            using (var query = Factory.CreateT_BAS_Areas())
            {
                if (array.Length == 1)
                {
                    var area = query.GetFirstData(m => m.AreaCode == array[0]);

                    if (area != null) return string.Empty;

                    return string.Empty;
                }
                else
                {
                    list = query.GetList(m => m.AreaCode.SqlIn(array));
                }
            }

            if (list == null || list.Count <= 0) return string.Empty;

            string str = string.Empty;

            foreach (var item in list)
            {
                str += string.Format("{0},", item.AreaName);
            }

            return str.Substring(0, str.Length - 1);
        }

        /// <summary>
        /// 获取地区编码
        /// </summary>
        public static string GetAreaCode(string provinceText, string cityText)
        {
            if (string.IsNullOrEmpty(provinceText) || string.IsNullOrEmpty(cityText)) return string.Empty;

            provinceText = provinceText.Trim();
            cityText = cityText.Trim();

            provinceText = provinceText.Length > 2 ? provinceText.Substring(0, 2) : provinceText;
            cityText = cityText.Length > 2 ? cityText.Substring(0, 2) : cityText;


            using (var query = Factory.CreateT_BAS_Areas())
            {
                var provice = query.GetFirstData(m => m.AreaName.SqlFunc(string.Format(" AreaName like '{0}%'", provinceText)) && m.ParentAreaCode == "0");

                if (provice == null) return string.Empty;

                var city = query.GetFirstData(m => m.AreaName.SqlFunc(string.Format(" AreaName like '{0}%'", cityText)) && m.ParentAreaCode == provice.AreaCode);

                if (city == null) return string.Empty;

                return city.AreaCode;
            }
        }
        /// <summary>
        /// 获取地区编码
        /// </summary>
        public static string GetAreaCode(T_BAS_RecieverAddress address)
        {
            if (address == null) return string.Empty;

            if (string.IsNullOrEmpty(address.Province) || string.IsNullOrEmpty(address.City)) return string.Empty;

            return GetAreaCode(address.Province, address.City);
        }
    }
}
