using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Dapper;
using MySql.Data.MySqlClient;

namespace Bailun.DC.SaveSkuDeliverWeighDiff
{
    public class SkuDeliverWeighServices: BackgroundService
    {
        private Timer _timer;

        private readonly string cn_str = "server=10.0.8.15;port=3306;database=bailun_datacenter;uid=root;password=#7kfnymAM$Y9-Ntf;";

        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 == 1 && now.Minute == 1)
                {
                    Console.WriteLine("服务启动--" + now.ToString("yyyy-MM-dd HH:mm:ss"));
                    Save(DateTime.Parse(now.AddDays(-1).ToString("yyyy-MM-dd")));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private void Save(DateTime day)
        {
            var sql = $@"select t1.pick_order_id,t1.bailun_sku,t2.weight,t1.bailun_sku_outbound_weight,(t2.weight-t1.bailun_sku_outbound_weight) as diffweigh from dc_base_oms_pick t1
                                join dc_base_sku t2 on t1.bailun_sku = t2.bailun_sku and t2.has_delete = 0
                                where t1.shipping_status = 'TotalShipping' and t1.has_delete = 0 and t1.shipping_time >= '{day.ToString("yyyy-MM-dd")}' and t1.shipping_time < '{day.AddDays(1).ToString("yyyy-MM-dd")}'";

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

                var list = cn.Query<Models.mDiffWeigh>(sql).AsList();
                var index = 1;
                var str = "";
                while (list.Count >= index)
                {
                    var item = list[index - 1];
                    str += $"insert dc_mid_skudeliver_weighdiff (day,pick_order_id,bailun_sku,weight,bailun_sku_outbound_weight,diffweigh,createtime) values ('{day.ToString("yyyy-MM-dd")}','{item.pick_order_id}','{item.bailun_sku}',{item.weight},{item.bailun_sku_outbound_weight},{item.diffweigh},'{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}');";

                    if (index / 2000 == 0 || index == list.Count)
                    {
                        cn.Execute(str);
                        str = "";
                    }
                    index++;
                }
            }
        }

        public override void Dispose()
        {
            base.Dispose();
            _timer?.Dispose();
        }

    }
}
