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

namespace Bailun.DC.Services
{
    public class CommonServices
    {
        public static List<Models.Common.CategoryDto> ListSkuCategory { get; set; }

        /// <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,int? companyid)
        {
            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 where 1=1 ";
                if (!string.IsNullOrWhiteSpace(platform))
                {
                    sql += " and platform_type=@platform_type";
                    sqlparam.Add("platform_type", platform);
                }

                if (companyid.HasValue && companyid.Value > 0)
                {
                    sql += " and company_id=@company_id";
                    sqlparam.Add("company_id", companyid.Value);
                }

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

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

        /// <summary>
        /// Paypal账户列表
        /// </summary>
        /// <param name="companyid">公司id</param>
        /// <returns></returns>
        //public static List<string> ListPaypalAccount0(int? companyid)
        //{
        //    using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
        //    {
        //        if (cn.State == System.Data.ConnectionState.Closed)
        //        {
        //            cn.Open();
        //        }

        //        var sqlparam = new DynamicParameters();
        //        var sql = "select account_name from dc_base_income_ebay_paypal where 1=1 ";

        //        if (companyid.HasValue && companyid.Value > 0)
        //        {
        //            sql += " and company_id=" + companyid.Value;
        //        }

        //        sql += " group by account_name";

        //        var obj = cn.Query<string>(sql, null, null, true, 2 * 60).AsList();

        //        return obj;
        //    }

        //}

        /// <summary>
        /// 获取平台站点列表
        /// </summary>
        /// <param name="platform">平台编码</param>
        /// <returns></returns>
        public static List<string> ListWebSite(string platform, int? companyid, DateTime? start,DateTime? end)
        {
            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 where 1=1 ";
                if (!string.IsNullOrWhiteSpace(platform))
                {
                    sql += " and platform_type=@platform_type";
                    sqlparam.Add("platform_type", platform);
                }

                if (companyid.HasValue && companyid.Value > 0)
                {
                    sql += " and company_id=@company_id";
                    sqlparam.Add("company_id", companyid.Value);
                }


                if (start.HasValue)
                {
                    sql += " and paid_time>='"+start.Value.ToString("yyyy-MM-dd")+"'";
                }
                if (end.HasValue)
                {
                    sql += " and paid_time<'"+end.Value.AddDays(1).ToString("yyyy-MM-dd")+"'";
                }


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

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

        /// <summary>
        /// 获取销售员列表
        /// </summary>
        /// <returns></returns>
        public static List<string> ListSeller(int? companyid)
        {
            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_name from dc_base_oms_sku where 1=1 ";

                if (companyid.HasValue && companyid.Value > 0)
                {
                    sql += " and company_id=@company_id";
                    sqlparam.Add("company_id", companyid.Value);
                }


                sql += "  group by seller_name ";
                return cn.Query<string>(sql,sqlparam).AsList();
            }
        }

        /// <summary>
        /// 获取百伦Sku分类
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        public static List<Models.Common.CategoryDto> GetCategoryList(int level = 1)
        {
            if (level == 0)
            {
                if (ListSkuCategory != null && ListSkuCategory.Count > 0)
                {
                    return ListSkuCategory;
                }

                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
                    {
                        ListSkuCategory = datas;
                        return datas;
                    }
                    tempLevel++;
                }
            }
            string appId = "SystemDCUI";
            string appKey = "YmFpbHVuRENVSQ==";
            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;

        }

