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

namespace Bailun.DC.SemiSkuWarehouseSales
{
    public class Services : BackgroundService
    {
        public Services()
        {
            Dapper.SimpleCRUD.SetDialect(SimpleCRUD.Dialect.MySQL);
        }

        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 == 45)  //每小时跑一次
                {
                    Init();

                    //更新逻辑仓库的半成品销量信息
                    UpdateLogicWareHouseSemiSale();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }


        public void Init()
        {
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " 执行任务...");

            var _url = "http://mjzz.bailuntec.com/api/StockReport?rows=1000";

            int page = 1;
            int totalpage = 0;

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

                //删除旧数据
                cn.Execute("truncate dc_semi_stock_sales_shipping;");
            }

            while (page == 1 || (page <= totalpage))
            {
                var result = Bailun.DC.Common.HttpHelper.NetHelper.Request(_url + "&page="+page);

                if (!string.IsNullOrEmpty(result))
                {
                    var json = Newtonsoft.Json.JsonConvert.DeserializeObject<mResponse>(result);

                    if (json.success)
                    {
                        Console.WriteLine("总页数：" + json.data.TotalPages + ",当前页：" + json.data.CurrentPage);

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

                            //保存数据
                            foreach (var item in json.data.Items)
                            {
                                var m = new dc_semi_stock_sales_shipping()
                                {
                                    material_id = item.material_id,
                                    available_days = item.available_days,
                                    buyer_price = item.buyer_price,
                                    material_data_center = item.material_data_center,
                                    need_quantity = item.need_quantity,
                                    on_the_way_amount = item.on_the_way_amount,
                                    on_the_way_count = item.on_the_way_count,
                                    out_of_stock = item.out_of_stock,
                                    out_stock_30 = item.out_stock_30,
                                    put_stock_30 = item.put_stock_30,
                                    redundancy_stock = item.redundancy_stock,


                                    sales_1 = item.sales_1,
                                    sales_14 = item.sales_14,
                                    sales_30 = item.sales_30,
                                    sales_7 = item.sales_7,
                                    sku = item.sku,
                                    sku_name = item.sku_name,
                                    stock = item.stock,
                                    stock_amount = item.stock_amount,


                                    stock_amount_1 = item.stock_amount_1,
                                    warehouse_id = item.warehouse_id,
                                    warehouse_name = item.warehouse_name
                                };

                                cn.Insert<dc_semi_stock_sales_shipping>(m);
                            }

                        }

                        totalpage = json.data.TotalPages;
                        page++;
                    }
                    else
                    {
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+" 接口返回错误信息：" +json.message);
                    }
                }

            }

            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " 结束任务");
        }


        public void UpdateLogicWareHouseSemiSale()
        {
            
            var sql = @"update dc_skuwarehouse_stock_sales t1
                join dc_semi_stock_sales_shipping t2 on t2.warehouse_name=t1.warehouse_name and t1.bailun_sku=t2.sku
                set t1.quantity_purchase=t2.on_the_way_count,t1.purchase_amount=t2.on_the_way_amount,t1.oneday_total_sales=t2.sales_1,t1.amount_onedaysale=t2.stock_amount_1,t1.sevenday_total_sales=t2.sales_7,t1.fourteenday_total_sales=t2.sales_14,t1.thirtyday_total_sales=t2.sales_30,t1.nostockcount=t2.out_of_stock,t1.noshippingcount=t2.need_quantity,t1.quantity_tuneout_30days=t2.out_stock_30,t1.quantity_tunein_30days=t2.put_stock_30;";

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

                var result= cn.Execute(sql);

                Console.WriteLine("更新逻辑仓库半成品销量成功，受影响行数："+result);
            }


        }
    }
}
