using Foresight.Data;
using Foresight.Fleet.Services;
using Foresight.Fleet.Services.Asset;
using Foresight.Fleet.Services.AssetHealth;
using Foresight.Fleet.Services.Device;
using Foresight.Fleet.Services.JobSite;
using Foresight.Fleet.Services.User;
using IronIntel.Contractor.Machines;
using IronIntel.Contractor.Maintenance;
using IronIntel.Contractor.Users;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Foresight.Standard;
using Foresight.Fleet.Services.Customer;
using Foresight.Fleet.Services.AssetHealth.WorkOrder;
using IronIntel.Contractor.Site.Maintenance;
using System.Drawing;

namespace IronIntel.Contractor.Site.Asset
{
    public class AssetBasePage : ContractorBasePage
    {
        protected void ProcessRequest(string method)
        {
            object result = null;
            string methodName = Request.Params["MethodName"];
            try
            {
                if (methodName != null)
                {
                    switch (methodName.ToUpper())
                    {
                        case "GETMACHINESBYCOMPANY":
                            result = GetMachinesByCompany();
                            break;
                        case "GETMACHINEINFO":
                            result = GetMachineInfo();
                            break;
                        case "SAVEMACHINE":
                            result = SaveMachine();
                            break;
                        case "CHANGEMACHINEICONFILE":
                            result = ChangeMachineIconFile();
                            break;
                        case "GETMACHINEATTRIBUTES":
                            result = GetMachineAttributes();
                            break;
                        case "GETCUSTOMERTIMEZONE":
                            result = GetCustomerTimeZone();
                            break;
                        case "GETODOMETERADJUSTMENTHISTORY":
                            result = GetOdometerAdjustmentHistory();
                            break;
                        case "GETENGINEHOURSADJUSTMENTHISTORY":
                            result = GetEngineHoursAdjustmentHistory();
                            break;
                        case "GETPMSCHEDULESBYASSET":
                            result = GetPMSchedulesByAsset();
                            break;
                        case "ADDASSETTOPMSCHEDULE":
                            result = AddAssetToPMSchedule();
                            break;
                        case "REMOVEASSETFROMPMSCHEDULE":
                            result = RemoveAssetFromPMSchedule();
                            break;
                        case "CHANGEASSETPROPERTY":
                            result = ChangeAssetProperty();
                            break;
                        case "GETASSETATTACHMENTINFO":
                            result = GetAssetAttachmentInfo();
                            break;
                        case "DELETEASSETS":
                            result = DeleteAssets();
                            break;
                        case "MERGEASSET":
                            result = MergeAsset();
                            break;
                        case "GETASSETDATASOURCES":
                            result = GetAssetDatasources();
                            break;
                        case "GETASSETS":
                            result = GetAssets();
                            break;
                        case "GETASSETHISTORYS":
                            result = GetAssetHistorys();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "AssetBasePage", ex.Message, ex.ToString());
                throw ex;
            }
            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }

        private object GetMachinesByCompany()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                    bool showHidden = HttpUtility.HtmlDecode(clientdata[1]) == "1";
                    var searchtxt = HttpUtility.HtmlDecode(clientdata[2]);
                    bool attachment = HttpUtility.HtmlDecode(clientdata[3]) == "1";
                    int att = attachment ? 0 : 2;

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

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

                    //GpsDeviceInfo[] devs = SystemParams.DeviceProvider.GetDeviceItems(contractorid, "");

                    AssetBasicInfo[] assets = CreateClient<AssetQueryClient>(companyid).GetAssetBasicInfoByUser(companyid, searchtxt, session.User.UID, att);

                    if (assets == null || assets.Length == 0)
                        return string.Empty;

                    assets = assets.OrderBy((m) => m.VIN).ToArray();

                    StringBuilder sb = new StringBuilder();
                    foreach (var a in assets)
                    {
                        if (!showHidden && a.Hide) continue;
                        AssetBasicItem asset = new AssetBasicItem();
                        Helper.CloneProperty(asset, a);
                        asset.EngineHours = a.EngineHours == null ? 0 : a.EngineHours.Value;
                        asset.Odometer = a.Odometer == null ? 0 : a.Odometer.Value;

                        sb.Append(SPLIT_CHAR180 + asset.ToString());
                    }
                    if (sb.Length > 0)
                    {
                        return sb.ToString().Substring(1);
                    }
                    return string.Empty;
                }
                else
                    return string.Empty;
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AssetBasePage.GetMachinesByCompany", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetMachineInfo()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                    var mid = HttpUtility.HtmlDecode(clientdata[1]);
                    long machineid = -1;
                    long.TryParse(mid, out machineid);

