using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using Dapper;
using Newtonsoft.Json;
using Bailun.DC.Common;
using Bailun.DC.Models;
using Bailun.DC.SyncFBAShippingInfo.Model;
using Microsoft.Extensions.Hosting;
using System.Threading;
using System.Threading.Tasks;

namespace Bailun.DC.SyncFBAShippingInfo
{
    public class Services : BackgroundService
    {

        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.Day==10 && now.Hour == 1 && now.Minute == 45 && now.Second == 1)  //每月10号 1点45分启动
                {
                    Console.WriteLine("开始启动 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    var start = DateTime.Parse(now.ToString("yyyy-MM")+"-01");

                    Init(start);

                    Console.WriteLine("任务运行完成 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public void Init(DateTime day)
        {

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

                cn.Execute("delete from dc_base_fba_shipping_detail where month = '"+day.ToString("yyyy-MM")+"'");
            }

            //请求接口获取数据
            int count = 0;
            int page = 1;
            int pagesize = 5000;

            while(page==1||(page>1&&count>0))
            {
                GetPage(page, pagesize, day, ref count);
                page++;
            }


            //生成汇总表
            SaveCount(day);

        }

        private void GetPage(int page,int pagesize,DateTime date,ref int count)
        {
            try
            {
                var url = $"http://fund.bailuntec.com/Api/GetAmazonFbaShip?page={page}&limit={pagesize}&date={date.ToString("yyyy-MM-dd")}";

                var str = Common.HttpHelper.NetHelper.Request(url);
                if (!string.IsNullOrEmpty(str))
                {
                    var json = JsonConvert.DeserializeObject<response_Data>(str);
                    if (json.data != null && json.data.Count > 0)
                    {
                        count = json.data.Count;
                        var sql = "insert dc_base_fba_shipping_detail (month,order_id,shipment_date,reporting_date,sku,currency,orderamount,createtime,seller_account,website,account_name) values ";
                        foreach (var item in json.data)
                        {
                            sql += $"('{date.ToString("yyyy-MM")}','{item.order_id}','{item.shipment_date.ToString("yyyy-MM-dd HH:mm:ss")}','{item.reporting_date.ToString("yyyy-MM-dd HH:mm:ss")}','{item.sku}','{item.currency}',{item.orderamount},'{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}','{item.sales_account}','{item.market}','{item.account_name}'),";
                        }

                        sql = sql.Substring(0, sql.Length - 1);

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

                            cn.Execute(sql);
                            Console.WriteLine($"{date.ToString("yyyy-MM-dd")} 保存第{page},每页记录数{pagesize} " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        }

                    }
                    else
                    {
                        count = 0;
                    }
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存第{page}时出现异常，异常信息：{ex.Message}，" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                Console.WriteLine($"暂停10分钟后重跑");
                System.Threading.Thread.Sleep(10 * 60);
                GetPage(page, pagesize, date, ref count);
            }
            

        }
    
        public void SaveCount(DateTime day)
        {
            var list = new List<dc_month_shipping_incoming>();

            //获取订单数据
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var sql = $@"select sum(t2.amount_sales*t2.bailun_sku_quantity_ordered) as amount_sales,if(t6.financecategoryname is null,'',t6.financecategoryname) as financecategoryname,t2.order_currency,t2.platform_type,t2.website 
                    from (select DISTINCT order_id,website,seller_account from dc_base_fba_shipping_detail where shipment_date>='{day.ToString("yyyy-MM-dd")}' and shipment_date<'{day.AddMonths(1).ToString("yyyy-MM-dd")}') t1
                    join dc_base_oms_sku_30 t2 on t1.order_id=t2.origin_order_id and t1.website=t2.website and t1.seller_account=t2.seller_account 
                    left join dc_base_sku t5 on t2.bailun_sku=t5.bailun_sku
                    left join dc_base_sku_finance_category t6 on t6.bailuncategoryid=t5.bailun_category_id
                    group by t6.financecategoryname,t2.order_currency,t2.platform_type,t2.website";

                var obj = cn.Query<Model.mPlatformIncoming>(sql, null, null, true, 2 * 60).AsList();
                foreach (var item in obj)
                {
                    list.Add(new dc_month_shipping_incoming
                    {
                        amount = item.amount_sales,
                        createtime = DateTime.Now,
                        currency = item.order_currency,
                        financecategoryname = item.financecategoryname,
                        month = day.ToString("yyyy-MM"),
                        platform_type = item.platform_type,
                        website = item.website
                    });
                }
            }

            if (list.Count > 0)
            {
                var sql = "insert dc_month_shipping_incoming (amount,createtime,currency,financecategoryname,month,platform_type,website) values ";

                foreach (var item in list)
                {
                    sql += $"({item.amount},'{item.createtime.ToString("yyyy-MM-dd HH:mm:ss")}','{item.currency}','{item.financecategoryname}','{item.month}','{item.platform_type}','{item.website}'),";
                }

                sql = sql.Substring(0, sql.Length - 1);

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

                    cn.Execute("delete from dc_month_shipping_incoming where month='" + day.ToString("yyyy-MM") + "' and platform_type='FBA'");

                    cn.Execute(sql);
                }
            }
        }
    }
}
