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 static bool isRuning = false;
        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%5==0 && !isRuning)  //每5分钟同步一次
                {
                    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()
        {
            try
            {
                isRuning = true;
                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<DateTime?>("select end_time from job_point_log where job_name='dc-base-logisticinfo'");
                    if (m != null && m.HasValue)
                    {
                        starttime = m.Value.AddMinutes(-2);
                        endtime = starttime.AddHours(8);
                    }

                }

                if (starttime >= DateTime.Now)
                {
                    starttime = DateTime.Now.AddMinutes(-2);
                }

                //starttime = DateTime.Parse("2020-09-05");
                //endtime = starttime.AddDays(1);
                if (endtime > DateTime.Now)
                {
                    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 != null && json.success && json.result.result.Count > 0)
                    {
                        Save(json.result.result);
                        Console.WriteLine("总记录数：" + json.result.total + ",当前页记录数：" + json.result.result.Count + "条记录。" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        total = json.result.total;
                        page++;
                    }
                    else
                    {
                        page = 1;
                        total = 0;
                        
                    }
                }

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

                    cn.Execute("update job_point_log set start_time='" + starttime.ToString("yyyy-MM-dd HH:mm:ss") + "',end_time='" + endtime.ToString("yyyy-MM-dd HH:mm:ss") + "' where job_name='dc-base-logisticinfo'");

                }

                isRuning = false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                isRuning = false;
            }
            
        }

        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,
                            
                            currencytype = item.currencyType,
                        };

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

            
        }

    }
}
