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

namespace Bailun.DC.CostFirstMonitoring
{
    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.Hour%6==0 &&now.Minute==55)  //每天晚上23:55分跑一次
                {
                    Init();
                }
                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }


        public void Init()
        {
            var sql = "select id,pre_avl_sku_cost_first,after_avl_sku_cost_first,(after_avl_sku_cost_first-pre_avl_sku_cost_first) as diff from dc_base_cost_first_finish where change_rate=0 and pre_avl_sku_cost_first>0;";

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

                var list = cn.Query<mCostFirstFinish>(sql).AsList();

                foreach(var item in list)
                {
                    sql = "update dc_base_cost_first_finish set change_rate="+(item.diff*100/item.pre_avl_sku_cost_first)+ ",exception_type="+(item.diff>0?1:(item.diff<0?2:0))+" where id="+item.id;
                    cn.Execute(sql);
                }

                Console.WriteLine("本次更新" + list.Count + "条记录 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            }
        }
    }
}