                    string connectionStr = string.Empty;
                    if (!SystemParams.IsDealer)
                    {
                        companyid = SystemParams.CompanyID;
                        connectionStr = SystemParams.DataDbConnectionString;
                    }
                    else
                    {
                        string connetionstring = SystemParams.GetDbStringByCompany(companyid);
                        connectionStr = connetionstring;
                    }

                    var client = CreateClient<AssetDataAdjustClient>(companyid);
                    AssetDetailInfo2 assetDetail = client.GetAssetDetailInfo2(companyid, machineid);
                    MachineOtherInfo mother = client.GetMachineOtherInfo(companyid, machineid);

                    AssetDetailItem2 assetItem = new AssetDetailItem2();
                    Helper.CloneProperty(assetItem, assetDetail);

                    assetItem.JobSites = mother.JobSites;
                    assetItem.ContactIDs = string.IsNullOrEmpty(mother.ContactIDs) ? new string[0] : mother.ContactIDs.Split(',');
                    assetItem.MachineGroupIDs = string.IsNullOrEmpty(mother.GroupIDs) ? new string[0] : mother.GroupIDs.Split(',');

                    //MachineRentalInfo[] machinerentals = new RentalManagement(connectionStr).SearchRentalsByAsset(machineid);
                    //if (machinerentals != null && machinerentals.Length > 0)
                    //{
                    //    DateTime nowdate = DateTime.Now;
                    //    //当前时间所在的rental
                    //    MachineRentalInfo rental = machinerentals.FirstOrDefault(m => m.RentalDate <= nowdate && nowdate.Date <= ((m.ReturnDate ?? m.ProjectReturnDate ?? DateTime.MaxValue)));
                    //    if (rental == null)//当前时间的下一个rental                                
                    //        rental = machinerentals.Where(m => m.RentalDate >= nowdate.Date).OrderBy(m => m.RentalDate).FirstOrDefault();
                    //    if (rental == null)//最新rental
                    //        rental = machinerentals[0];

                    //    assetItem.MachineRental = rental;
                    //}

                    return assetItem;
                }
                else
                    return new AssetDetailItem2();
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "AssetBasePage.GetMachineInfo", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object SaveMachine()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    if (!CheckRight(SystemParams.CompanyID, Foresight.Fleet.Services.User.Feature.MANAGE_ASSETS, Permissions.FullControl))
                        return "";
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    AssetDetailItem2 asset = JsonConvert.DeserializeObject<AssetDetailItem2>(clientdata);

                    if (SystemParams.IsDealer && string.IsNullOrWhiteSpace(asset.ContractorID))
                        return "Failed";

                    string connectionStr = string.Empty;
                    string customerid = string.Empty;
                    if (SystemParams.IsDealer)
                    {
                        string connetionstring = SystemParams.GetDbStringByCompany(asset.ContractorID);
                        connectionStr = connetionstring;
                        customerid = asset.ContractorID;
                    }
                    else
                    {
                        connectionStr = SystemParams.DataDbConnectionString;
                        customerid = SystemParams.CompanyID;
                    }

                    AssetDataAdjustClient client = CreateClient<AssetDataAdjustClient>(customerid);
                    if (asset.ID > 0)
                    {
                        var oldMachine = client.GetAssetDetailInfo2(customerid, asset.ID);
                        if (oldMachine.ShareStatus == AssetShareStatus.Child)
                        {
                            asset.VIN = oldMachine.VIN;//共享机器不能修改VIN/Make/Model/Type
                            asset.MakeID = oldMachine.MakeID;
                            asset.ModelID = oldMachine.ModelID;
                            asset.TypeID = oldMachine.TypeID;
                        }
                    }
                    else if (!asset.IgnoreDuplicate)
                    {
                        long[] dupassets = client.FindAssetsByVIN(customerid, asset.VIN);

                        if (dupassets.Length > 0)
                        {
                            return new
                            {
                                Result = 0,
                                Data = dupassets
                            };
                        }
                    }

                    AssetDetailInfo2 a = new AssetDetailInfo2();
                    Helper.CloneProperty(a, asset);
                    a.ID = client.UpdateAssetInfo(customerid, a, asset.ContactIDs, asset.MachineGroupIDs, session.User.UID);
                    CreateClient<JobSiteProvider>(customerid).AddAssetToJobSites(customerid, asset.OnSiteJobsiteIDs, a.ID, a.VIN);

