using FluentNHibernate.Cfg;
using FluentNHibernate.Mapping;
using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ProjectManagementSystem.NHibernateDBHelper
{
    class MiddleDBModelHelper
    {
        static private volatile ISessionFactory m_factory = null;
        static private object obj = new object();
        static private string _connectionString;
        static public ISession Session//
        {
            get
            {
                if (m_factory == null)
                {
                    lock (obj)
                    {
                        try
                        {
                            if (m_factory == null) m_factory = createSessionFactory();
                        }
                        catch { throw; }
                    }
                }
                return m_factory.OpenSession();
            }
        }

        static public void initialize(string path)
        {
            _connectionString = "Data Source =" + path;
            try
            {
                if (m_factory != null) m_factory.Dispose();
                m_factory = createSessionFactory();
            }
            catch (Exception ex) { Console.Write(ex.ToString()); throw; }
        }

        public static void initialize(string strDatabaseServer,
                                      int databasePort,
                                      string strDatabaseName,
                                      string strUserName,
                                      string strPassword)
        {
            //if (m_sessionFactory != null) return;

            try
            {
                string connectionString = string.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};",
                    strDatabaseServer, databasePort, strDatabaseName, strUserName, strPassword);
                FluentConfiguration config = Fluently.Configure()
                        .Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008
                        .ConnectionString(connectionString));

                Assembly curAssembly = Assembly.GetExecutingAssembly();
                NHibernate.Cfg.Configuration cfg = config.Mappings(m => m.FluentMappings.AddFromAssembly(curAssembly)).BuildConfiguration();
                m_factory = cfg.BuildSessionFactory();

                //  m_mappingSet.buildMappings(cfg);
            }
            catch { throw; }
        }
        static public void close()
        {
            if (m_factory != null) { m_factory.Close(); m_factory = null; }
        }
        static private ISessionFactory createSessionFactory()
        {
            try
            {
                string connectionString = _connectionString;
                FluentConfiguration config = Fluently.Configure()
                        .Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008
                        .ConnectionString(connectionString));
                Assembly curAssembly = Assembly.GetExecutingAssembly();
                NHibernate.Cfg.Configuration cfg = config.Mappings(m => m.FluentMappings.AddFromAssembly(curAssembly))
                                                         .ExposeConfiguration(f => f.SetInterceptor(new SqlStatementInterceptor()))
                                                         .BuildConfiguration();
                return cfg.BuildSessionFactory();
            }
            catch { throw; }
        }

        public class SqlStatementInterceptor : EmptyInterceptor
        {
            public override NHibernate.SqlCommand.SqlString OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
            {
                //#if DEBUG
                try
                {
                    //File.AppendAllText("c:\\log.txt", string.Format("{0}\n", sql.ToString()));
                }
                catch
                {

                }
                return sql;
            }
        }
       
    }

    #region MiddleTask
    public class MiddleTask
    {
        private string _TaskType;
        private string _ArrLength;
        private string _PosArr;
        private string _ManualOrAuto;


        public MiddleTask()
        {

        }
        public MiddleTask(string posarr, string arrlen, string tasktype, string manualorauto)
        {
            _PosArr = posarr;
            _TaskType = tasktype;
            _ManualOrAuto = manualorauto;
            _ArrLength = arrlen;
        }
        public virtual string TaskType
        {
            get
            {
                return _TaskType;
            }

            set
            {
                _TaskType = value;
            }
        }

        public virtual string PosArr
        {
            get
            {
                return _PosArr;
            }

            set
            {
                _PosArr = value;
            }
        }


        public virtual string ArrLength
        {
            get
            {
                return _ArrLength;
            }

            set
            {
                _ArrLength = value;
            }
        }

        public virtual string ManualOrAuto
        {
            get
            {
                return _ManualOrAuto;
            }

            set
            {
                _ManualOrAuto = value;
            }
        }
    }

    class MappingMiddleTask : ClassMap<MiddleTask>
    {
        public MappingMiddleTask()
        {
            Table("MiddleTask");
            Id(m => m.PosArr).GeneratedBy.Assigned();//.Increment();
            Map(m => m.ManualOrAuto);
            Map(m => m.ArrLength);
            Map(m => m.TaskType);
        }

        //private void Table(string v)
        //{
        //    //throw new NotImplementedException();
        //}
    }
    #endregion

    #region CarrierCommand
    public class CarrierCommand
    {
        private int _UID;
        private int _Carrier;
        private int _Command;
        private int _Status;
        private DateTime _Timestamp;


        public CarrierCommand()
        {

        }
        public CarrierCommand(int carrier, int command, int status)
        {
            _Command = command;
            _Status = status;
            _Carrier = carrier;
            _Timestamp = DateTime.Now;
        }
        public virtual int UID
        {
            get
            {
                return _UID;
            }

            set
            {
                _UID = value;
            }
        }

        public virtual int Command
        {
            get
            {
                return _Command;
            }

            set
            {
                _Command = value;
            }
        }


        public virtual int Carrier
        {
            get
            {
                return _Carrier;
            }

            set
            {
                _Carrier = value;
            }
        }

        public virtual int Status
        {
            get
            {
                return _Status;
            }

            set
            {
                _Status = value;
            }
        }

        public virtual DateTime Timestamp
        {
            get
            {
                return _Timestamp;
            }

            set
            {
                _Timestamp = value;
            }
        }
    }

    class MappingCarrierCommand : ClassMap<CarrierCommand>
    {
        public MappingCarrierCommand()
        {
            Table("CarrierCommand");
            Id(m => m.UID).GeneratedBy.Increment();//Assigned()
            Map(m => m.Status);
            Map(m => m.Carrier);
            Map(m => m.Command);
            Map(m => m.Timestamp);
        }

        //private void Table(string v)
        //{
        //    //throw new NotImplementedException();
        //}
    }
    #endregion

    #region Order
    //public enum OrderState { None, Add, Loaded, Start, Started, Executing, Finish, Finished, Cancel, Canceled, TerminateTask, Exception, Exceptioned, RecoveryException, 到风淋窗 = 76, 进车间风淋中 = 77, 出车间风淋中 = 78, 到工位, 待取料, 缓存位, 缓存中, 充电任务中, 电梯缓存中 }
    public enum WCSOrderState { None, NDC, BindingAGV, RunToUpWarehouse, Uploaded, RunToDownWarehouse, Downloaded, Finished, Canceled}
    public enum OrderType { None, One, Tow, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Eleven, Twrive }
    //public enum ETaskState
    //{
    //    None = 0,
    //    Add = 1,
    //    Loaded = 2,
    //    Start = 3,
    //    Started = 4,
    //    Executing = 5,
    //    Finish = 6,
    //    Finished = 7,
    //    Cancel = 8,
    //    Canceled = 9,
    //    TerminateTask = 10,
    //    Exception = 11,
    //    Exceptioned = 12,
    //    RecoveryException = 13
    //}
    //public class Order
    //{
    //    private string _OrderID;
    //    private int _Carrier;
    //    private OrderType _OrderType;
    //    private int _OrderState;
    //    private DateTime _CallTime;
    //    private DateTime _FinishTime;
    //    private bool _Suspend;
    //    private string _Material;
    //    private string _UpPos;
    //    private string _MiddlePos;
    //    private string _DownPos;
    //    private string _CurPos;
    //    private int _Remain;


    //    public Order()
    //    {

    //    }
    //    public Order(string orderid, OrderType ordertype, string uppos, string middlepos, string downpos, int orderstate = -1, int remain = 0, string material = "", int carrier = 0, bool suspend = false)
    //    {
    //        _OrderType = ordertype;
    //        _OrderState = orderstate;
    //        _Carrier = carrier;
    //        _DownPos = downpos;
    //        _UpPos = uppos;
    //        _MiddlePos = middlepos;
    //        _Suspend = suspend;
    //        _OrderID = orderid;
    //        _Material = material;
    //        _CallTime = DateTime.Now;
    //        _FinishTime = DateTime.Now;
    //        _CurPos = "";
    //        _Remain = remain;
    //    }
    //    public virtual string OrderID
    //    {
    //        get
    //        {
    //            return _OrderID;
    //        }

    //        set
    //        {
    //            _OrderID = value;
    //        }
    //    }

    //    public virtual OrderType OrderType
    //    {
    //        get
    //        {
    //            return _OrderType;
    //        }

    //        set
    //        {
    //            _OrderType = value;
    //        }
    //    }


    //    public virtual int Carrier
    //    {
    //        get
    //        {
    //            return _Carrier;
    //        }

    //        set
    //        {
    //            _Carrier = value;
    //        }
    //    }

    //    public virtual int OrderState
    //    {
    //        get
    //        {
    //            return _OrderState;
    //        }

    //        set
    //        {
    //            _OrderState = value;
    //        }
    //    }

    //    public virtual DateTime CallTime
    //    {
    //        get
    //        {
    //            return _CallTime;
    //        }

    //        set
    //        {
    //            _CallTime = value;
    //        }
    //    }

    //    public virtual DateTime FinishTime
    //    {
    //        get
    //        {
    //            return _FinishTime;
    //        }

    //        set
    //        {
    //            _FinishTime = value;
    //        }
    //    }

    //    public virtual bool Suspend
    //    {
    //        get
    //        {
    //            return _Suspend;
    //        }

    //        set
    //        {
    //            _Suspend = value;
    //        }
    //    }

    //    public virtual string UpPos
    //    {
    //        get
    //        {
    //            return _UpPos;
    //        }

    //        set
    //        {
    //            _UpPos = value;
    //        }
    //    }

    //    public virtual string MiddlePos
    //    {
    //        get
    //        {
    //            return _MiddlePos;
    //        }

    //        set
    //        {
    //            _MiddlePos = value;
    //        }
    //    }

    //    public virtual string DownPos
    //    {
    //        get
    //        {
    //            return _DownPos;
    //        }

    //        set
    //        {
    //            _DownPos = value;
    //        }
    //    }

    //    public virtual string CurPos
    //    {
    //        get
    //        {
    //            return _CurPos;
    //        }

    //        set
    //        {
    //            _CurPos = value;
    //        }
    //    }
    //    public virtual string Material
    //    {
    //        get
    //        {
    //            return _Material;
    //        }

    //        set
    //        {
    //            _Material = value;
    //        }
    //    }
    //    public virtual int Remain
    //    {
    //        get
    //        {
    //            return _Remain;
    //        }

    //        set
    //        {
    //            _Remain = value;
    //        }
    //    }
    //}

    //class MappingOrder : ClassMap<Order>
    //{
    //    public MappingOrder()
    //    {
    //        Table("MiddleOrder");
    //        Id(m => m.OrderID).GeneratedBy.Assigned();//Assigned()
    //        Map(m => m.OrderState);
    //        Map(m => m.Carrier);
    //        Map(m => m.OrderType).CustomType<OrderType>();
    //        Map(m => m.CallTime);
    //        Map(m => m.FinishTime);
    //        Map(m => m.Material);
    //        Map(m => m.UpPos);
    //        Map(m => m.MiddlePos);
    //        Map(m => m.DownPos);
    //        Map(m => m.Suspend);
    //        Map(m => m.CurPos);
    //        Map(m => m.Remain);
    //    }

    //    //private void Table(string v)
    //    //{
    //    //    //throw new NotImplementedException();
    //    //}
    //}

    public class Order
    {
        private string _OrderID;
        private int _Carrier;
        private OrderType _OrderType;
        private int _OrderState;
        private DateTime _CallTime;
        private DateTime _FinishTime;
        private bool _Suspend;
        private string _Material;//taskid
        private string _UpPos;
        private string _MiddlePos;
        private string _DownPos;
        private string _CurPos;
        private int _Remain;//agvid


        public Order()
        {

        }
        public Order(string orderid, OrderType ordertype, string uppos, string middlepos, string downpos, int orderstate = -1, int remain = 0, string material = "", int carrier = 0, bool suspend = false)
        {
            _OrderType = ordertype;
            _OrderState = orderstate;
            _Carrier = carrier;
            _DownPos = downpos;
            _UpPos = uppos;
            _MiddlePos = middlepos;
            _Suspend = suspend;
            _OrderID = orderid;
            _Material = material;
            _CallTime = DateTime.Now;
            _FinishTime = DateTime.Now;
            _CurPos = "";
            _Remain = remain;
        }
        public virtual string OrderID
        {
            get
            {
                return _OrderID;
            }

            set
            {
                _OrderID = value;
            }
        }

        public virtual OrderType OrderType
        {
            get
            {
                return _OrderType;
            }

            set
            {
                _OrderType = value;
            }
        }


        public virtual int Carrier
        {
            get
            {
                return _Carrier;
            }

            set
            {
                _Carrier = value;
            }
        }

        public virtual int OrderState
        {
            get
            {
                return _OrderState;
            }

            set
            {
                _OrderState = value;
            }
        }

        public virtual DateTime CallTime
        {
            get
            {
                return _CallTime;
            }

            set
            {
                _CallTime = value;
            }
        }

        public virtual DateTime FinishTime
        {
            get
            {
                return _FinishTime;
            }

            set
            {
                _FinishTime = value;
            }
        }

        public virtual bool Suspend
        {
            get
            {
                return _Suspend;
            }

            set
            {
                _Suspend = value;
            }
        }

        public virtual string UpPos
        {
            get
            {
                return _UpPos;
            }

            set
            {
                _UpPos = value;
            }
        }

        public virtual string MiddlePos
        {
            get
            {
                return _MiddlePos;
            }

            set
            {
                _MiddlePos = value;
            }
        }

        public virtual string DownPos
        {
            get
            {
                return _DownPos;
            }

            set
            {
                _DownPos = value;
            }
        }

        public virtual string CurPos
        {
            get
            {
                return _CurPos;
            }

            set
            {
                _CurPos = value;
            }
        }
        public virtual string Material
        {
            get
            {
                return _Material;
            }

            set
            {
                _Material = value;
            }
        }
        public virtual int Remain
        {
            get
            {
                return _Remain;
            }

            set
            {
                _Remain = value;
            }
        }

        public virtual string OrderStateString
        {
            get
            {
                string state = "";
                switch (_OrderState)
                {
                    case -2:
                        state = "待备料";
                        break;
                    case -1:
                        state = "排队中";
                        break;
                    case 0:
                        state = "默认";
                        break;
                    case 1:
                        state = "已添加";
                        break;
                    case 2:
                        state = "创建中";
                        break;
                    case 3:
                        state = "排队中";
                        break;
                    case 4:
                        state = "分配中";
                        break;
                    case 5:
                        state = "运送中";
                        break;
                    case 6:
                        state = "操作中";
                        break;
                    case 7:
                        state = "完成";
                        break;
                    case 8:
                        state = "取消";
                        break;
                    case 9:
                        state = "挂起";
                        break;
                    case 10:
                        state = "续接";
                        break;
                    case 11:
                        state = "续接"; //AppendCreate
                        break;
                    case 76:
                        state = "到风淋窗";
                        break;
                    case 77:
                        state = "进车间风淋中";
                        break;
                    case 78:
                        state = "出车间风淋中";
                        break;
                    case 255:
                        state = "异常";
                        break;
                    default:
                        break;
                }
                return state;
            }
        }
    }

    class MappingOrder : ClassMap<Order>
    {
        public MappingOrder()
        {
            Table("MiddleOrder");
            Id(m => m.OrderID).GeneratedBy.Assigned();//Assigned()
            Map(m => m.OrderState);
            Map(m => m.Carrier);
            Map(m => m.OrderType).CustomType<OrderType>();
            Map(m => m.CallTime);
            Map(m => m.FinishTime);
            Map(m => m.Material);
            Map(m => m.UpPos);
            Map(m => m.MiddlePos);
            Map(m => m.DownPos);
            Map(m => m.Suspend);
            Map(m => m.CurPos);
            Map(m => m.Remain);
        }

        //private void Table(string v)
        //{
        //    //throw new NotImplementedException();
        //}
    }
    #endregion
}

