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

namespace Bailun.DC.AllotOrderDetail
{
    public class Services : BackgroundService
    {
        static string url = "http://api.wms.bailuntec.com/api/services/app/AllotOrderService/SearchAllotOrderDataListPage";

        static DateTime endtime;

        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.Minute%4==0)
                {
                    Console.WriteLine("开始启动 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    Init();
                    Console.WriteLine("任务运行完成 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }


        public void Init()
        {
            

            var starttime = DateTime.Now;
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    var sql = "select timestamp from dc_base_transfer_info order by timestamp desc limit 1";
                    var result = cn.QueryFirstOrDefault<Models.dc_base_transfer_info>(sql);

                    if (result == null)
                    {
                        starttime = DateTime.Parse("2018-12-05");
                    }
                    else
                    {
                        starttime = result.timestamp;
                    }

                }
            }
            
            endtime = DateTime.Now;
            starttime = starttime.AddMinutes(-3);
            

            //测试
#if DEBUG
            starttime = DateTime.Parse("2020-12-08 09:37:30");
            endtime = starttime.AddSeconds(10);
#endif

            GetData(starttime, endtime);

        }

        public void GetData(DateTime starttime, DateTime end)
        {
            var page = 1;
            var rows = 1000;
            var total = -1;

            while (total == -1 || total > ((page - 1) * rows))
            {
                total = 0;

                var data = new
                {
                    Data = new
                    {
                        Page = new
                        {
                            page = page,
                            rows = rows
                        },
                        StartTime = starttime.ToString("yyyy-MM-dd HH:mm:ss"),
                        EndTime = end.ToString("yyyy-MM-dd HH:mm:ss"),
                    },
                };

                var str = Common.HttpHelper.NetHelper.HttpPostJson(url, Newtonsoft.Json.JsonConvert.SerializeObject(data));

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


                if (json.isSuccess && json.data.items.Count > 0)
                {
                    total = json.data.pageItem.total;

                    //保存数据
                    Save(json.data.items);

                    Console.WriteLine("时间：" + starttime.ToString("yyyy-MM-dd HH:mm:ss") + "-" + end.ToString("yyyy-MM-dd HH:mm:ss") + ",页码：" + page + ",请求记录数：" + json.data.items.Count + "，总记录数：" + total);

                    page++;
                }
                else
                {
                    Console.WriteLine("时间：" + starttime.ToString("yyyy-MM-dd HH:mm:ss") + "-" + end.ToString("yyyy-MM-dd HH:mm:ss") + ",页码：" + page + ",请求记录数：0");
                }
            }
        }

        public void Save(List<Models.AllotInfo> list)
        {
            Dapper.SimpleCRUD.SetDialect(SimpleCRUD.Dialect.MySQL);

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

                foreach (var item in list)
                {
                    cn.Execute("delete from dc_base_transfer_info where dataid="+item.Id);
                    

                    var m = new Models.dc_base_transfer_info
                    {
                        dataid = item.Id,
                        allocatecargostate = item.AllocateCargoState,
                        channelname = string.Join(",",item.ChannelName),
                        code = item.Code,
                        createusername = item.CreateUserName,
                        creationtime = item.CreationTime,
                        dc_createtime = DateTime.Now,
                        estimatedcost = item.EstimatedCost,
                        expectarrivaltime = item.ExpectArrivalTime,
                        isdeleted = item.IsDeleted?1:0,
                        isexception = item.IsException?1:0,
                        islockedposition = item.IsLockedPosition?1:0,
                        logisticscode = item.LogisticsCode,
                        logisticsname = item.LogisticsName,

                        packrequirements = item.PackRequirements,
                        producttype = item.ProductType,
                        purchasecode = item.PurchaseCode,
                        receiptno = item.ReceiptNo,
                        schedulecode = item.ScheduleCode,
                        scheduletype = item.ScheduleType,
                        sendrequire = item.SendRequire,
                        shipmentid = item.ShipmentId,
                        shipmentstatus = item.ShipmentStatus,
                        singleboxmaxweight = 0,
                        singleboxminweight = 0,
                        sinnleticketmaxweight = 0,
                        
                        sourcewarename = item.SourceWareName,
                        sourcewareno = item.SourceWareNo,
                        specialproblem = item.SpecialProblem,
                        targetwareaddress = item.TargetWareAddress,
                        targetwareaddressinfo = item.TargetWareAddress,
                        targetwarename = item.TargetWareName,
                        targetwareno = item.TargetWareNo,

                        timestamp = item.TimeStamp,
                        trackingno = string.Join(",",item.TrackingNo),
                        transfertype = item.TransferType,
                        transporttype = item.TransportType,
                        stateid = item.StateId,


                        skuweight = 0,
                        skuweightStr = "",
                        finishtime = item.CompletionDate,

                        deliverytime = item.DeliveryTime,

                        
                    };

                    cn.Insert<Models.dc_base_transfer_info>(m);

                    cn.Execute("delete from dc_base_transfer_info_skus where dataid=" + item.Id);
                    foreach (var sku in item.AllotOrderProducts)
                    {
                        var s = new Models.dc_base_transfer_info_skus {
                            createtime = DateTime.Now,
                            dataid = item.Id,
                            deliverycount = sku.DeliveryCount,
                            productname = sku.ProductName,
                            sku = sku.Sku,
                            storagecount = sku.StorageCount,
                            transferno = item.Code,
                            transitcount = sku.TransitCount,
                        };

                        cn.Insert<dc_base_transfer_info_skus>(s);
                    }
                }
            }
        }

    }
}
