using Foresight.Data;
using Foresight.Fleet.Services.Asset;
using Foresight.Fleet.Services.AssetHealth;
using Foresight.Fleet.Services.Attachment;
using Foresight.Fleet.Services.JobSite;
using Foresight.ServiceModel;
using IronIntel.Contractor.Attachment;
using IronIntel.Contractor.JobSites;
using IronIntel.Contractor.Machines;
using IronIntel.Contractor.Maintenance;
using IronIntel.Contractor.MapView;
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;

namespace IronIntel.Contractor.Site.Maintenance
{
    public class WorkOrderBasePage : ContractorBasePage
    {
        protected void ProcessRequest(string methodName)
        {
            object result = null;

            if (methodName != null)
            {
                switch (methodName.ToUpper())
                {
                    case "GETWORKORDERS":
                        result = GetWorkOrders();
                        break;
                    case "SAVEWORKORDER":
                        result = SaveWorkOrder();
                        break;
                    case "DELETEWORKORDER":
                        result = DeleteWorkOrder();
                        break;
                    case "GETCONTACTS":
                        result = GetContacts();
                        break;
                    case "GETMACHINES":
                        result = GetMachines();
                        break;
                    case "GETWORKORDERINFO":
                        result = GetWorkOrderInfo();
                        break;
                    case "GETOPENWORKORDERID":
                        result = GetOpenWorkOrderID();
                        break;
                    case "GETSEGMENTS":
                        result = GetSegments();
                        break;
                    case "SAVESEGMENT":
                        result = SaveSegment();
                        break;
                    case "DELETESEGMENT":
                        result = DeleteSegment();
                        break;
                    case "GETSEGMENTCLIENT":
                        result = GetSegmentClient();
                        break;
                    case "GETNONEASSIGNEDALERTS":
                        result = GetNoneAssignedAlerts();
                        break;
                    case "ADDORREMOVEALERTSFROMWORKORDER":
                        result = AddOrRemoveAlertsFromWorkOrder();
                        break;
                    case "GETATTACHMENTS":
                        result = GetAttachments();
                        break;
                    case "ADDATTACHMENT":
                        result = AddAttachment();
                        break;
                    case "DELETEATTACHMENT":
                        result = DeleteAttachment();
                        break;
                    case "GETASSETATTACHMENTS":
                        result = GetAssetAttachments();
                        break;
                    case "GETMACHINECONTACTS":
                        result = GetMachineContacts();
                        break;
                    case "SENDWORKORDER":
                        result = SendWorkOrder();
                        break;
                    case "GETINVOICENUMBER":
                        result = GetInvoiceNumber();
                        break;
                    case "GETALERTSFORWORKORDER":
                        result = GetAlertsForWorkOrder();
                        break;
                }
            }

            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }

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

                    WorkOrderItem[] workorders = null;
                    if (p.AssetID > 0)
                        workorders = CreateClient<WorkOrderClient>().GetWorkOrderItemsByAsset(SystemParams.CompanyID, p.AssetID);
                    else
                        workorders = CreateClient<WorkOrderClient>().GetWorkOrderItems(SystemParams.CompanyID, p.Contacts, p.Status, p.AssetGroups, p.SearchText, session.User.UID);

                    WorkOrderInfo[] maintenanceworkorders = null;//
                    if (p.ShowMaintenance)
                        maintenanceworkorders = MaintenanceManagement.GetMaintenanceWorkOrders(session.SessionID, SystemParams.CompanyID, p.Contacts, p.AssetGroups, p.SearchText, session.User.UID);

                    //普通用户机器权限过滤
                    var user = GetCurrentUser();
                    long[] availableAssetsids = null;
                    if (user.UserType < UserTypes.Admin)
                        availableAssetsids = CreateClient<AssetQueryClient>().GetAvailableAssetsForUsers(SystemParams.CompanyID, session.User.UID);

                    List<WorkOrderInfo> list = new List<WorkOrderInfo>();

