using irisHelper;
using irisMemory;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Odbc;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace irisDataBase.Service.mysqlImpl
{
    public class IrisPermisionServiceImpl:IrisPermisionService
    {
        public bool GetOpenDoorPermision(AuthConfig authConfig, long personId, string devCode, out string doorCode, out string inoutType)
        {

            doorCode = null;
            inoutType = null;
            bool blDoor = false;
            if (!authConfig.HasOpenDoorAuthority) return false;
            else
            {
                int open = isAlwaysOpen(devCode, out doorCode, out inoutType);
                //LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, "常开常闭权限：" + open);
                if (open == 0) return false;
                else if (open == 1) return true;
                else
                {
                    if (!authConfig.DoorDt.NeedPermisson) return true;
                    blDoor = isPermissionLocal(personId, devCode, out doorCode, out inoutType);
                    return blDoor;
                }
            }
        }

        private bool isPermissionLocal(long personId,string devCode,out string doorCode,out string inoutType)
        {

            MySqlDataReader aReader = null;
            doorCode = "";
            inoutType = "";

            //获取当前时间
            DateTime dateTimeNow = DateTime.Now;
            string nowStr = dateTimeNow.ToString("yyyy-MM-dd HH:mm:ss");

            if (DatabaseLocal.mySqlConnect.State == ConnectionState.Closed)
            {
                int langue = Convert.ToInt32(ConfigHelper.GetAppConfig("language"));
                if (langue == 1)
                    MessageBox.Show("与本地数据库连接断开，软件即将关闭，请检查后再启动！", "提示");
                else
                    MessageBox.Show("Disconnect from local database", "message");
                Application.Exit();
                return false;
            }

            string sQry = "SELECT DEV_IP,DOOR_CODE,INOUT_TYPE,STRATEGY_ID,ID, PERSON_ID,OPEN_STATUS,OPEN_STATUS_BEGIN_DATETIME,OPEN_STATUS_END_DATETIME" +
                ",STRATEGY_TYPE, BEGIN_DATETIME,END_DATETIME,WEEK,PERIOD,BEGIN_TIME,END_TIME,CREATE_TIME,DEV_CODE FROM permission_view WHERE PERSON_ID=@PERSON_ID" +
                " AND DEV_CODE = @DEV_CODE";
            MySqlCommand aCommand = new MySqlCommand(sQry, DatabaseLocal.mySqlConnect);
            aCommand.Parameters.Add("@PERSON_ID", MySqlDbType.Int64, 20).Value = (Int64)personId;
            aCommand.Parameters.Add("@DEV_CODE", MySqlDbType.String, 20).Value = devCode;

            try
            {
                aReader = aCommand.ExecuteReader(CommandBehavior.Default);
                //存在此门权限条目
                if (aReader != null)
                {
                    if (aReader.Read())
                    {
                        #region
                        //判断门的状态1常开，0常闭，2正常
                        /*if (!aReader.IsDBNull(6))
                        {
                            int openStatus = Convert.ToInt16(aReader.GetString(6));
                            if (openStatus == (int)EnumHelper.OpenStatus.常开)
                            {
                                DateTime openStatusBeginDatetime = Convert.ToDateTime(aReader.GetString(7));//Convert.ToDateTime(Convert.ToDateTime(dt.Rows[i]["recTime"]).ToString("yyyy-MM-dd HH:mm:ss"));
                                DateTime openStatusEndDatetime = Convert.ToDateTime(aReader.GetString(8));//dateTime
                                if (dateTimeNow >= openStatusBeginDatetime && dateTimeNow <= openStatusEndDatetime)
                                {
                                    //devCode = aReader.GetString(17);
                                    doorCode = aReader.GetString(1);
                                    inoutType = aReader.GetString(2);
                                    return true;
                                }
                            }
                            else if (openStatus == (int)EnumHelper.OpenStatus.常闭)
                            {
                                DateTime openStatusBeginDatetime = Convert.ToDateTime(aReader.GetString(7));
                                DateTime openStatusEndDatetime = Convert.ToDateTime(aReader.GetString(8));
                                if (dateTimeNow >= openStatusBeginDatetime && dateTimeNow <= openStatusEndDatetime)
                                {
                                    return false;
                                }
                            }
                        }*/
                        #endregion

                        //门的状态为正常或该字段null，继续判断是否有开门权限
                        if (!aReader.IsDBNull(9))
                        {
                            int strategyType = Convert.ToInt16(aReader.GetString(9));

                            //当天
                            if (strategyType == (int)EnumHelper.StrategyType.当天)
                            {
                                //策略创建时间
                                if (!aReader.IsDBNull(16))
                                {
                                    //string createDate = aReader.GetString(16).Substring(0, 10);//只取日期部分
                                    string createDateStr = aReader.GetString(16);
                                    DateTime createDate = Convert.ToDateTime(createDateStr);
                                    string createDateFormat = createDate.ToString("yyyy-MM-dd HH:mm:ss").Substring(0,10); 

                                    if (createDateFormat != nowStr.Substring(0, 10))
                                    {
                                        return false;
                                    }

                                    string beginTime = "";
                                    string endTime = "";
                                    if (!aReader.IsDBNull(14) && !aReader.IsDBNull(15))
                                    {
                                        beginTime = aReader.GetString(14);
                                        endTime = aReader.GetString(15);
                                        DateTime begin = Convert.ToDateTime(beginTime);
                                        DateTime end = Convert.ToDateTime(endTime);

                                        if (dateTimeNow >= begin && dateTimeNow <= end)
                                        {
                                            //devCode = aReader.GetString(17);
                                            doorCode = aReader.GetString(1);
                                            inoutType = aReader.GetString(2);
                                            //LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, "当日有权限");
                                            return true;
                                        }
                                        //LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, "当日权限时间不正确");
                                    }
                                }
                            }

                            //星期
                            if (strategyType == (int)EnumHelper.StrategyType.星期)
                            {
                                if (!aReader.IsDBNull(13))
                                {
                                    int periodType = Convert.ToInt16(aReader.GetString(13));
                                    string weekStr = aReader.GetString(12); //设置的星期几字符串
                                    if (periodType == (int)EnumHelper.StrategyPeriod.当次)
                                    {
                                        string createDateStr = aReader.GetString(16);
                                        DateTime createDate1 = Convert.ToDateTime(createDateStr);
                                        string createDateFormat = createDate1.ToString("yyyy-MM-dd HH:mm:ss").Substring(0, 10);
                                        DateTime createDate = Convert.ToDateTime(createDateFormat);

                                        //string createDateStr = aReader.GetString(16).Substring(0, 10);//只取日期部分
                                        //DateTime createDate = Convert.ToDateTime(createDateStr);
                                        int scope = 0;
                                        DayOfWeek weekNow = createDate.DayOfWeek;
                                        if (weekNow == DayOfWeek.Monday) scope = 6;
                                        else if (weekNow == DayOfWeek.Tuesday) scope = 5;
                                        else if (weekNow == DayOfWeek.Wednesday) scope = 4;
                                        else if (weekNow == DayOfWeek.Thursday) scope = 3;
                                        else if (weekNow == DayOfWeek.Friday) scope = 2;
                                        else if (weekNow == DayOfWeek.Saturday) scope = 1;

                                        //当前日期超出“当次星期周”
                                        if (dateTimeNow > createDate.AddDays(scope))
                                        {
                                            return false;
                                        }

                                        //当前日期在“当次星期周”之内                                        
                                        if (weekStr.Contains((7 - scope).ToString()))
                                        {
                                            //判断时间范围                                           
                                            if (!aReader.IsDBNull(14) && !aReader.IsDBNull(15))
                                            {
                                                //TimeSpan begin = new TimeSpan(aReader.GetDateTime(14).Ticks);
                                                //TimeSpan end = new TimeSpan(aReader.GetDateTime(15).Ticks);
                                                DateTime dtBegin = Convert.ToDateTime(aReader.GetString(14));
                                                DateTime dtEnd = Convert.ToDateTime(aReader.GetString(15));

                                                TimeSpan begin = dtBegin.TimeOfDay;
                                                TimeSpan end = dtEnd.TimeOfDay;

                                                if (dateTimeNow.TimeOfDay >= begin && dateTimeNow.TimeOfDay <= end)
                                                {
                                                    doorCode = aReader.GetString(1);
                                                    inoutType = aReader.GetString(2);
                                                    return true;
                                                }
                                            }
                                        }

                                    }
                                    else if (periodType == (int)EnumHelper.StrategyPeriod.永久)
                                    {
                                        DayOfWeek weekNow = dateTimeNow.DayOfWeek;
                                        string weekNowS = "";
                                        if (weekNow == DayOfWeek.Monday) weekNowS = "1";
                                        else if (weekNow == DayOfWeek.Tuesday) weekNowS = "2";
                                        else if (weekNow == DayOfWeek.Wednesday) weekNowS = "3";
                                        else if (weekNow == DayOfWeek.Thursday) weekNowS = "4";
                                        else if (weekNow == DayOfWeek.Friday) weekNowS = "5";
                                        else if (weekNow == DayOfWeek.Saturday) weekNowS = "6";
                                        else if (weekNow == DayOfWeek.Sunday) weekNowS = "7";

                                        if (weekStr.Contains(weekNowS))
                                        {
                                            //判断时间范围                                           
                                            if (!aReader.IsDBNull(14) && !aReader.IsDBNull(15))
                                            {
                                                DateTime dtBegin = Convert.ToDateTime(aReader.GetString(14));
                                                DateTime dtEnd = Convert.ToDateTime(aReader.GetString(15));

                                                TimeSpan begin = dtBegin.TimeOfDay;
                                                TimeSpan end = dtEnd.TimeOfDay;

                                                if (dateTimeNow.TimeOfDay >= begin && dateTimeNow.TimeOfDay <= end)
                                                {
                                                    doorCode = aReader.GetString(1);
                                                    inoutType = aReader.GetString(2);
                                                    return true;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            return false;
                                        }
                                    }

                                }
                            }


                            // 日期
                            if (strategyType == (int)EnumHelper.StrategyType.日期)
                            {
                                if (!aReader.IsDBNull(10) && !aReader.IsDBNull(11))
                                {
                                    DateTime begin = Convert.ToDateTime(aReader.GetString(10));
                                    DateTime end = Convert.ToDateTime(aReader.GetString(11));
                                    if (dateTimeNow >= begin && dateTimeNow <= end)
                                    {
                                        //devCode = aReader.GetString(17);
                                        doorCode = aReader.GetString(1);
                                        inoutType = aReader.GetString(2);
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (OdbcException exSqlDb)
            {
                LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, "  isPermission : " + exSqlDb.Message);
                return false;
            }
            finally
            {
                aReader.Close();
                aReader.Dispose();
                aCommand.Dispose();
            }
            return false;
        }
        /// <summary>
        /// 0,不能开门；1，开门；2，正常
        /// </summary>
        /// <param name="devCode"></param>
        /// <param name="doorCode"></param>
        /// <param name="inoutType"></param>
        /// <returns></returns>
        private int isAlwaysOpen(string devCode, out string doorCode, out string inoutType)
        {
            MySqlDataReader aReader = null;
            doorCode = "";
            inoutType = "";

            //获取当前时间
            DateTime dateTimeNow = DateTime.Now;
            //string nowStr = dateTimeNow.ToString("yyyy-MM-dd HH:mm:ss");

            if (DatabaseLocal.mySqlConnect.State == ConnectionState.Closed)
            {
                int langue = Convert.ToInt32(ConfigHelper.GetAppConfig("language"));
                if (langue == 1)
                    MessageBox.Show("与本地数据库连接断开，软件即将关闭，请检查后再启动！", "提示");
                else
                    MessageBox.Show("Disconnect from local database", "message");
                Application.Exit();
                return 0;
            }

            string sQry = "SELECT a.DOOR_CODE,a.OPEN_STATUS,a.BEGIN_DATETIME,a.END_DATETIME,b.INOUT_TYPE " +
                "FROM acs_door a,bus_device b WHERE a.DOOR_CODE = b.DOOR_CODE AND b.DEV_CODE = @DEV_CODE";

            MySqlCommand aCommand = new MySqlCommand(sQry, DatabaseLocal.mySqlConnect);
            aCommand.Parameters.Add("@DEV_CODE", MySqlDbType.String, 20).Value = devCode;

            try
            {
                aReader = aCommand.ExecuteReader(CommandBehavior.Default);
                if (aReader != null)
                {
                    if (aReader.Read())
                    {
                        //判断门的状态1常开，0常闭，2正常
                        if (!aReader.IsDBNull(1))
                        {
                            int openStatus = Convert.ToInt16(aReader.GetString(1));
                            doorCode = aReader.GetString(0);
                            inoutType = aReader.GetString(4);

                            if (openStatus == (int)EnumHelper.OpenStatus.正常)
                                return 2;
                            else
                            {
                                DateTime openStatusBeginDatetime = Convert.ToDateTime(aReader.GetString(2));//Convert.ToDateTime(Convert.ToDateTime(dt.Rows[i]["recTime"]).ToString("yyyy-MM-dd HH:mm:ss"));
                                DateTime openStatusEndDatetime = Convert.ToDateTime(aReader.GetString(3));//dateTime
                                if (openStatus == (int)EnumHelper.OpenStatus.常开)
                                {
                                    if (dateTimeNow >= openStatusBeginDatetime && dateTimeNow <= openStatusEndDatetime)
                                        return 1;
                                    else
                                        return 2;
                                }
                                else if(openStatus == (int)EnumHelper.OpenStatus.常闭)
                                {

                                    if (dateTimeNow >= openStatusBeginDatetime && dateTimeNow <= openStatusEndDatetime)
                                        return 0;
                                    else
                                        return 2;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, "isPermission :常开常闭判断失败");
                return 0;
            }
            finally
            {
                aReader.Close();
                aReader.Dispose();
                aCommand.Dispose();
            }

            return 2;
        }
        
    }
}