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

namespace Bailun.DC.SyncWarehouseInfo
{
    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 == 23 && now.Minute == 58)  //凌晨23：58分启动
                {
                    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);
            }
        }


        protected string url = "http://api.wms.bailuntec.com/api/services/app/WarehouseService/SearchWarehouse";

        public Services()
        {
            Dapper.SimpleCRUD.SetDialect(SimpleCRUD.Dialect.MySQL);
        }

        public void Init()
        {
            var result = Bailun.DC.Common.HttpHelper.NetHelper.HttpPostJson(url, Newtonsoft.Json.JsonConvert.SerializeObject(new { data =new { } }));

            var json = JsonConvert.DeserializeObject<mResult_Request>(result);

            if (json.isSuccess)
            {
                Save(json.data);
            }

        }

        public void Save(List<mData> list)
        {

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


                foreach (var item in list)
                {
                    if (item.id == 0)
                    {
                        continue;
                    }

                    var accountname = "";
                    if (item.accountId > 0)
                    {
                        accountname = cn.QueryFirstOrDefault<string>("select concat(account_name,'-',site_en) as account from dc_base_company_account where account_id=" + item.accountId);
                    }

                    var m = cn.QueryFirstOrDefault<dc_base_warehouse>("select * from dc_base_warehouse where warehouse_code='" + item.code+"'");
                    if (m == null)
                    {
                        m = new dc_base_warehouse
                        {
                            area_id = item.area.id,
                            area_name = item.area.name,
                            bailun_account = accountname,
                            bailun_account_id = item.accountId,
                            company_id = 0,
                            functions = JsonConvert.SerializeObject(item.functions),

                            gmt_create = DateTime.Now,
                            gmt_modified = DateTime.Now,
                            hq_type = item.hqType,
                            system_flag = item.systemFlag,
                            type_id = item.typeId,
                            type_name = item.typeName,

                            warehouse_code = item.code,
                            warehouse_name = item.name,
                            warehouse_extend_name = item.extendName,
                            warehouse_id = item.id,
                            warehouse_old_code = item.oldCode,
                            warehouse_type_ex = "0"

                        };

                        cn.Insert(m);

                    }
                    else
                    {
                        m.area_id = item.area.id;
                        m.area_name = item.area.name;
                        m.bailun_account = accountname;
                        m.bailun_account_id = item.accountId;
                        m.company_id = 0;
                        m.functions = JsonConvert.SerializeObject(item.functions);

                        m.gmt_modified = DateTime.Now;
                        m.hq_type = item.hqType;
                        m.system_flag = item.systemFlag;
                        m.type_id = item.typeId;
                        m.type_name = item.typeName;

                        m.warehouse_code = item.code;
                        m.warehouse_name = item.name;
                        m.warehouse_extend_name = item.extendName;
                        m.warehouse_id = item.id;
                        m.warehouse_old_code = item.oldCode;
                        m.warehouse_type_ex = "0";

                        cn.Update(m);
                    }
                    
                }
            }
        }

        
    }
}
