using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using IronIntel.Contractor.Machines;
using IronIntel.Contractor.Maintenance;
using IronIntel.Services.Business.Admin;
using System.Web;
using IronIntel.Contractor.Users;
using Foresight.ServiceModel;
using Foresight.Fleet.Services.Attachment;
using IronIntel.Contractor.Attachment;

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 "GETMACHINES":
                            Getmachines();
                            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>>();
            MachineServiceClient2 mc = new MachineServiceClient2(SystemParams.SystemServiceAddresses[0]);
            MachineType[] types = mc.GetMachineTypes();
            foreach (MachineType 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"]);
            MaintenanceLogInfo[] logs = MaintenanceManagement.GetMaintenanceLog(session.SessionID, assetid, maintenanceType, string.IsNullOrWhiteSpace(mtype) ? -1 : Convert.ToInt32(mtype), searchtxt, 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);
            MaintenanceMachineInfo machine = MaintenanceManagement.GetmachineByMachineID(mid);
            json += JsonConvert.SerializeObject(machine);
            Response.Write(json);
            Response.End();
        }
        private void Getmachines()
        {
            var session = GetCurrentLoginSession();
            string json = "";
            string mtype = Request.Params["type"];
            string searchtxt = HttpUtility.UrlDecode(Request.Params["searchtxt"]);
            MaintenanceMachineInfo[] machines = MaintenanceManagement.GetMaintenanceMachines(session.SessionID, string.IsNullOrWhiteSpace(mtype) ? -1 : Convert.ToInt32(mtype), searchtxt, session.User.UID).OrderBy(t => t.VIN).ToArray();
            json += JsonConvert.SerializeObject(machines);
            Response.Write(json);
            Response.End();
        }
        private void SearchmachineList()
        {
            var session = GetCurrentLoginSession();
            string json = "";
            string mtype = Request.Params["type"];
            string searchtxt = HttpUtility.UrlDecode(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"];
                    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.UrlDecode(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]);

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

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

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

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

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

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

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

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

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

        }


        #endregion
    }
}
