using Foresight.Fleet.Services;
using Foresight.Fleet.Services.Asset;
using Foresight.ServiceModel;
using IronIntel.Contractor.Maintenance;
using IronIntel.Contractor.Users;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

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

            try
            {
                if (methodName != null)
                {
                    switch (methodName.ToUpper())
                    {
                        case "GETTYPESDATA":
                            GetTypesData();
                            break;
                        case "GETRECORDS":
                            GetRecords();
                            break;
                        case "GETMACHINEINFO":
                            GetmachineInfo();
                            break;
                        case "SEARCHMACHINELIST":
                            SearchmachineList();
                            break;
                        case "ADDMAINTENANCE":
                            result = Addmaintenance();
                            break;
                        case "GETRECORDSBYMACHINEID":
                            GetRecordsbymachineID();
                            break;
                        case "DELETEMAINTENANCE":
                            Deletemaintenance();
                            break;
                        case "GETUNCOMPLETEDPMALERTS":
                            result = GetUnCompletedPMAlerts();
                            break;
                        case "GETUSERSDATA":
                            GetUsersData();
                            break;
                        case "GETMAINTANENCELOGATTACHLIST":
                            result = GetMaintanenceLogAttachList();
                            break;
                        case "GETMAINTENANCEINFO":
                            result = GetMaintenanceInfo();
                            break;
                        case "GETATTACHMENTS":
                            result = GetAttachments();
                            break;
                        case "ADDATTACHMENT":
                            result = AddAttachment();
                            break;
                        case "DELETEATTACHMENT":
                            result = DeleteAttachment();
                            break;
                    }
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "MaintanceRecordsBasePage" + methodName, ex.Message, ex.ToString());
            }
            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }
        private void GetTypesData()
        {
            string json = "";
            List<KeyValuePair<int, string>> typeskeypair = new List<KeyValuePair<int, string>>();
            AssetType[] types = CreateClient<AssetClassProvider>().GetAssetTypes(SystemParams.CompanyID);
            foreach (AssetType item in types)
            {
                typeskeypair.Add(new KeyValuePair<int, string>(item.ID, item.Name));
            }
            if (typeskeypair.Count > 0)
            {
                typeskeypair = typeskeypair.OrderBy(t => t.Value).ToList();
            }
            json += JsonConvert.SerializeObject(typeskeypair);
            Response.Write(json);
            Response.End();
        }

        private void GetRecords()
        {
            var session = GetCurrentLoginSession();
            string json = "";
            long assetid = -1;
            long.TryParse(Request.Params["assetid"], out assetid);
            string maintenanceType = Request.Params["maintenancetype"];
            string mtype = Request.Params["type"];
            string searchtxt = HttpUtility.UrlDecode(Request.Params["searchtxt"]);
            string sortype = HttpUtility.UrlDecode(Request.Params["sortype"]);
            string sortdata = HttpUtility.UrlDecode(Request.Params["sortdata"]);
            string sdatestr = HttpUtility.UrlDecode(Request.Params["startdate"]);
            string edatestr = HttpUtility.UrlDecode(Request.Params["enddate"]);

            DateTime beginDate = Helper.DBMinDateTime;
            DateTime endDate = DateTime.MaxValue;
            if (!DateTime.TryParse(sdatestr, out beginDate))
                beginDate = Helper.DBMinDateTime;
            if (!DateTime.TryParse(edatestr, out endDate))
                endDate = DateTime.MaxValue;

            MaintenanceLogInfo[] logs = MaintenanceManagement.GetMaintenanceLog(session.SessionID, assetid, maintenanceType, string.IsNullOrWhiteSpace(mtype) ? -1 : Convert.ToInt32(mtype), searchtxt, beginDate, endDate, session.User.UID);

            if (!string.IsNullOrWhiteSpace(sortype))
            {
                if (string.Compare(sortype, "1", true) == 0)
                {
                    if (string.Compare(sortdata, "DESC", true) == 0)
                    {
                        logs = logs.OrderByDescending(m => m.MaintenanceDate).ToArray();
                    }
                    else
                    {
                        logs = logs.OrderBy(m => m.MaintenanceDate).ToArray();
                    }
                }

                if (string.Compare(sortype, "2", true) == 0)
                {
                    if (string.Compare(sortdata, "DESC", true) == 0)
                    {
                        logs = logs.OrderByDescending(m => m.AlertTime).ToArray();
                    }
                    else
                    {
                        logs = logs.OrderBy(m => m.AlertTime).ToArray();
                    }
                }
            }


            json += JsonConvert.SerializeObject(logs);
            Response.Write(json);
            Response.End();
        }

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

                    MaintenanceLogInfo ml = MaintenanceManagement.GetMaintenanceInfo(id);
                    return ml;
                }
                else
                    return new MaintenanceLogInfo();
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "MaintanceRecordsBasePage.GetMaintenanceInfo", ex.Message, ex.ToString());
                return ex.Message;
            }
        }


        private void GetRecordsbymachineID()
        {
            string json = "";
            long mid = -1;
            long.TryParse(Request.Params["machineID"].ToString(), out mid);
            string maintenanceType = Request.Params["maintenancetype"];
            MaintenanceLogInfo[] logs = MaintenanceManagement.GetMaintenanceLogByMachineID(mid, maintenanceType).OrderByDescending(log => log.MaintenanceDate).ToArray();
            json += JsonConvert.SerializeObject(logs);
            Response.Write(json);
            Response.End();
        }
        private void GetmachineInfo()
        {
            string json = "";
            long mid = -1;
            long.TryParse(Request.Params["machineID"].ToString(), out mid);
            AssetBasicInfo asset = CreateClient<AssetQueryClient>().GetAssetBasicInfoByID(SystemParams.CompanyID, mid);

            MaintenanceMachineInfo mi = new MaintenanceMachineInfo();
            mi.MachineID = asset.ID;
            mi.MachineName = asset.Name;
            mi.MachineName2 = asset.Name2;
            mi.VIN = asset.VIN;
            mi.EngineHours = asset.EngineHours == null ? 0 : asset.EngineHours.Value;
            mi.Make = asset.MakeName;
            mi.Model = asset.ModelName;
            mi.TypeID = asset.TypeID;
            mi.MachineType = asset.TypeName;
            json += JsonConvert.SerializeObject(mi);
            Response.Write(json);
            Response.End();
        }
        private void SearchmachineList()
        {
            var session = GetCurrentLoginSession();
            string json = "";
            string mtype = Request.Params["type"];
            string searchtxt = HttpUtility.HtmlDecode(Request.Params["searchtxt"]);

            MaintenanceMachineInfo[] machines = MaintenanceManagement.GetMaintenanceMachines(session.SessionID, string.IsNullOrWhiteSpace(mtype) ? -1 : Convert.ToInt32(mtype), searchtxt, session.User.UID);
            if (machines.Length > 0)
            {
                json = JsonConvert.SerializeObject(machines);
            }
            Response.Write(json);
            Response.End();
        }

        private object Addmaintenance()
        {
            try
            {
                UserInfo u = GetCurrentUser();
                if (u != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    clientdata = HttpUtility.HtmlDecode(clientdata);
                    MaintenanceLogInfo m = JsonConvert.DeserializeObject<MaintenanceLogInfo>(clientdata);

                    MaintenanceLogInfo oldinfo = null;
                    if (!string.IsNullOrEmpty(m.MaintenanceID))
                    {
                        oldinfo = MaintenanceManagement.GetMaintenanceLogByMaintenanceID(m.MaintenanceID);
                    }
                    if (oldinfo == null)
                    {
                        oldinfo = new MaintenanceLogInfo();
                        oldinfo.MaintenanceID = Guid.NewGuid().ToString().ToUpper();
                    }
                    oldinfo.MachineID = m.MachineID;
                    oldinfo.MaintenanceDate = m.MaintenanceDate;
                    oldinfo.MaintenanceHours = m.MaintenanceHours;
                    oldinfo.ODOMeter = m.ODOMeter;
                    oldinfo.ODOMemterUOM = m.ODOMemterUOM;
                    oldinfo.Notes = HttpUtility.HtmlDecode(m.Notes);
                    oldinfo.LogType = m.LogType;
                    oldinfo.Cost = m.Cost;
                    oldinfo.InvoiceNumber = m.InvoiceNumber;
                    oldinfo.AttachmentIDs = m.AttachmentIDs;

                    if (oldinfo.AlertID != m.AlertID && oldinfo.AlertID > 0)
                    {//取消旧的Alert Completed状态
                        MaintenanceManagement.SetPMAlertCompleted(oldinfo.AlertID, false, "");
                    }
                    if (m.AlertID > 0)//对于Alert，关联了Maintenance Rocord才认为是完成
                    {//更新新的Alert Completed状态
                        MaintenanceManagement.SetPMAlertCompleted(m.AlertID, true, m.CompletedByName);
                    }

                    oldinfo.CompletedByName = m.CompletedByName;
                    oldinfo.Completed = !string.IsNullOrWhiteSpace(m.CompletedByName);//对于Maintenance Rocord选择了Completed By就认为是完成
                    oldinfo.AlertID = m.AlertID;

                    MaintenanceManagement.UpdateMaintenanceLog(oldinfo, u.IID);
                    AttachmentsManagement.SaveAttach(oldinfo.MaintenanceID, u.IID, oldinfo.AttachmentIDs, AttachmentType.MaintenanceLog);

                    return new string[] { oldinfo.MaintenanceID, "Saved Successfully." };
                }
                else
                    return "Failed to save,The user is not logged.";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        private void Deletemaintenance()
        {
            string maintenanceID = Request.Params["maintenanceid"].ToString();
            UserInfo u = GetCurrentUser();
            if (u != null)
            {
                MaintenanceLogInfo m = MaintenanceManagement.GetMaintenanceLogByMaintenanceID(maintenanceID);
                if (m.AlertID > 0)//取消Alert Completed状态
                    MaintenanceManagement.SetPMAlertCompleted(m.AlertID, false, "");
                MaintenanceManagement.DeleteMaintenanceLog(maintenanceID);
                Response.Write(JsonConvert.SerializeObject("Deleted Successfully."));
            }
            else
                Response.Write(JsonConvert.SerializeObject("Failed to delete record."));
            Response.End();
        }

        private object GetUnCompletedPMAlerts()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    long machineid = -1;
                    long.TryParse(clientdata[0], out machineid);
                    string maintenanceid = clientdata[1];

                    PMAlert[] pmalerts = MaintenanceManagement.GetUnCompletedPMAlerts(machineid, maintenanceid);

                    return pmalerts;
                }
                else
                    return new PMAlert[0];

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

        private void GetUsersData()
        {
            UserInfo[] user = UserManagement.GetUsers();
            user = user.OrderBy((u) => u.DisplayName).ToArray();
            string json = JsonConvert.SerializeObject(user);
            Response.Write(json);
            Response.End();
        }

        private object GetMaintanenceLogAttachList()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var id = HttpUtility.HtmlDecode(clientdata[0]);
                    var type = HttpUtility.HtmlDecode(clientdata[1]);
                    StringKeyValue[] attas = AttachmentsManagement.GetAttachList(id, type);

                    return attas;
                }
                else
                    return new StringKeyValue[0];

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


        #region Attachment

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

                    AttachmentItem[] atts = CreateClient<AttachmentProvider>().GetAttachmentItems(SystemParams.CompanyID, "MaintenanceLog", woid);
                    if (atts == null || atts.Length <= 0)
                        return new AttachmentItem[0];

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

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

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

                    string FileName = uploadFile == null ? "" : uploadFile.FileName;
                    long attid = CreateClient<AttachmentProvider>().AddAttachment(SystemParams.CompanyID, "MaintenanceLog", woid, FileName, "", iconfilebyte);

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

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

                    CreateClient<AttachmentProvider>().DeleteAttachment(SystemParams.CompanyID, long.Parse(attachid));
                    return "OK";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }


        #endregion
    }
}