                    long rentalID = -1;
                    if (a.ShareStatus != AssetShareStatus.Child)
                    {
                        UpdateMachineAttributes(a.ID, asset.ContractorID, asset.MachineAttributes, session.User.UID);

                        if (asset.MachineRental != null)
                        {
                            asset.MachineRental.MachineID = a.ID;
                            AssetRentalInfo rentalinfo = new AssetRentalInfo();
                            Helper.CloneProperty(rentalinfo, asset.MachineRental);
                            rentalinfo.RentalRate = (double)asset.MachineRental.RentalRate;
                            rentalID = CreateClient<AssetQueryClient>(customerid).SaveAssetRental(customerid, rentalinfo, session.User.UID);
                        }
                        if (asset.AttachmentInfo != null)
                        {
                            asset.AttachmentInfo.AssetId = a.ID;
                            client.UpdateAssetAttachmentAttribute(customerid, asset.AttachmentInfo, session.User.UID);
                        }
                    }

                    return new
                    {
                        Result = 1,
                        Data = new long[] { a.ID, rentalID }
                    };
                }
                else
                {
                    return "Failed";
                }
            }
            catch (BusinessException bex)
            {
                return bex.Message;
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "AssetBasePage.SaveMachine", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetAssetAttachmentInfo()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                    if (string.IsNullOrEmpty(companyid))
                        companyid = SystemParams.CompanyID;
                    var mid = HttpUtility.HtmlDecode(clientdata[1]);
                    long machineid = -1;
                    long.TryParse(mid, out machineid);

                    var client = CreateClient<AssetDataAdjustClient>(companyid);
                    AttachmentAttributeItem attaitem = null;
                    AttachmentAttributeInfo attainfo = client.GetAssetAttachmentAttribute(companyid, machineid);
                    if (attainfo != null)
                    {
                        attaitem = new AttachmentAttributeItem();
                        Helper.CloneProperty(attaitem, attainfo);
                        if (attaitem.AttachedtoAssetId != null && attaitem.AttachedtoAssetId.Value > 0)
                        {
                            var asset = CreateClient<AssetQueryClient>(companyid).GetAssetBasicInfoByID(companyid, attaitem.AttachedtoAssetId.Value);
                            if (asset != null)
                                attaitem.AttachedtoAssetName = asset.DisplayName;
                        }
                    }

                    return attaitem;
                }
                else
                    return new AttachmentAttributeItem();
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "AssetBasePage.GetAssetAttachmentInfo", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private string ChangeAssetProperty()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    var contractorid = ps[0];
                    if (string.IsNullOrWhiteSpace(contractorid))
                        contractorid = SystemParams.CompanyID;
                    long assetid = 0;
                    long.TryParse(ps[1], out assetid);
                    var name = ps[2];
                    bool value = Helper.IsTrue(ps[3]);

                    switch (name)
                    {
                        case "Hide":
                            CreateClient<AssetDataAdjustClient>(contractorid).ChangeAssetHideProperty(contractorid, assetid, value, "", user.IID);
                            break;
                        case "OnRoad":
                            CreateClient<AssetDataAdjustClient>(contractorid).ChangeAssetOnRoadProperty(contractorid, assetid, value, "", user.IID);
                            break;
                        case "TelematicsEnabled":
                            CreateClient<AssetDataAdjustClient>(contractorid).ChangeAssetTelematicsProperty(contractorid, assetid, value, "", user.IID);
                            break;
                        case "Attachment":
                            CreateClient<AssetDataAdjustClient>(contractorid).ChangeAssetAttachmentProperty(contractorid, assetid, value, "", user.IID);
                            break;
                        case "Preloaded":
                            CreateClient<AssetDataAdjustClient>(contractorid).ChangeAssetPreloadedProperty(contractorid, assetid, value, "", user.IID);
                            break;
                        default:
                            break;
                    }
                    return "OK";
                }
                else
                    return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #region Machine Attributes

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

                    if (string.IsNullOrWhiteSpace(companyid))
                    {
                        if (SystemParams.IsDealer)
                            return new MachineAttributeCategoryClient[0];
                        companyid = SystemParams.CompanyID;
                    }

                    MachineAttributes abt = CreateClient<AssetDataAdjustClient>(companyid).GetMachineAttributes(companyid, machineid);

                    List<MachineAttributeCategoryClient> list = new List<MachineAttributeCategoryClient>();
                    if (abt != null && abt.Category.Count > 0)
                    {
                        ConvertMachineAttributesCategory(abt, ref list);
                    }
                    return list.OrderBy(m => m.OrderIndex);
                }
                else
                    return new MachineAttributeCategoryClient[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private void UpdateMachineAttributes(long machineid, string companyid, MachineAttributeClient[] attributes, string useriid)
        {
            try
            {

                if (attributes != null && attributes.Length > 0)
                {
                    if (string.IsNullOrWhiteSpace(companyid))
                        companyid = SystemParams.CompanyID;

                    List<MachineAttributeItem> attritems = new List<MachineAttributeItem>();
                    foreach (MachineAttributeClient attclient in attributes)
                    {
                        MachineAttributeItem machineattributeitem = new MachineAttributeItem();
                        Helper.CloneProperty(machineattributeitem, attclient);
                        attritems.Add(machineattributeitem);
                    }

                    List<MachineAttributeCategory> listcate = new List<MachineAttributeCategory>();
                    MachineAttributeCategory category = new MachineAttributeCategory();
                    category.Attributes.AddRange(attritems);
                    listcate.Add(category);

                    MachineAttributes att = new MachineAttributes();
                    att.Category.AddRange(listcate);
                    CreateClient<AssetDataAdjustClient>(companyid).UpdateMachineAttributes(companyid, machineid, att, useriid);
                }
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AssetBasePage.UpdateMachineAttributes", ex.Message, ex.ToString());
                throw new Exception(ex.Message);
            }
        }

        private static void ConvertMachineAttributesCategory(MachineAttributes abtc, ref List<MachineAttributeCategoryClient> list)
        {
            if (abtc != null && abtc.Category.Count > 0)
            {
                foreach (MachineAttributeCategory cateitem in abtc.Category)
                {
                    MachineAttributeCategoryClient cateclt = new MachineAttributeCategoryClient();
                    Helper.CloneProperty(cateclt, cateitem);

                    var tab = abtc.Tabs.FirstOrDefault(m => m.ID == cateitem.TabID);
                    if (tab == null)
                        continue;
                    else
                    {
                        cateclt.TabName = tab.Name;
                        cateclt.OrderIndex = abtc.Tabs.IndexOf(tab);
                    }
                    cateclt.MachineAttributes = new List<MachineAttributeClient>();

                    foreach (MachineAttributeItem attitem in cateitem.Attributes)
                    {
                        MachineAttributeClient attclt = new MachineAttributeClient();
                        Helper.CloneProperty(attclt, attitem);
                        cateclt.MachineAttributes.Add(attclt);
                    }
                    list.Add(cateclt);
                }
            }
        }

        private static void ConvertMachineAttributes(MachineAttributes abtc, ref List<MachineAttributeClient> list)
        {
            if (abtc != null && abtc.Category.Count > 0)
            {
                foreach (MachineAttributeCategory cateitem in abtc.Category)
                {
                    foreach (MachineAttributeItem attitem in cateitem.Attributes)
                    {
                        MachineAttributeClient attclt = new MachineAttributeClient();
                        Helper.CloneProperty(attclt, attitem);
                        list.Add(attclt);
                    }
                }
            }
        }

        #endregion

        #region Odometer Adjustment History

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

                    DateTime starttime = Helper.DBMinDateTime;
                    DateTime endtime = DateTime.MaxValue;
                    if (!DateTime.TryParse(sdate, out starttime))
                        starttime = Helper.DBMinDateTime;

                    if (!DateTime.TryParse(edate, out endtime))
                        endtime = DateTime.MaxValue;

                    AssetBasicInfo asset = CreateClient<AssetQueryClient>(customerid).GetAssetBasicInfoByID(customerid, Convert.ToInt64(assetid));
                    AssetOdometerAdjustInfo[] odos = CreateClient<AssetDataAdjustClient>(customerid).GetOdometerAdjustmentHistory(customerid, Convert.ToInt64(assetid), starttime, endtime);
                    if (odos == null || odos.Length == 0)
                        return new AssetOdometerAdjustItem[0];

                    List<AssetOdometerAdjustItem> list = new List<AssetOdometerAdjustItem>();
                    foreach (AssetOdometerAdjustInfo odo in odos)
                    {
                        AssetOdometerAdjustItem item = new AssetOdometerAdjustItem();
                        Helper.CloneProperty(item, odo);
                        item.DisplayName = asset.DisplayName;
                        item.VIN = asset.VIN;
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new AssetOdometerAdjustItem[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion


        #region Engine Hours Adjustment History
        private object GetEngineHoursAdjustmentHistory()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var customerid = HttpUtility.HtmlDecode(clientdata[0]);
                    var assetid = HttpUtility.HtmlDecode(clientdata[1]);
                    var sdate = HttpUtility.HtmlDecode(clientdata[2]);
                    var edate = HttpUtility.HtmlDecode(clientdata[3]);
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    DateTime starttime = Helper.DBMinDateTime;
                    DateTime endtime = DateTime.MaxValue;
                    if (!DateTime.TryParse(sdate, out starttime))
                        starttime = Helper.DBMinDateTime;

                    if (!DateTime.TryParse(edate, out endtime))
                        endtime = DateTime.MaxValue;

                    AssetBasicInfo asset = CreateClient<AssetQueryClient>(customerid).GetAssetBasicInfoByID(customerid, Convert.ToInt64(assetid));
                    AssetEngineHoursAdjustInfo[] hours = CreateClient<AssetDataAdjustClient>(customerid).GetEngineHoursAdjustmentHistory(customerid, Convert.ToInt64(assetid), starttime, endtime);
                    if (hours == null || hours.Length == 0)
                        return new AssetEngineHoursAdjustItem[0];

                    List<AssetEngineHoursAdjustItem> list = new List<AssetEngineHoursAdjustItem>();
                    foreach (AssetEngineHoursAdjustInfo hour in hours)
                    {
                        AssetEngineHoursAdjustItem item = new AssetEngineHoursAdjustItem();
                        Helper.CloneProperty(item, hour);
                        item.DisplayName = asset.DisplayName;
                        item.VIN = asset.VIN;
                        list.Add(item);
                    }
                    return list.ToArray();
                }
                else
                    return new AssetEngineHoursAdjustItem[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion
        private object GetCustomerTimeZone()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string custid = Request.Form["ClientData"];
                    FISqlConnection db = null;
                    if (SystemParams.IsDealer)
                    {
                        if (string.IsNullOrEmpty(custid))
                            custid = SystemParams.CompanyID;
                        string connetionstring = SystemParams.GetDbStringByCompany(custid);
                        db = new FISqlConnection(connetionstring);
                    }
                    else
                        custid = SystemParams.CompanyID;

                    StringKeyValue kv = new StringKeyValue();

                    kv.Key = CreateClient<CustomerProvider>(custid).GetCustomerTimeZone(custid);
                    TimeZoneInfo tz = SystemParams.GetTimeZoneInfo(custid);
                    DateTime time = SystemParams.ConvertToUserTimeFromUtc(session.User, DateTime.Now.ToUniversalTime());
                    kv.Value = time.ToString("MM/dd/yyyy HH:mm:ss");//此处格式不能修改
                    return kv;
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            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 connetionstring = SystemParams.GetDbStringByCompany(kv.Key);
                        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;
            }
        }

        private object GetPMSchedulesByAsset()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    long assetid = 0;
                    long.TryParse(clientdata, out assetid);
                    return MaintenanceManagement.GetPmScheduleByAsset(session.SessionID, assetid, true);
                }
                else
                    return new PmScheduleInfo[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AssetBasePage.GetPmSchedules", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object AddAssetToPMSchedule()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    PMScheduleAssetItem p = JsonConvert.DeserializeObject<PMScheduleAssetItem>(clientdata);

                    PMAssetInfo pmAsset = new PMAssetInfo();
                    pmAsset.AssetId = p.AssetId;
                    pmAsset.StartHours = p.StartHours;
                    pmAsset.StartOdometer = p.StartOdometer;
                    pmAsset.StartDate = p.StartDate;
                    pmAsset.StartIntervalValue = p.StartIntervalValue;

                    var client = CreateClient<PMClient>();
                    client.UpdatePMScheduleAsset(SystemParams.CompanyID, p.PmScheduleID, pmAsset, session.User.UID);
                    if (!string.IsNullOrEmpty(p.SelectedIntervalID))
                    {
                        //SystemParams.PMClient.TriggerPMAlert(SystemParams.CompanyID, p.PmScheduleID, pmAsset.AssetId);
                        client.GenerateMissedPMAlert(SystemParams.CompanyID, p.SelectedIntervalID, pmAsset.AssetId);
                    }
                }
                return "OK";
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AssetBasePage.GetPmSchedules", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object RemoveAssetFromPMSchedule()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    long assetid = 0;
                    long.TryParse(ps[0], out assetid);

                    CreateClient<PMClient>().DeleteAssetsFromSchedule(SystemParams.CompanyID, ps[1], new long[] { assetid }, session.User.UID);
                }
                return "OK";
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AssetBasePage.GetPmSchedules", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object DeleteAssets()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null && session.User.UserType == Foresight.Fleet.Services.User.UserTypes.SupperAdmin)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    string custid = ps[0];
                    long[] assetids = JsonConvert.DeserializeObject<long[]>(ps[1]);
                    string notes = ps[2];

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

                    var client = CreateClient<AssetDataAdjustClient>(custid);
                    foreach (long assetid in assetids)
                    {
                        client.DeleteAsset(custid, Convert.ToInt64(assetid), notes);
                    }
                    return "";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "AssetBasePage.DeleteAsset", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object MergeAsset()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null && session.User.UserType == Foresight.Fleet.Services.User.UserTypes.SupperAdmin)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    string custid = ps[0];
                    string fromassetid = ps[1];
                    string toassetid = ps[2];
                    string notes = ps[3];

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

                    CreateClient<AssetDataAdjustClient>(custid).MergeAsset(custid, Convert.ToInt64(fromassetid), Convert.ToInt64(toassetid), notes);
                    return "";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "AssetBasePage.MergeAsset", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetAssetDatasources()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    var companyid = HttpUtility.HtmlDecode(ps[0]);
                    var mid = HttpUtility.HtmlDecode(ps[1]);
                    long machineid = -1;
                    long.TryParse(mid, out machineid);

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

                    var client = CreateClient<AssetDataAdjustClient>(companyid);
                    string[] datasources = client.GetAssetDatasources(companyid, machineid);
                    if (datasources == null)
                        return new string[0];

                    return datasources;
                }
                else
                    return new string[0];
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "AssetBasePage.GetAssetDatasources", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        #region Asset History
        private object GetAssets()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {

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

                    var items = CreateClient<AssetQueryClient>(companyid).GetAssetListItemsByUser(companyid, session.User.UID, string.Empty, true, 0, false, null, null, null);
                    return items.OrderBy(g => g.VIN).Select(i => new
                    {
                        i.Id,
                        DisplayName = GetDisplayName(i),
                    }).ToArray();
                }
                else
                    return new AssetGroupInfo[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "MachineDeviceBasePage.GetAssetList", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetAssetHistorys()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);

                    var companyid = ps[0];
                    long assetid = Convert.ToInt64(ps[1]);
                    DateTime beginDate = Helper.DBMinDateTime;
                    DateTime endDate = DateTime.MaxValue;
                    if (!DateTime.TryParse(ps[2], out beginDate))
                        beginDate = Helper.DBMinDateTime;
                    if (!DateTime.TryParse(ps[3], out endDate))
                        endDate = DateTime.MaxValue;

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

                    AssetHistoryInfo[] items = CreateClient<AssetQueryClient>(companyid).GetAssetHistorys(companyid, assetid, beginDate, endDate, "");
                    if (items == null || items.Length == 0)
                        return new AssetHistoryItem[0];

                    List<AssetHistoryItem> ls = new List<AssetHistoryItem>();
                    foreach (AssetHistoryInfo item in items)
                    {
                        AssetHistoryItem his = new AssetHistoryItem();
                        Helper.CloneProperty(his, item);
                        ls.Add(his);
                    }
                    return ls.ToArray();
                }
                else
                    return new AssetHistoryItem[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        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;
        }
        class AssetHistoryItem : AssetHistoryInfo
        {
            public string DateTimeStr { get { return DateTime == null ? "" : DateTime.Value.ToString(); } }
        }
        #endregion

        class PMScheduleAssetItem
        {
            public long AssetId { get; set; }
            public string PmScheduleID { get; set; }
            public double? StartHours { get; set; }
            public double? StartOdometer { get; set; }
            public DateTime? StartDate { get; set; }
            public int? StartIntervalValue { get; set; }
            public string SelectedIntervalID { get; set; }
        }
        class AttachmentAttributeItem : AttachmentAttributeInfo
        {
            public string AttachedtoAssetName { get; set; }
        }

        class AssetMergeItem : AssetMergeInfo
        {
            public string CompletedOnStr { get { return CompletedOn == DateTime.MinValue ? "" : CompletedOn.ToString(); } }
            public string MergeOnStr { get { return MergeOn == DateTime.MinValue ? "" : MergeOn.ToString(); } }
        }
    }
}