                    if (maintenanceworkorders != null)
                    {
                        foreach (WorkOrderInfo wi in maintenanceworkorders)
                        {
                            if (availableAssetsids != null && !availableAssetsids.Contains(wi.AssetID))
                                continue;

                            list.Add(wi);
                        }
                    }

                    foreach (WorkOrderItem wo in workorders)
                    {
                        WorkOrderInfo wi = new WorkOrderInfo();
                        Helper.CloneProperty(wi, wo);
                        if (availableAssetsids != null && !availableAssetsids.Contains(wi.AssetID))
                            continue;

                        list.Add(wi);
                    }

                    return list.OrderBy(m => m.ID).ToArray();
                }
                else
                    return new WorkOrderInfo[0];

            }
            catch (Exception ex)
            {
                AddLog("ERROR", "WorkOrderBasePage.GetWorkOrders", ex.Message, ex.ToString());
                return ex.Message;
            }
        }


        private object GetWorkOrderInfo()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var woid = Request.Form["ClientData"];

                    WorkOrderDetail wod = CreateClient<WorkOrderClient>().GetWorkOrderDetail(SystemParams.CompanyID, Convert.ToInt64(woid));

                    WorkOrderDetailInfo wo = new WorkOrderDetailInfo();
                    Helper.CloneProperty(wo, wod);
                    return wo;
                }
                else
                    return new WorkOrderDetailInfo();
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "WorkOrderBasePage.GetWorkOrderInfo", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

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

                    var woid = ps[0];
                    var aid = ps[1];
                    long workorderid = Convert.ToInt64(woid);
                    long assetid = Convert.ToInt64(aid);
                    AlertManager am = new AlertManager(SystemParams.DataDbConnectionString);
                    AlertInfo[] alerts = am.GetAlertsByWorkOrder(workorderid);

                    AssetAlertItem[] aAlerts = CreateClient<WorkOrderClient>().GetNoneAssignedAlerts(SystemParams.CompanyID, assetid);
                    List<AlertInfo> assetAlerts = new List<AlertInfo>();
                    if (aAlerts != null)
                    {
                        foreach (var aa in aAlerts)
                        {
                            AlertInfo ai = new AlertInfo();
                            ai.AlertID = aa.ID;
                            ai.MachineID = aa.AssetID;
                            ai.AlertType = aa.AlertType;
                            ai.Description = aa.Description;
                            ai.AlertTime_UTC = aa.AlertTime;
                            assetAlerts.Add(ai);
                        }
                    }

                    WorkorderAlerts wa = new WorkorderAlerts();
                    wa.Alerts = alerts;
                    wa.AssetAlerts = assetAlerts.ToArray(); ;

                    return wa;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetAlertsByWorkOrder", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetOpenWorkOrderID()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var mid = Request.Form["ClientData"];
                    long aid = 0;
                    long.TryParse(mid, out aid);

                    var wos = CreateClient<WorkOrderClient>().GetWorkOrderItemsByAsset(SystemParams.CompanyID, aid);
                    List<long> workorderids = new List<long>();
                    foreach (var wo in wos)
                    {
                        if (!wo.Completed)
                            workorderids.Add(wo.ID);
                    }
                    //WorkOrderManager workordermanager = new WorkOrderManager(SystemParams.DataDbConnectionString);
                    //long[] workorderids = workordermanager.GetOpenWorkOrderID(mid);
                    string ids = string.Join(", ", workorderids);
                    ids = mid + "|" + ids;
                    return ids;
                }
                else
                    return new WorkOrderInfo();
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "WorkOrderBasePage.GetOpenWorkOrderID", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object SaveWorkOrder()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var workorderitem = HttpUtility.HtmlDecode(clientdata[0]);
                    var ids = HttpUtility.HtmlDecode(clientdata[1]);
                    long[] alertids = JsonConvert.DeserializeObject<long[]>(ids);

                    WorkOrderDetailInfo wdi = JsonConvert.DeserializeObject<WorkOrderDetailInfo>(workorderitem);
                    if (wdi.CompleteDate != null)
                        wdi.Status = "Completed";

                    WorkOrderDetail wo = new WorkOrderDetail();
                    Helper.CloneProperty(wo, wdi);

                    long workorderid = wo.ID;
                    if (wo.ID == -1)
                    {
                        wo = CreateClient<WorkOrderClient>().AddNewWorkOrder(SystemParams.CompanyID, wo, alertids, session.User.UID);
                        workorderid = wo.ID;
                    }
                    else
                    {
                        WorkOrderDetail oldwo = CreateClient<WorkOrderClient>().GetWorkOrderDetail(SystemParams.CompanyID, workorderid);
                        var user = UserManagement.GetUserByIID(session.User.UID);
                        if (oldwo.Status == "Completed" && user.UserType < UserTypes.Admin)
                        {
                            return "";
                        }
                        CreateClient<WorkOrderClient>().UpdateWorkOrder(SystemParams.CompanyID, wo, session.User.UID);
                    }

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

        private object DeleteWorkOrder()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Form["ClientData"];
                    int id = Convert.ToInt32(HttpUtility.HtmlDecode(clientdata));

                    CreateClient<WorkOrderClient>().DeleteWorkOrder(SystemParams.CompanyID, id, session.User.UID);

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

        private UserInfo[] GetContacts()
        {
            var session = GetCurrentLoginSession();
            UserInfo[] users = null;
            if (GetCurrentLoginSession() != null)
            {
                //contact = ContactManagement.GetContacts();
                users = UserManagement.GetActiveUsers(session.SessionID);
                users = users.OrderBy(u => u.DisplayName).ToArray();
            }
            else
            {
                users = new UserInfo[0];
            }
            return users;
        }

        private MachineItem[] GetMachines()
        {
            var session = GetCurrentLoginSession();
            MachineItem[] machines = null;
            if (GetCurrentLoginSession() != null)
            {
                machines = MachineManagement.GetMachines(session.SessionID, session.User.UID, "");
            }
            else
            {
                machines = new MachineItem[0];
            }
            return machines.Where(m => m.Hide == false).OrderBy(m => m.ShowName).ToArray();
        }


        private object GetNoneAssignedAlerts()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var id = Request.Form["ClientData"];
                    long assetid = Convert.ToInt64(id);

                    AssetAlertItem[] alerts = CreateClient<WorkOrderClient>().GetNoneAssignedAlerts(SystemParams.CompanyID, assetid);
                    if (alerts == null || alerts.Length == 0)
                        return new AssetAlertInfo[0];

                    List<AssetAlertInfo> list = new List<AssetAlertInfo>();
                    foreach (AssetAlertItem alert in alerts)
                    {
                        AssetAlertInfo ai = new AssetAlertInfo();
                        Helper.CloneProperty(ai, alert);
                        ai.AlertTime = ai.AlertTime.ToLocalTime();
                        ai.CompletedDate = ai.AlertTime.ToLocalTime();
                        list.Add(ai);
                    }
                    return list.ToArray();
                }
                else
                    return new AssetAlertInfo[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetNoneAssignedAlerts", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object AddOrRemoveAlertsFromWorkOrder()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var woid = HttpUtility.HtmlDecode(clientdata[0]);
                    var ids = HttpUtility.HtmlDecode(clientdata[1]);
                    var isaddstr = HttpUtility.HtmlDecode(clientdata[2]);
                    bool isadd = Helper.IsTrue(isaddstr);
                    long[] alertids = JsonConvert.DeserializeObject<long[]>(ids);


                    CreateClient<WorkOrderClient>().AddOrRemoveAlertsFromWorkOrder(SystemParams.CompanyID, Convert.ToInt64(woid), alertids, isadd, session.User.UID);

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


        #region Segment

        private object GetSegmentClient()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    SegmentClient client = new SegmentClient();

                    client.Users = UserManagement.GetUsers();
                    if (client.Users == null)
                        client.Users = new UserInfo[0];

                    var jss = CreateClient<JobSiteProvider>().GetJobSiteItems(SystemParams.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);
                    }

                    client.JobSites = list.ToArray();
                    if (client.JobSites == null)
                        client.JobSites = new JobSiteViewItem[0];

                    return client;
                }
                else
                    return new SegmentClient();
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "WorkOrderBasePage.GetSegmentClient", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

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

                    WorkOrderSegmentItem[] segments = CreateClient<WorkOrderClient>().GetSegments(SystemParams.CompanyID, woid);
                    if (segments == null || segments.Length == 0)
                        return new SegmentInfo[0];

                    List<SegmentInfo> list = new List<SegmentInfo>();
                    foreach (WorkOrderSegmentItem se in segments)
                    {
                        SegmentInfo si = new SegmentInfo();
                        Helper.CloneProperty(si, se);
                        list.Add(si);
                    }
                    return list.ToArray();
                }
                else
                    return new SegmentInfo[0];

            }
            catch (Exception ex)
            {
                AddLog("ERROR", "WorkOrderBasePage.GetSegments", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object SaveSegment()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Form["ClientData"];
                    SegmentInfo si = JsonConvert.DeserializeObject<SegmentInfo>(clientdata);
                    if (si.CompletedDate != null)
                        si.Completed = true;

                    WorkOrderSegmentItem segment = new WorkOrderSegmentItem();
                    Helper.CloneProperty(segment, si);

                    long segmentid = segment.SegmentID;
                    if (segmentid == -1)
                    {
                        segment = CreateClient<WorkOrderClient>().AddSegment(SystemParams.CompanyID, segment, session.User.UID);
                        segmentid = segment.SegmentID;
                    }
                    else
                    {
                        CreateClient<WorkOrderClient>().UpdateSegment(SystemParams.CompanyID, segment, session.User.UID);
                    }

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

        private object DeleteSegment()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Form["ClientData"];
                    int id = Convert.ToInt32(HttpUtility.HtmlDecode(clientdata));

                    CreateClient<WorkOrderClient>().DeleteSegment(SystemParams.CompanyID, id, session.User.UID);

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


        #endregion

        #region Attachment

        private object GetAttachments()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var woid = HttpUtility.HtmlDecode(clientdata[0]);

                    AttachmentInfo[] atts = CreateClient<AttachmentClient>().GetAttachments(SystemParams.CompanyID, "WorkOrder", woid);
                    if (atts == null || atts.Length <= 0)
                        return new AttachmentItem[0];

                    List<AttachmentItem> list = new List<AttachmentItem>();
                    foreach (AttachmentInfo att in atts)
                    {
                        AttachmentItem item = new AttachmentItem();
                        Helper.CloneProperty(item, att);
                        item.AddedOn = item.AddedOn.AddHours(SystemParams.GetHoursOffset());
                        list.Add(item);
                    }
                    return list.OrderBy(m => m.AddedOn).ToArray();
                }
                else
                    return new AttachmentItem[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object AddAttachment()
        {
            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);
                    }

                    AttachmentInfo attachment = new AttachmentInfo();
                    attachment.StringID = Guid.NewGuid().ToString().ToUpper();
                    attachment.FileName = uploadFile == null ? "" : uploadFile.FileName;
                    attachment.Source = "WorkOrder";
                    attachment.SourceID = woid;
                    attachment.FileData = iconfilebyte;
                    attachment.AddedByUserIID = session.User.UID;

                    string attid = CreateClient<AttachmentClient>().AddAttachmentLegacy(SystemParams.CompanyID, attachment);

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

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

                    CreateClient<AttachmentClient>().DeleteAttachmentLegacy(SystemParams.CompanyID, attachid, session.User.UID);
                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

        private object GetAssetAttachments()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var assetid = Request.Form["ClientData"];
                    AssetAttachmentInfo[] atts = CreateClient<AssetAttachmentProvider>().GetAttachments(SystemParams.CompanyID, Convert.ToInt64(assetid)).Where(m => m.VisibleOnWorkOrder == true).ToArray();
                    if (atts == null || atts.Length <= 0)
                        return new AssetAttachmentItem[0];

                    List<AssetAttachmentItem> list = new List<AssetAttachmentItem>();
                    foreach (AssetAttachmentInfo att in atts)
                    {
                        AssetAttachmentItem item = new AssetAttachmentItem();
                        Helper.CloneProperty(item, att);
                        item.AddedOn = item.AddedOn.AddHours(SystemParams.GetHoursOffset());
                        list.Add(item);
                    }
                    return list.OrderBy(m => m.AddedOn).ToArray();
                }
                else
                    return new AssetAttachmentInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        #endregion

        #region Sned Email
        private object GetMachineContacts()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var assetid = Request.Form["ClientData"];
                    return UserManagement.GetUsersByAssetID(session.SessionID, Convert.ToInt64(assetid), SystemParams.CompanyID);
                }
                else
                    return new UserInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object SendWorkOrder()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var woid = HttpUtility.HtmlDecode(clientdata[0]);
                    var address = HttpUtility.HtmlDecode(clientdata[1]);
                    var desc = HttpUtility.HtmlDecode(clientdata[2]);
                    string[] emailaddress = JsonConvert.DeserializeObject<string[]>(address);

                    WorkOrderDetail wod = CreateClient<WorkOrderClient>().GetWorkOrderDetail(SystemParams.CompanyID, Convert.ToInt64(woid));
                    WorkOrderDetailInfo wo = new WorkOrderDetailInfo();
                    Helper.CloneProperty(wo, wod);
                    SendMail(wo, emailaddress, desc, session.User);
                    return "OK";
                }
                else
                    return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private void SendMail(WorkOrderDetailInfo wo, string[] emailaddress, string desc, Services.Users.UserInfoEx user)
        {
            if (emailaddress == null || emailaddress.Length == 0)
                return;

            string Subject = "Work Order " + wo.ID;
            string Body = OrdinaryEmailFormat(wo, desc, user.ID);

            CreateClient<AttachmentClient>().SendWorkOrderEmail(SystemParams.CompanyID, wo.ID, Subject, Body, emailaddress.ToArray(), user.UID);
        }

        private string OrdinaryEmailFormat(WorkOrderDetailInfo wo, string desc, string userid)
        {
            string EmailFormat = "<table>";
            EmailFormat += "<tr><td><span>Details for work order <lable style=\"color:red;\"> <{3}> </lable> are listed below.To view or edit this work order,please click the below link:<br/></span><a href=\"{4}\">Link</a></td></tr>";
            EmailFormat += "<tr><td><span style=\"font-weight:bold;\">Message from:&nbsp;</span>{0}</td></tr>";
            EmailFormat += "<tr><td style=\"font-weight:700;\">Description:&nbsp;</td></tr>";
            EmailFormat += "<tr><td style=\"padding-left:30px;padding-right:20px;\">{1}</td></tr>";

            EmailFormat += "<tr><td style=\"font-weight:700;\">Work Order Information:&nbsp;</td></tr>";
            EmailFormat += "<tr><td style=\"padding-left:30px;\">{2}</td></tr>";

            EmailFormat += "</table>";

            string absuri = Context.Request.Url.AbsoluteUri;
            string wourl = absuri.Substring(0, absuri.LastIndexOf("/Maintenance", StringComparison.OrdinalIgnoreCase));
            wourl = wourl + "/jump.aspx?p=" + Convert.ToBase64String(Encoding.UTF8.GetBytes("jt=woe;woid=" + wo.ID));

            return string.Format(EmailFormat, userid, desc.Replace("\n", "<br>"), WorkOrderFormat(wo), wo.ID, wourl);
        }

        public static string WorkOrderFormat(WorkOrderDetailInfo wo)
        {
            string EmailFormat = "<table>";
            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Work Order Type:&nbsp;</span>{0}</td></tr>";
            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Assigned To:&nbsp;</span>{1}</td></tr>";
            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Status:&nbsp;</span>{2}</td></tr>";
            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Due Date:&nbsp;</span>{3}</td></tr>";
            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Description:&nbsp;</span>{4}</td></tr>";
            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Meter Type:&nbsp;</span>{5}</td></tr>";
            if (string.Compare(wo.MeterType, "HourMeter", true) == 0 || string.Compare(wo.MeterType, "Both", true) == 0)
                EmailFormat += "<tr><td><span style=\"font-weight:700;\">Hour Meter:&nbsp;</span>{6}</td></tr>";
            if (string.Compare(wo.MeterType, "Odometer", true) == 0 || string.Compare(wo.MeterType, "Both", true) == 0)
                EmailFormat += "<tr><td><span style=\"font-weight:700;\">Odometer:&nbsp;</span>{7}&nbsp;{8}</td></tr>";
            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Work Order Total Costs ($):&nbsp;</span>{9}</td></tr>";

            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Other Cost ($):&nbsp;</span>{19}</td></tr>";
            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Parts Cost ($):&nbsp;</span>{14}</td></tr>";
            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Travel Time Cost ($):&nbsp;</span>{15}</td></tr>";
            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Labor Cost ($):&nbsp;</span>{16}</td></tr>";
            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Hourly Rate:&nbsp;</span>{17}</td></tr>";

            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Time To Complete(Hrs):&nbsp;</span>{10}</td></tr>";
            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Completed Date:&nbsp;</span>{11}</td></tr>";
            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Internal ID:&nbsp;</span>{12}</td></tr>";

            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Invoice Number:&nbsp;</span>{18}</td></tr>";

            EmailFormat += "<tr><td><span style=\"font-weight:700;\">Notes:&nbsp;</span>{13}</td></tr>";
            EmailFormat += "</table>";

            string SendStr = string.Format(EmailFormat,
                HttpUtility.HtmlEncode(wo.WorkOrderType),
                HttpUtility.HtmlEncode(wo.AssignedToName),
                HttpUtility.HtmlEncode(wo.Status),
                HttpUtility.HtmlEncode(wo.DueDateStr),
                HttpUtility.HtmlEncode(wo.Description).Replace("\n", "<br>"),
                HttpUtility.HtmlEncode(wo.MeterType),
                HttpUtility.HtmlEncode(wo.HourMeter),
                HttpUtility.HtmlEncode(wo.Odometer),
                HttpUtility.HtmlEncode(wo.OdometerUnits),
                HttpUtility.HtmlEncode(wo.WorkOrderTotalCost),
                HttpUtility.HtmlEncode(wo.HoursToComplete),
                HttpUtility.HtmlEncode(wo.CompleteDateStr),
                HttpUtility.HtmlEncode(wo.InternalID),
                HttpUtility.HtmlEncode(wo.Notes).Replace("\n", "<br>"),
                HttpUtility.HtmlEncode(wo.PartsCost),
                HttpUtility.HtmlEncode(wo.TravelTimeCost),
                HttpUtility.HtmlEncode(wo.LaborCost),
                HttpUtility.HtmlEncode(wo.HourlyRate),
                HttpUtility.HtmlEncode(wo.InvoiceNumber),
                HttpUtility.HtmlEncode(wo.OtherCost));
            return SendStr;
        }

        #endregion

        private object GetInvoiceNumber()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var woid = Request.Form["ClientData"];
                    return new WorkOrderManager(SystemParams.DataDbConnectionString).GetInvoiceNumber(woid);
                }
                else
                    return new string[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }



    public class SegmentClient
    {
        public UserInfo[] Users { get; set; }
        public JobSiteViewItem[] JobSites { get; set; }
    }

    public class WorkOrderQueryParams
    {
        public long AssetID { get; set; }
        public string SearchText { get; set; }
        public string[] Contacts { get; set; }
        public string[] Status { get; set; }
        public string[] AssetGroups { get; set; }
        public bool ShowMaintenance { get; set; }
    }

    class WorkorderAlerts
    {
        public AlertInfo[] Alerts { get; set; }
        public AlertInfo[] AssetAlerts { get; set; }
    }
}