        /// <summary>
        /// 获取采购公司列表
        /// </summary>
        /// <returns></returns>
        public static List<CompanyValue> ListCompanyValue()
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                return cn.Query<CompanyValue>("select company_value,company_name from dc_fixed_assets_detail group by company_value,company_name").AsList();

            }
        }

        /// <summary>
        /// 根据账号名称获取账号信息
        /// </summary>
        /// <param name="accountname">账号名称</param>
        /// <param name="companyid">公司id</param>
        /// <returns></returns>
        public static dc_base_company_account GetCompanyAccount(string accountname, int companyid)
        {
            var sql = "select * from dc_base_company_account where account_name=@account_name and company_id="+companyid;
            var sqlparam = new DynamicParameters();
            sqlparam.Add("account_name", accountname);

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<dc_base_company_account>(sql, sqlparam, null, 2 * 60);
                return obj;
            }

        }

        /// <summary>
        /// paypal帐号列表
        /// </summary>
        /// <param name="companyid"></param>
        /// <returns></returns>
        public static List<dc_base_paypal_account> ListPaypalAccount(int? companyid)
        {
            var sql = "select * from dc_base_paypal_account";

            if (companyid.HasValue && companyid.Value > 0)
            {
                sql += " where company_id="+companyid.Value;
            }

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_base_paypal_account>(sql, null, null, true, 2 * 60).AsList();
                return obj;
            }
        }

        /// <summary>
        /// 获取paypal帐号信息
        /// </summary>
        /// <param name="account">paypal帐号</param>
        /// <returns></returns>
        public static dc_base_paypal_account GetPaypalAccount(string account)
        {
            var sql = "select * from dc_base_paypal_account where seller=@account";
            var sqlparam = new DynamicParameters();
            sqlparam.Add("account", account);

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.QueryFirstOrDefault<dc_base_paypal_account>(sql, sqlparam, null, 2 * 60);
                return obj;
            }
            

        }

        /// <summary>
        /// 获取所有oa用户
        /// </summary>
        /// <returns></returns>
        public static List<mOAUser> GetListOAUser()
        {
            var list = new List<mOAUser>();

            //先判断有没有缓存
            //var cache = GetCache("OAUSER");
            //if (cache != null)
            //{
            //    list = (List<mOAUser>)cache;
            //    return list;
            //}

            try
            {
                var url = "http://oa.bailuntec.com/api/User/GetUser";
                var result = Common.HttpHelper.NetHelper.Request(url);

                result = result.Substring(1);
                result = (result.Substring(0, result.Length - 2) + "]").Replace(@"\", @"");

                list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<mOAUser>>(result);

                //if (list.Count > 0)
                //{
                //    AddCache("OAUSER", list);  //添加到缓存
                //}

            }
            catch (Exception ex)
            {

            }

            return list;
        }

        /// <summary>
        /// 获取每日汇率
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public List<dc_exchange_rate> ListDateExchangeRate(DateTime date)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_exchange_rate>("select * from dc_exchange_rate where record_time='" + date.ToString("yyyy-MM-dd") + "'").ToList();
                return obj;
            }
        }

        /// <summary>
        /// 获取物流方式配置
        /// </summary>
        /// <param name="type">1：专线</param>
        /// <returns></returns>
        public static List<dc_base_logistics_config> ListLogisticsConfig(int type)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<dc_base_logistics_config>("select * from dc_base_logistics_config where type="+1);

                return obj.ToList();
            }

        }

        /// <summary>
        /// 获取百伦新分类
        /// </summary>
        /// <param name="level">等级</param>
        /// <param name="parentid">父级id</param>
        /// <returns></returns>
        public static List<Models.Sku.dc_base_bailuncategory> ListBailunNewCategory(int? level,List<int> parentid)
        {
            var sql = "select c_id,c_parentid,c_name,c_sort,c_level from dc_base_bailuncategory t1 where has_delete=0 ";

            if (level.HasValue)
            {
                sql += " and c_level="+level.Value;
            }

            if (parentid != null && parentid.Count > 0)
            {
                sql += " and c_parentid in ("+string.Join(",",parentid)+")";
            }

            sql += " order by c_sort ";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Query<Models.Sku.dc_base_bailuncategory>(sql);

                return obj.ToList();
            }
        }

        /// <summary>
        /// 获取百伦新分类详情信息
        /// </summary>
        /// <param name="id">分类id</param>
        /// <returns></returns>
        public static Models.Sku.dc_base_bailuncategory getBailunNewCategory(int id)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                return cn.QueryFirstOrDefault<Models.Sku.dc_base_bailuncategory>("select * from dc_base_bailuncategory where c_id="+id);

            }
        }

        /// <summary>
        /// 根据分类id获取所有子级id
        /// </summary>
        /// <param name="parentid">父级分类id</param>
        /// <returns></returns>
        public static string BailunNewCategory(int parentid, List<Models.Sku.dc_base_bailuncategory> list)
        {
            var str = "";

            if (list==null || list.Count==0)
            {
                list = ListBailunNewCategory(null, null);
            }
            
            var obj = list.Where(a => a.c_parentid == parentid);

            foreach (var item in obj)
            {
                str += item.c_id+",";
                GetChildrenCategory(list, item.c_id,ref str);
            }

            if (str.Length > 0)
            {
                str = str.Substring(0, str.Length - 1);
            }

            return str;
        }

        private static void GetChildrenCategory(List<Models.Sku.dc_base_bailuncategory> list,int parentid,ref string s)
        {
            var obj = list.Where(a => a.c_parentid == parentid);
            foreach (var item in obj)
            {
                s += item.c_id + ",";
                GetChildrenCategory(list, item.c_id, ref s);
            }

        }



    }

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

    /// <summary>
    /// 采购公司
    /// </summary>
    public class CompanyValue
    {
        public int company_value { get; set; }

        public string company_name { get; set; }

    }

}
