using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Foresight.Data;
using System.Web;
using Foresight.Fleet.Services.AssetHealth;
using Foresight.Fleet.Services.Asset;

namespace IronIntel.Contractor.Maintenance
{
    public class WorkOrderManager : BusinessBase
    {
        public WorkOrderManager(string dbstr) : base(dbstr)
        {
        }

        public long[] GetOpenWorkOrderID(string machineid)
        {
            const string SQL = "select WORKORDERID from WORKORDER where MACHINEID={0} and STATUS<>'Completed' and and isnull(DELETED,0)=0";
            DataTable tb = GetDataTableBySQL(SQL, machineid);

            List<long> result = new List<long>();
            foreach (DataRow dr in tb.Rows)
            {
                result.Add(FIDbAccess.GetFieldInt(dr[0], 0));
            }

            return result.ToArray();
        }

        public bool CanAccessWorkOrder(string sessionid, string woid, string mid, string useriid)
        {
            const string SQL = "select count(1) from WORKORDER where WORKORDERID={0} and ASSIGNEDTO={1}";

            bool result = true;
            var user = FleetServiceClientHelper.CreateClient<Foresight.Fleet.Services.User.UserQueryClient>(sessionid).GetUserByIID(useriid);
            if ((!user.IsForesightUser) && (user.ContactType == Foresight.Fleet.Services.User.ContactTypes.Technician))
            {
                result = FIDbAccess.GetFieldInt(GetRC1BySQL(SQL, woid, useriid), 0) > 0;
            }
            if (result && user.UserType < Foresight.Fleet.Services.User.UserTypes.Admin)
            {
                long assetid = -1;
                if (!string.IsNullOrEmpty(mid))
                    Int64.TryParse(mid, out assetid);
                else
                {
                    var client = FleetServiceClientHelper.CreateClient<WorkOrderClient>(sessionid);
                    var workorder = client.GetWorkOrderDetail(SystemParams.CompanyID, Convert.ToInt64(woid));
                    assetid = workorder.AssetID;
                }
                long[] availableAssetsids = FleetServiceClientHelper.CreateClient<AssetQueryClient>(sessionid).GetAvailableAssetsForUsers(SystemParams.CompanyID, useriid);
                if (availableAssetsids != null && !availableAssetsids.Contains(assetid))
                    result = false;
            }
            return result;
        }

        public string[] GetInvoiceNumber(string woid)
        {
            const string SQL = @"select a.INVOICENUMBER from WORKORDER_ALERTS t  left join MAINTENANCELOG a on a.ALERTID=t.ALERTID,MACHINES b 
            where t.WORKORDERID={0} and a.MACHINEID = b.MACHINEID and ISNULL(b.HIDE,0)<>1 and ISNULL(a.INVOICENUMBER,'')<>'' ORDER BY a.ADDEDON DESC";

            DataTable dt = GetDataTableBySQL(SQL, woid);
            if (dt.Rows.Count == 0)
                return new string[0];

            List<string> list = new List<string>();
            foreach (DataRow dr in dt.Rows)
            {
                string num = FIDbAccess.GetFieldString(dr["INVOICENUMBER"], string.Empty);
                if (!string.IsNullOrEmpty(num))
                    list.Add(num);
            }
            return list.ToArray();
        }

        public static string GenerateWorkOrderPrintHtml(string sessionid, string companyid, long woid)
        {
            StringBuilder str = new StringBuilder();
            str.AppendLine("<H1 style='text-align:center;'>Work Order</H1>");
            str.AppendFormat("<div style='font-weight:bold;'>Details for work order <{0}> are listed below:</div>", woid);
            str.AppendLine("");
            //str.AppendLine("<div class='label' style='text-align:left;'>Work Order Information:</div>");
            str.AppendLine("<div style='padding-left:30px;margin-bottom:36px;'>");

            var client = FleetServiceClientHelper.CreateClient<WorkOrderClient>(companyid, sessionid);
            WorkOrderDetail wo = client.GetWorkOrderDetail(companyid, woid);
            str.Append(GenerateWorkOrderInfoHtml(wo));
            str.AppendLine("</div>");
            //str.AppendLine("<div class='label' style='text-align:left;'>Segments:</div>");

            WorkOrderSegmentItem[] segments = client.GetSegments(companyid, woid);

            if (segments != null && segments.Length > 0)
            {
                for (int i = 0; i < segments.Length; i++)
                {
                    var se = segments[i];
                    str.Append(GenerateSegmentHtml(se, i + 1));
                }
            }

            return str.ToString();
        }

