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
    {
        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;
            }
            

        }
    }

    #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; }

    }

}
