using Bailun.DC.DailyPlatformAccountBalance.Models;
using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using Dapper;
using System.Linq;
using Microsoft.Extensions.Hosting;
using System.Threading;
using System.Threading.Tasks;

namespace Bailun.DC.DailyPlatformAccountBalance
{
    public class Services : BackgroundService
    {
        public static string url = "http://fund.bailuntec.com/PlateformBalance/GetPaltformBalanceByDate"; //?StartDate=2020-6-19&EndDate=2020-6-20&page=1&limit=30


        private Timer _timer;

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromMinutes(1));
            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            try
            {
                var now = DateTime.Now;

                if (now.Hour == 9 && now.Minute==01)  //
                {
                    Console.WriteLine("开始启动 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                    var day = DateTime.Parse(DateTime.Now.AddDays(-1).ToShortDateString());

                    Init(day);
                    
                    Console.WriteLine("任务运行完成 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                    //每天跑一次
                    Console.WriteLine("开始启动每日记录保存 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    SaveDaily();
                    Console.WriteLine("结束每日记录保存 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                    //更新资产负债表平台余额字段
                    Console.WriteLine("开始启动更新资产负债表平台余额字段 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    UpdateBalanceSheet(DateTime.Now.AddDays(-1));
                    Console.WriteLine("结束更新资产负债表平台余额字段 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        
        public void Init(DateTime day)
        {
            var _url = url+ "?datadate="+day.ToString("yyyy-MM-dd");

            var str = Common.HttpHelper.NetHelper.Request(_url);

            var json = Newtonsoft.Json.JsonConvert.DeserializeObject<RequestResult>(str);

            if (json.code == 0 && json.count>0)
            {
                Save(json.data);
                Console.WriteLine("获取到了"+json.count+"条记录。");
            }

        }

        private void Save(List<mAccountInfo> list)
        {

            var sql = "insert dc_base_platform_account_balance (dataid,account,platform_id,platform_name,currency,currencyrate,availableamount,availableamount_rmb,frozenmoney,frozenmoney_rmb,totalamount,totalamount_rmb,createtime,createname,updatename,updatetime,dc_createtime,source) values ";

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

                //删除所有数据
                cn.Execute($"delete from dc_base_platform_account_balance");

                var str = "";
                var strId = "";
                foreach (var item in list)
                {
                    foreach (var c in item.Currencymoney)
                    {
                        str += $"({c.Id},'{item.Account}',{item.Plateform},'{item.PlateformText}','{c.Currency}',{c.CurrencyRate},{c.AvailableAmount},{c.AvailableCurrencyAmount},{c.FrozenMoney},{c.FrozenCurrencyAmount},{c.TotalAmount},{c.TotalCurrencyAmount},'{item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")}','{item.CreateName}','{item.UpdateName}','{item.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss")}','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}','{item.AccessMethod}'),";
                        strId += c.Id+",";
                    }
                }

                if (!string.IsNullOrEmpty(str))
                {
                    str = str.Substring(0, str.Length - 1);
                    strId = strId.Substring(0, strId.Length - 1);
                    
                    cn.Execute(sql + str);
                }

            }
            
        }

        /// <summary>
        /// 更新资产负债表余额
        /// </summary>
        /// <param name="day"></param>
        public void UpdateBalanceSheet(DateTime day)
        {
            //platformBalanceUpdate
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var sql = $"select sum(totalamount_rmb) as totalamount_rmb from dc_daily_platform_account_balance where day='{day.ToString("yyyy-MM-dd")}'";

                var amount = cn.QueryFirstOrDefault<decimal>(sql);

                UpdateLogisticsEndAmount(day, amount, "platformBalanceUpdate");

            }

        }

        /// <summary>
        /// 保存每日余额
        /// </summary>
        public void SaveDaily()
        {
            var sql = $@"insert into dc_daily_platform_account_balance (day,account,platform_name,currency,currencyrate,availableamount,availableamount_rmb,frozenmoney,frozenmoney_rmb,totalamount,totalamount_rmb,dc_createtime) 
                        select DATE_SUB(curdate(),INTERVAL 1 DAY),account,platform_name,currency,currencyrate,availableamount,availableamount_rmb,frozenmoney,frozenmoney_rmb,totalamount,totalamount_rmb,now() from dc_base_platform_account_balance t1";

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

                cn.Execute("delete from dc_daily_platform_account_balance where day=DATE_SUB(curdate(),INTERVAL 1 DAY);");

                cn.Execute(sql);
            }
            
        }

        /// <summary>
        /// 更新资产负债表的物流应付款额
        /// </summary>
        /// <param name="day">日期</param>
        /// <param name="amount">金额</param>
        /// <param name="paramname">参数名</param>
        /// <returns></returns>
        public string UpdateLogisticsEndAmount(DateTime day, decimal amount, string paramname)
        {
            var url = "http://fee.bailuntec.com/balanceSheet/updateSheetLogisticsSupplier?date=" + day.ToString("yyyy-MM-dd") + "&" + paramname + "=" + amount;

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

            var json = Newtonsoft.Json.Linq.JObject.Parse(result);
            if (json["success"].ToString().ToLower() == "true")
            {
                return "";
            }
            else
            {
                return json["message"].ToString();
            }
        }

    }
}
