using Foresight.Data;
using Foresight.Fleet.Services;
using Foresight.Fleet.Services.Asset;
using Foresight.Fleet.Services.Customer;
using Foresight.Fleet.Services.Device;
using Foresight.Fleet.Services.JobSite;
using Foresight.Fleet.Services.User;
using Foresight.ServiceModel;
using Foresight.Standard.Units;
using IronIntel.Contractor.ExportExcel;
using IronIntel.Contractor.Machines;
using IronIntel.Contractor.MapView;
using IronIntel.Contractor.Users;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using FFSDevice = Foresight.Fleet.Services.Device;

namespace IronIntel.Contractor.Site
{
    public class MachineDeviceBasePage : ContractorBasePage
    {
        protected void ProcessRequest(string method)
        {
            object result = null;
            try
            {
                string methodName = Request.Params["MethodName"];
                if (methodName != null)
                {
                    switch (methodName.ToUpper())
                    {
                        //case "GETMACHINES":
                        //    result = GetMachines();
                        //    break;
                        case "GETGPSDEVICES":
                            result = GetGPSDevices();
                            break;
                        case "SAVEGPSDEVICE":
                            result = SaveGPSDevice();
                            break;
                        case "GETGPSSOURCES":
                            result = GetGPSSources();
                            break;
                        case "GETNIMBELINGTYPES":
                            result = GetNimbelingTypes();
                            break;
                        case "CHANGEGPSCONTRACTOR":
                            result = ChangeGPSContractor();
                            break;
                        case "GETDEVICECOMMENTS":
                            result = GetDeviceComments();
                            break;
                        case "ADDDEVICECOMMENT":
                            result = AddDeviceComment();
                            break;
                        case "GETDEVICEINSTALLATIONNOTES":
                            result = GetDeviceInstallationNotes();
                            break;
                        case "ADDINSTALLATIONNOTES":
                            result = AddInstallationNotes();
                            break;
                        case "GETMACHINETYPES":
                            result = GetMachineTypes();
                            break;
                        case "GETCONTRACTORS":
                            result = GetContractors();
                            break;
                        case "GETCONTRACTORSBYUSER":
                            result = GetContractorsByUser();
                            break;
                        case "SAVEMACHINEGROUP":
                            result = SaveMachineGroup();
                            break;
                        case "SAVEASSETGROUP":
                            result = SaveAssetGroup();
                            break;
                        case "DELETEMACHINEGROUP":
                            result = DeleteMachineGroup();
                            break;
                        case "DELETEASSETGROUP":
                            result = DeleteAssetGroup();
                            break;
                        case "GETMACHINEGROUPS":
                            result = GetMachineGroups();
                            break;
                        case "GETASSETGROUPS":
                            result = GetAssetGroups();
                            break;
                        case "GETASSETLIST":
                            result = GetAssetList();
                            break;
                        case "GETUSERASSIGNEDASSETS":
                            result = GetUserAssignedAssets();
                            break;
                        case "GETJOBSITEASSETLIST":
                            result = GetJobsiteAssetList();
                            break;
                        case "GETASSETSBYGROUP":
                            result = GetAssetsByGroup();
                            break;
                        case "GETMACHINEGROUPBYUSER":
                            result = GetMachineGroupByUser();
                            break;
                        case "SAVEMACHINEMAKE":
                            result = SaveMachineMake();
                            break;
                        case "SAVEMACHINEMODEL":
                            result = SaveMachineModel();
                            break;
                        case "DELETEMACHINEMAKE":
                            result = DeleteMachineMake();
                            break;
                        case "DELETEMACHINEMODEL":
                            result = DeleteMachineModel();
                            break;
                        case "GETASSETMAKES":
                            result = GetAssetMakes();
                            break;
                        case "GETASSETMODELS":
                            result = GetAssetModels();
                            break;
                        case "GETACTIVEJOBSITES":
                            result = GetActiveJobsites();
                            break;
                        case "GETCONTACTS":
                            result = GetContacts();
                            break;
                        case "CHANGEMACHINEICONFILE":
                            result = ChangeMachineIconFile();
                            break;
                        case "SEARCHRENTALS":
                            result = SearchRentals();
                            break;
                        case "SEARCHRENTALSBYASSET":
                            result = SearchRentalsByAsset();
                            break;
                        case "GETRENTALINFO":
                            result = GetRentalInfo();
                            break;
                        case "SAVERENTAL":
                            result = SaveRental();
                            break;
                        case "DELETERENTAL":
                            result = DeleteRental();
                            break;
                        case "SEARCHRENTALCHANGEHISTORY":
                            result = SearchRentalChangeHistory();
                            break;
                        case "GETMACHINEDETAILURL":
                            result = GetMachineDetailURL();
                            break;
                        case "GETSELECTMACHINESBYRENTAL":
                            result = GetSelectMachinesByRental();
                            break;
                        case "GETATTACHMENTS":
                            result = GetAttachments();
                            break;
                        case "UPLOADASSETDOCUMENT":
                            result = UploadAssetDocument();
                            break;
                        case "UPDATEASSETDOCUMENT":
                            result = UpdateAssetDocument();
                            break;
                        case "DELETEATTACHMENT":
                            result = DeleteAttachment();
                            break;
                        case "GETASSETCURRENTODOMETER":
                            result = GetAssetCurrentOdometer();
                            break;
                        case "SAVEADJUSTODOMETER":
                            result = SaveAdjustOdometer();
                            break;
                        case "GETASSETCURRENTENGINEHOURS":
                            result = GetAssetCurrentEngineHours();
                            break;
                        case "SAVEADJUSTENGINEHOURS":
                            result = SaveAdjustEngineHours();
                            break;
                        case "GETASSETCURRENTLOCATION":
                            result = GetAssetCurrentLocation();
                            break;
                        case "GETASSETCURRENTIDLEHOURS":
                            result = GetAssetCurrentIdleHours();
                            break;
                        case "GETASSETCURRENTFUELUSED":
                            result = GetAssetCurrentFuelUsed();
                            break;
                        case "CHANGEPRIMARYDATASOURCE":
                            result = ChangePrimaryDataSource();
                            break;
                        case "GETCALAMPODOMETERHISTORY":
                            result = GetCalampOdometerHistory();
                            break;
                        case "GETCALAMPODOMETERHISTORYPREVIEW":
                            result = GetCalampOdometerHistoryPreview();
                            break;
                        case "GETPEDIGREEODOMETERHISTORY":
                            result = GetPedigreeOdometerHistory();
                            break;
                        case "GETPEDIGREEODOMETERHISTORYPREVIEW":
                            result = GetPedigreeOdometerHistoryPreview();
                            break;
                        case "GETSMARTWITNESSODOMETERHISTORY":
                            result = GetSmartWitnessOdometerHistory();
                            break;
                        case "GETSMARTWITNESSODOMETERHISTORYPREVIEW":
                            result = GetSmartWitnessOdometerHistoryPreview();
                            break;
                        case "GETTIMEZONES":
                            result = GetTimeZones();
                            break;
                        case "GETCALAMPENGINEHOURSHISTORY":
                            result = GetCalampEngineHoursHistory();
                            break;
                        case "GETCALAMPENGINEHOURSHISTORYPREVIEW":
                            result = GetCalampEngineHoursHistoryPreview();
                            break;
                        case "GETPEDIGREEENGINEHOURSHISTORY":
                            result = GetPedigreeEngineHoursHistory();
                            break;
                        case "GETPEDIGREEENGINEHOURSHISTORYPREVIEW":
                            result = GetPedigreeEngineHoursHistoryPreview();
                            break;
                        case "GETOEMDD2ENGINEHOURSHISTORY":
                            result = GetOEMDD2EngineHoursHistory();
                            break;
                        case "GETOEMDD2ENGINEHOURSHISTORYPREVIEW":
                            result = GetOEMDD2EngineHoursHistoryPreview();
                            break;
                        case "CHECKODOMETERMINNIMUMTIME":
                            result = CheckOdometerMinnimumTime();
                            break;
                        case "CHECKENGINEHOURMINIMUMTIME":
                            result = CheckEngineHourMinimumTime();
                            break;
                        case "GETUSERPERMISSION":
                            result = GetUserPermission();
                            break;
                        case "ADDMANUALLYINPUTODOMETER":
                            result = AddManuallyInputOdometer();
                            break;
                        case "ADDMANUALLYINPUTENGINEHOURS":
                            result = AddManuallyInputEngineHours();
                            break;
                        case "GETASSETSUMMARYINFO":
                            result = GetAssetSummaryInfo();
                            break;
                        case "GETASSETEXTINFO":
                            result = GetAssetExtInfo();
                            break;
                        case "GETASSETCURRENTFUELREMAINING":
                            result = GetAssetCurrentFuelRemaining();
                            break;
                        case "GETIMPORTMACHINECOLUMNS":
                            result = GetImportMachineColumns();
                            break;
                        case "IMPORTMACHINES":
                            result = ImportMachines();
                            break;
                        case "GETIMPORTDEVICESCOLUMNS":
                            result = GetImportDevicesColumns();
                            break;
                        case "IMPORTDEVICES":
                            result = ImportDevices();
                            break;
                        case "CALAMPDEVICEHASDATA":
                            result = CalampDeviceHasData();
                            break;
                        case "GETCALAMPDEVICESNINFO":
                            result = GetCalampDeviceSNInfo();
                            break;
                        case "GETDEVICEPAIRINGLOGSBYDEVICE":
                            result = GetDevicePairingLogsByDevice();
                            break;
                        case "GETDEVICEPAIRINGLOGSBYASSET":
                            result = GetDevicePairingLogsByAsset();
                            break;
                        case "GETPAIRINGATTACHMENTS":
                            result = GetPairingAttachments();
                            break;
                        case "GETPAIRINGSIGNATURE":
                            result = GetPairingSignature();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "MachineDeviceBasePage", ex.Message, ex.ToString());
                throw ex;
            }
            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }

        private object GetAssetSummaryInfo()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                    var assetid = HttpUtility.HtmlDecode(clientdata[1]);

                    if (string.IsNullOrEmpty(companyid))
                        companyid = SystemParams.CompanyID;

                    if (string.IsNullOrWhiteSpace(companyid) && SystemParams.IsDealer)
                        return new AssetSummaryItem();

                    AssetSummaryInfo summary = CreateClient<AssetQueryClient>(companyid).GetAssetSummaryInfo(companyid, Convert.ToInt64(assetid));
                    AssetSummaryItem item = new AssetSummaryItem();
                    Helper.CloneProperty(item, summary);

                    if (item.Location == null)
                        item.Location = new AssetAddressInfo();
                    item.Location.Speed = Math.Round(item.Location.Speed);
                    item.Location.PostedSpeedLimit = Math.Round(item.Location.PostedSpeedLimit);
                    item.TimeZoneAbbreviation = SystemParams.TimeZoneAbbreviation;
                    return item;
                }
                else
                    return new AssetSummaryItem();
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "MachineDeviceBasePage.GetAssetSummaryInfo", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetAssetExtInfo()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                    var assetid = HttpUtility.HtmlDecode(clientdata[1]);
                    var viewalertstypes = HttpUtility.HtmlDecode(clientdata[2]);

                    if (string.IsNullOrEmpty(companyid))
                        companyid = SystemParams.CompanyID;

                    if (string.IsNullOrWhiteSpace(companyid) && SystemParams.IsDealer)
                        return new AssetSummaryItem();
                    AssetExtItem item = new AssetExtItem();
                    AssetExtInfo ext = CreateClient<AssetQueryClient>(companyid).GetAssetExtInfo(companyid, Convert.ToInt64(assetid), viewalertstypes);
                    Helper.CloneProperty(item, ext);
                    if (item.InspectReportItem != null)
                    {
                        var temp = new SingleAssetViewBasePage.InspectReportInfo();
                        Helper.CloneProperty(temp, item.InspectReportItem);
                        item.InspectReportItem = temp;
                        Helper.CloneProperty(item.InspectReportItem, item.InspectReportItem);
                        item.InspectReportItem.CommitTime = item.InspectReportItem.LocalCommitTime == null ? DateTime.MinValue : item.InspectReportItem.LocalCommitTime.Value;
                        item.InspectReportItem.LastUpdatedTime = item.InspectReportItem.LocalLastUpdatedTime == null ? DateTime.MinValue : item.InspectReportItem.LocalLastUpdatedTime.Value;
                    }
                    if (item.Alerts != null)
                    {
                        List<AssetAlertItem> list = new List<AssetAlertItem>();
                        foreach (var a in item.Alerts)
                        {
                            AssetAlertItem ai = new AssetAlertItem();
                            Helper.CloneProperty(ai, a);
                            if (ai.Description.IndexOf("\r\n") > 0)
                                ai.Description = ai.Description.Substring(0, ai.Description.IndexOf("\r\n"));
                            if (ai.Description.IndexOf("\n") > 0)
                                ai.Description = ai.Description.Substring(0, ai.Description.IndexOf("\n"));

                            list.Add(ai);
                        }
                        item.AlertItems = list.ToArray();
                    }
                    if (item.PMPlanInfos != null)
                    {
                        List<AssetPMPlanItem> list = new List<AssetPMPlanItem>();
                        foreach (var a in item.PMPlanInfos)
                        {
                            AssetPMPlanItem ai = new AssetPMPlanItem();
                            Helper.CloneProperty(ai, a);

                            list.Add(ai);
                        }
                        item.PMPlanItems = list.ToArray();
                    }
                    if (item.AssetMaintenanceRecord != null)
                    {
                        item.MaintenanceRecordItem = new AssetMaintenanceRecordItem();
                        Helper.CloneProperty(item.MaintenanceRecordItem, item.AssetMaintenanceRecord);
                    }
                    if (SystemParams.IsDealer)
                        item.InspectReportItem = null;
                    return item;
                }
                else
                    return new AssetSummaryItem();
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "MachineDeviceBasePage.GetAssetExtInfo", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        #region Rentals

        private object SearchRentals()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                    var searchtext = HttpUtility.HtmlDecode(clientdata[1]);
                    var sdate = HttpUtility.HtmlDecode(clientdata[2]);
                    var edate = HttpUtility.HtmlDecode(clientdata[3]);
                    var machineid = HttpUtility.HtmlDecode(clientdata[4]);

                    if (string.IsNullOrEmpty(companyid))
                        companyid = SystemParams.CompanyID;

                    if (string.IsNullOrWhiteSpace(companyid) && SystemParams.IsDealer)
                        return new MachineRentalInfo[0];

                    AssetRentalInfo[] rentalinfos = CreateClient<AssetQueryClient>(companyid).GetAssetRentals(companyid, searchtext, session.User.UID);
                    if (rentalinfos == null)
                        return new MachineRentalInfo[0];

                    List<MachineRentalInfo> rentals = new List<MachineRentalInfo>();
                    foreach (AssetRentalInfo ri in rentalinfos)
                    {
                        MachineRentalInfo mi = new MachineRentalInfo();
                        Helper.CloneProperty(mi, ri);
                        mi.RentalRate = (decimal)ri.RentalRate;
                        rentals.Add(mi);
                    }