        private static string GenerateWorkOrderInfoHtml(WorkOrderDetail wo)
        {
            StringBuilder str = new StringBuilder();
            str.Append("<table>");
            str.AppendFormat("<tr><td class='label' style='width:170px;'>Work Order Type</td><td>{0}</td></tr>", wo.WorkOrderType);
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Assigned To</td><td>{0}</td></tr>", HttpUtility.HtmlEncode(wo.AssignedToName));
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Status</td><td>{0}</td></tr>", wo.Status);
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Due Date</td><td>{0}</td></tr>", wo.DueDate == null ? "" : wo.DueDate.Value.ToShortDateString());
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Description</td><td>{0}</td></tr>", HttpUtility.HtmlEncode(wo.Description).Replace("\n", "<br>"));
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Meter Type</td><td>{0}</td></tr>", wo.MeterType);
            str.AppendLine("");
            if (string.Compare(wo.MeterType, "HourMeter", true) == 0
                || string.Compare(wo.MeterType, "Both", true) == 0)
                str.AppendFormat("<tr><td class='label'>Hour Meter</td><td>{0}</td></tr>", wo.HourMeter);
            if (string.Compare(wo.MeterType, "Odometer", true) == 0
                || string.Compare(wo.MeterType, "Both", true) == 0)
                str.AppendFormat("<tr><td class='label'>Odometer</td><td>{0}&nbsp;{1}</td></tr>", wo.Odometer, wo.OdometerUnits);
            str.AppendFormat("<tr><td class='label'>Work Order Total Costs ($)</td><td>{0}</td></tr>", wo.WorkOrderTotalCost);
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Other Cost ($)</td><td>{0}</td></tr>", wo.OtherCost);
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Parts Cost ($)</td><td>{0}</td></tr>", wo.PartsCost);
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Travel Time Cost ($)</td><td>{0}</td></tr>", wo.TravelTimeCost);
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Labor Cost ($)</td><td>{0}</td></tr>", wo.LaborCost);
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Hourly Rate</td><td>{0}</td></tr>", wo.HourlyRate);
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Time To Complete(Hrs)</td><td>{0}</td></tr>", wo.HoursToComplete);
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Completed Date</td><td>{0}</td></tr>", wo.CompleteDate == null ? "" : wo.CompleteDate.Value.ToShortDateString());
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Internal ID</td><td>{0}</td></tr>", wo.InternalID);
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Invoice Number</td><td>{0}</td></tr>", HttpUtility.HtmlEncode(wo.InvoiceNumber));
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Notes</td><td>{0}</td></tr>", HttpUtility.HtmlEncode(wo.Notes).Replace("\n", "<br>"));
            str.AppendLine("");
            str.AppendFormat("</table>");

            return str.ToString();
        }

        private static string GenerateSegmentHtml(WorkOrderSegmentItem se, int index)
        {
            StringBuilder str = new StringBuilder();
            //str.AppendFormat("<div style='margin-bottom:36px;margin-left:30px;{0}'>", (index - 2) % 4 == 0 ? "page-break-after: always;" : "");
            //str.AppendLine("");
            str.AppendLine("<div style='margin-bottom:36px;margin-left:30px;'>");
            str.AppendLine("<table>");
            str.AppendFormat("<tr><td class='label' colspan='2' style='text-align:left;'>Segment&nbsp;{0}</td></tr>", index);
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label' style='width:170px;'>User</td><td>{0}</td></tr>", HttpUtility.HtmlEncode(se.UserName));
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Hours</td><td>{0}</td></tr>", se.Hours);
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Job Site</td><td>{0}</td></tr>", se.JobsiteName);
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Cost</td><td>{0}</td></tr>", se.Cost);
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Component</td><td>{0}</td></tr>", se.Component);
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Completed</td><td>{0}</td></tr>", se.Completed ? "Yes" : "No");
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Completed Date</td><td>{0}</td></tr>", se.CompletedDate == null ? "" : se.CompletedDate.Value.ToShortDateString());
            str.AppendFormat("<tr><td class='label'>Description</td><td>{0}</td></tr>", HttpUtility.HtmlEncode(se.Description));
            str.AppendLine("");
            str.AppendFormat("<tr><td class='label'>Notes</td><td>{0}</td></tr>", HttpUtility.HtmlEncode(se.Notes).Replace("\n", "<br>"));
            str.AppendLine("");
            str.AppendLine("</table>");
            str.AppendLine("</div>");
            return str.ToString();
        }
    }
}
