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

namespace Bailun.DC.SyncLogisticInfo
{
    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.Minute % 3==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);
            }
        }
        string url = "http://wms.bailuntec.com/api/services/app/LogisticsReconciliationService/GetNormalDataQuery";

        public void Init()
        {
            Dapper.SimpleCRUD.SetDialect(SimpleCRUD.Dialect.MySQL);

            var starttime = DateTime.Parse("2020-01-01");
            var endtime = starttime.AddDays(1);
            var page = 1;
            var pagesize = 1000;
            var total = -1;

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

                var m = cn.QueryFirstOrDefault<dc_base_logistics>("select * from dc_base_logistics order by last_modification_time desc limit 1");
                if (m != null && m.last_modification_time.HasValue)
                {
                    starttime = m.last_modification_time.Value;
                    endtime = DateTime.Now;
                }

            }


            while (total == -1 || total>((page-1)*pagesize))
            {
                var j = new
                {
                    StartModificationTime = starttime,
                    EndModificationTime = endtime,
                    pageIndex = page,
                    pageCount = pagesize,
                };

                Console.WriteLine("Page:" + page + "；starttime:" + starttime.ToString("yyyy-MM-dd HH:mm:ss") + "；endtime:" + endtime.ToString("yyyy-MM-dd HH:mm:ss"));

                var str = Common.HttpHelper.NetHelper.HttpPostJson(url, JsonConvert.SerializeObject(j));
                var json = Newtonsoft.Json.JsonConvert.DeserializeObject<mResult>(str);

                if (json.success && json.result.result.Count > 0)
                {
                    Save(json.result.result);
                    Console.WriteLine("获取到了" + json.result.result.Count + "条记录。");
                    total = json.result.total;
                    page++;
                }
                else
                {
                    page=1;
                    total = 0;
                    endtime = endtime.AddDays(1);
                }
            }
        }

        private void Save(List<DataInfo> list)
        {
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                foreach (var item in list)
                {
                    try
                    {
                        cn.Execute("delete from dc_base_logistics where wms_id=" + item.id);

                        var m = new dc_base_logistics
                        {
                            bailun_shipment_cost_cny = item.bailunShipmentCostCNY,
                            bill_code = item.billCode,
                            company_code = item.company_Code,
                            company_name = item.company_Name,
                            cost_diff_decimal = item.costDiffDecimal,
                            diff_state_type = item.diffStateType + "",
                            fee_code = item.feeCode,
                            fee_product_type = item.feeProductType,

                            generate_bill_status = item.generateBillStatus,
                            gmt_create_time = DateTime.Now,
                            gmt_modify_time = DateTime.Now,
                            info_id = item.infoId + "",
                            last_modification_time = item.lastModificationTime,
                            line_name = item.line_Name,
                            merchant_output_weight_kg = item.merchantOutputWeightKg,
                            merchant_output_weight_kg_original = item.merchantOutputWeightKg_Original ?? 0,
                            merchant_reconciliation_time = item.merchantReconciliationTime,
                            merchant_shipment_cost_cny = item.merchantShipmentCostCNY,
                            merchant_shipment_cost_sny_original = item.merchantShipmentCostCNY_Original ?? 0,
                            output_weight_kg = item.outputWeightKg,


                            reconciliation_type = item.reconciliationType,
                            remark = item.remark,
                            shipment_time = item.shipmentTime,
                            tracking_no = item.trackingNo,
                            weight_diff_decimal = item.weightDiffDecimal,
                            wms_id = item.id
                        };

                        cn.Insert<dc_base_logistics>(m);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        throw ex;
                    }
                }
            }

            
        }

    }
}