                    if (!string.IsNullOrWhiteSpace(machineid))
                        rentals = rentals.Where(m => m.MachineID == Convert.ToInt64(machineid)).ToList();

                    if (!string.IsNullOrWhiteSpace(sdate))
                    {
                        DateTime startdate = Convert.ToDateTime(sdate);
                        rentals = rentals.Where(m => m.RentalDate >= startdate).ToList();
                    }
                    if (!string.IsNullOrWhiteSpace(edate))
                    {
                        DateTime enddate = Convert.ToDateTime(edate).AddDays(1).AddSeconds(-1);
                        rentals = rentals.Where(m => m.RentalDate <= enddate).ToList();
                    }

                    return rentals.OrderBy(m => m.RentalDate);
                }
                else
                    return new MachineRentalInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object SearchRentalsByAsset()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string data = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(data);
                    string companyid = ps[0];
                    long assetid = 0;
                    long.TryParse(ps[1], out assetid);

                    if (string.IsNullOrEmpty(companyid))
                        companyid = SystemParams.CompanyID;

                    if (string.IsNullOrWhiteSpace(companyid) && SystemParams.IsDealer)
                        return new MachineRentalInfo[0];

                    AssetRentalInfo[] rentalinfos = CreateClient<AssetQueryClient>(companyid).SearchRentalsByAsset(companyid, assetid, session.User.UID);
                    if (rentalinfos == null)
                        return new MachineRentalInfo[0];

                    rentalinfos = rentalinfos.OrderByDescending(m => m.RentalDate).ToArray();

                    List<MachineRentalInfo> rentals = new List<MachineRentalInfo>();
                    foreach (AssetRentalInfo ri in rentalinfos)
                    {
                        MachineRentalInfo mi = new MachineRentalInfo();
                        Helper.CloneProperty(mi, ri);
                        mi.RentalRate = (decimal)ri.RentalRate;
                        rentals.Add(mi);
                    }
                    if (rentals != null && rentals.Count > 0)
                    {
                        DateTime nowdate = DateTime.Now;
                        //当前时间所在的rental
                        MachineRentalInfo rental = rentals.FirstOrDefault(m => m.RentalDate <= nowdate && nowdate.Date <= ((m.ReturnDate ?? m.ProjectReturnDate ?? DateTime.MaxValue)));
                        if (rental == null)//当前时间的下一个rental                                
                            rental = rentals.Where(m => m.RentalDate >= nowdate.Date).OrderBy(m => m.RentalDate).FirstOrDefault();
                        if (rental == null)//最新rental
                            rental = rentals[0];

                        rental.Selected = true;
                    }
                    if (rentals == null)
                        return new MachineRentalInfo[0];

                    return rentals.OrderBy(m => m.RentalDate);
                }
                else
                    return new MachineRentalInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object SearchRentalChangeHistory()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                    var searchtext = HttpUtility.HtmlDecode(clientdata[1]);
                    var sdate = HttpUtility.HtmlDecode(clientdata[2]);
                    var edate = HttpUtility.HtmlDecode(clientdata[3]);
                    var machineid = HttpUtility.HtmlDecode(clientdata[4]);
                    var rentalid = HttpUtility.HtmlDecode(clientdata[5]);

                    if (string.IsNullOrEmpty(companyid))
                        companyid = SystemParams.CompanyID;

                    if (string.IsNullOrWhiteSpace(companyid) && SystemParams.IsDealer)
                        return new RentalChangeHistoryInfo[0];

                    AssetRentalChangeHistoryInfo[] assetrentals = CreateClient<AssetQueryClient>(companyid).GetAssetRentalChangeHistory(companyid, Convert.ToInt64(rentalid));
                    if (assetrentals == null)
                        return new RentalChangeHistoryInfo[0];
                    List<RentalChangeHistoryInfo> rentals = new List<RentalChangeHistoryInfo>();
                    foreach (AssetRentalChangeHistoryInfo ari in assetrentals)
                    {
                        RentalChangeHistoryInfo mri = new RentalChangeHistoryInfo();
                        Helper.CloneProperty(mri, ari);
                        mri.RentalRate = (decimal)ari.RentalRate;
                        rentals.Add(mri);
                    }

                    if (!string.IsNullOrWhiteSpace(sdate))
                    {
                        DateTime startdate = Convert.ToDateTime(sdate);
                        rentals = rentals.Where(m => m.RentalDate >= startdate).ToList();
                    }
                    if (!string.IsNullOrWhiteSpace(edate))
                    {
                        DateTime enddate = Convert.ToDateTime(edate).AddDays(1).AddSeconds(-1);
                        rentals = rentals.Where(m => m.RentalDate <= enddate).ToList();
                    }
                    return rentals.OrderBy(m => m.LastUpdateDate);
                }
                else
                    return new MachineRentalInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetRentalInfo()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                    var rentalid = HttpUtility.HtmlDecode(clientdata[1]);

                    if (string.IsNullOrEmpty(companyid))
                        companyid = SystemParams.CompanyID;

                    if (string.IsNullOrWhiteSpace(companyid) && SystemParams.IsDealer)
                        return new MachineRentalInfo[0];

                    AssetRentalInfo rentalinfo = CreateClient<AssetQueryClient>(companyid).GetAssetRentalInfo(companyid, Convert.ToInt64(rentalid));

                    MachineRentalInfo rental = new MachineRentalInfo();
                    Helper.CloneProperty(rental, rentalinfo);
                    rental.RentalRate = (decimal)rentalinfo.RentalRate;
                    return rental;
                }
                else
                    return new MachineRentalInfo();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object SaveRental()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                    var data = HttpUtility.HtmlDecode(clientdata[1]);
                    MachineRentalInfo rentalInfo = JsonConvert.DeserializeObject<MachineRentalInfo>(data);

                    if (string.IsNullOrEmpty(companyid))
                        companyid = SystemParams.CompanyID;

                    AssetRentalInfo rental = new AssetRentalInfo();
                    Helper.CloneProperty(rental, rentalInfo);
                    rental.RentalRate = (double)rentalInfo.RentalRate;
                    long rentalid = CreateClient<AssetQueryClient>(companyid).SaveAssetRental(companyid, rental, session.User.UID);

                    return rentalid;
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object DeleteRental()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                    var id = HttpUtility.HtmlDecode(clientdata[1]);
                    long rentalid = Convert.ToInt64(id);

                    if (!SystemParams.IsDealer)
                        companyid = SystemParams.CompanyID;

                    CreateClient<AssetQueryClient>(companyid).DeleteAssetRental(companyid, rentalid, session.User.UID);

                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetSelectMachinesByRental()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var companyid = HttpUtility.HtmlDecode(Request.Params["ClientData"]);

                    FISqlConnection db = null;
                    if (SystemParams.IsDealer)
                    {
                        string connetionstring = SystemParams.GetDbStringByCompany(companyid);
                        db = new FISqlConnection(connetionstring);
                    }
                    MachineItem[] machines = MachineManagement.GetSelectMachinesByRental(session.SessionID, session.User.UID, "", companyid);
                    if (machines == null)
                        return new MachineItem[0];

                    return machines.Where(m => m.Hide == false).OrderBy(m => m.DisplayName).ToArray();
                }
                else
                    return new MachineItem[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion       

        private object SaveGPSDevice()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    if (!CheckRight(SystemParams.CompanyID, Foresight.Fleet.Services.User.Feature.MANAGE_DEVICES))
                        return "";

                    var clientdata = Request.Form["ClientData"];
                    var data = HttpUtility.HtmlDecode(clientdata);
                    DeviceItem deviceitem = JsonConvert.DeserializeObject<DeviceItem>(data);
                    if (string.IsNullOrWhiteSpace(deviceitem.ContractorID))
                        deviceitem.ContractorID = SystemParams.CompanyID;

                    FFSDevice.DeviceInfo device = new FFSDevice.DeviceInfo();
                    Helper.CloneProperty(device, deviceitem);

                    DeviceProvider deviceprovider = CreateClient<DeviceProvider>(deviceitem.ContractorID);
                    if (device.Id < 0)
                    {
                        device = deviceprovider.AddNewDevice(deviceitem.ContractorID, device);
                    }
                    else
                        deviceprovider.UpdateDevice(deviceitem.ContractorID, device);

                    DevicePairingInfo devicepairing = new DevicePairingInfo();
                    devicepairing.Notes = deviceitem.Notes;
                    if (session.User.UserType == Foresight.Fleet.Services.User.UserTypes.SupperAdmin)
                    {
                        devicepairing.InstallerName = deviceitem.Installer;
                        devicepairing.FIInstalltion = deviceitem.FIInstalltion;
                    }
                    else
                    {
                        devicepairing.FIInstalltion = false;
                    }

                    long logid = 0;
                    if (deviceitem.PairedAsset != null && deviceitem.PairedAsset.Id > 0)
                        logid = deviceprovider.PairAsset(deviceitem.ContractorID, device.Id, deviceitem.PairedAsset.Id, devicepairing);
                    else
                        deviceprovider.UnPairAsset(deviceitem.ContractorID, device.Id, "");

                    //Device Assignment
                    //List<StringKeyValue> list = new List<StringKeyValue>();
                    //StringKeyValue kv = new StringKeyValue();
                    //kv.Key = device.Id.ToString();
                    //kv.Value = mid;
                    //kv.Tag1 = device.ContractorID;
                    //kv.Tag2 = device.Notes;
                    //list.Add(kv);
                    //MachineServiceClient2 mc = SystemParams.GetMachineServiceClient();
                    //mc.SaveDeviceAssignments(0, list.ToArray());//修改Admin数据库
                    //SaveDeviceAssignments(list[0], session.User.UID);//修改本地数据库                    

                    return new string[] { device.Id.ToString(), logid.ToString() };
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetGPSDevices()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string data = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(data);
                    string contractorid = ps[0];
                    if (string.IsNullOrEmpty(contractorid))
                        contractorid = SystemParams.CompanyID;
                    string searchtxt = HttpUtility.HtmlDecode(ps[1]);
                    FFSDevice.DeviceInfo[] devs = CreateClient<DeviceProvider>(contractorid).GetDevices(contractorid, searchtxt);

                    if (devs == null)
                        return new DeviceItem[0];
                    List<DeviceItem> list = new List<DeviceItem>();
                    foreach (var dev in devs)
                    {
                        DeviceItem deviceitem = new DeviceItem();
                        Helper.CloneProperty(deviceitem, dev);

                        if (dev.PairedAsset != null)
                        {
                            deviceitem.PairedAsset = new PairedAssetItem();
                            Helper.CloneProperty(deviceitem.PairedAsset, dev.PairedAsset);
                        }

                        list.Add(deviceitem);
                    }

                    return list.ToArray();
                }
                else
                {
                    return new DeviceItem[0];
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object ChangeGPSContractor()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    string data = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(data);
                    long deviceid = -1;
                    long.TryParse(ps[0], out deviceid);
                    string newcontractorid = ps[1];
                    string notes = HttpUtility.HtmlDecode(ps[2]);
                    CreateClient<DeviceProvider>().ChangeDeviceContractor(deviceid, newcontractorid, notes);

                    return "OK";
                }
                else
                    return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetGPSSources()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    return FFSDevice.DeviceInfo.DEVICESES;
                }
                else
                {
                    return new KeyValuePair<string, string>();
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetNimbelingTypes()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    return FFSDevice.DeviceInfo.NimbelingTypes;
                }
                else
                {
                    return new KeyValuePair<string, string>();
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetDeviceComments()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    string contractorid = ps[0];
                    if (string.IsNullOrEmpty(contractorid))
                        contractorid = SystemParams.CompanyID;
                    long deviceid = 0;
                    long.TryParse(ps[1], out deviceid);

                    CommentInfo[] comments = CreateClient<DeviceProvider>(contractorid).GetDeviceComments(contractorid, deviceid);
                    List<CommentItem> list = new List<CommentItem>();
                    foreach (var c in comments)
                    {
                        CommentItem citem = new CommentItem();
                        Helper.CloneProperty(citem, c);

                        list.Add(citem);
                    }

                    return list.ToArray();
                }
                else
                {
                    return new CommentItem[0];
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object AddDeviceComment()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    string contractorid = ps[0];
                    if (string.IsNullOrEmpty(contractorid))
                        contractorid = SystemParams.CompanyID;
                    long deviceid = 0;
                    long.TryParse(ps[1], out deviceid);
                    string comment = ps[2];

                    CreateClient<DeviceProvider>(contractorid).SubmitDeviceComment(contractorid, user.IID, deviceid, comment);
                }
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetDeviceInstallationNotes()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    string contractorid = ps[0];
                    if (string.IsNullOrEmpty(contractorid))
                        contractorid = SystemParams.CompanyID;
                    long deviceid = 0;
                    long.TryParse(ps[1], out deviceid);

                    InstallNotesItem[] inotes = CreateClient<DeviceProvider>(contractorid).GetDeviceInstallNotes(contractorid, deviceid);
                    List<InstallNotesItemC> list = new List<InstallNotesItemC>();
                    foreach (var c in inotes)
                    {
                        InstallNotesItemC citem = new InstallNotesItemC();
                        Helper.CloneProperty(citem, c);

                        list.Add(citem);
                    }

                    return list.ToArray();
                }
                else
                {
                    return new CommentItem[0];
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object AddInstallationNotes()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    string contractorid = ps[0];
                    if (string.IsNullOrEmpty(contractorid))
                        contractorid = SystemParams.CompanyID;
                    long deviceid = 0;
                    long.TryParse(ps[1], out deviceid);
                    string notes = ps[2];

                    List<Tuple<string, byte[]>> imgs = new List<Tuple<string, byte[]>>();
                    byte[] filebytes = null;
                    if (Request.Files.Count > 0)
                    {
                        for (int i = 0; i < Request.Files.Count; i++)
                        {
                            HttpPostedFile uf = Request.Files[i];
                            filebytes = ConvertFile2bytes(uf);
                            Tuple<string, byte[]> tmpf = new Tuple<string, byte[]>(uf.FileName, filebytes);
                            imgs.Add(tmpf);
                        }
                    }

                    CreateClient<DeviceProvider>(contractorid).AddInstallNotes(contractorid, deviceid, -1, notes, imgs.ToArray(), user.IID, DateTime.Now.ToUniversalTime());
                }
                return "OK";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetContractors()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string searchtxt = HttpUtility.HtmlDecode(Request.Params["ClientData"]);

                    CustomerProvider cust = CreateClient<CustomerProvider>();
                    CustomerInfo[] compnays = cust.GetContractors(SystemParams.CompanyID);

                    List<StringKeyValue> list = new List<StringKeyValue>();
                    foreach (var cm in compnays)
                    {
                        StringKeyValue kv = new StringKeyValue();
                        kv.Key = cm.ID;
                        kv.Value = cm.Name;
                        list.Add(kv);
                    }
                    return list.OrderBy((m) => m.Value).ToArray();

                }
                else
                    return new StringKeyValue[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetMachineTypes()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    AssetType[] types = CreateClient<AssetClassProvider>().GetAssetTypes(SystemParams.CompanyID);
                    types = types.OrderBy((t) => t.Name).ToArray();
                    List<StringKeyValue> list = new List<StringKeyValue>();
                    foreach (AssetType md in types)
                    {
                        StringKeyValue kv = new StringKeyValue();
                        kv.Key = md.ID.ToString();
                        kv.Value = md.Name;
                        list.Add(kv);
                    }
                    return list.ToArray();

                }
                else
                    return new StringKeyValue[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetContractorsByUser()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    CustomerInfo[] companys = GetCompanyIDByUserIID(session.User.UID);
                    if (companys == null || companys.Length <= 0)
                        return new StringKeyValue[0];

                    List<StringKeyValue> list = new List<StringKeyValue>();
                    foreach (var cm in companys)
                    {
                        StringKeyValue kv = new StringKeyValue();
                        kv.Key = cm.ID;
                        kv.Value = cm.Name;
                        list.Add(kv);
                    }

                    return list.OrderBy((m) => m.Value).ToArray();

                }
                else
                    return new StringKeyValue[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        //delear可操作的contractor
        private CustomerInfo[] GetCompanyIDByUserIID(string useriid)
        {
            CustomerProvider cust = CreateClient<CustomerProvider>();
            CustomerInfo[] allcompany = cust.GetContractors(SystemParams.CompanyID);
            string[] contractors = Acl.GetUserAvailableContractors(useriid);

            if (contractors != null && contractors.Length > 0)
            {
                List<CustomerInfo> list = new List<CustomerInfo>();
                foreach (string id in contractors)
                {
                    if (!string.IsNullOrWhiteSpace(id))
                    {
                        CustomerInfo ci = allcompany.FirstOrDefault(m => m.ID == id);

                        if (ci != null)
                            list.Add(ci);
                    }
                }
                return list.ToArray();
            }
            else
                return null;
        }

        private object SaveMachineGroup()
        {
            if (GetCurrentLoginSession() != null)
            {
                if (!CheckRight(SystemParams.CompanyID, Foresight.Fleet.Services.User.Feature.MANAGE_ASSETS))
                    return "";
                string clientdata = Request.Form["ClientData"];
                clientdata = HttpUtility.HtmlDecode(clientdata);
                MachineGroup mg = JsonConvert.DeserializeObject<MachineGroup>(clientdata);

                MachineManagement.SaveMachineGroup(mg);

                return "OK";
            }
            return "Failed";
        }

        private object SaveAssetGroup()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Form["ClientData"];
                    clientdata = HttpUtility.HtmlDecode(clientdata);
                    AssetGroupInfo ag = JsonConvert.DeserializeObject<AssetGroupInfo>(clientdata);
                    if (string.IsNullOrEmpty(ag.Id))
                    {
                        // add
                        ag.Id = Guid.NewGuid().ToString();
                    }
                    CreateClient<AssetDataAdjustClient>().UpdataAssetGroup(SystemParams.CompanyID, ag, session.User.UID);
                    return ag.Id;
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "MachineDeviceBasePage.SaveAssetGroup", ex.Message, ex.ToString());
                return "Failed to save asset group: " + ex.Message;
            }
        }

        private object DeleteMachineGroup()
        {
            if (GetCurrentLoginSession() != null)
            {
                string clientdata = Request.Form["ClientData"];
                string groupID = HttpUtility.HtmlDecode(clientdata);

                int result = MachineManagement.DeleteMachineGroup(groupID);
                if (result == -1)
                    return "-1";

                return "OK";
            }
            return "Failed";
        }

        private object DeleteAssetGroup()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Form["ClientData"];
                    string groupID = HttpUtility.HtmlDecode(clientdata);

                    CreateClient<AssetDataAdjustClient>().DeleteAssetGroup(SystemParams.CompanyID, groupID, session.User.UID);

                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "MachineDeviceBasePage.DeleteAssetGroup", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetMachineGroups()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {

                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                    var searchtext = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(companyid))
                        companyid = SystemParams.CompanyID;

                    FISqlConnection db = null;
                    if (SystemParams.IsDealer)
                    {
                        string connetionstring = SystemParams.GetDbStringByCompany(companyid);
                        db = new FISqlConnection(connetionstring);
                    }

                    var groups = MachineManagement.GetMachineGroups(searchtext, db);
                    return groups.OrderBy((m) => m.GroupName).ToArray();
                }
                else
                    return new MachineGroup[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "MachineDeviceBasePage.GetMachineGroups", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetAssetGroups()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {

                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                    var searchtext = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(companyid))
                        companyid = SystemParams.CompanyID;

                    var groups = CreateClient<AssetQueryClient>(companyid).GetAssetGroups(companyid, searchtext, session.User.UID);
                    return groups.OrderBy(g => g.Name).ToArray();
                }
                else
                    return new AssetGroupInfo[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "MachineDeviceBasePage.GetAssetGroups", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetAssetList()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {

                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                    var searchtext = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(companyid))
                        companyid = SystemParams.CompanyID;
                    var hidden = (clientdata[2] == "1");
                    var child = (clientdata[3] == "1");

                    string[] assetgroups = null;
                    if (clientdata[4] != "-1")
                        assetgroups = new string[] { clientdata[4] };
                    long[] jobsites = null;
                    if (clientdata[5] != "-1")
                        jobsites = new long[] { long.Parse(clientdata[5]) };
                    string[] jobsitecodes = null;
                    if (clientdata[6] != "-1")
                        jobsitecodes = new string[] { clientdata[6] };

                    var items = CreateClient<AssetQueryClient>(companyid).GetAssetListItemsByUser(companyid, session.User.UID, searchtext, hidden, 0, child, assetgroups, jobsites, jobsitecodes);
                    return items.OrderBy(g => g.VIN).Select(i => new
                    {
                        i.Id,
                        Name = string.IsNullOrEmpty(i.Name2) ? i.Name : i.Name2,
                        i.VIN,
                        i.MakeName,
                        i.ModelName,
                        i.TypeID,
                        i.TypeName,
                        EngineHours = Math.Round(i.EngineHours ?? 0, 2),
                        Odometer = Math.Round(i.Odometer ?? 0, 2),
                        i.OdometerUnits,
                        DisplayName = GetDisplayName(i),
                        i.OnRoad,
                        i.ShareStatus,
                        i.AcquisitionType,
                        i.AssetGroups,
                        i.Jobsites
                    }).ToArray();
                }
                else
                    return new AssetGroupInfo[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "MachineDeviceBasePage.GetAssetList", ex.Message, ex.ToString());
                return ex.Message;
            }
        }
        private object[] GetUserAssignedAssets()
        {
            var session = GetCurrentLoginSession();
            if (session != null)
            {
                var clientdata = Request.Form["ClientData"].Split((char)170);
                var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                var searchtext = HttpUtility.HtmlDecode(clientdata[1]);
                if (string.IsNullOrEmpty(companyid))
                    companyid = SystemParams.CompanyID;
                var hidden = (clientdata[2] == "1");
                var child = (clientdata[3] == "1");

                string[] assetgroups = null;
                if (clientdata[4] != "-1")
                    assetgroups = new string[] { clientdata[4] };
                long[] jobsites = null;
                if (clientdata[5] != "-1")
                    jobsites = new long[] { long.Parse(clientdata[5]) };
                string[] jobsitecodes = null;
                if (clientdata[6] != "-1")
                    jobsitecodes = new string[] { clientdata[6] };

                string uid = clientdata[7];
                if (string.IsNullOrWhiteSpace(uid))
                    uid = session.User.UID;

                var ui = UserManagement.GetUserByIID(uid);
                AssetListItemInfo[] machines = null;

                if (ui.UserType < Users.UserTypes.Admin)
                {
                    bool accessallassets = false;
                    UserAdditionalAttribute attrs = CreateClient<UserQueryClient>(SystemParams.CompanyID).GetUserAdditionalAttribute(uid);
                    if (attrs != null)
                        accessallassets = attrs.AccessAllAssets;

                    if (accessallassets)
                        machines = CreateClient<AssetQueryClient>(companyid).GetAssetListItemsByUser(companyid, uid, searchtext, hidden, 0, child, assetgroups, jobsites, jobsitecodes);

                    else
                        machines = CreateClient<AssetDataAdjustClient>(companyid).GetAssetsAssignedToUser(companyid, uid);
                }
                else
                    machines = CreateClient<AssetQueryClient>(companyid).GetAssetListItemsByUser(companyid, uid, searchtext, hidden, 0, child, assetgroups, jobsites, jobsitecodes);

                //if (ui.UserType < Users.UserTypes.Admin)
                //    machines = CreateClient<AssetDataAdjustClient>(companyid).GetAssetsAssignedToUser(companyid, uid);
                //if (machines == null || machines.Length == 0)
                //    machines = CreateClient<AssetQueryClient>(companyid).GetAssetListItemsByUser(companyid, uid, searchtext, hidden, 0, child, assetgroups, jobsites, jobsitecodes);
                if (!string.IsNullOrWhiteSpace(searchtext))
                {
                    machines = machines.Where(mi => Helper.Contains(mi.VIN, searchtext)
                                || Helper.Contains(mi.Id.ToString(), searchtext)
                                || Helper.Contains(mi.Name, searchtext)
                                || Helper.Contains(mi.Name2, searchtext)
                                || Helper.Contains(mi.MakeName, searchtext)
                                || Helper.Contains(mi.TypeName, searchtext)
                                || Helper.Contains(mi.ModelName, searchtext)).ToArray();
                }

                return machines.OrderBy(m => m.VIN).Select(i => new
                {
                    i.Id,
                    Name = string.IsNullOrEmpty(i.Name2) ? i.Name : i.Name2,
                    i.VIN,
                    i.MakeName,
                    i.ModelName,
                    i.TypeName,
                    EngineHours = Math.Round(i.EngineHours ?? 0, 2),
                    Odometer = Math.Round(i.Odometer ?? 0, 2),
                    i.OdometerUnits,
                    DisplayName = GetDisplayName(i),
                    i.OnRoad,
                    i.ShareStatus,
                    i.AcquisitionType,
                    i.AssetGroups,
                    i.Jobsites
                }).ToArray();
            }
            else
                return new AssetGroupInfo[0];
        }
        private string GetDisplayName(AssetListItemInfo a)
        {
            //Name取值顺序为Name2,Name,VIN,ID用于前端显示
            string name = a.Name2;
            if (string.IsNullOrWhiteSpace(name))
                name = a.Name;
            if (string.IsNullOrWhiteSpace(name))
                name = a.VIN;
            if (string.IsNullOrWhiteSpace(name))
                name = a.Id.ToString();
            return name;
        }

        private object GetJobsiteAssetList()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {

                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                    var searchtext = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(companyid))
                        companyid = SystemParams.CompanyID;
                    var jobsiteid = long.Parse(clientdata[2]);

                    var items = CreateClient<JobSiteProvider>(companyid).GetAssetsNotInJobSite(companyid, jobsiteid, searchtext, session.User.UID);
                    return items.Select(i => new
                    {
                        Id = i.AssetId,
                        Name = string.IsNullOrEmpty(i.AssetName2) ? i.AssetName : i.AssetName2,
                        i.VIN,
                        i.MakeName,
                        i.ModelName,
                        i.TypeName,
                        DistanceFromSite = Math.Round(i.DistanceFromSite, 2),
                        i.DistanceUnits,
                        i.Suggested
                    }).ToArray();
                }
                else
                    return new AssetGroupInfo[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "MachineDeviceBasePage.GetJobsiteAssetList", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetMachineGroupByUser()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var groups = MachineManagement.GetMachineGroupByUser(session.User.UID);

                    return groups.OrderBy((m) => m.GroupName).ToArray();
                }
                else
                    return new MachineItem[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "MachineDeviceBasePage.GetMachineGroupByUser", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetAssetsByGroup()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    var groupid = HttpUtility.HtmlDecode(clientdata);

                    var assets = CreateClient<AssetQueryClient>().GetAssetsByAssetGroup(SystemParams.CompanyID, groupid);
                    return assets.Where(a => !a.Hide).ToArray();
                }
                else
                    return "";
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "MachineDeviceBasePage.GetAssetsByGroup", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetAssetMakes()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    var searchtxt = HttpUtility.HtmlDecode(clientdata);

                    AssetMake[] makes = CreateClient<AssetClassProvider>().GetAssetMakes(searchtxt);
                    List<AssetMakeItem> ls = new List<AssetMakeItem>();
                    foreach (var mk in makes)
                    {
                        AssetMakeItem item = new AssetMakeItem();
                        Helper.CloneProperty(item, mk);
                        ls.Add(item);
                    }
                    return ls.OrderBy(m => m.Name).ToArray();

                }
                else
                    return new AssetMakeItem[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetAssetModels()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    int makeid = -1;
                    int.TryParse(ps[0], out makeid);
                    var searchtxt = HttpUtility.HtmlDecode(ps[1]);

                    AssetModel[] models = CreateClient<AssetClassProvider>().GetAssetModels(makeid, searchtxt);
                    List<AssetModelItem> ls = new List<AssetModelItem>();
                    foreach (var md in models)
                    {
                        //if (!string.IsNullOrEmpty(md.AddedBy)
                        //    && !md.AddedBy.Equals(SystemParams.CompanyID, StringComparison.OrdinalIgnoreCase))
                        //    continue;
                        AssetModelItem item = new AssetModelItem();
                        Helper.CloneProperty(item, md);
                        if (md.MakeId > 0)
                        {
                            item.MakeID = md.MakeId;
                            item.MakeName = md.MakeName;
                        }
                        if (md.TypeId > 0)
                        {
                            item.TypeID = md.TypeId;
                            item.TypeName = md.TypeName;
                        }
                        ls.Add(item);
                    }

                    return ls.OrderBy(m => m.Name).ToArray();
                }
                else
                    return new AssetModelItem[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object SaveMachineMake()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Form["ClientData"];
                    clientdata = HttpUtility.HtmlDecode(clientdata);
                    AssetMakeItem item = JsonConvert.DeserializeObject<AssetMakeItem>(clientdata);

                    if (item.ID > 0)//界面不允许修改和删除
                        return "OK";

                    CreateClient<AssetClassProvider>().UpdateOrCreateMake(item.ID, item.Name, session.User.UID);

                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object SaveMachineModel()
        {
            try
            {
                var user = GetCurrentUser();
                bool permission = CheckRight(SystemParams.CompanyID, Feature.MANAGE_ASSETS);
                if (user != null && (user.UserType == Users.UserTypes.SupperAdmin || user.UserType == Users.UserTypes.Admin))
                {
                    string clientdata = Request.Form["ClientData"];
                    clientdata = HttpUtility.HtmlDecode(clientdata);
                    AssetModelItem item = JsonConvert.DeserializeObject<AssetModelItem>(clientdata);

                    if (item.ID > 0)//界面不允许修改和删除
                        return "OK";

                    CreateClient<AssetClassProvider>().UpdateOrCreateModel(item.MakeID, item.ID, item.Name, item.TypeID, user.IID);

                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object DeleteMachineMake()
        {
            return "OK";//界面不允许修改和删除
                        //try
                        //{
                        //    if (GetCurrentLoginSession() != null)
                        //    {
                        //        string clientdata = Request.Form["ClientData"];
                        //        int id = Convert.ToInt32(HttpUtility.HtmlDecode(clientdata));

            //        MachineServiceClient2 mc = SystemParams.GetMachineServiceClient();
            //        mc.DeleteMachineMake(id);

            //        return "OK";
            //    }
            //    return "Failed";
            //}
            //catch (Exception ex)
            //{
            //    return ex.Message;
            //}
        }

        private object DeleteMachineModel()
        {
            return "OK";//界面不允许修改和删除
                        //try
                        //{
                        //    var user = GetCurrentUser();
                        //    if (GetCurrentLoginSession() != null)
                        //    {
                        //        string clientdata = Request.Form["ClientData"];
                        //        int id = Convert.ToInt32(HttpUtility.HtmlDecode(clientdata));

            //        SystemParams.AssetClassClient.DeleteModel(id, user.IID);
            //        //MachineServiceClient2 mc = SystemParams.GetMachineServiceClient();
            //        //mc.DeleteMachineModel(id);

            //        return "OK";
            //    }
            //    return "Failed";
            //}
            //catch (Exception ex)
            //{
            //    return ex.Message;
            //}
        }

        private object GetActiveJobsites()
        {
            try
            {
                JobSiteViewItem[] items = null;
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = Request.Form["ClientData"];
                    string companyid = HttpUtility.HtmlDecode(clientdata);
                    if (string.IsNullOrEmpty(companyid))
                        companyid = SystemParams.CompanyID;

                    var jss = CreateClient<JobSiteProvider>(companyid).GetJobSiteItems(companyid, "", false);
                    List<JobSiteViewItem> list = new List<JobSiteViewItem>();
                    foreach (var js in jss)
                    {
                        JobSiteViewItem item = new JobSiteViewItem();
                        item.ID = js.ID;
                        item.Name = js.Name;

                        list.Add(item);
                    }
                    items = list.ToArray();
                }
                else
                {
                    items = new JobSiteViewItem[0];
                }
                return items.OrderBy(m => m.Name);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetContacts()
        {
            try
            {
                var session = GetCurrentLoginSession();
                Users.UserInfo[] users = null;
                if (session != null)
                {
                    //contact = ContactManagement.GetContacts();
                    string clientdata = Request.Form["ClientData"];
                    string companyid = HttpUtility.HtmlDecode(clientdata);
                    if (string.IsNullOrEmpty(companyid))
                        companyid = SystemParams.CompanyID;

                    users = UserManagement.GetActiveUsers(session.SessionID, companyid);
                    users = users.OrderBy(u => u.DisplayName).ToArray();
                }
                else
                {
                    users = new Users.UserInfo[0];
                }
                return users;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object ChangeMachineIconFile()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    StringKeyValue kv = JsonConvert.DeserializeObject<StringKeyValue>(clientdata);

                    HttpPostedFile uploadFile = null;
                    byte[] iconfilebyte = null;
                    if (Request.Files.Count > 0)
                    {
                        uploadFile = Request.Files[0];
                        iconfilebyte = ConvertFile2bytes(uploadFile);
                    }
                    FISqlConnection db = null;
                    if (SystemParams.IsDealer)
                    {
                        string companyid = kv.Key;
                        if (string.IsNullOrEmpty(companyid))
                            companyid = SystemParams.CompanyID;
                        string connetionstring = SystemParams.GetDbStringByCompany(companyid);
                        db = new FISqlConnection(connetionstring);
                    }
                    MachineManagement.ChangeMachineIconFile(Convert.ToInt64(kv.Value), uploadFile == null ? "" : uploadFile.FileName, iconfilebyte, db);

                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #region Asset Attachment

        private object GetAttachments()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var customerid = HttpUtility.HtmlDecode(clientdata[0]);
                    long assetid = Convert.ToInt64(HttpUtility.HtmlDecode(clientdata[1]));
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    AssetDocumentInfo[] atts = CreateClient<AssetDocumentProvider>(customerid).GetAssetDocuments(customerid, assetid);
                    if (atts == null || atts.Length <= 0)
                        return new AssetDocumentItem[0];

                    List<AssetDocumentItem> ls = new List<AssetDocumentItem>();
                    foreach (AssetDocumentInfo att in atts)
                    {
                        AssetDocumentItem ai = new AssetDocumentItem();
                        Helper.CloneProperty(ai, att);
                        ls.Add(ai);
                    }

                    return ls.OrderBy(m => m.AddedOn).ToArray();
                }
                else
                    return new AssetDocumentItem[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object UploadAssetDocument()
        {
            try
            {
                var loginsession = GetCurrentLoginSession();
                if (loginsession != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    AssetDocumentItem doc = JsonConvert.DeserializeObject<AssetDocumentItem>(clientdata);
                    if (string.IsNullOrEmpty(doc.CustomerID))
                        doc.CustomerID = SystemParams.CompanyID;

                    byte[] iconfilebyte = null;
                    if (string.Compare("url", doc.FileType.ToLower(), true) != 0)
                    {
                        HttpPostedFile uploadFile = null;
                        if (Request.Files.Count > 0)
                        {
                            uploadFile = Request.Files[0];
                            iconfilebyte = ConvertFile2bytes(uploadFile);
                        }
                    }

                    CreateClient<AssetDocumentProvider>(doc.CustomerID).UploadAssetDocument(doc.CustomerID, doc.AssetID, doc.Name, doc.Description, doc.FileType, doc.Url, doc.VisibleOnWorkOrder, doc.VisibleOnMap, doc.VisibleOnMobile, iconfilebyte, loginsession.User.UID);

                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object UpdateAssetDocument()
        {
            try
            {
                var loginsession = GetCurrentLoginSession();
                if (loginsession != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    AssetDocumentItem doc = JsonConvert.DeserializeObject<AssetDocumentItem>(clientdata);
                    if (string.IsNullOrEmpty(doc.CustomerID))
                        doc.CustomerID = SystemParams.CompanyID;

                    CreateClient<AssetDocumentProvider>(doc.CustomerID).UpdateAssetDocument(doc.CustomerID, doc.Id, doc.Name, doc.Description, doc.VisibleOnWorkOrder, doc.VisibleOnMap, doc.VisibleOnMobile, doc.Url, loginsession.User.UID);

                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object DeleteAttachment()
        {
            try
            {
                var loginsession = GetCurrentLoginSession();
                if (loginsession != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var customerid = HttpUtility.HtmlDecode(clientdata[0]);
                    var attid = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    CreateClient<AssetDocumentProvider>(customerid).DeleteAssetDocument(customerid, Convert.ToInt64(attid), loginsession.User.UID);
                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

        #endregion

        #region Adjust Odometer
        private object GetAssetCurrentOdometer()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var customerid = HttpUtility.HtmlDecode(clientdata[0]);
                    var assetid = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    AssetOdometerInfo[] odometers = CreateClient<AssetQueryClient>(customerid).GetAssetCurrentOdometer(customerid, Convert.ToInt64(assetid));
                    if (odometers == null || odometers.Length <= 0)
                        return new OdometerInfo[0];

                    List<OdometerInfo> list = new List<OdometerInfo>();
                    foreach (AssetOdometerInfo odo in odometers)
                    {
                        OdometerInfo item = new OdometerInfo();
                        Helper.CloneProperty(item, odo);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new OdometerInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetCalampOdometerHistory()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var customerid = HttpUtility.HtmlDecode(clientdata[0]);
                    var assetid = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    DateTime now = DateTime.Now.ToUniversalTime();
                    CalampOdoInfo[] odometers = CreateClient<AssetDataAdjustClient>(customerid).GetMostRecentCalampOdometerHistory(customerid, Convert.ToInt64(assetid));
                    if (odometers == null || odometers.Length <= 0)
                        return new CalampOdoInfo[0];

                    List<CalampOdometerInfo> list = new List<CalampOdometerInfo>();
                    foreach (CalampOdoInfo odo in odometers)
                    {
                        CalampOdometerInfo item = new CalampOdometerInfo();
                        Helper.CloneProperty(item, odo);
                        item.Gps_Calc = Math.Round(item.Gps_Calc, 2);
                        item.VBUS_Calc = Math.Round(item.VBUS_Calc, 2);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new CalampOdoInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetCalampOdometerHistoryPreview()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    AdjustOdometerInfo p = JsonConvert.DeserializeObject<AdjustOdometerInfo>(clientdata);
                    if (string.IsNullOrEmpty(p.CustomerID))
                        p.CustomerID = SystemParams.CompanyID;

                    DateTime utctime = p.OdometerDate.AddMinutes(-p.OffsetMinute);

                    CalampOdoInfo[] odometers = CreateClient<AssetDataAdjustClient>(p.CustomerID).GetCalampOdometerHistoryPreview(p.CustomerID, p.AssetID, p.Odometer, p.UOM, utctime);
                    if (odometers == null || odometers.Length <= 0)
                        return new CalampOdoInfo[0];

                    List<CalampOdometerInfo> list = new List<CalampOdometerInfo>();
                    foreach (CalampOdoInfo odo in odometers)
                    {
                        CalampOdometerInfo item = new CalampOdometerInfo();
                        Helper.CloneProperty(item, odo);
                        item.AsofTimeLocal = item.AsofTime.AddMinutes(p.OffsetMinute);
                        item.Gps_Calc = Math.Round(item.Gps_Calc, 2);
                        item.VBUS_Calc = Math.Round(item.VBUS_Calc, 2);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new CalampOdoInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetPedigreeOdometerHistory()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var customerid = HttpUtility.HtmlDecode(clientdata[0]);
                    var assetid = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    DateTime now = DateTime.Now.ToUniversalTime();
                    PedigreeOdoInfo[] odometers = CreateClient<AssetDataAdjustClient>(customerid).GetMostRecentPedigreeOdometerHistory(customerid, Convert.ToInt64(assetid));
                    if (odometers == null || odometers.Length <= 0)
                        return new CalampOdoInfo[0];

                    List<PedigreeOdometerInfo> list = new List<PedigreeOdometerInfo>();
                    foreach (PedigreeOdoInfo odo in odometers)
                    {
                        PedigreeOdometerInfo item = new PedigreeOdometerInfo();
                        Helper.CloneProperty(item, odo);
                        item.Gps_Calc = Math.Round(item.Gps_Calc, 2);
                        item.VBUS_Calc = Math.Round(item.VBUS_Calc, 2);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new PedigreeOdometerInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetPedigreeOdometerHistoryPreview()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    AdjustOdometerInfo p = JsonConvert.DeserializeObject<AdjustOdometerInfo>(clientdata);
                    if (string.IsNullOrEmpty(p.CustomerID))
                        p.CustomerID = SystemParams.CompanyID;

                    DateTime utctime = p.OdometerDate.AddMinutes(-p.OffsetMinute);

                    PedigreeOdoInfo[] odometers = CreateClient<AssetDataAdjustClient>(p.CustomerID).GetPedigreeOdometerHistoryPreview(p.CustomerID, p.AssetID, p.Odometer, p.UOM, utctime);
                    if (odometers == null || odometers.Length <= 0)
                        return new CalampOdoInfo[0];

                    List<PedigreeOdometerInfo> list = new List<PedigreeOdometerInfo>();
                    foreach (PedigreeOdoInfo odo in odometers)
                    {
                        PedigreeOdometerInfo item = new PedigreeOdometerInfo();
                        Helper.CloneProperty(item, odo);
                        item.AsofTimeLocal = item.AsofTime.AddMinutes(p.OffsetMinute);
                        item.Gps_Calc = Math.Round(item.Gps_Calc, 2);
                        item.VBUS_Calc = Math.Round(item.VBUS_Calc, 2);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new PedigreeOdometerInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetSmartWitnessOdometerHistory()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var customerid = HttpUtility.HtmlDecode(clientdata[0]);
                    var assetid = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    DateTime now = DateTime.Now.ToUniversalTime();
                    SmartWitnessOdoInfo[] odometers = CreateClient<AssetDataAdjustClient>(customerid).GetMostRecentSmartWitnessOdometerHistory(customerid, Convert.ToInt64(assetid));
                    if (odometers == null || odometers.Length <= 0)
                        return new CalampOdoInfo[0];

                    List<SmartWitnessOdometerInfo> list = new List<SmartWitnessOdometerInfo>();
                    foreach (SmartWitnessOdoInfo odo in odometers)
                    {
                        SmartWitnessOdometerInfo item = new SmartWitnessOdometerInfo();
                        Helper.CloneProperty(item, odo);
                        item.Gps_Calc = Math.Round(item.Gps_Calc, 2);
                        //item.VBUS_Calc = Math.Round(item.VBUS_Calc, 2);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new SmartWitnessOdometerInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetSmartWitnessOdometerHistoryPreview()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    AdjustOdometerInfo p = JsonConvert.DeserializeObject<AdjustOdometerInfo>(clientdata);
                    if (string.IsNullOrEmpty(p.CustomerID))
                        p.CustomerID = SystemParams.CompanyID;

                    DateTime utctime = p.OdometerDate.AddMinutes(-p.OffsetMinute);

                    SmartWitnessOdoInfo[] odometers = CreateClient<AssetDataAdjustClient>(p.CustomerID).GetSmartWitnessOdometerHistoryPreview(p.CustomerID, p.AssetID, p.Odometer, p.UOM, utctime);
                    if (odometers == null || odometers.Length <= 0)
                        return new CalampOdoInfo[0];

                    List<SmartWitnessOdometerInfo> list = new List<SmartWitnessOdometerInfo>();
                    foreach (SmartWitnessOdoInfo odo in odometers)
                    {
                        SmartWitnessOdometerInfo item = new SmartWitnessOdometerInfo();
                        Helper.CloneProperty(item, odo);
                        item.AsofTimeLocal = item.AsofTime.AddMinutes(p.OffsetMinute);
                        item.Gps_Calc = Math.Round(item.Gps_Calc, 2);
                        //item.VBUS_Calc = Math.Round(item.VBUS_Calc, 2);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new SmartWitnessOdometerInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        private object SaveAdjustOdometer()
        {
            try
            {
                var loginsession = GetCurrentLoginSession();
                if (loginsession != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    AdjustOdometerInfo odo = JsonConvert.DeserializeObject<AdjustOdometerInfo>(clientdata);
                    if (string.IsNullOrEmpty(odo.CustomerID))
                        odo.CustomerID = SystemParams.CompanyID;
                    var asset = CreateClient<AssetQueryClient>(odo.CustomerID).GetAssetBasicInfoByID(odo.CustomerID, odo.AssetID);
                    //if (asset.ShareStatus == AssetShareStatus.Child)
                    //    return "Failed";

                    DateTime utctime = odo.OdometerDate.AddMinutes(-odo.OffsetMinute);//UTC
                    DateTime localtime = SystemParams.ConvertToUserTimeFromUtc(loginsession.User, utctime);

                    bool isallowed = false;
                    if (!loginsession.User.IsForesightUser)
                        isallowed = CheckRight(SystemParams.CompanyID, Foresight.Fleet.Services.User.Feature.ASSET_ATTRIBUTE_ADJUSTMENT);
                    //isallowed = UserManagement.CheckUserPermission(loginsession.SessionID, loginsession.User.UID, 20);

                    if (loginsession.User.IsForesightUser || isallowed)
                        CreateClient<AssetDataAdjustClient>(odo.CustomerID).AdjustOdometer(odo.CustomerID, odo.AssetID, odo.DataSource, localtime, utctime, odo.Odometer, odo.UOM, odo.Notes, loginsession.User.UID);

                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion

        #region Add Odometer
        private object AddManuallyInputOdometer()
        {
            try
            {
                var loginsession = GetCurrentLoginSession();
                if (loginsession != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    AdjustOdometerInfo odo = JsonConvert.DeserializeObject<AdjustOdometerInfo>(clientdata);
                    if (string.IsNullOrEmpty(odo.CustomerID))
                        odo.CustomerID = SystemParams.CompanyID;

                    DateTime utctime = odo.OdometerDate.AddMinutes(-odo.OffsetMinute);//UTC

                    bool isallowed = false;
                    if (!loginsession.User.IsForesightUser)
                        isallowed = CheckRight(SystemParams.CompanyID, Foresight.Fleet.Services.User.Feature.ASSET_ATTRIBUTE_ADJUSTMENT);
                    //isallowed = UserManagement.CheckUserPermission(loginsession.SessionID, loginsession.User.UID, 20);

                    if (loginsession.User.IsForesightUser || isallowed)
                        CreateClient<AssetDataAdjustClient>(odo.CustomerID).AddManuallyInputOdometer(odo.CustomerID, odo.AssetID, loginsession.User.UID, odo.Odometer, odo.UOM, utctime, odo.Notes);
                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        #endregion

        #region Adjust EngineHours

        private object GetAssetCurrentEngineHours()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var customerid = HttpUtility.HtmlDecode(clientdata[0]);
                    var assetid = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    AssetEngineHoursInfo[] enginehours = CreateClient<AssetQueryClient>(customerid).GetAssetCurrentEngineHours(customerid, Convert.ToInt64(assetid));
                    if (enginehours == null || enginehours.Length <= 0)
                        return new EngineHoursInfo[0];

                    List<EngineHoursInfo> list = new List<EngineHoursInfo>();
                    foreach (AssetEngineHoursInfo eng in enginehours)
                    {
                        EngineHoursInfo item = new EngineHoursInfo();
                        Helper.CloneProperty(item, eng);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new EngineHoursInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetCalampEngineHoursHistory()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var customerid = HttpUtility.HtmlDecode(clientdata[0]);
                    var assetid = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    DateTime now = DateTime.Now.ToUniversalTime();
                    CalampHourInfo[] eninehours = CreateClient<AssetDataAdjustClient>(customerid).GetMostRecentCalampHourHistory(customerid, Convert.ToInt64(assetid));
                    if (eninehours == null || eninehours.Length <= 0)
                        return new CalampEngineHoursInfo[0];

                    List<CalampEngineHoursInfo> list = new List<CalampEngineHoursInfo>();
                    foreach (CalampHourInfo eng in eninehours)
                    {
                        CalampEngineHoursInfo item = new CalampEngineHoursInfo();
                        Helper.CloneProperty(item, eng);
                        item.Gps_Calc = Math.Round(item.Gps_Calc, 2);
                        item.VBUS_Calc = Math.Round(item.VBUS_Calc, 2);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new CalampEngineHoursInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetCalampEngineHoursHistoryPreview()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    AdjustEngineHoursInfo p = JsonConvert.DeserializeObject<AdjustEngineHoursInfo>(clientdata);
                    if (string.IsNullOrEmpty(p.CustomerID))
                        p.CustomerID = SystemParams.CompanyID;

                    DateTime utctime = p.EngineHoursDate.AddMinutes(-p.OffsetMinute);

                    CalampHourInfo[] odometers = CreateClient<AssetQueryClient>(p.CustomerID).GetCalampHourHistoryPreview(p.CustomerID, p.AssetID, p.EngineHours, "Hour", utctime);
                    if (odometers == null || odometers.Length <= 0)
                        return new CalampEngineHoursInfo[0];

                    List<CalampEngineHoursInfo> list = new List<CalampEngineHoursInfo>();
                    foreach (CalampHourInfo odo in odometers)
                    {
                        CalampEngineHoursInfo item = new CalampEngineHoursInfo();
                        Helper.CloneProperty(item, odo);
                        item.AsofTimeLocal = item.AsofTime.AddMinutes(p.OffsetMinute);
                        item.Gps_Calc = Math.Round(item.Gps_Calc, 2);
                        item.VBUS_Calc = Math.Round(item.VBUS_Calc, 2);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new CalampEngineHoursInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetPedigreeEngineHoursHistory()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var customerid = HttpUtility.HtmlDecode(clientdata[0]);
                    var assetid = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    DateTime now = DateTime.Now.ToUniversalTime();
                    PedigreeHourInfo[] eninehours = CreateClient<AssetDataAdjustClient>(customerid).GetMostRecentPedigreeHourHistory(customerid, Convert.ToInt64(assetid));
                    if (eninehours == null || eninehours.Length <= 0)
                        return new PedigreeEngineHoursInfo[0];

                    List<PedigreeEngineHoursInfo> list = new List<PedigreeEngineHoursInfo>();
                    foreach (PedigreeHourInfo eng in eninehours)
                    {
                        PedigreeEngineHoursInfo item = new PedigreeEngineHoursInfo();
                        Helper.CloneProperty(item, eng);
                        item.VBUS_Calc = Math.Round(item.VBUS_Calc, 2);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new PedigreeEngineHoursInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetPedigreeEngineHoursHistoryPreview()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    AdjustEngineHoursInfo p = JsonConvert.DeserializeObject<AdjustEngineHoursInfo>(clientdata);
                    if (string.IsNullOrEmpty(p.CustomerID))
                        p.CustomerID = SystemParams.CompanyID;

                    DateTime utctime = p.EngineHoursDate.AddMinutes(-p.OffsetMinute);

                    PedigreeHourInfo[] eninehours = CreateClient<AssetDataAdjustClient>(p.CustomerID).GetPedigreeHourHistoryPreview(p.CustomerID, p.AssetID, p.EngineHours, "Hour", utctime);
                    if (eninehours == null || eninehours.Length <= 0)
                        return new PedigreeEngineHoursInfo[0];

                    List<PedigreeEngineHoursInfo> list = new List<PedigreeEngineHoursInfo>();
                    foreach (PedigreeHourInfo odo in eninehours)
                    {
                        PedigreeEngineHoursInfo item = new PedigreeEngineHoursInfo();
                        Helper.CloneProperty(item, odo);
                        item.AsofTimeLocal = item.AsofTime.AddMinutes(p.OffsetMinute);
                        item.VBUS_Calc = Math.Round(item.VBUS_Calc, 2);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new PedigreeEngineHoursInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        private object GetOEMDD2EngineHoursHistory()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var customerid = HttpUtility.HtmlDecode(clientdata[0]);
                    var assetid = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    DateTime now = DateTime.Now.ToUniversalTime();
                    OEMDD2HourInfo[] eninehours = CreateClient<AssetDataAdjustClient>(customerid).GetMostRecentOEMDD2HourHistory(customerid, Convert.ToInt64(assetid));
                    if (eninehours == null || eninehours.Length <= 0)
                        return new OEMDD2EngineHoursInfo[0];

                    List<OEMDD2EngineHoursInfo> list = new List<OEMDD2EngineHoursInfo>();
                    foreach (OEMDD2HourInfo eng in eninehours)
                    {
                        OEMDD2EngineHoursInfo item = new OEMDD2EngineHoursInfo();
                        Helper.CloneProperty(item, eng);
                        item.Calculated = Math.Round(item.Calculated, 2);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new OEMDD2EngineHoursInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetOEMDD2EngineHoursHistoryPreview()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    AdjustEngineHoursInfo p = JsonConvert.DeserializeObject<AdjustEngineHoursInfo>(clientdata);
                    if (string.IsNullOrEmpty(p.CustomerID))
                        p.CustomerID = SystemParams.CompanyID;

                    DateTime utctime = p.EngineHoursDate.AddMinutes(-p.OffsetMinute);

                    OEMDD2HourInfo[] eninehours = CreateClient<AssetDataAdjustClient>(p.CustomerID).GetOEMDD2HourHistoryPreview(p.CustomerID, p.AssetID, p.EngineHours, "Hour", utctime);
                    if (eninehours == null || eninehours.Length <= 0)
                        return new OEMDD2EngineHoursInfo[0];

                    List<OEMDD2EngineHoursInfo> list = new List<OEMDD2EngineHoursInfo>();
                    foreach (OEMDD2HourInfo odo in eninehours)
                    {
                        OEMDD2EngineHoursInfo item = new OEMDD2EngineHoursInfo();
                        Helper.CloneProperty(item, odo);
                        item.AsofTimeLocal = item.AsofTime.AddMinutes(p.OffsetMinute);
                        item.Raw = Math.Round(item.Raw, 2);
                        item.Calculated = Math.Round(item.Calculated, 2);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new PedigreeEngineHoursInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        private object SaveAdjustEngineHours()
        {
            try
            {
                var loginsession = GetCurrentLoginSession();
                if (loginsession != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    AdjustEngineHoursInfo eng = JsonConvert.DeserializeObject<AdjustEngineHoursInfo>(clientdata);

                    if (string.IsNullOrEmpty(eng.CustomerID))
                        eng.CustomerID = SystemParams.CompanyID;

                    DateTime utctime = eng.EngineHoursDate.AddMinutes(-eng.OffsetMinute);//UTC
                    DateTime localtime = SystemParams.ConvertToUserTimeFromUtc(loginsession.User, utctime);

                    bool isallowed = false;
                    if (!loginsession.User.IsForesightUser)
                        isallowed = CheckRight(SystemParams.CompanyID, Foresight.Fleet.Services.User.Feature.ASSET_ATTRIBUTE_ADJUSTMENT);
                    //isallowed = UserManagement.CheckUserPermission(loginsession.SessionID, loginsession.User.UID, 20);

                    if (loginsession.User.IsForesightUser || isallowed)
                        CreateClient<AssetDataAdjustClient>(eng.CustomerID).AdjustEngineHours(eng.CustomerID, eng.AssetID, eng.DataSource, localtime, utctime, eng.EngineHours, eng.Notes, loginsession.User.UID);
                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion

        #region Add Engine Hours
        private object AddManuallyInputEngineHours()
        {
            try
            {
                var loginsession = GetCurrentLoginSession();
                if (loginsession != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    AdjustEngineHoursInfo eng = JsonConvert.DeserializeObject<AdjustEngineHoursInfo>(clientdata);

                    if (string.IsNullOrEmpty(eng.CustomerID))
                        eng.CustomerID = SystemParams.CompanyID;

                    DateTime utctime = eng.EngineHoursDate.AddMinutes(-eng.OffsetMinute);//UTC

                    bool isallowed = false;
                    if (!loginsession.User.IsForesightUser)
                        isallowed = CheckRight(SystemParams.CompanyID, Foresight.Fleet.Services.User.Feature.ASSET_ATTRIBUTE_ADJUSTMENT);
                    //isallowed = UserManagement.CheckUserPermission(loginsession.SessionID, loginsession.User.UID, 20);
                    if (loginsession.User.IsForesightUser || isallowed)
                        CreateClient<AssetDataAdjustClient>(eng.CustomerID).AddManuallyInputEngineHours(eng.CustomerID, eng.AssetID, loginsession.User.UID, eng.EngineHours, utctime, eng.Notes);
                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion

        #region Adjust Location

        private object GetAssetCurrentLocation()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var customerid = HttpUtility.HtmlDecode(clientdata[0]);
                    var assetid = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    AssetLocationInfo[] locations = CreateClient<AssetQueryClient>(customerid).GetAssetCurrentLocation(customerid, Convert.ToInt64(assetid));
                    if (locations == null || locations.Length <= 0)
                        return new LocationInfo[0];

                    List<LocationInfo> list = new List<LocationInfo>();
                    foreach (AssetLocationInfo loc in locations)
                    {
                        LocationInfo item = new LocationInfo();
                        Helper.CloneProperty(item, loc);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new LocationInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion

        #region Adjust IdleHours

        private object GetAssetCurrentIdleHours()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var customerid = HttpUtility.HtmlDecode(clientdata[0]);
                    var assetid = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    AssetIdlehoursInfo[] ihs = CreateClient<AssetQueryClient>(customerid).GetAssetCurrentIdleHours(customerid, Convert.ToInt64(assetid));
                    if (ihs == null || ihs.Length <= 0)
                        return new IdlehoursInfo[0];

                    List<IdlehoursInfo> list = new List<IdlehoursInfo>();
                    foreach (AssetIdlehoursInfo ih in ihs)
                    {
                        IdlehoursInfo item = new IdlehoursInfo();
                        Helper.CloneProperty(item, ih);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new IdlehoursInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion

        #region Adjust FuelUsed

        private object GetAssetCurrentFuelUsed()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var customerid = HttpUtility.HtmlDecode(clientdata[0]);
                    var assetid = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    AssetFuelusedInfo[] fus = CreateClient<AssetQueryClient>(customerid).GetAssetCurrentFuelUsed(customerid, Convert.ToInt64(assetid));
                    if (fus == null || fus.Length <= 0)
                        return new FuelusedInfo[0];

                    List<FuelusedInfo> list = new List<FuelusedInfo>();
                    foreach (AssetFuelusedInfo fu in fus)
                    {
                        FuelusedInfo item = new FuelusedInfo();
                        Helper.CloneProperty(item, fu);
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new FuelusedInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion

        #region Adjust Remaining

        private object GetAssetCurrentFuelRemaining()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var customerid = HttpUtility.HtmlDecode(clientdata[0]);
                    var assetid = HttpUtility.HtmlDecode(clientdata[1]);
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    AssetFuelusedInfo[] fus = CreateClient<AssetDataAdjustClient>(customerid).GetAssetCurrentFuelRemaining(customerid, Convert.ToInt64(assetid), false);
                    if (fus == null || fus.Length <= 0)
                        return new FuelusedInfo[0];

                    List<FuelusedInfo> list = new List<FuelusedInfo>();
                    foreach (AssetFuelusedInfo fu in fus)
                    {
                        FuelusedInfo item = new FuelusedInfo();
                        Helper.CloneProperty(item, fu);
                        item.PercentText = fu.PercentText;
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new FuelusedInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion

        #region Set Primary

        private object ChangePrimaryDataSource()
        {
            try
            {
                var loginsession = GetCurrentLoginSession();
                if (loginsession != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    PrimaryDataSourceInfo item = JsonConvert.DeserializeObject<PrimaryDataSourceInfo>(clientdata);
                    if (string.IsNullOrEmpty(item.CustomerID))
                        item.CustomerID = SystemParams.CompanyID;

                    bool isallowed = false;
                    if (!loginsession.User.IsForesightUser)
                        isallowed = CheckRight(SystemParams.CompanyID, Foresight.Fleet.Services.User.Feature.ASSET_ATTRIBUTE_ADJUSTMENT);
                    //isallowed = UserManagement.CheckUserPermission(loginsession.SessionID, loginsession.User.UID, 20);
                    if (loginsession.User.IsForesightUser || isallowed)
                    {
                        if (item.Type == 0)
                        {
                            CreateClient<AssetDataAdjustClient>(item.CustomerID).ChangeOdometerPrimaryDataSource(item.CustomerID, item.AssetID, item.DataSource, item.SubSource, item.Notes, loginsession.User.UID);
                        }
                        else if (item.Type == 1)
                        {
                            CreateClient<AssetDataAdjustClient>(item.CustomerID).ChangeEngineHoursPrimaryDataSource(item.CustomerID, item.AssetID, item.DataSource, item.SubSource, item.Notes, loginsession.User.UID);
                        }
                        else if (item.Type == 2)
                        {
                            CreateClient<AssetDataAdjustClient>(item.CustomerID).ChangeLocationPrimaryDataSource(item.CustomerID, item.AssetID, item.DataSource, item.SubSource, item.Notes, loginsession.User.UID);
                        }
                        else if (item.Type == 3)
                        {
                            CreateClient<AssetDataAdjustClient>(item.CustomerID).ChangeIdlehoursPrimaryDataSource(item.CustomerID, item.AssetID, item.DataSource, item.SubSource, item.Notes, loginsession.User.UID);
                        }
                        else if (item.Type == 4)
                        {
                            CreateClient<AssetDataAdjustClient>(item.CustomerID).ChangeFuelUsedPrimaryDataSource(item.CustomerID, item.AssetID, item.DataSource, item.SubSource, item.Notes, loginsession.User.UID);
                        }
                        else if (item.Type == 5)
                        {
                            CreateClient<AssetDataAdjustClient>(item.CustomerID).ChangeFuelRemainingPrimaryDataSource(item.CustomerID, item.AssetID, item.DataSource, item.SubSource, item.Notes, loginsession.User.UID);
                        }
                    }

                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion


        private object GetMachineDetailURL()
        {
            var clientdata = Context.Request.Params["ClientData"];
            string[] pvs = JsonConvert.DeserializeObject<string[]>(clientdata);
            if (pvs.Length == 2)
            {
                int openMode = 0;
                string url = MachineDetailWorkspace.GenerateMachineDetailWSPURL(pvs[0], pvs[1], out openMode);
                return new string[] { openMode.ToString(), url };
            }
            return "";
        }

        private object GetTimeZones()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var timezones = SystemParams.GetTimeZones();
                    return timezones;
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object CheckOdometerMinnimumTime()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    AdjustOdometerInfo p = JsonConvert.DeserializeObject<AdjustOdometerInfo>(clientdata);
                    if (string.IsNullOrEmpty(p.CustomerID))
                        p.CustomerID = SystemParams.CompanyID;

                    DateTime odometertime = p.OdometerDate.AddMinutes(-p.OffsetMinute);

                    AssetOdometerInfo odometer = CreateClient<AssetQueryClient>(p.CustomerID).GetAssetCurrentOdometer(p.CustomerID, p.AssetID).FirstOrDefault(m => m.IsPrimary);
                    if (odometer == null)
                        return true;
                    AssetDataAdjustClient client = CreateClient<AssetDataAdjustClient>(p.CustomerID);
                    DateTime mintime = client.GetAssetOdometerMinimumAsofTime(p.CustomerID, p.AssetID, odometer.DataSource, odometer.SubSource, false);
                    DateTime maxtime = client.GetAssetOdometerMaximumAsofTime(p.CustomerID, p.AssetID, odometer.DataSource, odometer.SubSource, false);

                    if (odometertime < mintime)
                        return 1;
                    if (odometertime > maxtime.AddMinutes(1) || odometertime > DateTime.UtcNow)//10825要求增加1分钟
                        return 2;

                    return 0;
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object CheckEngineHourMinimumTime()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    AdjustEngineHoursInfo p = JsonConvert.DeserializeObject<AdjustEngineHoursInfo>(clientdata);
                    if (string.IsNullOrEmpty(p.CustomerID))
                        p.CustomerID = SystemParams.CompanyID;

                    DateTime hourstime = p.EngineHoursDate.AddMinutes(-p.OffsetMinute);

                    AssetEngineHoursInfo hours = CreateClient<AssetQueryClient>(p.CustomerID).GetAssetCurrentEngineHours(p.CustomerID, p.AssetID).FirstOrDefault(m => m.IsPrimary);
                    if (hours == null)//获取当前IsPrimary数据源
                        return true;

                    AssetDataAdjustClient client = CreateClient<AssetDataAdjustClient>(p.CustomerID);
                    DateTime mintime = client.GetAssetEngineHourMinimumAsofTime(p.CustomerID, p.AssetID, hours.DataSource, hours.SubSource, false);
                    DateTime maxtime = client.GetAssetEngineHourMaximumAsofTime(p.CustomerID, p.AssetID, hours.DataSource, hours.SubSource, false);

                    if (hourstime < mintime)
                        return 1;
                    if (hourstime > maxtime.AddMinutes(1) || hourstime > DateTime.UtcNow)
                        return 2;

                    return 0;
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetUserPermission()
        {
            try
            {
                var session = GetCurrentLoginSession();
                bool result = false;
                if (session != null)
                {
                    result = CheckRight(SystemParams.CompanyID, Foresight.Fleet.Services.User.Feature.ASSET_ATTRIBUTE_ADJUSTMENT);
                    //result = UserManagement.CheckUserPermission(session.SessionID, session.User.UID, 20);
                }
                return result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object CalampDeviceHasData()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    string data = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(data);
                    string contractorid = ps[0];
                    if (string.IsNullOrEmpty(contractorid))
                        contractorid = SystemParams.CompanyID;
                    return CreateClient<DeviceProvider>().CalampDeviceHasData(contractorid, ps[1]);
                }
                else
                    return true;
            }
            catch (Exception ex)
            {
                return true;
            }
        }
        private object GetCalampDeviceSNInfo()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    return CreateClient<DeviceProvider>()._GetCalampDeviceSN(clientdata);
                }
                else
                    return "";
            }
            catch
            {
                return "";
            }
        }

        private object GetImportMachineColumns()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string woid = HttpUtility.HtmlDecode(Request.Form["ClientData"]);

                    HttpPostedFile uploadFile = null;
                    byte[] iconfilebyte = null;
                    if (Request.Files.Count > 0)
                    {
                        uploadFile = Request.Files[0];
                        iconfilebyte = ConvertFile2bytes(uploadFile);
                    }

                    if (iconfilebyte != null)
                    {
                        string[] columns = new ImportFromExcel().LoadExcelColumnHead(iconfilebyte);
                        if (columns != null && columns.Length > 0)
                            return columns;
                    }
                }
                return new string[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetImportDevicesColumns()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string woid = HttpUtility.HtmlDecode(Request.Form["ClientData"]);

                    HttpPostedFile uploadFile = null;
                    byte[] iconfilebyte = null;
                    if (Request.Files.Count > 0)
                    {
                        uploadFile = Request.Files[0];
                        iconfilebyte = ConvertFile2bytes(uploadFile);
                    }

                    if (iconfilebyte != null)
                    {
                        string[] columns = new ImportFromExcel().LoadExcelColumnHead(iconfilebyte);
                        if (columns != null && columns.Length > 0)
                            return columns;
                    }
                }
                return new string[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        public class ImportResult
        {
            public int Count = -1;
            public List<DeviceItem> Datas = new List<DeviceItem>();
        }
        private object ImportDevices()
        {
            try
            {
                int count = 0;
                var session = GetCurrentLoginSession();
                ImportResult result = new ImportResult();
                if (session != null)
                {
                    string p = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                    string contractorID = HttpUtility.HtmlDecode(Request.Form["ContractorID"]);
                    bool getData = Convert.ToBoolean(HttpUtility.HtmlDecode(Request.Form["Get"]));
                    string selected = HttpUtility.HtmlDecode(Request.Form["SelectedData"]);
                    StringKeyValue[] kvs = JsonConvert.DeserializeObject<StringKeyValue[]>(p);
                    HttpPostedFile uploadFile = null;

                    byte[] iconfilebyte = null;
                    if (Request.Files.Count > 0)
                    {
                        uploadFile = Request.Files[0];
                        iconfilebyte = ConvertFile2bytes(uploadFile);
                    }

                    if (iconfilebyte != null)
                    {
                        if (!CheckRight(SystemParams.CompanyID, Feature.MANAGE_DEVICES))
                            return 0;
                        DataTable dt = new ImportFromExcel().LoadExcelData(iconfilebyte);
                        string customerid = string.Empty;
                        if (SystemParams.IsDealer)
                        {
                            customerid = contractorID;
                        }
                        else
                        {
                            customerid = SystemParams.CompanyID;
                        }
                        AssetDataAdjustClient client = CreateClient<AssetDataAdjustClient>(customerid);

                        if (dt != null && dt.Rows.Count > 0)
                        {
                            List<string> sels = new List<string>();
                            if (!string.IsNullOrEmpty(selected))
                            {
                                string[] ss = selected.Split(',');
                                sels = ss.ToList();
                            }
                            int index = 0;
                            foreach (DataRow dr in dt.Rows)
                            {
                                if (!getData && sels.Count > 0 && sels.Count >= index + 1 && (sels[index] == "false"))
                                {
                                    index++;
                                    continue;
                                }
                                index++;
                                DeviceItem deviceitem = null;
                                try
                                {
                                    deviceitem = ConvertToDeviceItem(dr, kvs, client, customerid, session.User.UserType == Foresight.Fleet.Services.User.UserTypes.SupperAdmin);
                                    if (!getData)
                                    {
                                        if (string.IsNullOrEmpty(deviceitem.SerialNumber)
                                        || string.IsNullOrEmpty(deviceitem.Source))
                                        {
                                            result.Datas.Add(deviceitem);
                                            continue;
                                        }
                                        if (deviceitem.DeviceType == "ATU-RB-8")
                                            deviceitem.Source = "DigitalMatter";
                                        if (new string[] { "nimbelink", "digitalmatter" }.Contains(deviceitem.Source, StringComparer.OrdinalIgnoreCase) && string.IsNullOrEmpty(deviceitem.DeviceType))
                                        {
                                            result.Datas.Add(deviceitem);
                                            continue;
                                        }
                                        deviceitem.ContractorID = customerid;
                                        if (string.IsNullOrWhiteSpace(deviceitem.ContractorID))
                                            deviceitem.ContractorID = SystemParams.CompanyID;

                                        FFSDevice.DeviceInfo device = new FFSDevice.DeviceInfo();
                                        Helper.CloneProperty(device, deviceitem);
                                        if (deviceitem.PairedAsset != null && deviceitem.PairedAsset.Id > 0)
                                            device.PairedAsset = new PairedAssetInfo() { Id = deviceitem.PairedAsset.Id, VIN = deviceitem.PairedAsset.VIN };

                                        DeviceProvider deviceprovider = CreateClient<DeviceProvider>(deviceitem.ContractorID);
                                        var existeddevice = deviceprovider.GetDevicesBySN(deviceitem.ContractorID, device.Source, device.SerialNumber);
                                        if (existeddevice != null && existeddevice.Id > 0)
                                        {
                                            device.Id = existeddevice.Id;
                                            device.AlternativeSerialNumber = existeddevice.AlternativeSerialNumber;
                                            deviceprovider.UpdateDevice(deviceitem.ContractorID, device);
                                        }
                                        else
                                            device = deviceprovider.AddNewDevice(deviceitem.ContractorID, device);

                                        DevicePairingInfo devicepairing = new DevicePairingInfo();
                                        devicepairing.Notes = deviceitem.Notes;
                                        if (session.User.UserType == Foresight.Fleet.Services.User.UserTypes.SupperAdmin)
                                        {
                                            devicepairing.InstallerName = deviceitem.Installer;
                                            devicepairing.FIInstalltion = deviceitem.FIInstalltion;
                                        }
                                        else
                                        {
                                            devicepairing.FIInstalltion = false;
                                        }

                                        if (deviceitem.PairedAsset != null && deviceitem.PairedAsset.Id > 0)
                                            deviceprovider.PairAsset(deviceitem.ContractorID, device.Id, deviceitem.PairedAsset.Id, devicepairing);

                                        count++;
                                    }
                                    else
                                    {
                                        result.Datas.Add(deviceitem);
                                    }
                                }
                                catch (Exception e)
                                {
                                    if (deviceitem != null)
                                    {
                                        result.Datas.Add(deviceitem);
                                    }
                                }
                            }

                        }
                    }
                    if (!getData)
                    {
                        result.Count = count;
                    }
                }

                return JsonConvert.SerializeObject(result);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        KeyValuePair<string, string>[] source = null;
        private DeviceItem ConvertToDeviceItem(DataRow dr, StringKeyValue[] kvs, AssetDataAdjustClient client, string contractorID, bool isSuperAdmin)
        {
            DeviceItem device = new DeviceItem();
            device.Source = "";
            device.SourceName = "";
            device.DeviceType = "";
            foreach (StringKeyValue kv in kvs)
            {
                if (string.IsNullOrEmpty(kv.Key) || string.IsNullOrEmpty(kv.Value))
                {
                    continue;
                }
                if (dr[kv.Value] == DBNull.Value || dr[kv.Value] == null)
                {
                    continue;
                }
                if (string.Compare(kv.Key, "SN", true) == 0)
                {
                    var s = dr[kv.Value].ToString().Trim();
                    device.SerialNumber = s;
                }
                else if (string.Compare(kv.Key, "ESN", true) == 0)
                {
                    switch (device.Source.ToLower())
                    {
                        case "calamp":
                            device.AlternativeSerialNumber = dr[kv.Value].ToString().Trim();
                            break;
                        default:
                            device.AlternativeSerialNumber = "";
                            break;
                    }
                }
                else if (string.Compare(kv.Key, "DeviceType", true) == 0)
                {
                    switch (device.Source.ToLower())
                    {
                        case "nimbelink":
                            string t = dr[kv.Value].ToString().Trim();
                            switch (t.ToUpper())
                            {
                                case "ATU-RB-1":
                                case "ATU-RB-5":
                                case "ATU-RB-6":
                                case "ATU-RB-8":
                                case "ATU-RB-10":
                                    device.DeviceType = t;
                                    break;
                                default:
                                    device.DeviceType = "";
                                    break;
                            }
                            break;
                        default:
                            device.DeviceType = dr[kv.Value].ToString().Trim();
                            break;
                    }
                }
                else if (string.Compare(kv.Key, "Source", true) == 0)
                {
                    if (source == null)
                    {
                        source = FFSDevice.DeviceInfo.DEVICESES;
                        source = source.Where(t => t.Key != "DigitalMatter").ToArray();
                    }
                    var s = dr[kv.Value].ToString().Trim();
                    device.Source = "";
                    device.SourceName = "";
                    foreach (var k in source)
                    {
                        if (k.Value.Equals(s, StringComparison.OrdinalIgnoreCase))
                        {
                            device.Source = k.Key;
                            device.SourceName = k.Value;
                            break;
                        }
                    }
                }
                else if (string.Compare(kv.Key, "Status", true) == 0)
                {
                    var s = dr[kv.Value].ToString().Trim();
                    if (string.IsNullOrEmpty(s))
                    {
                        device.Status = 0;
                    }
                    else
                    {
                        if (s.Equals("Active", StringComparison.OrdinalIgnoreCase))
                        {
                            device.Status = 1;
                        }
                        else if (s.Equals("Inactive", StringComparison.OrdinalIgnoreCase))
                        {
                            device.Status = 0;
                        }
                        else
                        {
                            if (Helper.IsTrue(s))
                            {
                                device.Status = 1;
                            }
                            else
                            {
                                device.Status = 0;
                            }
                        }
                    }
                }
                else if (string.Compare(kv.Key, "InvoiceDate", true) == 0)
                {
                    var s = dr[kv.Value].ToString().Trim();
                    if (!string.IsNullOrEmpty(s))
                    {
                        device.InvoiceDate = Convert.ToDateTime(s);
                    }
                }
                else if (string.Compare(kv.Key, "ServiceStartDate", true) == 0)
                {
                    var s = dr[kv.Value].ToString().Trim();
                    if (!string.IsNullOrEmpty(s))
                    {
                        device.ServiceStartDate = Convert.ToDateTime(s);
                    }
                }
                else if (string.Compare(kv.Key, "InvoiceNumber", true) == 0)
                {
                    device.InvoiceNumber = dr[kv.Value].ToString().Trim();
                }
                else if (string.Compare(kv.Key, "TamperAlerts", true) == 0)
                {
                    switch (device.Source.ToLower())
                    {
                        case "nimbelink":
                            if (device.DeviceType.ToUpper() == "ATU-RB-8")
                                device.Tamper = false;
                            else
                            {
                                string t = dr[kv.Value].ToString().Trim();
                                device.Tamper = Helper.IsTrue(t);
                            }
                            break;
                        default:
                            device.Tamper = false;
                            break;
                    }
                }
                else if (string.Compare(kv.Key, "Notes", true) == 0)
                {
                    device.Notes = dr[kv.Value].ToString().Trim();
                }
                else if (string.Compare(kv.Key, "VIN/SN", true) == 0)
                {
                    var s = dr[kv.Value].ToString().Trim();
                    if (!string.IsNullOrEmpty(s))
                    {
                        long[] dupassets = client.FindAssetsByVIN(contractorID, s);
                        if (dupassets != null && dupassets.Length > 0)
                        {
                            device.PairedAsset = new PairedAssetItem() { Id = dupassets[0], VIN = s };
                        }
                    }
                }
                else if (string.Compare(kv.Key, "Utilization", true) == 0)
                {
                    switch (device.Source.ToLower())
                    {
                        case "nimbelink":
                            string t = dr[kv.Value].ToString().Trim();
                            switch (device.DeviceType.ToUpper())
                            {
                                case "ATU-RB-5":
                                case "ATU-RB-6":
                                    device.Utilization = Helper.IsTrue(t);
                                    break;
                                default:
                                    device.Utilization = false;
                                    break;
                            }
                            break;
                        default:
                            device.Utilization = false;
                            break;
                    }
                }
                else if (string.Compare(kv.Key, "FIInstallation", true) == 0)
                {
                    if (isSuperAdmin)
                    {
                        device.FIInstalltion = Helper.IsTrue(dr[kv.Value].ToString().Trim());
                    }
                }
                else if (string.Compare(kv.Key, "Installer", true) == 0)
                {
                    if (isSuperAdmin)
                    {
                        device.Installer = dr[kv.Value].ToString().Trim();
                    }
                }
                else if (string.Compare(kv.Key, "SalesOrderNumber", true) == 0)
                {
                    if (isSuperAdmin)
                    {
                        device.SalesOrderNumber = dr[kv.Value].ToString().Trim();
                    }
                }
            }
            return device;
        }


        Dictionary<string, int> makeDic = null;
        Dictionary<string, int> typeDic = null;
        Dictionary<int, Dictionary<string, int>> modelDic = null;
        Dictionary<string, string> atDic = null;

        private AssetDetailInfo2 ConvertToAssetItem(DataRow dr, StringKeyValue[] kvs, string uid, bool getData, bool isSuperAdmin)
        {
            AssetDetailInfo2 asset = new AssetDetailInfo2();
            asset.MakeID = -1;
            asset.ModelID = -1;
            asset.MakeYear = -1;
            //asset.Odometer = -1;
            //asset.EngineHours = -1;
            foreach (StringKeyValue kv in kvs)
            {
                if (string.IsNullOrEmpty(kv.Key) || string.IsNullOrEmpty(kv.Value))
                {
                    continue;
                }
                if (dr[kv.Value] == DBNull.Value || dr[kv.Value] == null)
                {
                    continue;
                }

                if (string.Compare(kv.Key, "VIN/SN", true) == 0)
                {
                    asset.VIN = dr[kv.Value].ToString().Trim();
                }
                else if (string.Compare(kv.Key, "Asset Name", true) == 0)
                {
                    asset.Name = dr[kv.Value].ToString().Trim();
                }
                else if (string.Compare(kv.Key, "Asset Name(Custom)", true) == 0)
                {
                    asset.Name2 = dr[kv.Value].ToString().Trim();
                }
                else if (string.Compare(kv.Key, "Year", true) == 0)
                {
                    string year = dr[kv.Value].ToString().Trim();
                    if (string.IsNullOrEmpty(year))
                    {
                        asset.MakeYear = -1;
                    }
                    else
                    {
                        asset.MakeYear = Helper.ConvertToInt32(year, -1);
                    }

                }
                else if (string.Compare(kv.Key, "Make", true) == 0)
                {
                    string m = dr[kv.Value].ToString().Trim();

                    if (makeDic == null)
                    {
                        AssetMake[] makes = CreateClient<AssetClassProvider>().GetAssetMakes("");
                        makeDic = new Dictionary<string, int>();
                        if (makes != null && makes.Length > 0)
                        {
                            foreach (var d in makes)
                            {
                                if (makeDic.ContainsKey(d.Name.ToLower()))
                                {
                                    makeDic[d.Name.ToLower()] = d.ID;
                                }
                                else
                                {
                                    makeDic.Add(d.Name.ToLower(), d.ID);
                                }
                            }
                        }
                    }

                    if (makeDic.ContainsKey(m.ToLower()))
                    {
                        asset.MakeID = makeDic[m.ToLower()];
                        asset.MakeName = m;
                    }
                    else
                    {
                        if (!getData)
                        {
                            AssetMake am = CreateClient<AssetClassProvider>().UpdateOrCreateMake(0, m, uid);
                            makeDic.Add(m.ToLower(), am.ID);
                            asset.MakeID = am.ID;
                            asset.MakeName = m;
                        }
                        else
                        {
                            asset.MakeName = m;
                        }
                    }
                }
                else if (string.Compare(kv.Key, "Model", true) == 0)
                {
                    string m = dr[kv.Value].ToString().Trim();

                    if (modelDic == null)
                    {
                        modelDic = new Dictionary<int, Dictionary<string, int>>();
                    }

                    if (!modelDic.ContainsKey(asset.MakeID))
                    {
                        AssetModel[] models = CreateClient<AssetClassProvider>().GetAssetModels(asset.MakeID, "");
                        Dictionary<string, int> mDic = new Dictionary<string, int>();

                        if (models != null && models.Length > 0)
                        {
                            foreach (var d in models)
                            {
                                if (mDic.ContainsKey(d.Name.ToLower()))
                                {
                                    mDic[d.Name.ToLower()] = d.ID;
                                }
                                else
                                {
                                    mDic.Add(d.Name.ToLower(), d.ID);
                                }
                            }
                        }
                        modelDic.Add(asset.MakeID, mDic);
                    }

                    if (modelDic.ContainsKey(asset.MakeID) && modelDic[asset.MakeID].ContainsKey(m.ToLower()))
                    {
                        asset.ModelID = modelDic[asset.MakeID][m.ToLower()];
                        asset.ModelName = m;
                    }
                    else
                    {
                        if (!getData)
                        {
                            AssetModel am = CreateClient<AssetClassProvider>().UpdateOrCreateModel(asset.MakeID, 0, m, asset.TypeID, uid);
                            modelDic[asset.MakeID].Add(m.ToLower(), am.ID);
                            asset.ModelID = am.ID;
                            asset.ModelName = m;
                        }
                        else
                        {
                            asset.ModelName = m;
                        }
                    }
                }
                else if (string.Compare(kv.Key, "Eq.Class", true) == 0)
                {
                    asset.EQClass = dr[kv.Value].ToString().Trim();
                }
                else if (string.Compare(kv.Key, "Hide/Hidden", true) == 0)
                {
                    asset.Hidden = Helper.IsTrue(dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "On-Road", true) == 0)
                {
                    asset.OnRoad = Helper.IsTrue(dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "Telematics Enabled", true) == 0)
                {
                    asset.TelematicsEnabled = Helper.IsTrue(dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "Attachment", true) == 0)
                {
                    asset.Attachment = Helper.IsTrue(dr[kv.Value].ToString());
                }
                else if (string.Compare(kv.Key, "Preloaded", true) == 0)
                {
                    if (isSuperAdmin)
                    {
                        asset.Preloaded = Helper.IsTrue(dr[kv.Value].ToString());
                    }
                }
                else if (string.Compare(kv.Key, "Asset Type", true) == 0)
                {
                    string m = dr[kv.Value].ToString().Trim();
                    if (!string.IsNullOrEmpty(m))
                    {
                        if (typeDic == null)
                        {
                            AssetType[] types = CreateClient<AssetClassProvider>().GetAssetTypes(SystemParams.CompanyID);
                            typeDic = new Dictionary<string, int>();
                            if (types != null && types.Length > 0)
                            {
                                foreach (var d in types)
                                {
                                    if (typeDic.ContainsKey(d.Name.ToLower()))
                                    {
                                        typeDic[d.Name.ToLower()] = d.ID;
                                    }
                                    else
                                    {
                                        typeDic.Add(d.Name.ToLower(), d.ID);
                                    }
                                }
                            }
                        }

                        if (typeDic.ContainsKey(m.ToLower()))
                        {
                            asset.TypeID = typeDic[m.ToLower()];
                            asset.TypeName = m;
                        }
                        else
                        {
                            asset.TypeID = -1;
                            asset.TypeName = "";
                        }
                    }
                    else
                    {
                        asset.TypeID = -1;
                    }
                }
                else if (string.Compare(kv.Key, "Description", true) == 0)
                {
                    asset.Description = dr[kv.Value].ToString().Trim();
                }
                else if (string.Compare(kv.Key, "Odometer", true) == 0)
                {
                    string eh = dr[kv.Value].ToString().Trim();
                    if (string.IsNullOrEmpty(eh) || eh == "0")
                    {
                        asset.Odometer = null;
                        asset.OdometerUnits = "";
                    }
                    else
                    {
                        asset.Odometer = Helper.ConvertToDouble(eh);
                    }
                }
                else if (string.Compare(kv.Key, "Acquisition Type", true) == 0)
                {
                    string at = dr[kv.Value].ToString().Trim();
                    if (atDic == null)
                    {
                        atDic = new Dictionary<string, string>();
                        atDic.Add("Rental".ToLower(), "Rental");
                        atDic.Add("Rerent".ToLower(), "Rerent");
                        atDic.Add("RPO".ToLower(), "RPO");
                        atDic.Add("Leased".ToLower(), "Leased");
                        atDic.Add("Owned - Purchase".ToLower(), "Owned - Purchase");
                        atDic.Add("Owned - Lease".ToLower(), "Owned - Lease");
                    }

                    if (atDic.ContainsKey(at.ToLower()))
                    {
                        asset.AquisitionType = atDic[at.ToLower()];
                    }
                }
                else if (string.Compare(kv.Key, "Cost Center", true) == 0)
                {
                    asset.CostCenter = dr[kv.Value].ToString().Trim();
                }
            }

            if (asset.MakeID == -1)
            {
                if (!getData)
                {
                    if (makeDic == null)
                    {
                        AssetMake[] makes = CreateClient<AssetClassProvider>().GetAssetMakes("");
                        makeDic = new Dictionary<string, int>();
                        if (makes != null && makes.Length > 0)
                        {
                            foreach (var d in makes)
                            {
                                if (makeDic.ContainsKey(d.Name.ToLower()))
                                {
                                    makeDic[d.Name.ToLower()] = d.ID;
                                }
                                else
                                {
                                    makeDic.Add(d.Name.ToLower(), d.ID);
                                }
                            }
                        }
                    }

                    if (makeDic.ContainsKey(""))
                    {
                        asset.MakeID = makeDic[""];
                        asset.MakeName = "";
                    }
                }
            }
            if (asset.ModelID == -1)
            {
                if (!getData)
                {
                    if (modelDic == null)
                    {
                        modelDic = new Dictionary<int, Dictionary<string, int>>();
                    }

                    if (!modelDic.ContainsKey(asset.MakeID))
                    {
                        AssetModel[] models = CreateClient<AssetClassProvider>().GetAssetModels(asset.MakeID, "");
                        Dictionary<string, int> mDic = new Dictionary<string, int>();

                        if (models != null && models.Length > 0)
                        {
                            foreach (var d in models)
                            {
                                if (mDic.ContainsKey(d.Name.ToLower()))
                                {
                                    mDic[d.Name.ToLower()] = d.ID;
                                }
                                else
                                {
                                    mDic.Add(d.Name.ToLower(), d.ID);
                                }
                            }
                        }
                        modelDic.Add(asset.MakeID, mDic);
                    }

                    if (modelDic.ContainsKey(asset.MakeID) && modelDic[asset.MakeID].ContainsKey(""))
                    {
                        asset.ModelID = modelDic[asset.MakeID][""];
                        asset.ModelName = "";
                    }
                }

            }
            return asset;
        }
        public class ImportAssertResult
        {
            public int Count = -1;
            public List<AssetDetailInfo2> Datas = new List<AssetDetailInfo2>();
        }

        private object ImportMachines()
        {
            try
            {
                int count = 0;
                var session = GetCurrentLoginSession();
                ImportAssertResult result = new ImportAssertResult();
                if (session != null)
                {
                    string p = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                    string contractorID = HttpUtility.HtmlDecode(Request.Form["ContractorID"]);
                    bool getData = Convert.ToBoolean(HttpUtility.HtmlDecode(Request.Form["Get"]));
                    string selected = HttpUtility.HtmlDecode(Request.Form["SelectedData"]);
                    StringKeyValue[] kvs = JsonConvert.DeserializeObject<StringKeyValue[]>(p);
                    HttpPostedFile uploadFile = null;
                    byte[] iconfilebyte = null;
                    if (Request.Files.Count > 0)
                    {
                        uploadFile = Request.Files[0];
                        iconfilebyte = ConvertFile2bytes(uploadFile);
                    }

                    if (iconfilebyte != null)
                    {
                        if (SystemParams.IsDealer && string.IsNullOrWhiteSpace(contractorID))
                            return 0;

                        string connectionStr = string.Empty;
                        string customerid = string.Empty;
                        if (SystemParams.IsDealer)
                        {
                            string connetionstring = SystemParams.GetDbStringByCompany(contractorID);
                            connectionStr = connetionstring;
                            customerid = contractorID;
                        }
                        else
                        {
                            connectionStr = SystemParams.DataDbConnectionString;
                            customerid = SystemParams.CompanyID;
                        }
                        DataTable dt = new ImportFromExcel().LoadExcelData(iconfilebyte);


                        if (dt != null && dt.Rows.Count > 0)
                        {
                            List<string> sels = new List<string>();
                            if (!string.IsNullOrEmpty(selected))
                            {
                                string[] ss = selected.Split(',');
                                sels = ss.ToList();
                            }
                            int index = 0;
                            foreach (DataRow dr in dt.Rows)
                            {
                                if (!getData && sels.Count > 0 && sels.Count >= index + 1 && (sels[index] == "false"))
                                {
                                    index++;
                                    continue;
                                }
                                index++;
                                AssetDetailInfo2 asset = null;
                                try
                                {
                                    asset = ConvertToAssetItem(dr, kvs, session.User.UID, getData, session.User.UserType == Foresight.Fleet.Services.User.UserTypes.SupperAdmin);
                                    if (!getData)
                                    {
                                        AssetDataAdjustClient client = CreateClient<AssetDataAdjustClient>(customerid);
                                        if (string.IsNullOrEmpty(asset.VIN))
                                        {
                                            result.Datas.Add(asset);
                                            continue;
                                        }
                                        if (asset.MakeID == -1 || asset.ModelID == -1)
                                        {
                                            result.Datas.Add(asset);
                                            continue;
                                        }
                                        long dupassets = client.FindAsset(customerid, asset.VIN, asset.MakeName, asset.ModelName);
                                        if (dupassets > 0)
                                        {
                                            result.Datas.Add(asset);
                                            continue;
                                        }
                                        asset.ID = client.UpdateAssetInfo(customerid, asset, null, null, session.User.UID);
                                        CreateClient<JobSiteProvider>(customerid).AddAssetToJobSites(customerid, null, asset.ID, asset.VIN);
                                        count++;
                                    }
                                    else
                                    {
                                        result.Datas.Add(asset);
                                    }
                                }
                                catch (Exception e)
                                {
                                    if (asset != null)
                                    {
                                        result.Datas.Add(asset);
                                    }
                                }
                            }
                        }
                    }
                    if (!getData)
                    {
                        result.Count = count;
                    }
                }
                return JsonConvert.SerializeObject(result);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }


        }


        #region Device Paring Info

        private object GetDevicePairingLogsByDevice()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string data = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(data);
                    string contractorid = ps[0];
                    if (string.IsNullOrEmpty(contractorid))
                        contractorid = SystemParams.CompanyID;
                    long deviceid = Convert.ToInt64(ps[1]);
                    string searchtxt = ps[2];

                    DevicePairingLog[] logs = CreateClient<DeviceProvider>(contractorid).GetDevicePairingLogsByDevice(contractorid, deviceid, searchtxt);
                    if (logs == null)
                        return new DevicePairingLogItem[0];

                    List<DevicePairingLogItem> list = new List<DevicePairingLogItem>();
                    foreach (var log in logs)
                    {
                        DevicePairingLogItem logitem = new DevicePairingLogItem();
                        Helper.CloneProperty(logitem, log);
                        list.Add(logitem);
                    }

                    return list.ToArray();
                }
                else
                {
                    return new DevicePairingLogItem[0];
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetDevicePairingLogsByAsset()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string data = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(data);
                    string contractorid = ps[0];
                    if (string.IsNullOrEmpty(contractorid))
                        contractorid = SystemParams.CompanyID;
                    long assetid = Convert.ToInt64(ps[1]);
                    string searchtxt = ps[2];

                    DevicePairingLog[] logs = CreateClient<DeviceProvider>(contractorid).GetDevicePairingLogsByAsset(contractorid, assetid, searchtxt);
                    if (logs == null)
                        return new DevicePairingLogItem[0];

                    List<DevicePairingLogItem> list = new List<DevicePairingLogItem>();
                    foreach (var log in logs)
                    {
                        DevicePairingLogItem logitem = new DevicePairingLogItem();
                        Helper.CloneProperty(logitem, log);
                        list.Add(logitem);
                    }

                    return list.ToArray();
                }
                else
                {
                    return new DevicePairingLogItem[0];
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetPairingSignature()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string data = Request.Params["ClientData"];
                    long pairinglogid = Convert.ToInt64(HttpUtility.HtmlDecode(data));
                    byte[] bytedata = CreateClient<DeviceProvider>(session.User.UID).GetPairingSignature(pairinglogid);
                    return bytedata;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetPairingAttachments()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string data = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(data);
                    string contractorid = ps[0];
                    if (string.IsNullOrEmpty(contractorid))
                        contractorid = SystemParams.CompanyID;
                    long pairinglogid = Convert.ToInt64(HttpUtility.HtmlDecode(ps[1]));
                    DevicePairingAttachmentItem[] atts = CreateClient<DeviceProvider>(contractorid).GetPairingAttachments(pairinglogid);
                    if (atts == null)
                        return new DevicePairingAttachmentItem[0];

                    return atts;
                }
                else
                {
                    return new DevicePairingAttachmentItem[0];
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion

        private class MachineGroupInfoItem
        {
            public MachineItem[] AllMachines { get; set; }
            public MachineItem[] Machines { get; set; }
        }

        public class AssetSummaryItem : AssetSummaryInfo
        {
            public string TimeZoneAbbreviation { get; set; }
            public string OdometerAsofTimeLocalStr { get { return (Odometer == null || Odometer.AsofTimeLocal == null || Odometer.AsofTimeLocal == DateTime.MinValue) ? "" : Odometer.AsofTimeLocal.ToString("M/d/yyyy h:mm:ss tt"); } }
            public bool IsOdometerRed
            {
                get
                {
                    bool result = false;
                    if (Odometer != null && Odometer.AsofTimeLocal != null && Odometer.AsofTimeLocal != DateTime.MinValue
                        && Odometer.AsofTimeLocal < DateTime.Now.AddDays(-3))
                        result = true;

                    return result;
                }
            }
            public string EngineHoursAsofTimeLocalStr { get { return (EngineHours == null || EngineHours.AsofTimeLocal == null || EngineHours.AsofTimeLocal == DateTime.MinValue) ? "" : EngineHours.AsofTimeLocal.ToString("M/d/yyyy h:mm:ss tt"); } }
            public bool IsEngineHoursRed
            {
                get
                {
                    bool result = false;
                    if (EngineHours != null && EngineHours.AsofTimeLocal != null && EngineHours.AsofTimeLocal != DateTime.MinValue
                        && EngineHours.AsofTimeLocal < DateTime.Now.AddDays(-3))
                        result = true;

                    return result;
                }
            }

            public string LocationAsofTimeLocalStr { get { return (Location == null || Location.AsofTimeLocal == null || Location.AsofTimeLocal == DateTime.MinValue) ? "" : Location.AsofTimeLocal.ToString("M/d/yyyy h:mm:ss tt"); } }
            public bool IsLocationRed
            {
                get
                {
                    bool result = false;
                    if (Location != null && Location.AsofTimeLocal != null && Location.AsofTimeLocal != DateTime.MinValue
                        && Location.AsofTimeLocal < DateTime.Now.AddDays(-3))
                        result = true;

                    return result;
                }
            }
            public string LocationAddress
            {
                get
                {
                    return Location?.Address;
                }
            }
        }
        public class AssetExtItem : AssetExtInfo
        {
            public AssetAlertItem[] AlertItems { get; set; }
            public AssetPMPlanItem[] PMPlanItems { get; set; }
            public AssetMaintenanceRecordItem MaintenanceRecordItem { get; set; }
            public AssetStatusItem[] AssetStatusItems { get; set; }
            public string CommitTimeStr { get { return (InspectReportItem == null || InspectReportItem.CommitTime == null || InspectReportItem.CommitTime == DateTime.MinValue) ? "" : InspectReportItem.CommitTime.ToString("M/d/yyyy"); } }
            public string LastUpdatedTimeStr { get { return (InspectReportItem == null || InspectReportItem.LastUpdatedTime == null || InspectReportItem.LastUpdatedTime == DateTime.MinValue) ? "" : InspectReportItem.LastUpdatedTime.ToString("M/d/yyyy"); } }
        }

        public class AssetAlertItem : AssetAlertsInfo
        {
            public string AlertLocalDateStr { get { return (AlertLocalTime == null || AlertLocalTime == null || AlertLocalTime == DateTime.MinValue) ? "" : AlertLocalTime.ToString("M/d/yyyy"); } }
            public string AlertLocalTimeStr { get { return (AlertLocalTime == null || AlertLocalTime == null || AlertLocalTime == DateTime.MinValue) ? "" : AlertLocalTime.ToString("h:mm:ss tt"); } }
        }

        public class AssetPMPlanItem : AssetPMPlanInfo
        {
            public string NextPlan
            {
                get
                {
                    return string.Format("{0:#,##0.##} {1} {2}", Math.Abs(DueIn), FormatUOM(), DueIn < 0 ? "OVERDUE" : "");
                }
            }
            public string NextPlanDetail
            {
                get
                {
                    if (UOM.Equals("Days", StringComparison.OrdinalIgnoreCase))
                    {
                        if (DueIn >= 0)
                            return string.Format("{0} due in {1} {2} ({3})", AlertTime.AddDays(DueIn).ToShortDateString(), Math.Abs(DueIn), FormatUOM(), ServiceName);
                        else
                            return string.Format("{0} overdue {1} {2} ({3})", AlertTime.AddDays(DueIn).ToShortDateString(), Math.Abs(DueIn), FormatUOM(), ServiceName);
                    }
                    else
                    {
                        if (DueIn >= 0)
                            return string.Format("{0:#,##0.##} {2} due in {1} {2} ({3})", DueAt, Math.Abs(DueIn), FormatUOM(), ServiceName);
                        else
                            return string.Format("{0:#,##0.##} {2} overdue {1} {2} ({3})", DueAt, Math.Abs(DueIn), FormatUOM(), ServiceName);
                    }
                }
            }

            private string FormatUOM()
            {
                if (UOM.StartsWith("K", StringComparison.OrdinalIgnoreCase)
                    || UOM.StartsWith("M", StringComparison.OrdinalIgnoreCase))
                    return UOM + "s";
                return UOM;
            }

            public bool LastAlertUnAddressed
            {
                get
                {
                    return LastAlertID > 0 && (string.IsNullOrEmpty(LastMaintenanceValue) || LastMaintenanceValue == "0");
                }
            }

        }
        public class AssetMaintenanceRecordItem
        {
            public string ID { get; set; }
            public long AssetID { get; set; }
            public double? Hours { get; set; }
            public double? Odometer { get; set; }
            public string OdometerUom { get; set; }
            public DateTime CompetedTime { get; set; }
            public DateTime CompetedLocalTime { get; set; }
            public string CompetedLocalTimeStr { get { return (CompetedLocalTime == null || CompetedLocalTime == DateTime.MinValue) ? "" : CompetedLocalTime.ToString("M/d/yyyy"); } }

            public DateTime AlertTime { get; set; }
            public string AlertType { get; set; }
            public double? AlertHours { get; set; }
            public double? AlertOdometer { get; set; }
            public string CompletedByUserIID { get; set; }
            public string CompletedByUserName { get; set; }
            public string PMPlanName { get; set; }
            public string LastCompletedText
            {
                get
                {
                    string txt = "";
                    if (AlertType == "PM_ALERT" || AlertType == "HM_ALERT")
                    {
                        //txt = string.Format("{0} Hours at {1} on {2} by {3}", AlertHours, Hours, CompetedLocalTimeStr, string.IsNullOrEmpty(CompletedByUserName) ? "N/A" : CompletedByUserName);

                        txt = string.Format("Completed {0} Hour plan at {1} Hours on {2} by {3}", Hours, AlertHours, CompetedLocalTimeStr, string.IsNullOrEmpty(CompletedByUserName) ? "N/A" : CompletedByUserName);
                    }
                    else if (AlertType == "TBM_ALERT")
                    {
                        //txt = string.Format("{0} ({1}) by {2}", CompetedLocalTimeStr, PMPlanName, string.IsNullOrEmpty(CompletedByUserName) ? "N/A" : CompletedByUserName);

                        //Completed (plan) on date by User. 
                        txt = string.Format("Completed ({0}) on {1} by {2}", PMPlanName, CompetedLocalTimeStr, string.IsNullOrEmpty(CompletedByUserName) ? "N/A" : CompletedByUserName);
                    }
                    else
                    {
                        //txt = string.Format("{0} {1} at {2} on {3} by {4}", AlertOdometer, OdometerUom, Odometer, CompetedLocalTimeStr, string.IsNullOrEmpty(CompletedByUserName) ? "N/A" : CompletedByUserName);

                        txt = string.Format("Completed {0} {2} plan at {1} {3} on {4} by {5}", Odometer, AlertOdometer,
                           DistanceNumber.DetermineDistanceUnits(OdometerUom) == DistanceUnits.Miles ? "Mile" : "Kilometer",
                           DistanceNumber.DetermineDistanceUnits(OdometerUom) == DistanceUnits.Miles ? "Miles" : "Kilometers"
                            , CompetedLocalTimeStr, string.IsNullOrEmpty(CompletedByUserName) ? "N/A" : CompletedByUserName);
                    }
                    return txt;
                }
            }
        }

        public class AssetStatusItem
        {
            public long AssetID { get; set; }
            public long AttributeID { get; set; }
            public string AttributeName { get; set; }
            public string Result { get; set; }
            public DateTime EventTime { get; set; }
            public DateTime EventLocalTime { get; set; }
            public string EventLocalTimeStr { get { return (EventLocalTime == null || EventLocalTime == DateTime.MinValue) ? "" : EventLocalTime.ToString("M/d/yyyy"); } }

        }
    }

    public class AssetDocumentItem : AssetDocumentInfo
    {
        public string CustomerID { get; set; }
        public long AssetID { get; set; }
        public string AddedOnLocalStr { get { return (AddedOnLocal == null || AddedOnLocal == DateTime.MinValue) ? "" : AddedOnLocal.ToString(); } }

    }

    public class DevicePairingLogItem : DevicePairingLog
    {
        public string InstallTime_LocalStr { get { return (InstallTime_Local == null || InstallTime_Local == DateTime.MinValue) ? "" : InstallTime_Local.ToString(); } }
    }

}
