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;
using System.Linq;

namespace Bailun.DC.SyncLogisticInfo
{
    public class Services : BackgroundService
    {
        private static bool isRuning = false;
        private Timer _timer;
        private static List<Tuple<DateTime, string, decimal>> listMonthExchange = new List<Tuple<DateTime, string, decimal>>();

        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%30==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"));
                    UpdateRMBAmount();

                    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 currenttime = DateTime.Now;


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

                using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
                {
                    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(2);
                    }

                }

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

                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,
                        };

                        //获取相应汇率 取当月顺延第一日的汇率
                        if(m.currencytype.ToLower()=="cny")
                        {
                            m.amount_rmb = m.merchant_shipment_cost_cny;
                            m.exchangerate = 1;
                        }
                        else if(m.merchant_reconciliation_time.HasValue)
                        {
                            var objRate = listMonthExchange.Where(a => a.Item1.Year == m.merchant_reconciliation_time.Value.Year && a.Item1.Month == m.merchant_reconciliation_time.Value.Month && a.Item2==m.currencytype.ToUpper()).FirstOrDefault();

                            if(objRate!=null)
                            {
                                m.exchangerate = objRate.Item3;
                                m.amount_rmb = m.merchant_shipment_cost_cny * objRate.Item3;
                            }
                            else
                            {
                                //获取当月汇率
                                try
                                {
                                    var _url_exchange = $"http://oa.bailuntec.com/Api/ExchangeRate/GetMonthlyExchangeRateByDate?date={m.merchant_reconciliation_time.Value.ToString("yyyy-MM")}&toCur=CNY&fromCur="+m.currencytype.ToUpper();

                                    var result_Exchange = Common.HttpHelper.NetHelper.Request(_url_exchange);
                                    if (!string.IsNullOrEmpty(result_Exchange))
                                    {
                                        var json = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.response_Exchange>(result_Exchange);
                                        objRate = new Tuple<DateTime, string, decimal>(DateTime.Parse(m.merchant_reconciliation_time.Value.ToString("yyyy-MM")+"-01"),m.currencytype.ToUpper(),json.rate);

                                        listMonthExchange.Add(objRate);

                                        m.exchangerate = objRate.Item3;
                                        m.amount_rmb = objRate.Item3 * m.merchant_shipment_cost_cny;

                                    }
                                    
                                }
                                catch (Exception ex)
                                {
                                    
                                }
                            }
                        }


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

            
        }

        public void UpdateRMBAmount()
        {
            var list = new List<dc_base_logistics>();
            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString_read))
            {
                if(cn.State== System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                list = cn.Query<dc_base_logistics>("select * from dc_base_logistics where merchant_reconciliation_time>='2020-09-01' and amount_rmb is null",null,null,true,6*60).ToList();
            }

            if(list.Count>0)
            {
                //
                using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
                {
                    foreach (var item in list)
                    {
                        if (item.currencytype.ToLower() == "cny")
                        {
                            item.amount_rmb = item.merchant_shipment_cost_cny;
                            item.exchangerate = 1;

                            if (cn.State == System.Data.ConnectionState.Closed)
                            {
                                cn.Open();
                            }

                            cn.Execute($"update dc_base_logistics set exchangerate={item.exchangerate},amount_rmb={item.amount_rmb} where id={item.id}");
                        }
                        else
                        {
                            var objRate = listMonthExchange.Where(a => a.Item1.Year == item.merchant_reconciliation_time.Value.Year && a.Item1.Month == item.merchant_reconciliation_time.Value.Month && a.Item2 == item.currencytype.ToUpper()).FirstOrDefault();

                            if (objRate != null)
                            {
                                item.exchangerate = objRate.Item3;
                                item.amount_rmb = item.merchant_shipment_cost_cny * objRate.Item3;

                                if (cn.State == System.Data.ConnectionState.Closed)
                                {
                                    cn.Open();
                                }

                                cn.Execute($"update dc_base_logistics set exchangerate={item.exchangerate},amount_rmb={item.amount_rmb} where id={item.id}");
                            }
                            else
                            {
                                //获取当月汇率
                                try
                                {
                                    var _url_exchange = $"http://oa.bailuntec.com/Api/ExchangeRate/GetMonthlyExchangeRateByDate?date={item.merchant_reconciliation_time.Value.ToString("yyyy-MM")}&toCur=CNY&fromCur=" + item.currencytype.ToUpper();

                                    var result_Exchange = Common.HttpHelper.NetHelper.Request(_url_exchange);
                                    if (!string.IsNullOrEmpty(result_Exchange))
                                    {
                                        var json = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.response_Exchange>(result_Exchange);
                                        objRate = new Tuple<DateTime, string, decimal>(DateTime.Parse(item.merchant_reconciliation_time.Value.ToString("yyyy-MM") + "-01"), item.currencytype.ToUpper(), json.rate);

                                        listMonthExchange.Add(objRate);

                                        item.exchangerate = objRate.Item3;
                                        item.amount_rmb = objRate.Item3 * item.merchant_shipment_cost_cny;

                                        if (cn.State == System.Data.ConnectionState.Closed)
                                        {
                                            cn.Open();
                                        }

                                        cn.Execute($"update dc_base_logistics set exchangerate={item.exchangerate},amount_rmb={item.amount_rmb} where id={item.id}");
                                    }

                                }
                                catch (Exception ex)
                                {

                                }
                            }
                        }
                    }
                }

                Console.WriteLine("本次更新" + list.Count + "条记录");

            }
        }

    }
}
