using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Threading;
using MySystem.Models;
using Library;
using LitJson;

namespace MySystem
{
    public class AutoOpOrderService
    {
        public readonly static AutoOpOrderService Instance = new AutoOpOrderService();
        private AutoOpOrderService()
        { }

        public void StartOrderCancel()
        {
            Thread th = new Thread(StartOrderCancelDo);
            th.IsBackground = true;
            th.Start();
        }
        
        private void StartOrderCancelDo()
        { 
            while (true)
            {
                try
                {
                    string conn = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
                    string checkDate = DateTime.Now.AddMinutes(-20).ToString("yyyy-MM-dd HH:mm:ss");
                    CustomerSqlConn.op("update OrderProduct set Status=-1 where OrderId in (select Id from Orders where Status=0 and CreateDate<'" + checkDate + "')", conn);
                    CustomerSqlConn.op("update Orders set Status=-1 where Status=0 and CreateDate<'" + checkDate + "'", conn);
                    Thread.Sleep(60000);
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "定时取消未支付订单异常");
                }
            }
        }




        public void StartOrderConfirm()
        {
            Thread th = new Thread(StartOrderConfirmDo);
            th.IsBackground = true;
            th.Start();
        }
        
        private void StartOrderConfirmDo()
        { 
            while (true)
            {
                try
                {
                    string conn = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
                    string checkDate = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd HH:mm:ss");
                    CustomerSqlConn.op("update Orders set Status=-1 where Status=2 and SendDate<'" + checkDate + "'", conn);
                    Thread.Sleep(3600000);
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "定时自动确认收货异常");
                }
            }
        }

    }
}