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.SyncSkuFinanceCategory
{
    
    public class Services : BackgroundService
    {
        string url = "http://api.skums.bailuntec.com/api/category/CategoryBailun/getcategorymappinglist?Plat=financecate"; // Index=1 Num=20

        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.Hour == 23 && now.Minute==10)  //每晚23：10同步一次
                {
                    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 Services() {
            Dapper.SimpleCRUD.SetDialect(SimpleCRUD.Dialect.MySQL);
        }

        public void Init()
        {
            var page = 0;
            var pagesize = 1000;
            var count = 0;

            while (count == 0 || count == pagesize)
            {
                var result = Bailun.DC.Common.HttpHelper.NetHelper.Request(url + "&Index=" + page + "&Num=" + pagesize);
                if (!string.IsNullOrEmpty(result))
                {
                    var json = Newtonsoft.Json.JsonConvert.DeserializeObject<mResponseResult>(result);
                    if (json.statusCode == 200)
                    {
                        count = json.result.Count;

                        //保存数据
                        Save(json.result);
                        page++;
                    }
                }
            }
        }

        public void Save(List<Models.mCategory> list)
        {
            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_sku_finance_category where bailuncategoryid=" + item.bailunCategoryId + " and financecategoryid=" + item.platCateoryId);

                    var m = new Models.dc_base_sku_finance_category {
                        bailuncategoryid = item.bailunCategoryId,
                        bailuncategoryname = item.bailunCateFullName,

                        financecategoryid = item.platCateoryId,
                        financecategoryname = item.platCateFullName,
                        createtime =DateTime.Now,
                        site = item.site,
                    };

                    cn.Insert(m);
                }
            }
        }

    }

    public class mResponseResult
    {
        public int statusCode { get; set; }

        public string message { get; set; }

        public List<Models.mCategory> result { get; set; }
    }
}
