using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Bailun.DC.Common;
using Bailun.DC.Models;
using Dapper;
using MySql.Data.MySqlClient;

namespace Bailun.DC.Services
{
    public class CommonServices
    {
        /// <summary>
        /// 获取即时汇率
        /// </summary>
        /// <param name="fromUnitCode"></param>
        /// <param name="toUnitCode"></param>
        /// <returns></returns>
        public static decimal GetExchangeRate(string fromUnitCode, string toUnitCode)
        {
            var url = Common.GlobalConfig.OAUrl + "/api/ExchangeRate/GetExchangeRateByCurAndDate?fromCur=" + fromUnitCode + "&toCur=" + toUnitCode;

            var result = HttpHelper.NetHelper.Request(url);

            try
            {
                // "\"{\\\"Rate\\\":6.7941,\\\"ToCurName\\\":\\\"USD->CNY\\\",\\\"CreateTime\\\":\\\"2019-01-25 19:36:38\\\"}\""
                //result = result.Replace("\\", "").Substring(1);
                //result = result.Substring(0, result.Length - 1);

                var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<ExchangeRate>(result);
                return obj.Rate;

            }
            catch (Exception ex)
            {

            }

            return 1;
        }

        /// <summary>
        /// 获取平台列表
        /// </summary>
        /// <returns></returns>
        public static List<string> ListPlatForm()
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var sql = "select platform_type from dc_base_oms_order";

                sql += " group by platform_type order by platform_type";

                return cn.Query<string>(sql).AsList();
            }
        }

        /// <summary>
        /// 获取销售帐号列表
        /// </summary>
        /// <param name="platform">平台编码</param>
        /// <returns></returns>
        public static List<string> ListAccount(string platform)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var sqlparam = new DynamicParameters();
                var sql = "select seller_account from dc_base_oms_order";
                if (!string.IsNullOrWhiteSpace(platform))
                {
                    sql += " where platform_type=@platform_type";
                    sqlparam.Add("platform_type", platform);
                }

                sql += " group by seller_account order by seller_account";

                return cn.Query<string>(sql, sqlparam).AsList();
            }
        }

        /// <summary>
        /// 获取平台站点列表
        /// </summary>
        /// <param name="platform">平台编码</param>
        /// <returns></returns>
        public static List<string> ListWebSite(string platform)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var sqlparam = new DynamicParameters();
                var sql = "select website from dc_base_oms_order";
                if (!string.IsNullOrWhiteSpace(platform))
                {
                    sql += " where platform_type=@platform_type";
                    sqlparam.Add("platform_type", platform);
                }

                sql += " group by website order by website";

                return cn.Query<string>(sql, sqlparam).AsList();
            }
        }

        /// <summary>
        /// 获取销售员列表
        /// </summary>
        /// <returns></returns>
        public static List<string> ListSeller()
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var sql = "select seller_name from dc_base_oms_sku group by seller_name";
                return cn.Query<string>(sql).AsList();
            }
        }

        /// <summary>
        /// 获取百伦Sku分类
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        public static List<Models.Common.CategoryDto> GetCategoryList(int level = 1)
        {
            if (level == 0)
            {
                List<Models.Common.CategoryDto> datas = new List<Models.Common.CategoryDto>();
                var tempLevel = 1;
                while (true)
                {
                    var tempDatas = GetCategoryList(tempLevel);
                    if (tempDatas != null && tempDatas.Count >= 1 && level <= 4)
                    {
                        datas.AddRange(tempDatas);
                    }
                    else
                    {
                        return datas;
                    }
                    tempLevel++;

                }
            }
            string appId = "SystemDC";
            string appKey = "YmFpbHVuREM=";
            string url = Common.GlobalConfig.SkumsCategory;

            List<Models.Common.CategoryDto> result = new List<Models.Common.CategoryDto>();

            Models.Common.ApiEntrance model = new Models.Common.ApiEntrance();
            model.code = appId;
            model.data = level.ToString();

            string sign = Common.CommonHelper.md5Encrypt(appKey + model.code + CommonHelper.md5Encrypt(model.key + model.data));
            string resultStr = HttpHelper.NetHelper.Request(url + $"?sign={sign}&appId={appId}&level={level}");
            Models.Common.ApiResult apiResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.Common.ApiResult>(resultStr);
            if (apiResult.result_code == 1)
            {
                result =  Newtonsoft.Json.JsonConvert.DeserializeObject<List<Models.Common.CategoryDto>>(WebUtility.UrlDecode(apiResult.data)).Where(s => s.C_LEVEL == level).ToList();
            }
            return result;

        }

        /// <summary>
        /// 获取百伦所有sku分类
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public static List<Models.Common.CategoryDto> GetCategoryListAll(List<Models.Common.CategoryDto> all, int id)
        {
            // 查询所有数据
            if (all == null)
            {
                all = GetCategoryList(0);
            }
            List<Models.Common.CategoryDto> clients = all.Where(s => s.C_ID == id).ToList();
            var cNodes = all.Where(s => s.C_PARENTID == id).ToList();
            if (cNodes != null || cNodes.Count >= 1)
            {
                foreach (var item in cNodes)
                {
                    clients.AddRange(GetCategoryListAll(all, item.C_ID));
                }
            }
            return clients;

        }

    }

    #region 汇率实体 ExchangeRate
    /// <summary>
    /// 汇率
    /// </summary>
    class ExchangeRate
    {
        public decimal Rate { get; set; }
        public string ToCurName { get; set; }
        public DateTime CreateTime { get; set; }
    }
    #endregion

    
}
