using Foresight.Data;
using Foresight.Fleet.Services.Asset;
using Foresight.Fleet.Services.AssetHealth;
using Foresight.Fleet.Services.User;
using IronIntel.Contractor.Machines;
using IronIntel.Services;
using IronIntel.Services.Business.Admin;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IronIntel.Contractor.Maintenance
{
    public class MaintenanceManagement
    {

        #region PM SCHEDULES

        public static PmScheduleInfo[] GetPmSchedule(string sessionid, string pmtype)
        {
            var items = FleetServiceClientHelper.CreateClient<PMClient>(sessionid).GetPMScheduleItems(SystemParams.CompanyID, pmtype, string.Empty, true);
            if (items == null || items.Length == 0)
                return new PmScheduleInfo[0];
            List<PmScheduleInfo> list = new List<PmScheduleInfo>();
            foreach (var item in items)
            {
                PmScheduleInfo pm = new PmScheduleInfo();
                pm.PmScheduleID = item.Id;
                pm.PmScheduleName = item.Name;
                pm.PmScheduleUom = item.UOM;
                pm.PmScheduleType = item.ScheduleType;
                pm.Notes = item.Notes;
                if (item.Intervals != null || item.Intervals.Count > 0)
                {
                    List<PmIntervalItem> lsinterval = new List<PmIntervalItem>();
                    foreach (var pi in item.Intervals)
                    {
                        PmIntervalItem piclient = new PmIntervalItem();
                        Helper.CloneProperty(piclient, pi);
                        piclient.PmIntervalID = pi.Id;
                        lsinterval.Add(piclient);
                    }
                    pm.Intervals = lsinterval.ToArray();

                    if (pm.PmScheduleType == "HM" || pm.PmScheduleType == "RDM" || pm.PmScheduleType == "TBM")
                        pm.AllIntervals = GetAllIntervals(item);
                }
                else
                    pm.Intervals = new PmIntervalItem[0];
                list.Add(pm);
            }
            return list.ToArray();
        }

        public static PmScheduleInfo GetPMScheduleByID(string sessionid, string scheduleid)
        {
            var item = FleetServiceClientHelper.CreateClient<PMClient>(sessionid).GetPMScheduleItem(SystemParams.CompanyID, scheduleid, true);
            PmScheduleInfo pm = new PmScheduleInfo();
            pm.PmScheduleID = item.Id;
            pm.PmScheduleName = item.Name;
            pm.PmScheduleUom = item.UOM;
            pm.PmScheduleType = item.ScheduleType;
            pm.Notes = item.Notes;
            if (item.Intervals != null || item.Intervals.Count > 0)
            {
                List<PmIntervalItem> lsinterval = new List<PmIntervalItem>();
                foreach (var pi in item.Intervals)
                {
                    PmIntervalItem piclient = new PmIntervalItem();
                    Helper.CloneProperty(piclient, pi);
                    piclient.PmIntervalID = pi.Id;
                    lsinterval.Add(piclient);
                }
                pm.Intervals = lsinterval.ToArray();

                if (pm.PmScheduleType == "HM" || pm.PmScheduleType == "RDM" || pm.PmScheduleType == "TBM")
                    pm.AllIntervals = GetAllIntervals(item);
            }
            else
                pm.Intervals = new PmIntervalItem[0];


            return pm;
        }
        //private static int[] GetAllIntervals(PMScheduleItem sc)
        //{
        //    Dictionary<int, List<PMIntervalItem>> result = new Dictionary<int, List<PMIntervalItem>>();

        //    var intervals = sc.Intervals.Where(i => i.Recurring).OrderBy(i => i.Interval).ThenByDescending(i => i.Priority).ToList();
        //    if (intervals.Count == 0)
        //        return new int[0];

        //    int maxInterval = intervals[intervals.Count() - 1].Interval;
        //    for (int i = intervals.Count - 1; i >= 0; i--)
        //    {//从最大的Interval开始
        //        PMIntervalItem ia = intervals[i];

        //        int tempInterval = ia.Interval;
        //        var existIntervals = result.OrderBy(kv => kv.Key).Select(kv => kv.Key).ToList();

        //        if (!result.ContainsKey(tempInterval))//加入自己
        //        {
        //            result[tempInterval] = new List<PMIntervalItem>();
        //        }
        //        result[tempInterval].Add(ia);

        //        tempInterval += ia.Interval;
        //        foreach (var ti in existIntervals)
        //        {//result排序后找第一个比tempInterval大的值
        //            while (tempInterval < ti)
        //            {
        //                if (!result.ContainsKey(tempInterval))
        //                {
        //                    result[tempInterval] = new List<PMIntervalItem>();
        //                }
        //                result[tempInterval].Add(ia);
        //                tempInterval += ia.Interval;
        //            }

        //            tempInterval = ti;
        //            tempInterval += ia.Interval;
        //        }
        //    }

        //    return result.Select(r => r.Key).OrderBy(r => r).ToArray();
        //}

        private static int[] GetAllIntervals(PMScheduleItem sc)
        {
            Dictionary<int, PMIntervalItem> result = new Dictionary<int, PMIntervalItem>();

            var intervals = sc.Intervals.Where(i => i.Recurring).OrderBy(i => i.Interval).ThenByDescending(i => i.Priority).ToList();
            if (intervals.Count == 0)
                return null;

            int maxInterval = 0;
            for (int i = 0; i < intervals.Count; i++)
            {
                PMIntervalItem ia = intervals[i];
                if (maxInterval == 0)
                    maxInterval = ia.Interval;
                else
                    maxInterval = GetMinCommonMultiple(maxInterval, ia.Interval);
            }
            for (int i = 0; i < intervals.Count; i++)
            {
                PMIntervalItem ia = intervals[i];
                int tempInterval = ia.Interval;
                while (tempInterval <= maxInterval)
                {
                    if (result.ContainsKey(tempInterval))
                    {
                        if (ia.Priority < result[tempInterval].Priority
                            || (ia.Priority == result[tempInterval].Priority
                               && ia.Interval == result[tempInterval].Interval))
                            result[tempInterval] = ia;
                    }
                    else
                        result[tempInterval] = ia;

                    tempInterval += ia.Interval;
                }
            }

            return result.Select(r => r.Key).OrderBy(r => r).Take(1000).ToArray();
            //最大只取1000个，正常设置不会超过1000，异常设置数量太多会使前端页面卡死
        }

        private static int GetMaxCommonDivisor(int a, int b)
        {
            if (a < b) { a = a + b; b = a - b; a = a - b; }
            return (a % b == 0) ? b : GetMaxCommonDivisor(a % b, b);
        }

        private static int GetMinCommonMultiple(int a, int b)
        {
            return a * b / GetMaxCommonDivisor(a, b);
        }

        public static PmIntervalItem[] GetPmInterval(string sessionid, string scheduleid)
        {
            var items = FleetServiceClientHelper.CreateClient<PMClient>(sessionid).GetPMIntervals(SystemParams.CompanyID, scheduleid);
            if (items == null || items.Length == 0)
                return new PmIntervalItem[0];

            List<PmIntervalItem> list = new List<PmIntervalItem>();
            foreach (var pi in items)
            {
                PmIntervalItem piclient = new PmIntervalItem();
                Helper.CloneProperty(piclient, pi);
                piclient.PmIntervalID = pi.Id;
                list.Add(piclient);
            }

            return list.ToArray();
        }

        public static PMAssetAlertInfo[] GetPmScheduleByAsset(string sessionid, long assetid)
        {
            List<PMAssetAlertInfo> result = new List<PMAssetAlertInfo>();
            var client = FleetServiceClientHelper.CreateClient<PMClient>(sessionid);
            var sches = client.GetPMScheduleItems(SystemParams.CompanyID, "", string.Empty, true);
            var aas = client.GetPMAssetAlertItems(SystemParams.CompanyID, assetid);
            foreach (var item in sches)
            {
                PMAssetAlertInfo pm = new PMAssetAlertInfo();
                pm.PmScheduleID = item.Id;
                pm.PmScheduleName = item.Name;
                pm.PmScheduleUom = item.UOM;
                pm.PmScheduleType = item.ScheduleType;
                pm.Notes = item.Notes;
                if (item.Intervals != null || item.Intervals.Count > 0)
                {
                    List<PmIntervalItem> lsinterval = new List<PmIntervalItem>();
                    foreach (var pi in item.Intervals)
                    {
                        PmIntervalItem piclient = new PmIntervalItem();
                        Helper.CloneProperty(piclient, pi);
                        piclient.PmIntervalID = pi.Id;
                        lsinterval.Add(piclient);
                    }
                    pm.Intervals = lsinterval.ToArray();

                    if (pm.PmScheduleType == "HM" || pm.PmScheduleType == "RDM" || pm.PmScheduleType == "TBM")
                        pm.AllIntervals = GetAllIntervals(item);
                }
                else
                    pm.Intervals = new PmIntervalItem[0];

                if (aas != null)
                {
                    var aa = aas.FirstOrDefault(a => a.PMScheduleId.Equals(pm.PmScheduleID, StringComparison.OrdinalIgnoreCase));
                    if (aa != null)
                    {
                        pm.Selected = true;
                        pm.AssetId = aa.AssetId;
                        pm.PmScheduleID = aa.PMScheduleId;
                        pm.PmIntervalId = aa.PMIntervalId;
                        pm.ServiceName = aa.ServiceName;
                        pm.LastAlertTime = aa.LastAlertTime;
                        pm.StartDate = aa.StartDate;
                        pm.StartHours = aa.StartHours;
                        pm.StartOdometer = aa.StartOdometer;
                        pm.StartIntervalValue = aa.StartIntervalValue;
                        pm.UnMaintainedAlert = aa.UnMaintainedAlert;
                    }
                }

                result.Add(pm);
            }
            return result.ToArray();
        }

        public static PmScheduleInfo GetPmScheduleByID(string sessionid, string scheduleid)
        {
            const string SQL = @"select PMSCHEDULEID,SCHEDULENAME,SCHEDULETYPE,NOTES,SCHEDULEUOM from PM_SCHEDULES where PMSCHEDULEID={0}";
            FISqlConnection db = SystemParams.GetDbInstance();
            DataTable dt = db.GetDataTableBySQL(SQL, scheduleid);
            if (dt.Rows.Count == 0)
            {
                return new PmScheduleInfo();
            }
            PmScheduleInfo si = ConvertPmScheduleInfo(dt.Rows[0]);
            si.Intervals = GetPmInterval(sessionid, si.PmScheduleID);
            return si;
        }

        public static void UpdatePmSchedule(string sessionid, PmScheduleInfo si, string useriid)
        {
            PMScheduleItem pm = new PMScheduleItem();
            pm.Id = si.PmScheduleID;
            pm.Name = si.PmScheduleName;
            pm.UOM = si.PmScheduleUom;
            pm.ScheduleType = si.PmScheduleType;
            pm.Notes = si.Notes;
            if (si.Intervals != null && si.Intervals.Length > 0)
            {
                List<PMIntervalItem> list = new List<PMIntervalItem>();
                foreach (PmIntervalItem piclient in si.Intervals)
                {
                    PMIntervalItem pi = new PMIntervalItem();
                    Helper.CloneProperty(pi, piclient);
                    pi.Id = piclient.PmIntervalID;
                    pi.ScheduleId = pm.Id;
                    list.Add(pi);
                }
                pm.Intervals.AddRange(list);
            }
            FleetServiceClientHelper.CreateClient<PMClient>(sessionid).UpdatePMSchedule(SystemParams.CompanyID, pm, useriid);
        }

        public static void UpdatePmInterval(string sessionid, PmIntervalItem piclient, string useriid)
        {
            PMIntervalItem interval = new PMIntervalItem();
            Helper.CloneProperty(interval, piclient);
            interval.Id = piclient.PmIntervalID;
            FleetServiceClientHelper.CreateClient<PMClient>(sessionid).UpdatePMInterval(SystemParams.CompanyID, interval, useriid);
        }

        public static MaintenanceMachineInfo[] GetPmMachinesByScheduleId(string scheduleid)
        {
            const string SQL = @"select a.MACHINEID,a.STARTDATE,a.STARTHOURS,a.STARTOTOMETER,b.MACHINENAME,b.MACHINENAME2,b.VIN,b.MAKEID,b.MODELID,b.TYPEID,b.HIDE,
                            ISNULL(b.ENGINEHOURS,0) as ENGINEHOURS,ISNULL(b.ODOMETER,0) as ODOMETER,ISNULL(b.ODOMETERUOM,'Mile') AS ODOMETERUOM
                            from PM_MACHINES a,MACHINES b where a.MACHINEID=b.MACHINEID and a.PMSCHEDULEID={0}";

            FISqlConnection db = SystemParams.GetDbInstance();
            DataTable tb = db.GetDataTableBySQL(SQL, scheduleid);
            if (tb.Rows.Count == 0)
            {
                return new MaintenanceMachineInfo[0];
            }
            MachineManagement.RefreshBaseData();
            MachineMake[] makes = MachineManagement.GetMachineMakes();
            MachineModel[] models = MachineManagement.GetMachineModels();
            MachineType[] types = MachineManagement.GetMachineTypes();
            List<MaintenanceMachineInfo> ls = new List<MaintenanceMachineInfo>();
            foreach (DataRow dr in tb.Rows)
            {
                MaintenanceMachineInfo mi = ConvertToMaintenanceMachineInfo(dr, makes, models, types);
                ls.Add(mi);
            }
            return ls.ToArray();
        }


        private static object GetValueOrNull(DateTime v)
        {
            if (v == DateTime.MinValue || v == new DateTime(1900, 1, 1))
                return null;
            else
                return v;
        }

        public static void DeletePmMachine(string scheduleid, string machineid)
        {
            const string SQL = "delete from PM_MACHINES where PMSCHEDULEID={0} and MACHINEID={1}";
            FISqlConnection db = SystemParams.GetDbInstance();
            db.ExecSQL(SQL, scheduleid, machineid);
        }

        private static bool CheckPmScheduleNameRepeat(string scheduleid, string schedulename)
        {
            const string SQL = "select COUNT(1) from PM_SCHEDULES where PMSCHEDULEID!={0} and SCHEDULENAME={1}";
            FIDbAccess db = SystemParams.GetDbInstance();
            object obj = db.GetRC1BySQL(SQL, scheduleid, schedulename);
            if (Convert.ToInt32(obj) > 0)
            {
                return true;
            }
            return false;
        }
        public static bool CheckPmScheduleHasMachine(string scheduleid)
        {
            const string SQL_M = "select COUNT(1) from PM_MACHINES where PMSCHEDULEID={0}";
            FIDbAccess db = SystemParams.GetDbInstance();
            object objm = db.GetRC1BySQL(SQL_M, scheduleid);
            if (Convert.ToInt32(objm) > 0)
            {
                return true;
            }
            return false;
        }
        private static PmScheduleInfo ConvertPmScheduleInfo(DataRow dr)
        {
            PmScheduleInfo si = new PmScheduleInfo();
            si.PmScheduleID = FIDbAccess.GetFieldString(dr["PMSCHEDULEID"], string.Empty);
            si.PmScheduleName = FIDbAccess.GetFieldString(dr["SCHEDULENAME"], string.Empty);
            si.PmScheduleType = FIDbAccess.GetFieldString(dr["SCHEDULETYPE"], string.Empty);
            si.Notes = FIDbAccess.GetFieldString(dr["NOTES"], string.Empty);
            si.PmScheduleUom = FIDbAccess.GetFieldString(dr["SCHEDULEUOM"], string.Empty);
            return si;
        }

        #endregion

        #region Maintenance Log

        public static MaintenanceLogInfo[] GetMaintenanceLog(string sessionid, long assetid, string maintenancetype, int machinetype, string searchtxt, string useriid)
        {
            const string SQL = @"select a.MAINTENANCEID,a.MACHINEID,a.MAINTENANCEDATE,a.MAINTENANCEHOURS,a.NOTES,a.ALERTID,b.MACHINENAME,b.MACHINENAME2, b.VIN,b.MAKEID, b.MODELID,b.TYPEID,ISNULL(b.ENGINEHOURS,0) as ENGINEHOURS,
            t.ALERTTYPE,t.ALERTTITLE,t.ALERTTIME_UTC,ISNULL(a.ODOMETER,0) AS ODOMETER,ISNULL(a.ODOMETERUOM,'Hour') AS ODOMETERUOM, isnull(LOGTYPE,'Hours') AS LOGTYPE ,a.COST,a.INVOICENUMBER,a.COMPLETEDBY,a.COMPLETEDBYUSERNAME,
            (select top 1 ATTACHID from ATTACHES where SOURCE='MaintenanceLog' and REFID=a.MAINTENANCEID and isnull(DELETED,0)=0) ATTACHID
            from MAINTENANCELOG a left join ALERTS t on a.ALERTID=t.ALERTID,MACHINES b 
            where a.MACHINEID = b.MACHINEID and ISNULL(b.HIDE,0)<>1";
            const string ORDER_BY = "  ORDER BY a.ADDEDON DESC";

            string sql = SQL;
            //if (string.Compare("Distance", maintenancetype, true) == 0)
            //{
            //    sql = SQL + " and a.LOGTYPE='" + maintenancetype + "'";
            //}
            //else
            //{
            //    sql = SQL + " and a.LOGTYPE='" + maintenancetype + "'";
            //    sql = SQL + " and (a.LOGTYPE='" + maintenancetype + "' or a.LOGTYPE is null)";
            //}
            if (assetid > 0)
            {
                sql = sql + " and  a.MACHINEID=" + assetid;
            }
            if (machinetype >= 0)
            {
                sql = sql + " and  b.TYPEID=" + machinetype.ToString() + ORDER_BY;
            }
            else
            {
                sql = sql + ORDER_BY;
            }

            FISqlConnection db = SystemParams.GetDbInstance();
            DataTable dt = db.GetDataTableBySQL(sql, useriid);
            if (dt.Rows.Count == 0)
            {
                return new MaintenanceLogInfo[0];
            }

            long[] availableAssetsids = null;
            var user = Users.UserManagement.GetUserByIID(useriid);
            if (user.UserType < Users.UserTypes.Admin)
                availableAssetsids = FleetServiceClientHelper.CreateClient<AssetQueryClient>(sessionid).GetAvailableAssetsForUsers(SystemParams.CompanyID, useriid);

            MachineManagement.RefreshBaseData();
            MachineMake[] makes = MachineManagement.GetMachineMakes();
            MachineModel[] models = MachineManagement.GetMachineModels();
            MachineType[] types = MachineManagement.GetMachineTypes();

            List<MaintenanceLogInfo> list = new List<MaintenanceLogInfo>();
            foreach (DataRow dr in dt.Rows)
            {
                long mid = FIDbAccess.GetFieldInt64(dr["MACHINEID"], 0);
                if (user.UserType < Users.UserTypes.Admin && !availableAssetsids.Contains(mid))
                    continue;

                MaintenanceLogInfo ml = ConvertToMaintenanceLogInfo(dr, makes, models, types);
                ml.AlertTitle = FIDbAccess.GetFieldString(dr["ALERTTITLE"], string.Empty);
                ml.AlertType = FIDbAccess.GetFieldString(dr["ALERTTYPE"], string.Empty);
                ml.AlertTime = FIDbAccess.GetFieldDateTime(dr["ALERTTIME_UTC"], DateTime.MinValue);
                ml.HasAttachment = !string.IsNullOrWhiteSpace(FIDbAccess.GetFieldString(dr["ATTACHID"], string.Empty));

                if (!string.IsNullOrWhiteSpace(searchtxt))
                {
                    if (Helper.Contains(ml.MachineID.ToString(), searchtxt)
                        || Helper.Contains(ml.MachinePin, searchtxt)
                        || Helper.Contains(ml.MachineName, searchtxt)
                        || Helper.Contains(ml.MachineName2, searchtxt)
                        || Helper.Contains(ml.MachineMake, searchtxt)
                        || Helper.Contains(ml.MachineModel, searchtxt)
                        || Helper.Contains(ml.MachineType, searchtxt)
                        || Helper.Contains(ml.StrForMaintenanceDate, searchtxt)
                        || Helper.Contains(ml.Notes, searchtxt))
                    {
                        list.Add(ml);
                    }
                }
                else
                {
                    list.Add(ml);
                }
            }
            return list.ToArray();
        }

        public static MaintenanceLogInfo GetMaintenanceInfo(string maintenanceid)
        {
            const string SQL = @"select a.MAINTENANCEID,a.MACHINEID,a.MAINTENANCEDATE,a.MAINTENANCEHOURS,a.NOTES,a.ALERTID,b.MACHINENAME,b.MACHINENAME2,b.VIN,b.MAKEID,b.MODELID,b.TYPEID,ISNULL(b.ENGINEHOURS,0) as ENGINEHOURS,
            t.ALERTTYPE,t.ALERTTITLE,t.ALERTTIME_UTC,ISNULL(a.ODOMETER,0) AS ODOMETER,ISNULL(a.ODOMETERUOM,'Hour') AS ODOMETERUOM, isnull(LOGTYPE,'Hours') AS LOGTYPE 
            ,a.COST,a.INVOICENUMBER,a.COMPLETEDBY,a.COMPLETEDBYUSERNAME from MAINTENANCELOG a left join ALERTS t on a.ALERTID=t.ALERTID,MACHINES b 
            where a.MACHINEID = b.MACHINEID and ISNULL(b.HIDE,0)<>1 and a.MAINTENANCEID={0} ORDER BY a.ADDEDON DESC";

            FISqlConnection db = SystemParams.GetDbInstance();
            DataTable dt = db.GetDataTableBySQL(SQL, maintenanceid);
            if (dt.Rows.Count == 0)
            {
                return new MaintenanceLogInfo();
            }

            MachineManagement.RefreshBaseData();
            MachineMake[] makes = MachineManagement.GetMachineMakes();
            MachineModel[] models = MachineManagement.GetMachineModels();
            MachineType[] types = MachineManagement.GetMachineTypes();

            MaintenanceLogInfo ml = ConvertToMaintenanceLogInfo(dt.Rows[0], makes, models, types);
            return ml;
        }

        public static MaintenanceLogInfo[] GetMaintenanceLogByMachineID(long MachineID, string maintenanceType)
        {
            string SQL = @"select a.MAINTENANCEID,a.MACHINEID,a.MAINTENANCEDATE,a.MAINTENANCEHOURS,a.NOTES,a.ALERTID,b.MACHINENAME,b.MACHINENAME2,b.VIN,b.MAKEID,b.MODELID,b.TYPEID,ISNULL(b.ENGINEHOURS,0) as ENGINEHOURS, ISNULL(a.ODOMETER,0) AS ODOMETER,ISNULL(a.ODOMETERUOM,'Mile') AS ODOMETERUOM, isnull(LOGTYPE,'Hours') AS LOGTYPE 
                               ,a.COST,a.INVOICENUMBER,a.COMPLETEDBY,a.COMPLETEDBYUSERNAME from MAINTENANCELOG a, MACHINES b where a.MACHINEID = b.MACHINEID and  a.MACHINEID={0}";
            if (maintenanceType != null)
                SQL += " and LOGTYPE={1} ";
            SQL += " ORDER BY a.ADDEDON DESC";
            FISqlConnection db = SystemParams.GetDbInstance();
            DataTable dt = db.GetDataTableBySQL(SQL, MachineID, maintenanceType);
            if (dt.Rows.Count == 0)
            {
                return new MaintenanceLogInfo[0];
            }

            MachineManagement.RefreshBaseData();
            MachineMake[] makes = MachineManagement.GetMachineMakes();
            MachineModel[] models = MachineManagement.GetMachineModels();
            MachineType[] types = MachineManagement.GetMachineTypes();

            List<MaintenanceLogInfo> list = new List<MaintenanceLogInfo>();
            foreach (DataRow dr in dt.Rows)
            {
                MaintenanceLogInfo ml = ConvertToMaintenanceLogInfo(dr, makes, models, types);
                list.Add(ml);
            }
            return list.ToArray();
        }

        public static MaintenanceLogInfo GetMaintenanceLogByMaintenanceID(string MaintenanceID)
        {
            const string SQL = @"select a.MAINTENANCEID,a.MACHINEID,a.MAINTENANCEDATE,a.MAINTENANCEHOURS,a.NOTES,a.ALERTID,b.MACHINENAME,b.MACHINENAME2,b.VIN,b.MAKEID,b.MODELID,b.TYPEID
               ,ISNULL(b.ENGINEHOURS,0) as ENGINEHOURS,ISNULL(a.ODOMETER,0) AS ODOMETER,ISNULL(a.ODOMETERUOM,'Mile') AS ODOMETERUOM, isnull(LOGTYPE,'Hours') AS LOGTYPE 
              ,a.COST,a.INVOICENUMBER,a.COMPLETEDBY,a.COMPLETEDBYUSERNAME from MAINTENANCELOG a , MACHINES b where a.MACHINEID = b.MACHINEID and a.MAINTENANCEID={0}";

            FISqlConnection db = SystemParams.GetDbInstance();
            DataTable dt = db.GetDataTableBySQL(SQL, MaintenanceID);
            if (dt.Rows.Count == 0)
            {
                return new MaintenanceLogInfo();
            }
            MachineManagement.RefreshBaseData();
            MachineMake[] makes = MachineManagement.GetMachineMakes();
            MachineModel[] models = MachineManagement.GetMachineModels();
            MachineType[] types = MachineManagement.GetMachineTypes();

            MaintenanceLogInfo ml = ConvertToMaintenanceLogInfo(dt.Rows[0], makes, models, types);
            return ml;
        }

        public static void UpdateMaintenanceLog(MaintenanceLogInfo ml, string addedby)
        {
            const string SQL = @"if exists(select 1 from MAINTENANCELOG where MAINTENANCEID={0}) update MAINTENANCELOG set MACHINEID ={1},MAINTENANCEDATE ={2},
                MAINTENANCEHOURS={3},NOTES={4},LASTUPDATEDBY={5},LASTUPDATEDON=GETUTCDATE(),ALERTID={6},ODOMETER={7},ODOMETERUOM={8},LOGTYPE={9},COST={10},INVOICENUMBER={11},COMPLETEDBYUSERNAME={12},COMPLETED={13},COMPLETEDDATE_UTC= (case {13} when 1 then GETUTCDATE() else null end) where MAINTENANCEID={0} else insert into MAINTENANCELOG(MAINTENANCEID,
                MACHINEID,MAINTENANCEDATE,MAINTENANCEHOURS,NOTES,ADDEDBY,ADDEDON,LASTUPDATEDBY,LASTUPDATEDON,ALERTID,ODOMETER,ODOMETERUOM,LOGTYPE,COST,INVOICENUMBER,COMPLETEDBYUSERNAME,COMPLETED,COMPLETEDDATE_UTC) values({0},{1},{2},{3},{4},{5},GETUTCDATE(),{5},GETUTCDATE(),{6},{7},{8},{9},{10},{11},{12},{13},(case {13} when 1 then GETUTCDATE() else null end))";
            FISqlConnection db = SystemParams.GetDbInstance();
            db.ExecSQL(SQL, ml.MaintenanceID, ml.MachineID, ml.MaintenanceDate, ml.MaintenanceHours, ml.Notes, addedby, ml.AlertID, ml.ODOMeter, ml.ODOMemterUOM, ml.LogType, ml.Cost, ml.InvoiceNumber, ml.CompletedByName, ml.Completed ? 1 : 0);
        }

        public static void DeleteMaintenanceLog(string maintencelogid)
        {
            const string SQL = "delete from MAINTENANCELOG where MAINTENANCEID={0}";
            FISqlConnection db = SystemParams.GetDbInstance();
            db.ExecSQL(SQL, maintencelogid);
        }

        public static bool HasMaintenanceLog(long machineid)
        {
            const string SQL = "SELECT count([MAINTENANCEDATE]) FROM [MAINTENANCELOG] where MACHINEID={0}";
            var db = SystemParams.GetDbInstance();
            return (int?)db.GetRC1BySQL(SQL, machineid) > 0;
        }

        public static PMAlert[] GetUnCompletedPMAlerts(long machineid, string maintencelogid)
        {
            List<PMAlert> alerts = new List<PMAlert>();
            const string SQL = "select LOGID,pm.ALERTID,pm.ALERTTIME_UTC,ALERTTITLE from PM_ALERTS pm left join ALERTS a on pm.ALERTID=a.ALERTID where pm.MACHINEID={0} and ((ISNULL(a.COMPLETED,0)<>1 and ISNULL(a.ACKNOWLEDGED,0)<>1) or exists(select 1 from MAINTENANCELOG ml where ml.ALERTID=a.ALERTID and MAINTENANCEID={1} ))";
            var db = SystemParams.GetDbInstance();
            DataTable dt = db.GetDataTableBySQL(SQL, machineid, maintencelogid);
            foreach (DataRow dr in dt.Rows)
            {
                PMAlert alert = new PMAlert();
                alert.LogID = FIDbAccess.GetFieldString(dr["LOGID"], string.Empty);
                alert.AlertID = FIDbAccess.GetFieldString(dr["ALERTID"], string.Empty);
                alert.AlertTitle = FIDbAccess.GetFieldString(dr["ALERTTITLE"], string.Empty);
                DateTime at = FIDbAccess.GetFieldDateTime(dr["ALERTTIME_UTC"], DateTime.MinValue);
                if (at != DateTime.MinValue)
                    alert.AlertTime = at.ToString("yyyy-MM-dd HH:mm:ss");
                alerts.Add(alert);
            }
            return alerts.ToArray();
        }

        public static void SetPMAlertCompleted(long alertID, bool completed, string completedby)
        {
            const string SQL = "update ALERTS set COMPLETED={0},COMPLETEDBY={2},COMPLETEDDATE_UTC=(case {0} when 1 then GETUTCDATE() else null end) where ALERTID={1}";
            var db = SystemParams.GetDbInstance();
            db.ExecSQL(SQL, completed ? 1 : 0, alertID, completedby);
        }

        private static MaintenanceLogInfo ConvertToMaintenanceLogInfo(DataRow dr, MachineMake[] makes, MachineModel[] models, MachineType[] types)
        {
            MaintenanceLogInfo ml = new MaintenanceLogInfo();
            ml.MaintenanceID = FIDbAccess.GetFieldString(dr["MAINTENANCEID"], string.Empty);
            ml.MachineID = FIDbAccess.GetFieldInt(dr["MACHINEID"], 0);
            ml.MaintenanceDate = FIDbAccess.GetFieldDateTime(dr["MAINTENANCEDATE"], DateTime.MinValue);
            ml.MaintenanceHours = FIDbAccess.GetFieldDouble(dr["MAINTENANCEHOURS"], 0);
            ml.Notes = FIDbAccess.GetFieldString(dr["NOTES"], string.Empty);
            ml.AlertID = FIDbAccess.GetFieldInt(dr["ALERTID"], -1);
            ml.MachinePin = FIDbAccess.GetFieldString(dr["VIN"], string.Empty);
            ml.MachineName = FIDbAccess.GetFieldString(dr["MACHINENAME"], string.Empty);
            ml.MachineName2 = FIDbAccess.GetFieldString(dr["MACHINENAME2"], string.Empty);
            ml.EngineHours = FIDbAccess.GetFieldDouble(dr["ENGINEHOURS"], 0);
            ml.ODOMeter = FIDbAccess.GetFieldDouble(dr["ODOMETER"], 0);
            ml.ODOMemterUOM = FIDbAccess.GetFieldString(dr["ODOMETERUOM"], "Mile");
            ml.LogType = FIDbAccess.GetFieldString(dr["LOGTYPE"], "Hours");
            ml.Cost = FIDbAccess.GetFieldDouble(dr["COST"], 0);
            ml.InvoiceNumber = FIDbAccess.GetFieldString(dr["INVOICENUMBER"], "");
            ml.CompletedByName = FIDbAccess.GetFieldString(dr["COMPLETEDBYUSERNAME"], "");

            int makeid = FIDbAccess.GetFieldInt(dr["MAKEID"], 0);
            MachineMake make = MachineManagement.GetMachineMake(makes, makeid);
            ml.MachineMake = make == null ? string.Empty : make.Name;

            int modelid = FIDbAccess.GetFieldInt(dr["MODELID"], 0);
            MachineModel model = MachineManagement.GetMachineModel(models, modelid);
            ml.MachineModel = model == null ? string.Empty : model.Name;

            int typeid = FIDbAccess.GetFieldInt(dr["TYPEID"], 0);
            MachineType mtype = MachineManagement.GetMachineType(types, typeid);
            ml.MachineType = mtype == null ? string.Empty : mtype.Name;

            return ml;
        }

        public static WorkOrderInfo[] GetMaintenanceWorkOrders(string sessionid, string custid, string[] assignedusers, string[] asseitgroups, string filter, string useriid)
        {
            const string SQL = @"select m.MAINTENANCEID,m.COMPLETEDBY,(select USERNAME from USERS where USERS.USERIID=m.COMPLETEDBY) as ASSIGNEDTONAME,m.NOTES,m.MAINTENANCEDATE
            ,b.MACHINEID,b.VIN,b.MACHINENAME,b.MACHINENAME2 from MAINTENANCELOG m left join MACHINES b on b.MACHINEID=m.MACHINEID
			where m.ALERTID not in (select ALERTID from WORKORDER_ALERTS) and m.MACHINEID = b.MACHINEID and ISNULL(b.HIDE,0)<>1  ";
            const string SQL_FILTER = " and (m.NOTES like {0} or b.MACHINEID like {0} or b.VIN like {0}  or b.MACHINENAME like {0} or b.MACHINENAME2 like {0}) ";
            const string SQL_ORDERBY = " order by m.MAINTENANCEID";

            var user = FleetServiceClientHelper.CreateClient<UserQueryClient>(custid, sessionid).GetUserByIID(useriid);
            if (user == null || (!user.Active))
            {
                return new WorkOrderInfo[0];
            }
            if (user == null || (!user.Active))
            {
                return new WorkOrderInfo[0];
            }
            if (string.Compare(user.CompanyID, SystemParams.CompanyID, true) != 0 && (!user.IsForesightUser))
            {
                return new WorkOrderInfo[0];
            }

            string sql = SQL;
            if ((!user.IsForesightUser) && (user.ContactType == Foresight.Fleet.Services.User.ContactTypes.Technician))
            {
                sql += " and m.COMPLETEDBY in ('" + useriid + "') ";
            }
            else if (assignedusers != null && assignedusers.Length > 0)
            {
                string uids = JoinSQLString(assignedusers);
                sql += " and m.COMPLETEDBY in (" + uids + ") ";
            }

            FISqlConnection db = SystemParams.GetDbInstance();
            long[] assets = null;
            if (asseitgroups != null && asseitgroups.Length > 0)
            {
                assets = MachineManagement.GetGroupMachines(asseitgroups, db);
            }
            DataTable dt = null;
            if (string.IsNullOrWhiteSpace(filter))
                dt = db.GetDataTableBySQL(sql + SQL_ORDERBY);
            else
                dt = db.GetDataTableBySQL(sql + SQL_FILTER + SQL_ORDERBY, "%" + filter + "%");

            if (dt.Rows.Count == 0)
                return new WorkOrderInfo[0];

            List<WorkOrderInfo> list = new List<WorkOrderInfo>();
            foreach (DataRow dr in dt.Rows)
            {
                WorkOrderInfo wo = new WorkOrderInfo();

                long assetid = FIDbAccess.GetFieldInt64(dr["MACHINEID"], 0);
                if (assets != null && assets.Length > 0)
                {
                    if (!assets.Contains(assetid))
                    {
                        continue;
                    }
                }
                wo.AssetID = assetid;
                wo.AssignedTo = FIDbAccess.GetFieldString(dr["COMPLETEDBY"], string.Empty);
                wo.MaintenanceID = FIDbAccess.GetFieldString(dr["MAINTENANCEID"], string.Empty);
                wo.Description = FIDbAccess.GetFieldString(dr["NOTES"], string.Empty);
                wo.CompleteDate = FIDbAccess.GetFieldDateTime(dr["MAINTENANCEDATE"], DateTime.MinValue);
                wo.VIN = FIDbAccess.GetFieldString(dr["VIN"], string.Empty);
                wo.AssetName = FIDbAccess.GetFieldString(dr["MACHINENAME"], string.Empty);
                wo.AssignedToName = FIDbAccess.GetFieldString(dr["ASSIGNEDTONAME"], wo.AssignedTo);

                list.Add(wo);
            }
            return list.ToArray();
        }

        public static string JoinSQLString(IEnumerable<string> items)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in items)
            {
                if (sb.Length == 0)
                {
                    sb.Append("'" + s + "'");
                }
                else
                {
                    sb.Append(",'" + s + "'");
                }
            }
            return sb.ToString();
        }

        #endregion

        #region Machines


        public static MaintenanceMachineInfo[] GetMaintenanceMachines1(string sessionid, int machinetype, string searchtxt, string useriid, string companyid = null)
        {
            if (string.IsNullOrEmpty(companyid))
                companyid = SystemParams.CompanyID;
            //普通用户机器权限过滤
            long[] availableAssetsids = null;
            var user = Users.UserManagement.GetUserByIID(useriid);
            var client = FleetServiceClientHelper.CreateClient<AssetQueryClient>(companyid, sessionid);
            if (user.UserType < Users.UserTypes.Admin)
                availableAssetsids = client.GetAvailableAssetsForUsers(companyid, useriid);
            AssetBasicInfo[] assets = client.GetAssetBasicInfo(companyid, searchtxt, availableAssetsids);
            if (assets != null && machinetype != -1)
                assets = assets.Where(m => m.TypeID == machinetype).ToArray();
            long[] mids = null;
            if (assets != null)
                mids = assets.AsEnumerable().Select(m => m.ID).ToArray();
            //var ehs = SystemParams.AssetClient.GetAssetsCurrentPrimaryEngineHours(companyid, mids);
            var odos = client.GetAssetsCurrentPrimaryOdometer(companyid, mids);
            List<MaintenanceMachineInfo> list = new List<MaintenanceMachineInfo>();
            foreach (var a in assets)
            {
                if (a.Hide) continue;
                MaintenanceMachineInfo mi = new MaintenanceMachineInfo();
                mi.MachineID = a.ID;
                mi.VIN = a.VIN;
                mi.MachineName = a.Name;
                mi.MachineName2 = a.Name2;
                mi.Make = a.MakeName;
                mi.Model = a.ModelName;
                mi.TypeID = a.TypeID;
                mi.MachineType = a.TypeName;
                mi.Hide = a.Hide;
                mi.EngineHours = a.EngineHours;
                if (odos != null && odos.Length > 0)
                {
                    var odo = odos.FirstOrDefault((o) => o.AssetID == mi.MachineID);
                    if (odo != null)
                        mi.Odometer = odo.Corrected;
                }

                list.Add(mi);
            }

            return list.ToArray();
        }

        public static MaintenanceMachineInfo[] GetMaintenanceMachines(string sessionid, int machinetype, string searchtxt, string useriid, string companyid = null)
        {
            const string SQL = @"select m.MACHINEID,m.MACHINENAME2,m.MACHINENAME,m.MAKEID,m.MODELID,m.TYPEID,m.VIN,ISNULL(m.ENGINEHOURS,0) as ENGINEHOURS,
            ISNULL(m.ODOMETER,0) as ODOMETER,ISNULL(m.ODOMETERUOM,'Mile') AS ODOMETERUOM,m.HIDE from MACHINES m
            where 1=1";
            const string ORDER_BY = " order by MACHINEID";

            string sql = string.Empty;
            if (machinetype >= 0)
            {
                sql = SQL + " and TYPEID=" + machinetype.ToString() + ORDER_BY;
            }
            else
            {
                sql = SQL + ORDER_BY;
            }

            FIDbAccess db = null;
            if (string.IsNullOrEmpty(companyid))
            {
                companyid = SystemParams.CompanyID;
                db = SystemParams.GetDbInstance();
            }
            else
            {
                string connetionstring = SystemParams.GetDbStringByCompany(companyid);
                db = new FISqlConnection(connetionstring);
            }

            DataTable tb = db.GetDataTableBySQL(sql);
            if (tb.Rows.Count == 0)
            {
                return new MaintenanceMachineInfo[0];
            }

            long[] availableAssetsids = null;
            var user = Users.UserManagement.GetUserByIID(useriid);
            if (user.UserType < Users.UserTypes.Admin)
                availableAssetsids = FleetServiceClientHelper.CreateClient<AssetQueryClient>(companyid, sessionid).GetAvailableAssetsForUsers(companyid, useriid);

            MachineManagement.RefreshBaseData();
            MachineMake[] makes = MachineManagement.GetMachineMakes();
            MachineModel[] models = MachineManagement.GetMachineModels();
            MachineType[] types = MachineManagement.GetMachineTypes();
            List<MaintenanceMachineInfo> ls = new List<MaintenanceMachineInfo>();
            foreach (DataRow dr in tb.Rows)
            {
                long mid = Convert.ToInt64(dr["MACHINEID"]);
                if (user.UserType < Users.UserTypes.Admin && !availableAssetsids.Contains(mid))
                    continue;
                MaintenanceMachineInfo mi = ConvertToMaintenanceMachineInfo(dr, makes, models, types);
                mi.Hide = FIDbAccess.GetFieldInt(dr["HIDE"], 0) == 1;
                if (mi.Hide) continue;
                if (!string.IsNullOrWhiteSpace(searchtxt))
                {
                    if (Helper.Contains(mi.VIN, searchtxt)
                        || Helper.Contains(mi.MachineID.ToString(), searchtxt)
                        || Helper.Contains(mi.MachineName, searchtxt)
                        || Helper.Contains(mi.MachineName2, searchtxt)
                        || Helper.Contains(mi.Make, searchtxt)
                        || Helper.Contains(mi.MachineType, searchtxt)
                        || Helper.Contains(mi.Model, searchtxt))
                    {
                        ls.Add(mi);
                    }
                }
                else
                {
                    ls.Add(mi);
                }
            }
            return ls.ToArray();
        }

        public static MaintenanceMachineInfo GetmachineByMachineID(long machineid)
        {
            string SQL = @"select MACHINEID,MACHINENAME,MACHINENAME2,MAKEID,MODELID,TYPEID,VIN,ISNULL(ENGINEHOURS,0) as ENGINEHOURS,
                ISNULL(ODOMETER,0) as ODOMETER,ISNULL(ODOMETERUOM,'Mile') AS ODOMETERUOM from MACHINES where MACHINEID={0}";
            FISqlConnection db = SystemParams.GetDbInstance();
            DataTable tb = db.GetDataTableBySQL(SQL, machineid);
            MaintenanceMachineInfo mi = new MaintenanceMachineInfo();
            if (tb.Rows.Count == 0)
            {
                mi.MachineID = -1;
                return mi;
            }
            MachineManagement.RefreshBaseData();
            MachineMake[] makes = MachineManagement.GetMachineMakes();
            MachineModel[] models = MachineManagement.GetMachineModels();
            MachineType[] types = MachineManagement.GetMachineTypes();
            foreach (DataRow dr in tb.Rows)
            {
                mi = ConvertToMaintenanceMachineInfo(dr, makes, models, types);
            }
            return mi;
        }

        public static MaintenanceMachineInfo ConvertToMaintenanceMachineInfo(DataRow dr, MachineMake[] makes, MachineModel[] models, MachineType[] types)
        {
            MaintenanceMachineInfo mi = new MaintenanceMachineInfo();
            mi.MachineID = Convert.ToInt64(dr["MACHINEID"]);
            mi.MachineName = FIDbAccess.GetFieldString(dr["MACHINENAME"], string.Empty);
            mi.MachineName2 = FIDbAccess.GetFieldString(dr["MACHINENAME2"], string.Empty);
            mi.VIN = FIDbAccess.GetFieldString(dr["VIN"], string.Empty);
            mi.EngineHours = FIDbAccess.GetFieldDouble(dr["ENGINEHOURS"], 0);
            mi.Odometer = FIDbAccess.GetFieldDouble(dr["ODOMETER"], 0);

            int makeid = FIDbAccess.GetFieldInt(dr["MAKEID"], 0);
            MachineMake make = MachineManagement.GetMachineMake(makes, makeid);
            mi.Make = make == null ? string.Empty : make.Name;

            int modelid = FIDbAccess.GetFieldInt(dr["MODELID"], 0);
            MachineModel model = MachineManagement.GetMachineModel(models, modelid);
            mi.Model = model == null ? string.Empty : model.Name;

            int typeid = FIDbAccess.GetFieldInt(dr["TYPEID"], 0);
            MachineType mtype = MachineManagement.GetMachineType(types, typeid);
            mi.TypeID = mtype == null ? 0 : mtype.ID;
            mi.MachineType = mtype == null ? string.Empty : mtype.Name;


            if (dr.Table.Columns.Contains("STARTDATE"))
            {
                mi.StartDate = FIDbAccess.GetFieldDateTime(dr["STARTDATE"], DateTime.MinValue);
            }
            if (dr.Table.Columns.Contains("STARTHOURS"))
            {
                mi.StartHours = FIDbAccess.GetFieldDouble(dr["STARTHOURS"], 0);
            }
            if (dr.Table.Columns.Contains("STARTOTOMETER"))
            {
                mi.StartOdometer = FIDbAccess.GetFieldDouble(dr["STARTOTOMETER"], 0);
            }

            return mi;
        }

        #endregion

        public static string[] GetPMDescriptionByAssetID(string companyid, long assetid)
        {
            const string SQL_1 = @"select *  from usvMaintenanceAlertsMapLayer ml with (nolock) right join 
            (select cast(MachineID as nvarchar) + cast(max(MaintenanceDate) as nvarchar)  as MaintenanceID from usvMaintenanceAlertsMapLayer with (nolock)  where PMStatus = 'Complete'
            group by MachineID) a on ml.MaintenanceID = a.MaintenanceID where PMStatus = 'Complete' and MachineID={0}";
            const string SQL_2 = "select * from usvMaintenanceAlertsMapLayer with (nolock) where PMStatus = 'Overdue' and MachineID={0}";
            const string SQL_3 = "select * from usvMaintenanceAlertsMapLayer with (nolock) where PMStatus = 'Upcoming' and MachineID={0}";


            string connetionstring = SystemParams.DataDbConnectionString;
            if (SystemParams.IsDealer)
                connetionstring = SystemParams.GetDbStringByCompany(companyid);

            FISqlConnection db = new FISqlConnection(connetionstring);
            DataTable dt = db.GetDataTableBySQL(SQL_1, assetid);
            if (dt == null || dt.Rows.Count == 0)
                dt = db.GetDataTableBySQL(SQL_2, assetid);
            if (dt == null || dt.Rows.Count == 0)
                dt = db.GetDataTableBySQL(SQL_3, assetid);

            if (dt == null || dt.Rows.Count == 0)
                return new string[0];

            List<string> list = new List<string>();
            foreach (DataRow dr in dt.Rows)
            {
                string desc = FIDbAccess.GetFieldString(dr["DESCRIPTION"], string.Empty);
                list.Add(desc);
            }

            return list.ToArray();
        }

    }
}
