using MediII.Adapter.ReceiveToScanModel;
using MediII.Adapter.Scanner;
using System;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using IL.Common;

namespace MediII.Adapter.BizComponent.UE
{
    public class HL7_Lock_Scanner : DBScaner
    {

        private int TaskRunTime = 5;

        public HL7_Lock_Scanner()
        {

            var tm = ConfigurationManager.AppSettings["TaskRunTime"];
            if (!int.TryParse(tm, out TaskRunTime))
            {
                TaskRunTime = 5;
            }

        }


        protected override long OnDo(DateTime dtEventTime, Action<LogModel> setLog)
        {
            if (setLog != null)
                setLog(new LogModel { Message = "开始一次解锁消息处理扫描 " });
            var sql = string.Format(" SELECT * FROM HL7_Receive WHERE TaskStatus=2 AND StartTime<DATE_ADD(SYSDATE(),interval -{0} MINUTE)   ", TaskRunTime);//操作中数据
            try
            {
                var listRow = MySqlDataAccess.ExecuteSqlStringAccessor<HL7_ReceiveEntity>(ctx, sql).Take(100).ToList();
                if (listRow.Count() > 0)
                {
                    process(listRow, setLog);

                }
            }
            catch (Exception ex)
            {
                if (setLog != null)
                    setLog(new LogModel { Message = "解锁消息发生错误", ErrorMsg = ex.Message + "\r\n" + ex.StackTrace });
            }
            return 1;
        }


        private void process(IEnumerable<HL7_ReceiveEntity> listRow, Action<LogModel> setLog)
        {
            listRow.ToList().ForEach(o =>
            {
                try
                {
                    if (setLog != null)
                        setLog(new LogModel { Message = "解锁消息:"+o.MsgContent, MessageID = o.MessageID });

                    var sql = "UPDATE HL7_Receive SET TaskStatus=1,StartTime=NULL,TaskIP=NULL,TaskMsg = null, TaskMac=NULL WHERE ID=?ID";
                    var cmd = MySqlDataAccess.GetSqlStringCommand(ctx, sql);
                    MySqlDataAccess.AddInParameter(ctx, cmd, "ID", DbType.String, o.ID);
                    MySqlDataAccess.ExecuteNonQuery(ctx, cmd);
                }
                catch (Exception ex)
                {
                    if (setLog != null)
                        setLog(new LogModel
                        {
                            Message = string.Format("解锁消息发生错误:HL7ReceiveID:{0}", o.ID),
                            ErrorMsg = ex.Message + "\r\n" + ex.StackTrace
                        });
                }

            });
        }



    }
}
