using Foresight.Fleet.Services.Asset;
using Foresight.Fleet.Services.AssetHealth;
using Foresight.Fleet.Services.Inspection;
using Foresight.Fleet.Services.Inspection.Package;
using Foresight.Fleet.Services.User;
using IronIntel.Contractor.FilterQ;
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.AssetHealth.WorkOrder;
using FI.FIC;

namespace IronIntel.Contractor.Site
{
    public class InspectionBasePage : ContractorBasePage
    {
        protected void ProcessRequest(string method)
        {
            object result = null;
            try
            {
                string methodName = Request.Params["MethodName"];
                if (methodName != null)
                {
                    switch (methodName)
                    {
                        case "GetGlobalSections":
                            result = GetGlobalSections();
                            break;
                        case "GetGlobalQuestions":
                            result = GetGlobalQuestions();
                            break;
                        case "SaveGlobalSection":
                            result = SaveGlobalSection();
                            break;
                        case "SaveGlobalQuestion":
                            result = SaveGlobalQuestion();
                            break;
                        case "DeleteGlobalSection":
                            result = DeleteGlobalSection();
                            break;
                        case "DeleteGlobalQuestion":
                            result = DeleteGlobalQuestion();
                            break;
                        case "GetTemplates":
                            result = GetTemplates();
                            break;
                        case "GetTemplate":
                            result = GetTemplate();
                            break;
                        case "SaveTemplate":
                            result = SaveTemplate();
                            break;
                        case "DeleteTemplate":
                            result = DeleteTemplate();
                            break;
                        case "PublishTemplate":
                            result = PublishTemplate();
                            break;
                        case "GetAssetMakes":
                            result = GetAssetMakes();
                            break;
                        case "GetAssetModels":
                            result = GetAssetModels();
                            break;
                        case "GetAssetTypes":
                            result = GetAssetTypes();
                            break;
                        case "GetInspectItems":
                            result = GetInspectItems();
                            break;
                        case "GetGlobalSectionsByID":
                            result = GetGlobalSectionsByID();
                            break;
                        case "GetInspectionReport":
                            result = GetInspectionReport();
                            break;
                        case "TemplateSaveAs":
                            result = TemplateSaveAs();
                            break;
                        case "GetInspectEmailList":
                            result = GetInspectEmailList();
                            break;
                        case "GetInspectionReportForEdit":
                            result = GetInspectionReportForEdit();
                            break;
                        case "GetAssetBasicInfoForEdit":
                            result = GetAssetBasicInfoForEdit();
                            break;
                        case "UpdateInspectionReport":
                            result = UpdateInspectionReport();
                            break;
                        case "UploadStaticPicture":
                            result = UploadStaticPicture();
                            break;
                        case "GetStaticPictureContent":
                            result = GetStaticPictureContent();
                            break;
                        case "DeleteStaticPicture":
                            result = DeleteStaticPicture();
                            break;
                        case "GetFuelReportItems":
                            result = GetFuelReportItems();
                            break;
                        case "GetFuelReport":
                            result = GetFuelReport();
                            break;
                        case "GetFuelReportHeaderFooter":
                            result = GetFuelReportHeaderFooter();
                            break;
                        case "UpdateFuelReportHeaderFooter":
                            result = UpdateFuelReportHeaderFooter();
                            break;
                        case "SendFuelTruckFuelReport":
                            result = SendFuelTruckFuelReport();
                            break;
                        case "GetFuelLogEmailList":
                            result = GetFuelLogEmailList();
                            break;
                        case "GetFuelTypes":
                            result = GetFuelTypes();
                            break;
                        case "GetCreatedPackages":
                            result = GetCreatedPackages();
                            break;
                        case "DeletePackage":
                            result = DeletePackage();
                            break;
                        case "CreatePackage":
                            result = CreatePackage();
                            break;
                        case "GetPackageData":
                            result = GetPackageData();
                            break;
                        case "ImportPackage":
                            result = ImportPackage();
                            break;
                        case "GetAssetWorkOrders":
                            result = GetAssetWorkOrders();
                            break;
                        case "GetInspectLayouts":
                            result = GetInspectionLayouts();
                            break;
                        case "GetInspectLayout":
                            result = GetInspectLayout();
                            break;
                        case "SaveInspectLayout":
                            result = SaveInspectLayout();
                            break;
                        case "DeleteInspectLayout":
                            result = DeleteInspectLayout();
                            break;
                        case "UpdateInspectionWorkOrder":
                            result = UpdateInspectionWorkOrder();
                            break;
                        case "GetInspectHistoryItems":
                            result = GetInspectHistoryItems();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "InspectionBasePage", ex.Message, ex.ToString());
                throw ex;
            }
            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }
        protected void ProcessFileRequest()
        {
            bool download = false;
            string fileName = "";
            byte[] buffer = null;
            try
            {
                string type = Request.Params["t"];
                if (type != null)
                {
                    switch (type)
                    {
                        case "1"://download
                            buffer = GetInspectionPDF(out fileName, false);
                            download = true;
                            break;
                        case "2"://print
                            buffer = GetInspectionPDF(out fileName);
                            break;
                        case "3"://download fuel
                            buffer = GetFuelReportPDF(out fileName, false);
                            download = true;
                            break;
                        case "4"://print fuel
                            buffer = GetFuelReportPDF(out fileName);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "InspectionBasePage", ex.Message, ex.ToString());
                throw ex;
            }

            fileName = HttpUtility.UrlEncode(string.IsNullOrEmpty(fileName) ? "attachment" : fileName, System.Text.Encoding.UTF8) + ".pdf";

            Response.ContentType = "application/pdf";
            Response.BufferOutput = false;
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.AddHeader("Content-Disposition"
                , string.Format("{0}filename={1}", download ? "attachment;" : "", fileName));
            if (buffer != null)
            {
                Response.AddHeader("Content-Length", buffer.Length.ToString());
                Response.BinaryWrite(buffer);
            }
            Response.Flush();
            Response.End();
        }

        protected object GetInspectItem(string inspectionid)
        {//只有id，不知道类型 
            var sesstion = GetCurrentLoginSession();

            AssetInspectClient aclient = CreateClient<AssetInspectClient>();
            AssetInspectItem aitem = aclient.GetInspectItem(SystemParams.CompanyID, inspectionid, sesstion.User.UID);
            if (aitem != null)
            {
                if (!CheckRight(SystemParams.CompanyID, Foresight.Fleet.Services.User.Feature.INSPECTION_REPORTS))
                    return null;
                else
                    return aitem;
            }

            TeamIntelligenceClient tclient = CreateClient<TeamIntelligenceClient>();
            TeamInspectItem titem = tclient.GetInspectItem(SystemParams.CompanyID, inspectionid, sesstion.User.UID);

            if (!CheckRight(SystemParams.CompanyID, Foresight.Fleet.Services.User.Feature.TEAM_REPORTS))
                return null;
            else
                return titem;
        }


        private object GetInspectItems()
        {
            try
            {
                var sesstion = GetCurrentLoginSession();
                if (sesstion != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    DateTime startdate = Helper.DBMinDateTime;
                    DateTime enddate = DateTime.MaxValue;
                    if (!DateTime.TryParse(ps[1], out startdate))
                        startdate = Helper.DBMinDateTime;
                    if (!DateTime.TryParse(ps[2], out enddate))
                        enddate = DateTime.MaxValue;

                    string filter = HttpUtility.HtmlDecode(ps[3]);

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        TeamInspectItem[] insplectitems = client.GetInspectItems(SystemParams.CompanyID, startdate, enddate, filter, sesstion.User.UID);
                        if (insplectitems == null || insplectitems.Length == 0)
                            return new TeamInspectInfo[0];

                        List<TeamInspectInfo> list = new List<TeamInspectInfo>();
                        foreach (TeamInspectItem item in insplectitems)
                        {
                            TeamInspectInfo inspect = new TeamInspectInfo();
                            Helper.CloneProperty(inspect, item);
                            list.Add(inspect);
                        }
                        return list.ToArray();
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        AssetInspectItem[] insplectitems = client.GetInspectItems(SystemParams.CompanyID, startdate, enddate, filter, sesstion.User.UID);
                        if (insplectitems == null || insplectitems.Length == 0)
                            return new AssetInspectInfo[0];

                        List<AssetInspectInfo> list = new List<AssetInspectInfo>();
                        foreach (AssetInspectItem item in insplectitems)
                        {
                            AssetInspectInfo inspect = new AssetInspectInfo();
                            Helper.CloneProperty(inspect, item);
                            if (inspect.WorkOrderId <= 0)
                            {
                                inspect.WorkOrderNumber = "Not Assigned";
                            }

                            List<WorkOrderListItem> lswo = new List<WorkOrderListItem>();
                            lswo.Add(new WorkOrderListItem() { Id = -1, WorkOrderNumber = "Not Assigned" });
                            if (inspect.WorkOrderId > 0)
                                lswo.Add(new WorkOrderListItem() { Id = inspect.WorkOrderId, WorkOrderNumber = inspect.WorkOrderNumber });
                            inspect.WorkOrders = lswo.ToArray();

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

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

        private object UpdateInspectionWorkOrder()
        {
            try
            {
                var sesstion = GetCurrentLoginSession();
                if (sesstion != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    string ispid = ps[0];
                    long woid = 0;
                    long oldwoid = 0;
                    long.TryParse(ps[1], out woid);
                    long.TryParse(ps[2], out oldwoid);

                    CreateClient<AssetInspectClient>().UpdateInspectionWorkOrder(SystemParams.CompanyID, ispid, woid, oldwoid);
                    return new string[0];
                }
                else
                    return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetInspectHistoryItems()
        {
            try
            {
                var sesstion = GetCurrentLoginSession();
                if (sesstion != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string inspectid = HttpUtility.HtmlDecode(ps[1]);

                    AssetInspectItem[] insplectitems = null;

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        insplectitems = client.GetInspectHistoryItems(SystemParams.CompanyID, inspectid);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        insplectitems = client.GetInspectHistoryItems(SystemParams.CompanyID, inspectid);
                    }

                    if (insplectitems == null || insplectitems.Length == 0)
                        return new AssetInspectInfo[0];

                    List<AssetInspectInfo> list = new List<AssetInspectInfo>();
                    foreach (AssetInspectItem item in insplectitems)
                    {
                        AssetInspectInfo inspect = new AssetInspectInfo();
                        Helper.CloneProperty(inspect, item);
                        list.Add(inspect);
                    }
                    return list.ToArray();
                }
                else
                    return new AssetInspectItem[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        private object GetInspectionReportForEdit()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string id = HttpUtility.HtmlDecode(ps[1]);
                    string companyId = SystemParams.CompanyID;

                    InspectReportInfo report = null;
                    var aic = CreateClient<AssetInspectClient>();
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        report = client.GetInspection(companyId, id);
                    }
                    else
                    {
                        report = aic.GetInspection(companyId, id);
                    }

                    if (report == null)
                        return null;

                    var ir = new InspectReportEditItem();
                    Helper.CloneProperty(ir, report);
                    ir.CommitTime = ir.CommitTimeLocal;
                    ir.Answers.AddRange(report.Answers);
                    ir.Medias.AddRange(report.Medias);
                    if (!teamintelligence)
                    {
                        var aclient = FleetServiceClientHelper.CreateClient<AssetQueryClient>(companyId, session.SessionID);
                        ir.Asset = aclient.GetAssetBasicInfoByID(companyId, ir.AssetId);
                    }
                    // list
                    //bool hasAsset = false;
                    bool hasEmail = false;
                    bool hasJobsite = false;
                    foreach (var p in report.Template.Pages)
                    {
                        foreach (var s in p.Sections)
                        {
                            foreach (var q in s.Questions)
                            {
                                if (q.QuestionType == QuestionTypes.DropDown)
                                {
                                    //if (q.LookupSource == LookupSources.Assets)
                                    //{
                                    //    hasAsset = true;
                                    //}
                                    //else
                                    if (q.LookupSource == LookupSources.Employee)
                                    {
                                        hasEmail = true;
                                    }
                                    else if (q.LookupSource == LookupSources.Jobsites)
                                    {
                                        hasJobsite = true;
                                    }
                                }
                                else if (q.QuestionType == QuestionTypes.EmailList)
                                {
                                    hasEmail = true;
                                }
                            }
                        }
                    }
                    var ic = CreateClient<InspectMobileClient>();
                    if (hasEmail)
                    {
                        ir.EmailList = Download(() => ic.DownloadTeamIntelligenceUsers(companyId)).OrderBy(e => e.UserName).ToArray();
                    }
                    //if (hasAsset)
                    //{
                    //    var ac = CreateClient<AssetQueryClient>();
                    //    ir.AssetList = ac.GetAssetBasicInfoByUser(companyId, string.Empty, session.User.UID);
                    //}
                    if (hasJobsite)
                    {
                        ir.JobSiteList = Download(() => ic.DownloadJobSites(companyId, session.User.UID)).OrderBy(j => j.Name).ToArray();
                    }
                    return ir;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

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

                    var ac = CreateClient<InspectMobileClient>();
                    var list = new List<AssetItem>();
                    var assets = Download(startid => ac.DownloadAssets(companyId, session.User.UID, startid, 20000))
                        .OrderBy(a => a.Name)
                        .ToArray();

                    return assets;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private List<AssetItem> Download(Func<long, AssetItem[]> download, long startid = -1, int size = 100)
        {
            var list = new List<AssetItem>();
            int count = 0;
            while (count < 5)
            {
                try
                {
                    var items = download(startid);
                    list.AddRange(items);
                    if (items.Length < size)
                    {
                        return list;
                    }
                    else
                    {
                        startid = items[items.Length - 1].Id;
                    }
                }
                catch
                {
                    count++;
                }
            }
            return null;
        }

        IEnumerable<T> Download<T>(Func<IEnumerable<T>> download)
        {
            int count = 0;
            while (count < 5)
            {
                try
                {
                    return download();
                }
                catch
                {
                    count++;
                }
            }
            return null;
        }

        private object UpdateInspectionReport()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    clientdata = HttpUtility.HtmlDecode(clientdata);
                    var report = JsonConvert.DeserializeObject<InspectReportInfo>(clientdata);
                    bool isTeam = report.Target == TemplateTargets.Person;

                    string companyId = SystemParams.CompanyID;
                    foreach (var a in report.Answers)
                    {
                        if (string.IsNullOrEmpty(a.Id))
                        {
                            a.Id = Guid.NewGuid().ToString();
                        }
                    }

                    // TODO: media

                    if (isTeam)
                    {
                        var tc = CreateClient<TeamIntelligenceClient>();
                        tc.UpdateTeamInspect(companyId, report, session.User.UID);
                    }
                    else
                    {
                        var ac = CreateClient<AssetInspectClient>();
                        ac.UpdateAssetInspect(companyId, report, session.User.UID);
                    }

                    return true;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetInspectionReport()
        {
            try
            {
                var sesstion = GetCurrentLoginSession();
                if (sesstion != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string id = HttpUtility.HtmlDecode(ps[1]);

                    InspectReportInfo report = null;
                    ReportLayoutInfo layout = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        report = client.GetInspection(SystemParams.CompanyID, id);
                        if (report != null)
                            layout = client.GetInspectReportLayout(SystemParams.CompanyID, id);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        report = client.GetInspection(SystemParams.CompanyID, id);
                        if (report != null)
                            layout = client.GetInspectReportLayout(SystemParams.CompanyID, id);
                    }

                    if (report == null)
                        return null;

                    InspectReportItem ir = new InspectReportItem();
                    Helper.CloneProperty(ir, report);
                    ir.CommitTime = ir.CommitTimeLocal;
                    ir.Answers.AddRange(report.Answers);
                    ir.Medias.AddRange(report.Medias);
                    ir.IdentifiedQuestions = new List<IdentifiedQuestionItem>();
                    foreach (var p in ir.Template.Pages)
                    {
                        foreach (var s in p.Sections)
                        {
                            foreach (var q in s.Questions)
                            {
                                var qType = ConvertQuestionType(q);
                                foreach (var a in ir.Answers)
                                {
                                    if (q.Id.Equals(a.QuestionId, StringComparison.OrdinalIgnoreCase))
                                    {
                                        if (qType == QuestionTypes.Date || qType == QuestionTypes.DateAndTime)
                                        {
                                            DateTime dt = DateTime.Now;
                                            if (DateTime.TryParse(a.Result, out dt))
                                            {
                                                if (qType == QuestionTypes.Date)
                                                    a.Result = dt.ToString("M/d/yyyy tt");
                                                else if (qType == QuestionTypes.DateAndTime)
                                                    a.Result = dt.ToString("M/d/yyyy h:mm:ss tt");
                                            }
                                        }
                                        else if (qType == QuestionTypes.Number
                                            || qType == QuestionTypes.Integer
                                            || qType == QuestionTypes.EngingHours
                                            || qType == QuestionTypes.Odometer)
                                        {
                                            double tn = 0;
                                            if (double.TryParse(a.Result, out tn))
                                                a.Result = tn.ToString("#,##0.##");
                                        }

                                        //IdentifiedQuestion
                                        if (qType != QuestionTypes.DropDown
                                             && qType != QuestionTypes.YesOrNo
                                             && qType != QuestionTypes.List)
                                        {
                                            if (a.SeverityLevel != SeverityLeveles.None)
                                            {
                                                if (qType == QuestionTypes.Picture)
                                                {
                                                    var ms = ir.Medias.FirstOrDefault(m => m.AnswerId.ToString() == a.Id.ToString());
                                                    if (ms == null)
                                                        continue;
                                                }
                                                IdentifiedQuestionItem iq = new IdentifiedQuestionItem();
                                                Helper.CloneProperty(iq, q);
                                                if (q.StaticPictures != null && q.StaticPictures.Count > 0)
                                                {
                                                    foreach (var sp in q.StaticPictures)
                                                    {
                                                        PictureInfo isp = new PictureInfo();
                                                        Helper.CloneProperty(isp, sp);
                                                        iq.StaticPictures.Add(isp);
                                                    }
                                                }
                                                iq.IdentifiedSeverityLevel = a.SeverityLevel;
                                                ir.IdentifiedQuestions.Add(iq);
                                            }
                                        }
                                        else
                                        {
                                            if (a.SelectedItems != null && a.SelectedItems.Count() > 0)
                                            {
                                                bool hasseveritylevel = a.SelectedItems.Count(m => m.SeverityLevel != SeverityLeveles.None) > 0;
                                                if (hasseveritylevel)
                                                {
                                                    IdentifiedQuestionItem iq = new IdentifiedQuestionItem();
                                                    Helper.CloneProperty(iq, q);
                                                    if (q.StaticPictures != null && q.StaticPictures.Count > 0)
                                                    {
                                                        foreach (var sp in q.StaticPictures)
                                                        {
                                                            PictureInfo isp = new PictureInfo();
                                                            Helper.CloneProperty(isp, sp);
                                                            iq.StaticPictures.Add(isp);
                                                        }
                                                    }

                                                    iq.IdentifiedSeverityLevel = SeverityLeveles.Low;
                                                    bool isHigh = a.SelectedItems.Count(m => m.SeverityLevel == SeverityLeveles.High) > 0;
                                                    if (isHigh)
                                                        iq.IdentifiedSeverityLevel = SeverityLeveles.High;
                                                    else
                                                    {
                                                        bool isMedium = a.SelectedItems.Count(m => m.SeverityLevel == SeverityLeveles.Medium) > 0;
                                                        if (isMedium)
                                                            iq.IdentifiedSeverityLevel = SeverityLeveles.Medium;
                                                    }
                                                    ir.IdentifiedQuestions.Add(iq);
                                                }
                                            }
                                            else
                                            {
                                                if (a.SeverityLevel != SeverityLeveles.None)
                                                {
                                                    IdentifiedQuestionItem iq = new IdentifiedQuestionItem();
                                                    Helper.CloneProperty(iq, q);
                                                    if (q.StaticPictures != null && q.StaticPictures.Count > 0)
                                                    {
                                                        foreach (var sp in q.StaticPictures)
                                                        {
                                                            PictureInfo isp = new PictureInfo();
                                                            Helper.CloneProperty(isp, sp);
                                                            iq.StaticPictures.Add(isp);
                                                        }
                                                    }
                                                    iq.IdentifiedSeverityLevel = a.SeverityLevel;
                                                    ir.IdentifiedQuestions.Add(iq);
                                                }
                                            }
                                        }

                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (!teamintelligence)
                    {
                        var aclient = FleetServiceClientHelper.CreateClient<AssetQueryClient>(SystemParams.CompanyID, sesstion.SessionID);
                        ir.Asset = aclient.GetAssetBasicInfoByID(SystemParams.CompanyID, ir.AssetId);
                    }
                    ir.IdentifiedQuestions = ir.IdentifiedQuestions.OrderByDescending(m => m.IdentifiedSeverityLevel).ToList();

                    if (layout != null)
                    {
                        layout.PageHeaderLeft = Escape(layout.PageHeaderLeft);
                        layout.PageHeaderCenter = Escape(layout.PageHeaderCenter);
                        layout.PageHeaderRight = Escape(layout.PageHeaderRight);
                        layout.PageFooterLeft = Escape(layout.PageFooterLeft);
                        layout.PageFooterCenter = Escape(layout.PageFooterCenter);
                        layout.PageFooterRight = Escape(layout.PageFooterRight);
                    }
                    ir.ReportLayout = layout;
                    return ir;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        string Escape(string html)
        {
            if (string.IsNullOrEmpty(html))
            {
                return string.Empty;
            }
            return HttpUtility.HtmlEncode(html).Replace("\n", "<br/>");
        }

        private QuestionTypes ConvertQuestionType(Question q)
        {
            var questionType = q.QuestionType;
            if (questionType == QuestionTypes.FuelRecords)
            {
                switch (q.SubType)
                {
                    case (int)FuelRecordTypes.TransactionDate:
                        questionType = QuestionTypes.DateAndTime;
                        break;
                    case (int)FuelRecordTypes.Odometer:
                    case (int)FuelRecordTypes.Quantity:
                    case (int)FuelRecordTypes.UnitCost:
                    case (int)FuelRecordTypes.TotalCost:
                        questionType = QuestionTypes.Odometer;
                        break;
                    case (int)FuelRecordTypes.FuelType:
                    case (int)FuelRecordTypes.State:
                    case (int)FuelRecordTypes.DistributedBy:
                        questionType = QuestionTypes.DropDown;
                        break;
                    case (int)FuelRecordTypes.Notes:
                        questionType = QuestionTypes.MultipleLineText;
                        break;
                    case (int)FuelRecordTypes.Picture:
                        questionType = QuestionTypes.Picture;
                        break;
                    default:
                        break;
                }
            }

            return questionType;
        }

        private byte[] GetInspectionPDF(out string fileName, bool print = true)
        {
            fileName = "";
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string id = Request.Params["id"];
                    bool teamintelligence = Helper.IsTrue(Request.Params["team"]);
                    byte[] bytes = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        bytes = client.GetInspectionPDF(SystemParams.CompanyID, id);
                        fileName = client.GetInspection(SystemParams.CompanyID, id).Template.Name;
                        FICHostEnvironment.WriteExportAuditTrail(session.User.UID, "Inspection", "", print ? "Print" : "Download", fileName, print ? "" : ".pdf", bytes);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        bytes = client.GetInspectionPDF(SystemParams.CompanyID, id);
                        fileName = client.GetInspection(SystemParams.CompanyID, id).Template.Name;
                        FICHostEnvironment.WriteExportAuditTrail(session.User.UID, "AssetInspect", "", print ? "Print" : "Download", fileName, print ? "" : ".pdf", bytes);
                    }
                    return bytes;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        private object GetTemplates()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    int state = 0;
                    if (!int.TryParse(ps[1], out state))
                        state = -1;
                    string filter = HttpUtility.HtmlDecode(ps[2]);

                    int makeid = -1;
                    if (!int.TryParse(ps[3], out makeid))
                        makeid = -1;
                    int modelid = -1;
                    if (!int.TryParse(ps[4], out modelid))
                        modelid = -1;
                    int typeid = -1;
                    if (!int.TryParse(ps[5], out typeid))
                        typeid = -1;

                    FormTemplateItem[] templates = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        templates = client.GetFormTemplateItems(SystemParams.CompanyID, filter, user.IID, state);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        templates = client.GetAssetTemplateItems(SystemParams.CompanyID, filter, makeid, modelid, typeid, user.IID, state);
                    }
                    return templates;
                }
                else
                    return new FormTemplateItem[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetInspectEmailList()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    bool teamintelligence = Helper.IsTrue(clientdata);

                    UserEmailInfo[] users = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        users = client.GetInspectEmailList(SystemParams.CompanyID, string.Empty);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        users = client.GetInspectEmailList(SystemParams.CompanyID, string.Empty);
                    }
                    return users;
                }
                else
                    return new UserEmailInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetTemplate()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string id = HttpUtility.HtmlDecode(ps[1]);

                    FormTemplateInfo template = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        template = client.GetFormTemplate(SystemParams.CompanyID, Convert.ToInt64(id));
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        template = client.GetFormTemplate(SystemParams.CompanyID, Convert.ToInt64(id));
                    }
                    return template;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object TemplateSaveAs()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    long srctempid = Convert.ToInt64(ps[1]);
                    string newtemplatename = HttpUtility.HtmlDecode(ps[2]);

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        long id = client.TemplateSaveAs(SystemParams.CompanyID, srctempid, newtemplatename, session.User.UID);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        long id = client.TemplateSaveAs(SystemParams.CompanyID, srctempid, newtemplatename, session.User.UID);
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object SaveTemplate()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    var data = HttpUtility.HtmlDecode(ps[1]);
                    FormTemplateInfo templateinfo = JsonConvert.DeserializeObject<FormTemplateInfo>(HttpUtility.HtmlDecode(data));

                    var user = UserManagement.GetUserByIID(session.User.UID);
                    if (user.UserType == Users.UserTypes.Readonly)
                        return "";
                    else if (user.UserType == Users.UserTypes.Common)
                    {
                        var pc = CreateClient<PermissionProvider>(session.SessionID);
                        Tuple<Feature, Permissions>[] pmss = pc.GetUserPermissions(SystemParams.CompanyID, user.IID);
                        if (pmss.Length > 0)
                        {
                            int pkey = teamintelligence ? Feature.TEAM_TEMPLATES : Feature.INSPECTION_TEMPLATES;
                            Tuple<Feature, Permissions> pm = pmss.FirstOrDefault(m => m.Item1.Id == pkey);
                            if (pm.Equals(default(KeyValuePair<int, Permissions>))
                                || pm.Item2 != Permissions.FullControl)
                            {
                                return "";
                            }
                        }
                        else
                            return "";
                    }

                    if (templateinfo != null)
                    {
                        if (templateinfo.Pages != null)
                        {
                            foreach (var p in templateinfo.Pages)
                            {
                                if (string.IsNullOrWhiteSpace(p.Id))
                                    p.Id = Guid.NewGuid().ToString();
                                if (p.Sections != null)
                                {
                                    foreach (var s in p.Sections)
                                    {
                                        if (string.IsNullOrWhiteSpace(s.Id))
                                            s.Id = Guid.NewGuid().ToString();

                                        if (s.Questions != null)
                                        {
                                            foreach (var q in s.Questions)
                                            {
                                                if (string.IsNullOrWhiteSpace(q.Id))
                                                    q.Id = Guid.NewGuid().ToString();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (user.UserType < Users.UserTypes.SupperAdmin && !templateinfo.Editable)
                    {
                        if (teamintelligence)
                        {
                            var client = CreateClient<TeamIntelligenceClient>();
                            string[] useriids = null;
                            if (templateinfo.EmailList != null)
                                useriids = templateinfo.EmailList.Select(u => u.UserIID).ToArray();
                            client.SetTemplateEmailList(SystemParams.CompanyID, templateinfo.Id, useriids, templateinfo.Emails);
                        }
                        else
                        {
                            var client = CreateClient<AssetInspectClient>();
                            string[] useriids = null;
                            if (templateinfo.EmailList != null)
                                useriids = templateinfo.EmailList.Select(u => u.UserIID).ToArray();

                            client.SetTemplateEmailList(SystemParams.CompanyID, templateinfo.Id, useriids, templateinfo.Emails);
                        }
                        return new string[] { templateinfo.Id.ToString(), "Saved successfully." };
                    }

                    FormTemplateInfo newtemp = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        newtemp = client.UpdateTemplate(SystemParams.CompanyID, templateinfo, session.User.UID);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        newtemp = client.UpdateTemplate(SystemParams.CompanyID, templateinfo, session.User.UID);
                    }
                    return new string[] { newtemp.Id.ToString(), "Saved successfully." };
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object DeleteTemplate()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    long tempid = Convert.ToInt64(ps[1]);

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        client.DeleteTemplate(SystemParams.CompanyID, tempid, session.User.UID, string.Empty);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        client.DeleteTemplate(SystemParams.CompanyID, tempid, session.User.UID, string.Empty);
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object PublishTemplate()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    long tempid = Convert.ToInt64(ps[1]);

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        client.PublishTemplate(SystemParams.CompanyID, tempid, session.User.UID);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        client.PublishTemplate(SystemParams.CompanyID, tempid, session.User.UID);
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetGlobalSections()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var data = Request.Params["ClientData"];
                    bool teamintelligence = Helper.IsTrue(data);

                    Section[] sections = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        sections = client.GetGlobalSectionItems(SystemParams.CompanyID);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        sections = client.GetGlobalSectionItems(SystemParams.CompanyID);
                    }
                    return sections;
                }
                else
                    return new Section[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetGlobalQuestions()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string sectionid = HttpUtility.HtmlDecode(ps[1]);

                    Question[] questions = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        questions = client.GetGlobalQuestions(SystemParams.CompanyID, sectionid);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        questions = client.GetGlobalQuestions(SystemParams.CompanyID, sectionid);
                    }
                    return questions;
                }
                else
                    return new Question[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object SaveGlobalSection()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    var data = HttpUtility.HtmlDecode(ps[1]);
                    Section sec = JsonConvert.DeserializeObject<Section>(data);

                    if (string.IsNullOrEmpty(sec.Id))
                        sec.Id = Guid.NewGuid().ToString();

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        client.UpdateGlobalSectionItem(SystemParams.CompanyID, sec, session.User.UID);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        client.UpdateGlobalSectionItem(SystemParams.CompanyID, sec, session.User.UID);
                    }

                    return new string[] { sec.Id, "Saved successfully." };
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object SaveGlobalQuestion()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] data = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(data[0]);
                    string sectioinid = data[1];
                    Question q = JsonConvert.DeserializeObject<Question>(HttpUtility.HtmlDecode(data[2]));

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        if (string.IsNullOrEmpty(q.Id))
                        {
                            q.Id = Guid.NewGuid().ToString();
                            client.AddGlobalQuestion(SystemParams.CompanyID, sectioinid, q, session.User.UID);
                        }
                        else
                        {
                            client.UpdateGlobalQuestion(SystemParams.CompanyID, sectioinid, q, session.User.UID);
                        }
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        if (string.IsNullOrEmpty(q.Id))
                        {
                            q.Id = Guid.NewGuid().ToString();
                            client.AddGlobalQuestion(SystemParams.CompanyID, sectioinid, q, session.User.UID);
                        }
                        else
                        {
                            client.UpdateGlobalQuestion(SystemParams.CompanyID, sectioinid, q, session.User.UID);
                        }
                    }

                    return new string[] { q.Id, "Saved successfully." };
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object DeleteGlobalSection()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string sectionid = HttpUtility.HtmlDecode(ps[1]);

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        client.DeleteGlobalSection(SystemParams.CompanyID, sectionid, "", session.User.UID);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        client.DeleteGlobalSection(SystemParams.CompanyID, sectionid, "", session.User.UID);
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object DeleteGlobalQuestion()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string questionid = HttpUtility.HtmlDecode(ps[1]);

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        client.DeleteGlobalQuestion(SystemParams.CompanyID, questionid, "", session.User.UID);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        client.DeleteGlobalQuestion(SystemParams.CompanyID, questionid, "", session.User.UID);
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetGlobalSectionsByID()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string[] sids = JsonConvert.DeserializeObject<string[]>(ps[1]);

                    Section[] sections = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        sections = client.GetGlobalSection(SystemParams.CompanyID, sids);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        sections = client.GetGlobalSection(SystemParams.CompanyID, sids);
                    }
                    return sections;
                }
                else
                    return new Section[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetAssetMakes()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    AssetMake[] makes = CreateClient<AssetClassProvider>().GetAssetMakes(string.Empty);
                    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)
                    {
                        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 GetAssetTypes()
        {
            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 UploadStaticPicture()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    bool teamintelligence = Helper.IsTrue(clientdata);

                    HttpPostedFile uploadFile = null;
                    byte[] iconfilebyte = null;
                    if (Request.Files.Count > 0)
                    {
                        uploadFile = Request.Files[0];
                        iconfilebyte = ConvertFile2bytes(uploadFile);
                    }
                    string filetype = uploadFile.FileName.Substring(uploadFile.FileName.LastIndexOf("."));
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        Tuple<string, string> tp = client.UploadStaticPicture(SystemParams.CompanyID, filetype, iconfilebyte);
                        return tp;
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        Tuple<string, string> tp = client.UploadStaticPicture(SystemParams.CompanyID, filetype, iconfilebyte);
                        return tp;
                    }
                }
                return null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetStaticPictureContent()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string fileid = ps[1];
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        return client.GetStaticPictureContent(SystemParams.CompanyID, fileid);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        return client.GetStaticPictureContent(SystemParams.CompanyID, fileid);
                    }
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object DeleteStaticPicture()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string fileid = ps[1];
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        client.DeleteStaticPicture(SystemParams.CompanyID, fileid);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        client.DeleteStaticPicture(SystemParams.CompanyID, fileid);
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetFuelTypes()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    List<KeyValuePair<string, string>> list = FuelManagementClient.FuelTypes.OrderBy(m => m.Value).ToList();
                    var type1 = list.FirstOrDefault(m => m.Value == "Unleaded Regular");
                    var type2 = list.FirstOrDefault(m => m.Value == "Unleaded Plus");
                    var type3 = list.FirstOrDefault(m => m.Value == "Diesel #1");
                    list.Remove(type1);
                    list.Remove(type2);
                    list.Remove(type3);
                    list = list.OrderBy(m => m.Value).ToList();
                    list.Insert(0, type1);
                    list.Insert(1, type2);
                    list.Insert(2, type3);
                    return list.ToArray();
                }
                else
                    return new StringKeyValue[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "InspectionBasePage.GetFuelTypes", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        #region Fuel Log

        private object GetFuelReportItems()
        {
            try
            {
                var sesstion = GetCurrentLoginSession();
                if (sesstion != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    DateTime startdate = Helper.DBMinDateTime;
                    DateTime enddate = DateTime.MaxValue;
                    if (!DateTime.TryParse(ps[1], out startdate))
                        startdate = Helper.DBMinDateTime;
                    if (!DateTime.TryParse(ps[2], out enddate))
                        enddate = DateTime.MaxValue;

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        return new FuelTruckFuelReportItemInfo[0];
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        FuelTruckFuelReportItem[] fuelitems = client.GetFuelReportItems(SystemParams.CompanyID, startdate, enddate, -1);
                        if (fuelitems == null || fuelitems.Length == 0)
                            return new FuelLogItem[0];

                        fuelitems = fuelitems.OrderByDescending(m => m.CheckInTimeLocal).ToArray();

                        List<FuelLogItem> ls = new List<FuelLogItem>();
                        foreach (FuelTruckFuelReportItem item in fuelitems)
                        {
                            FuelTruckFuelReportItemInfo fuelinfo = new FuelTruckFuelReportItemInfo();
                            Helper.CloneProperty(fuelinfo, item);

                            FuelLogItem fuellog = ls.FirstOrDefault(m => m.LocalCalendarDate == fuelinfo.LocalCalendarDate);
                            if (fuellog == null)
                            {
                                fuellog = new FuelLogItem();
                                fuellog.LocalCalendarDate = fuelinfo.LocalCalendarDate;
                                fuellog.FuelReportItems = new List<FuelTruckFuelReportItemInfo>();
                                fuellog.FuelReportItems.Add(fuelinfo);
                                ls.Add(fuellog);
                            }
                            else
                            {
                                if (fuellog.FuelReportItems == null)
                                    fuellog.FuelReportItems = new List<FuelTruckFuelReportItemInfo>();
                                fuellog.FuelReportItems.Add(fuelinfo);
                            }
                        }

                        return ls.OrderByDescending(m => m.LocalCalendarDate).ToArray();
                    }

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

        private object GetFuelReport()
        {
            try
            {
                var sesstion = GetCurrentLoginSession();
                if (sesstion != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string id = HttpUtility.HtmlDecode(ps[1]);

                    FuelTruckFuelReport report = null;
                    FuelReportHeaderFooterItem hf = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        report = client.GetFuelReport(SystemParams.CompanyID, Convert.ToInt64(id));
                        hf = client.GetFuelReportHeaderFooter(SystemParams.CompanyID);
                    }

                    if (report == null)
                        return null;

                    FuelTruckFuelReportInfo fr = new FuelTruckFuelReportInfo();
                    Helper.CloneProperty(fr, report);
                    fr.TotalQtyStr = FormatDouble(report.TotalQty);
                    fr.StartMasterMeterStr = FormatDouble(report.StartMasterMeter);
                    fr.EndMasterMeterStr = FormatDouble(report.EndMasterMeter);
                    fr.InchesLeftonTruckStr = FormatDouble(report.InchesLeftonTruck);
                    if (report.Items != null)
                    {
                        List<FuelDetailInfo> list = new List<FuelDetailInfo>();
                        foreach (var a in report.Items)
                        {
                            FuelDetailInfo fi = new FuelDetailInfo();
                            Helper.CloneProperty(fi, a);
                            fi.AssetMeterStr = FormatDouble(fi.AssetMeter, fi.AssetMeterUnits);
                            fi.MasterMeterStr = FormatDouble(fi.MasterMeter);
                            fi.QtyPumpedStr = FormatDouble(fi.QtyPumped);
                            fi.QtyOnTruckStr = FormatDouble(fi.QtyOnTruck);
                            list.Add(fi);
                        }
                        fr.FuelDetailItems = list.ToArray();
                    }

                    fr.HeaderFooter = hf;
                    return fr;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetFuelReportHeaderFooter()
        {
            try
            {
                var sesstion = GetCurrentLoginSession();
                if (sesstion != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    bool teamintelligence = Helper.IsTrue(clientdata);

                    FuelReportHeaderFooterItem item = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        item = client.GetFuelReportHeaderFooter(SystemParams.CompanyID);
                    }

                    return item;

                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object UpdateFuelReportHeaderFooter()
        {
            try
            {
                var sesstion = GetCurrentLoginSession();
                if (sesstion != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string data = HttpUtility.HtmlDecode(ps[1]);
                    FuelReportHeaderFooterItem item = JsonConvert.DeserializeObject<FuelReportHeaderFooterItem>(data);
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        client.UpdateFuelReportHeaderFooter(SystemParams.CompanyID, item);
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetFuelLogEmailList()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    Foresight.Fleet.Services.User.UserInfo[] users = FleetServiceClientHelper.CreateClient<UserQueryClient>(SystemParams.CompanyID, session.SessionID).GetUsersByCustomerID(SystemParams.CompanyID, "");

                    if (users == null || users.Length == 0)
                        return new Foresight.Fleet.Services.User.UserInfo[0];

                    return users;
                }
                else
                    return new Foresight.Fleet.Services.User.UserInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object SendFuelTruckFuelReport()
        {
            try
            {
                var sesstion = GetCurrentLoginSession();
                if (sesstion != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string id = HttpUtility.HtmlDecode(ps[1]);
                    string edata = HttpUtility.HtmlDecode(ps[2]);
                    string[] emails = JsonConvert.DeserializeObject<string[]>(edata);
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        client.SendFuelTruckFuelReport(SystemParams.CompanyID, Convert.ToInt64(id), emails);
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private byte[] GetFuelReportPDF(out string fileName, bool print = true)
        {
            fileName = "";
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string id = Request.Params["id"];
                    bool teamintelligence = Helper.IsTrue(Request.Params["team"]);
                    byte[] bytes = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        bytes = client.GetFuelLogPDF(SystemParams.CompanyID, Convert.ToInt64(id));
                        fileName = "Fuel Log * Shipping Paper";//client.GetFuelReport(SystemParams.CompanyID, Convert.ToInt64(id)).EmployeeNumber;
                        FICHostEnvironment.WriteExportAuditTrail(session.User.UID, "FuelReport", "", print ? "Print" : "Download", fileName, print ? "" : ".pdf", bytes);
                    }
                    return bytes;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        protected object GetFuelReportItem(long reportid)
        {//只有id，不知道类型 
            var sesstion = GetCurrentLoginSession();
            bool fuellog = SystemParams.HasLicense("FuelLog");
            bool isadmin = (sesstion.User.UserType == Foresight.Fleet.Services.User.UserTypes.SupperAdmin || sesstion.User.UserType == Foresight.Fleet.Services.User.UserTypes.Admin);
            AssetInspectClient aclient = CreateClient<AssetInspectClient>();
            FuelTruckFuelReport aitem = aclient.GetFuelReport(SystemParams.CompanyID, reportid);
            if (aitem != null)
            {
                var ins = CheckRight(SystemParams.CompanyID, Feature.INSPECTION_REPORTS);
                if (fuellog && (isadmin || (sesstion.User.UserType == Foresight.Fleet.Services.User.UserTypes.Common && ins)))
                    return aitem;
                else
                    return null;
            }
            return null;
        }

        public static string FormatDouble(double val, string unit = "")
        {
            if (val > 0)
                return string.Format("{0:N2}", val) + " " + unit;
            return string.Empty;
        }
        #endregion

        #region Packages

        private object GetCreatedPackages()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var client = CreateClient<InspectPackageProvider>();
                    InspectPackageItem[] items = client.GetCreatedPackages(SystemParams.CompanyID);
                    if (items == null)
                        return new InspectPackageInfo[0];

                    List<InspectPackageInfo> ls = new List<InspectPackageInfo>();
                    foreach (InspectPackageItem item in items)
                    {
                        InspectPackageInfo pi = new InspectPackageInfo();
                        Helper.CloneProperty(pi, item);
                        ls.Add(pi);
                    }
                    return ls.ToArray();
                }
                else
                    return new InspectPackageInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object DeletePackage()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string packageid = ps[1];

                    var client = CreateClient<InspectPackageProvider>();
                    client.DeletePackage(SystemParams.CompanyID, packageid);
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetPackageContent()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string packageid = ps[1];

                    var client = CreateClient<InspectPackageProvider>();
                    client._GetPackageContent(SystemParams.CompanyID, packageid);
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object CreatePackage()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    long[] templates = JsonConvert.DeserializeObject<long[]>(ps[3]);
                    string[] globalsections = JsonConvert.DeserializeObject<string[]>(ps[4]);

                    var client = CreateClient<InspectPackageProvider>();
                    string pkgid = client.CreatePackage(SystemParams.CompanyID, ps[0], ps[1], ps[2], templates, globalsections);
                    return new { Id = pkgid };
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetPackageData()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    string pwd = clientdata;
                    byte[] buffer = null;
                    if (Request.Files.Count > 0)
                    {
                        var pkgfile = Request.Files[0];
                        buffer = ConvertFile2bytes(pkgfile);
                    }
                    if (buffer != null && !string.IsNullOrEmpty(pwd))
                    {
                        var pkgdata = InspectPackage.FromBuffer(pwd, buffer);
                        InspectPackageData data = new InspectPackageData();
                        data.GlobalSections.AddRange(pkgdata.GlobalItems.Values.Where(t => t.ItemType == 1));
                        data.IssueId = pkgdata.IssueId;
                        data.IssueName = pkgdata.IssueName;
                        data.Notes = pkgdata.Notes;
                        data.PackageId = pkgdata.PackageId;
                        data.PackageName = pkgdata.PackageName;
                        //data.StaticPictures
                        data.Templates.AddRange(pkgdata.Templates);
                        return data;
                    }
                    return "";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (BusinessException ex)
            {
                return ex.Message;
            }
            catch (Exception ex)
            {
                return "Invalid package.";
            }
        }
        private object ImportPackage()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    long[] templates = JsonConvert.DeserializeObject<long[]>(ps[1]);
                    string[] globalsections = JsonConvert.DeserializeObject<string[]>(ps[2]);

                    byte[] buffer = null;
                    if (Request.Files.Count > 0)
                    {
                        var pkgfile = Request.Files[0];
                        buffer = ConvertFile2bytes(pkgfile);
                    }
                    if (buffer != null)
                    {
                        var client = CreateClient<InspectPackageProvider>();
                        client.ImportPackage(SystemParams.CompanyID, buffer, templates, globalsections, ps[0] == "1");
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        #endregion

        private object GetAssetWorkOrders()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    long assetid = 0;
                    if (long.TryParse(clientdata, out assetid))
                    {
                        var wos = CreateClient<WorkOrderProvider>().GetWorkOrderItemsByAsset(SystemParams.CompanyID, assetid);
                        return wos.OrderByDescending(w => !w.Completed).ThenBy(w => w.WorkOrderNumber).ToArray();
                    }

                    return new WorkOrderListItem[0];
                }
                else
                    return new WorkOrderListItem[0];

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

        private object GetInspectionLayouts()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = HttpUtility.UrlDecode(Request.Form["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    if (teamintelligence)
                    {
                        return CreateClient<TeamIntelligenceClient>().GetReportLayoutItems(SystemParams.CompanyID, ps[1]);
                    }
                    else
                    {
                        return CreateClient<AssetInspectClient>().GetReportLayoutItems(SystemParams.CompanyID, ps[1]);
                    }
                }
                else
                {
                    return new ReportLayoutItem[0];
                }
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "InspectionPage.GetInspectionLayouts", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetInspectLayout()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = HttpUtility.UrlDecode(Request.Form["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string id = ps[1];
                    if (teamintelligence)
                    {
                        return CreateClient<TeamIntelligenceClient>().GetReportLayoutInfo(SystemParams.CompanyID, id);
                    }
                    else
                    {
                        return CreateClient<AssetInspectClient>().GetReportLayoutInfo(SystemParams.CompanyID, id);
                    }
                }
                else
                {
                    return new ReportLayoutItem[0];
                }
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "InspectionPage.GetInspectLayout", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object DeleteInspectLayout()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = HttpUtility.UrlDecode(Request.Form["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string id = ps[1];
                    if (teamintelligence)
                    {
                        CreateClient<TeamIntelligenceClient>().DeleteReportLayout(SystemParams.CompanyID, id);
                    }
                    else
                    {
                        CreateClient<AssetInspectClient>().DeleteReportLayout(SystemParams.CompanyID, id);
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "InspectionPage.DeleteInspectLayout", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object SaveInspectLayout()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = HttpUtility.UrlDecode(Request.Params["ClientData"]);
                    var layout = JsonConvert.DeserializeObject<ReportLayoutInfo>(clientdata);
                    if (string.IsNullOrEmpty(layout.Id))
                    {
                        layout.Id = Guid.NewGuid().ToString();
                    }
                    bool teamintelligence = layout.Target == TemplateTargets.Person;

                    if (Request.Files.Count > 0)
                    {
                        for (int i = 0; i < Request.Files.Count; i++)
                        {
                            var logoFile = Request.Files[i];
                            var logo = ConvertFile2bytes(logoFile);
                            string key = Request.Files.AllKeys[i];
                            if (string.Compare("iconFile", key, true) == 0)
                                layout.LOGO = FI.FIC.ResManager.MakeThumbnail(logo, 0, 180, "H");
                            else if (string.Compare("iconCenterFile", key, true) == 0)
                                layout.CenterLOGO = FI.FIC.ResManager.MakeThumbnail(logo, 0, 180, "H");
                            else if (string.Compare("iconRightFile", key, true) == 0)
                                layout.RightLOGO = FI.FIC.ResManager.MakeThumbnail(logo, 0, 180, "H");
                        }
                    }

                    if (teamintelligence)
                    {
                        CreateClient<TeamIntelligenceClient>().UpdateReportLayout(SystemParams.CompanyID, layout);
                    }
                    else
                    {
                        CreateClient<AssetInspectClient>().UpdateReportLayout(SystemParams.CompanyID, layout);
                    }

                    return new string[] { layout.Id, "Saved successfully." };
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "InspectionPage.SaveInspectLayout", ex.Message, ex.ToString());
                return ex.Message;
            }
        }
    }

    class TeamInspectInfo : TeamInspectItem
    {
        public string CommitTimeStr { get { return CommitTime == DateTime.MinValue ? "" : CommitTime.ToString(("M/d/yyyy h:mm tt")); } }
        public string CommitTimeLocalStr { get { return CommitTimeLocal == DateTime.MinValue ? "" : CommitTimeLocal.ToString(("M/d/yyyy h:mm tt")); } }
        public string LastUpdatedTimeLocalStr { get { return LastUpdatedTime.Year <= 1900 ? "" : LastUpdatedTimeLocal.ToString(("M/d/yyyy h:mm tt")); } }
    }

    class InspectReportItem : InspectReportInfo
    {
        public AssetBasicInfo Asset { get; set; }
        public string CommitTimeStr { get { return CommitTime == DateTime.MinValue ? "" : CommitTime.ToString("M/d/yyyy h:mm tt"); } }
        public string CommitTimeLocalStr { get { return CommitTimeLocal == DateTime.MinValue ? "" : CommitTimeLocal.ToString(("M/d/yyyy h:mm tt")); } }
        public List<IdentifiedQuestionItem> IdentifiedQuestions { get; set; }
        public ReportLayoutInfo ReportLayout { get; set; }
    }
    class IdentifiedQuestionItem : Question
    {
        public SeverityLeveles IdentifiedSeverityLevel { get; set; }
    }
    class InspectReportEditItem : InspectReportInfo
    {
        public AssetBasicInfo Asset { get; set; }
        public string CommitTimeStr { get { return CommitTime == DateTime.MinValue ? "" : CommitTime.ToString("M/d/yyyy h:mm tt"); } }
        public string CommitTimeLocalStr { get { return CommitTimeLocal == DateTime.MinValue ? "" : CommitTimeLocal.ToString("M/d/yyyy h:mm tt"); } }
        public UserEmailInfo[] EmailList { get; set; }
        public AssetBasicInfo[] AssetList { get; set; }
        public JobSiteItem[] JobSiteList { get; set; }
    }

    class FuelLogItem
    {
        public DateTime LocalCalendarDate { get; set; }
        public string LocalCalendarDateStr { get { return LocalCalendarDate == DateTime.MinValue ? "" : LocalCalendarDate.ToString("M/d/yyyy"); } }
        public int FuelReportCount { get { return FuelReportItems == null ? 0 : FuelReportItems.Count(); } }
        public List<FuelTruckFuelReportItemInfo> FuelReportItems { get; set; }
    }

    class FuelTruckFuelReportItemInfo : FuelTruckFuelReportItem
    {
        public string LocalCalendarDateStr { get { return LocalCalendarDate == DateTime.MinValue ? "" : LocalCalendarDate.ToString("M/d/yyyy"); } }
        public string CheckInTimeLocalStr { get { return CheckInTimeLocal == DateTime.MinValue ? "" : CheckInTimeLocal.ToString("h:mm tt"); } }
        public string CheckOutTimeLocalStr { get { return CheckOutTimeLocal == null ? "" : CheckOutTimeLocal.Value.ToString("h:mm tt"); } }
    }

    class FuelTruckFuelReportInfo : FuelTruckFuelReport
    {
        public string LocalCalendarDateStr { get { return LocalCalendarDate == DateTime.MinValue ? "" : LocalCalendarDate.ToString("M/d/yyyy"); } }
        public FuelDetailInfo[] FuelDetailItems { get; set; }
        public string CheckInLocalStr { get { return CheckInLocal == DateTime.MinValue ? "" : CheckInLocal.ToString("M/d/yyyy h:mm tt"); } }
        public string CheckOutLocalStr { get { return CheckOutLocal == null ? "" : CheckOutLocal.Value.ToString("M/d/yyyy h:mm tt"); } }

        public string StartMasterMeterStr { get; set; }
        public string EndMasterMeterStr { get; set; }
        public string TotalQtyStr { get; set; }
        public string InchesLeftonTruckStr { get; set; }
        public FuelReportHeaderFooterItem HeaderFooter { get; set; }
    }

    class FuelDetailInfo : FuelDetailItem
    {
        public string CommitTimeLocalStr { get { return CommitTimeLocal == DateTime.MinValue ? "" : CommitTimeLocal.ToString("M/d/yyyy h:mm tt"); } }
        public string AssetMeterStr { get; set; }
        public string MasterMeterStr { get; set; }
        public string QtyPumpedStr { get; set; }
        public string QtyOnTruckStr { get; set; }
    }
    class InspectPackageInfo : InspectPackageItem
    {
        public string CreatedOnLocalStr { get { return CreatedOnLocal == DateTime.MinValue ? "" : CreatedOnLocal.ToString("M/d/yyyy h:mm tt"); } }

    }
    class InspectPackageData : InspectPackage
    {
        public List<Pkg_TemplateItem> GlobalSections { get; set; } = new List<Pkg_TemplateItem>();
    }
}

