using Foresight.Fleet.Services.Asset;
using Foresight.Fleet.Services.JobSite;
using Foresight.Fleet.Services.MapView;
using Foresight.Fleet.Services.User;
using Foresight.Standard;
using IronIntel.Contractor.ExportExcel;
using IronIntel.Contractor.FilterQ;
using IronIntel.Contractor.JobSites;
using IronIntel.Contractor.Machines;
using IronIntel.Contractor.MapView;
using IronIntel.Contractor.Users;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace IronIntel.Contractor.Site.JobSite
{
    public class JobSitesBasePage : ContractorBasePage
    {
        protected void ProcessRequest()
        {
            object result = null;
            try
            {
                string methodName = Request.Params["MethodName"];
                if (methodName != null)
                {
                    switch (methodName)
                    {
                        case "GetNavigations":
                            result = GetNavigations();
                            break;
                        case "GetJobSites":
                            result = GetJobSites();
                            break;
                        case "SaveJobSite":
                            result = SaveJobSite();
                            break;
                        case "DeleteJobSite":
                            result = DeleteJobSite();
                            break;
                        case "SaveJobSiteMachines":
                            result = SaveJobSiteMachines();
                            break;
                        case "GetMachines":
                            result = GetMachines();
                            break;
                        case "GetCompanyLocations":
                            result = GetCompanyLocations();
                            break;
                        case "GetShapeFileInfos":
                            result = GetShapeFileInfos();
                            break;
                        case "GetShapeData":
                            result = GetShapeData();
                            break;
                        case "GetSelectedAssets":
                            result = GetSelectedAssets();
                            break;
                        case "AddAssetToJobSite":
                            result = AddAssetToJobSite();
                            break;
                        case "RemoveAssetFromJobSite":
                            result = RemoveAssetFromJobSite();
                            break;
                        case "ChangeAssetOnSiteState":
                            result = ChangeAssetOnSiteState();
                            break;
                        case "GetMachineTypes":
                            result = GetMachineTypes();
                            break;
                        case "GetBindingMachines":
                            result = GetBindingMachines();
                            break;
                        case "ImportJobsitePolygon":
                            result = ImportJobsitePolygon();
                            break;
                        case "GetJobSiteUsers":
                            result = GetJobSiteUsers();
                            break;
                        case "GetJobSiteTypes":
                            result = GetJobSiteTypes();
                            break;
                        case "GetForemans":
                            result = GetForemans();
                            break;
                        case "GetImportJobsiteColumns":
                            result = GetImportJobsiteColumns();
                            break;
                        case "ImportJobsites":
                            result = ImportJobsites();
                            break;
                        case "GetJobsiteAutoCreateItems":
                            result = GetJobsiteAutoCreateItems();
                            break;
                        case "SaveJobsiteAutoCreateItems":
                            result = SaveJobsiteAutoCreateItems();
                            break;
                        case "DeleteJobsiteAutoCreateItems":
                            result = DeleteJobsiteAutoCreateItems();
                            break;
                        case "GetRegions":
                            result = GetRegions();
                            break;
                        case "GetJobSiteDataSource":
                            result = GetJobSiteDataSource();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "JobSitesBasePage", ex.Message, ex.ToString());
                throw ex;
            }
            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }

        private object GetJobSites()
        {
            try
            {
                JobSiteViewItem[] items = null;
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    string[] types = JsonConvert.DeserializeObject<string[]>(clientdata[0]);
                    var filter = HttpUtility.HtmlDecode(clientdata[1]);
                    bool activesitesonly = Helper.IsTrue((clientdata[2]));

                    var jss = CreateClient<JobSiteProvider>().GetJobSiteItems(SystemParams.CompanyID, filter, types, activesitesonly);
                    List<JobSiteViewItem> list = new List<JobSiteViewItem>();

                    foreach (var js in jss)
                    {
                        JobSiteViewItem item = new JobSiteViewItem();
                        Helper.CloneProperty(item, js);
                        item.BaseOnMachineID = js.BaseonMachineID;
                        item.Types = new string[] { js.JobSiteTypes };
                        item.ColorString = js.Color;
                        System.Drawing.Color color = System.Drawing.Color.Black;
                        try
                        {
                            color = System.Drawing.ColorTranslator.FromHtml(item.ColorString);
                        }
                        catch
                        {
                            item.ColorString = "#000000";
                        }
                        item.Color = new IIColor() { Alpha = color.A, Red = color.R, Green = color.G, Blue = color.B };

                        item.StartDate = js.StartDate == null ? DateTime.MinValue : js.StartDate.Value;
                        item.EndDate = js.EndDate == null ? DateTime.MinValue : js.EndDate.Value;
                        item.ProjectedEndDate = js.ProjectedEndDate == null ? DateTime.MinValue : js.ProjectedEndDate.Value;
                        item.Radius_UOM = js.RadiusUOM;
                        if (js.Polygon != null && js.Polygon.Length > 0)
                        {
                            List<PostionItem> temps = new List<PostionItem>();
                            foreach (var p in js.Polygon)
                            {
                                temps.Add(new PostionItem(p.Latitude, p.Longtitude));
                            }
                            item.Polygon = temps.ToArray();
                        }

                        list.Add(item);
                    }
                    items = list.ToArray();
                    //items = JobSitesManagement.GetJobSite(s);
                }
                else
                {
                    items = new JobSiteViewItem[0];
                }
                return items;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetJobSiteDataSource()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var companyid = Request.Form["ClientData"];
                    if (string.IsNullOrEmpty(companyid))
                        companyid = SystemParams.CompanyID;
                    var jss = CreateClient<JobSiteProvider>().GetJobSiteItems(companyid, "", null, true);
                    var js = jss.OrderBy(g => g.Name).Select(i => new
                    {
                        i.ID,
                        i.Name,
                        i.Code
                    }).ToArray();
                    var codes = jss.Select(i => i.Code).Where(i => !string.IsNullOrWhiteSpace(i)).Distinct().OrderBy(i => i);
                    return new { Jobsites = js, Codes = codes };
                }
                return null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

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

                    var js = JsonConvert.DeserializeObject<JobSiteViewItem>(s);
                    JobSiteItem jobsite = new JobSiteItem();
                    Helper.CloneProperty(jobsite, js);
                    jobsite.RadiusUOM = js.Radius_UOM;
                    jobsite.BaseonMachineID = js.BaseOnMachineID;
                    jobsite.Color = js.ColorString;
                    jobsite.JobSiteTypes = string.Join(",", js.Types);
                    if (js.StartDate > Helper.DBMinDateTime)
                        jobsite.StartDate = js.StartDate;
                    if (js.ProjectedEndDate > Helper.DBMinDateTime)
                        jobsite.ProjectedEndDate = js.ProjectedEndDate;
                    if (js.EndDate > Helper.DBMinDateTime)
                        jobsite.EndDate = js.EndDate;
                    if (js.Polygon != null && js.Polygon.Length > 0)
                    {
                        List<Position> list = new List<Position>();
                        foreach (PostionItem pi in js.Polygon)
                        {
                            Position p = new Position(pi.Latitude, pi.Longitude);
                            list.Add(p);
                        }
                        jobsite.Polygon = list.ToArray();
                    }

                    long jobsiteid = CreateClient<JobSiteProvider>().SaveJobSite(SystemParams.CompanyID, jobsite, GetCurrentLoginSession().User.UID);

                    JobSitesManagement.RefreshJobsiteAssets(session.SessionID, jobsiteid);

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

        private string DeleteJobSite()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var s = HttpUtility.HtmlDecode(clientdata[0]);
                    long jsid = Convert.ToInt64(s);
                    var notes = HttpUtility.HtmlDecode(clientdata[1]);

                    CreateClient<JobSiteProvider>().DeleteJobSite(SystemParams.CompanyID, jsid, notes, user.IID);
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private string SaveJobSiteMachines()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var s = Request.Form["ClientData"];
                    s = HttpUtility.HtmlDecode(s);
                    var jobsite = JsonConvert.DeserializeObject<JobSiteViewItem>(s);

                    JobSitesManagement.AddMachinesToJobSite(jobsite);

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

        private AssetMapViewPinItem[] GetMachines()
        {
            var session = GetCurrentLoginSession();
            if (session != null)
            {
                AssetMapViewPinItem[] items = AssetMapViewManagement.GetAssets(session.SessionID, SystemParams.CompanyID, session.User.UID, "", -1, null, false, 0);
                return items;
            }
            return new AssetMapViewPinItem[0];
        }
        private CompanyLocationViewItem[] GetCompanyLocations()
        {
            CompanyLocationViewItem[] items = null;
            var session = GetCurrentLoginSession();
            if (session != null)
            {
                string p = Context.Request.Params["ClientData"];
                string companyid = p;
                if (string.IsNullOrEmpty(companyid))
                    companyid = SystemParams.CompanyID;

                var client = FleetServiceClientHelper.CreateClient<MapViewQueryClient>(companyid, session.SessionID);
                CustomerLocation[] locs = client.GetContractorAndDealerLocations(companyid);
                List<CompanyLocationViewItem> temps = new List<CompanyLocationViewItem>();
                foreach (var loc in locs)
                {
                    CompanyLocationViewItem l = new CompanyLocationViewItem();
                    l.ID = loc.ID;
                    l.Latitude = loc.Latitude;
                    l.Longitude = loc.Longitude;
                    l.LocationName = loc.Name;
                    l.Notes = loc.Notes;
                    l.IconUrl = loc.IconUrl;
                    temps.Add(l);
                }
                items = temps.ToArray();
            }
            else
            {
                items = new CompanyLocationViewItem[0];
            }
            return items.ToArray();
        }

        private object GetShapeFileInfos()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Context.Request.Params["ClientData"]);
                    StringKeyValue kv = JsonConvert.DeserializeObject<StringKeyValue>(clientdata);
                    string customerid = kv.Key;
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;

                    ShapeFileInfo[] files = FleetServiceClientHelper.CreateClient<ShapeFileProvider>(customerid, session.SessionID).GetShapeFileInfos(customerid, kv.Value);

                    return files.OrderBy(m => m.Name).ToArray();
                }
                else
                {
                    return new ShapeFileInfo[0];
                }
            }
            catch
            {
                return new ShapeFileInfo[0];
            }
        }
        private object GetShapeData()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Context.Request.Params["ClientData"]);
                    StringKeyValue kv = JsonConvert.DeserializeObject<StringKeyValue>(clientdata);
                    string customerid = kv.Key;
                    if (string.IsNullOrEmpty(customerid))
                        customerid = SystemParams.CompanyID;
                    string fileName = kv.Tag ?? "";

                    byte[] buffer = FleetServiceClientHelper.CreateClient<ShapeFileProvider>(customerid, session.SessionID).GetShapeData(customerid, Convert.ToInt64(kv.Value));

                    Shape.Shape shape = new Shape.Shape();
                    if (fileName == "" || fileName.EndsWith(".shp", StringComparison.OrdinalIgnoreCase))
                        Shape.ShapeFileParser.ParseFromShapeFile(buffer, shape);
                    else if (fileName.EndsWith(".kml", StringComparison.OrdinalIgnoreCase))
                        Shape.ShapeFileParser.ParseFromKMLFile(buffer, shape);
                    else if (fileName.EndsWith(".kmz", StringComparison.OrdinalIgnoreCase))
                        Shape.ShapeFileParser.ParseFromKMZFile(buffer, shape);
                    Shape.SimpleShape ss = new Shape.SimpleShape();
                    ss.FromShapeObj(shape);

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

        private object[] GetSelectedAssets()
        {
            var u = GetCurrentUser();
            if (u != null)
            {
                var clientdata = Request.Form["ClientData"].Split((char)170);
                var companyid = HttpUtility.HtmlDecode(clientdata[0]);
                if (string.IsNullOrEmpty(companyid))
                {
                    companyid = SystemParams.CompanyID;
                }
                var jobsiteid = long.Parse(clientdata[1]);
                var jsassets = CreateClient<JobSiteProvider>(companyid).GetAssetsCurrentInJobSite(companyid, jobsiteid);
                if (u.UserType < Users.UserTypes.Admin)
                {
                    AssetBasicInfo[] allassets = CreateClient<AssetQueryClient>(companyid).GetAssetBasicInfoByUser(companyid, "", u.IID, 0);
                    var allassetids = allassets.Select(a => a.ID).ToList();
                    jsassets = jsassets.Where(a => allassetids.Contains(a.AssetId)).ToArray();
                }
                return jsassets.Select(i => new
                {
                    i.AssetId,
                    i.OnSite,
                    Name = string.IsNullOrEmpty(i.AssetName2) ? (string.IsNullOrEmpty(i.AssetName) ? i.VIN : i.AssetName) : i.AssetName2,
                    i.VIN,
                    i.MakeName,
                    i.ModelName,
                    i.TypeName
                }).ToArray();
            }
            return new object[0];
        }

        private string AddAssetToJobSite()
        {
            try
            {
                var u = GetCurrentUser();
                if (u != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyId = HttpUtility.HtmlDecode(clientdata[0]);
                    if (string.IsNullOrEmpty(companyId))
                    {
                        companyId = SystemParams.CompanyID;
                    }
                    var jobsiteid = long.Parse(clientdata[1]);
                    var machineids = HttpUtility.HtmlDecode(clientdata[2]);

                    var ids = JsonConvert.DeserializeObject<long[]>(machineids);

                    var client = CreateClient<JobSiteProvider>(companyId);
                    client.AddAssetsToJobSite(companyId, jobsiteid, ids, false, u.IID);
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "JobSitesBasePage.AddAssetToJobSite", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private string RemoveAssetFromJobSite()
        {
            try
            {
                var u = GetCurrentUser();
                if (u != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyId = HttpUtility.HtmlDecode(clientdata[0]);
                    if (string.IsNullOrEmpty(companyId))
                    {
                        companyId = SystemParams.CompanyID;
                    }
                    var jobsiteid = long.Parse(clientdata[1]);
                    var machineids = HttpUtility.HtmlDecode(clientdata[2]);

                    var ids = JsonConvert.DeserializeObject<long[]>(machineids);

                    var client = CreateClient<JobSiteProvider>(companyId);
                    foreach (var id in ids)
                    {
                        client.RemoveAssetFromJobSite(companyId, jobsiteid, id, u.IID);
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "JobSitesBasePage.RemoveAssetFromJobSite", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private string ChangeAssetOnSiteState()
        {
            try
            {
                var u = GetCurrentUser();
                if (u != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyId = HttpUtility.HtmlDecode(clientdata[0]);
                    if (string.IsNullOrEmpty(companyId))
                    {
                        companyId = SystemParams.CompanyID;
                    }
                    var jobsiteid = long.Parse(clientdata[1]);
                    var assetid = long.Parse(clientdata[2]);
                    var onsite = (clientdata[3] == "1");

                    CreateClient<JobSiteProvider>(companyId).ChangeAssetOnSiteState(companyId, jobsiteid, assetid, onsite, u.IID);
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "JobSitesBasePage.ChangeAssetOnSiteState", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetBindingMachines()
        {
            var session = GetCurrentLoginSession();
            var assets = CreateClient<JobSiteProvider>().GetBindingMachines(SystemParams.CompanyID);// 获取可用于Jobsite 绑定的机器, Calamp和FI Tracker
            if (assets != null)
            {
                assets = assets.OrderBy((m) => m.DisplayName).ToArray();
            }
            return assets;
        }

        private MachineTypeItem[] GetMachineTypes()
        {
            MachineTypeItem[] types = JobSitesManagement.GetMachineTypes();
            if (types != null)
            {
                types = types.OrderBy((t) => t.Name).ToArray();
            }
            return types;
        }

        private object ImportJobsitePolygon()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    string fileName = clientdata;

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

                    return JobSitesManagement.ImportJobsitePolygon(fileName, buffer);
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetJobSiteUsers()
        {
            try
            {
                UserNameInfoItem[] items = null;
                if (GetCurrentLoginSession() != null)
                {
                    var data = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                    var jobsiteid = long.Parse(data);
                    var users = CreateClient<JobSiteProvider>().GetJobisteUserNamesList(SystemParams.CompanyID, jobsiteid);

                    List<UserNameInfoItem> list = new List<UserNameInfoItem>();
                    foreach (var user in users)
                    {
                        UserNameInfoItem ui = new UserNameInfoItem();
                        Helper.CloneProperty(ui, user);
                        list.Add(ui);
                    }
                    items = list.ToArray();
                }
                else
                {
                    items = new UserNameInfoItem[0];
                }
                return items;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetJobSiteTypes()
        {
            try
            {
                UserNameInfoItem[] items = null;
                if (GetCurrentLoginSession() != null)
                {
                    string[] types = CreateClient<JobSiteProvider>().GetJobsiteTypes(SystemParams.CompanyID);
                    if (types == null)
                        return new string[0];

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

        private object GetRegions()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {

                    var regions = CreateClient<Foresight.Fleet.Services.Customer.CustomerProvider>().GetRegions(SystemParams.CompanyID);

                    if (regions == null || regions.Length == 0)
                        return new Foresight.Fleet.Services.Customer.RegionInfo[0];

                    return regions.Where(m => m.IsActive).ToArray();
                }
                else
                {
                    return new string[0];
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetForemans()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    Users.UserInfo[] items = UserManagement.GetUsers(null, string.Empty);
                    items = items.Where(m => m.Active).OrderBy(u => u.ID).ToArray();
                    return items;
                }
                else
                {
                    return new Users.UserInfo[0];
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

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

                    if (iconfilebyte != null)
                    {
                        string[] columns = new ImportFromExcel().LoadExcelColumnHead(iconfilebyte);
                        if (columns != null && columns.Length > 0)
                            return columns;
                    }
                }
                return new string[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object ImportJobsites()
        {
            try
            {
                int count = 0;
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string p = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                    StringKeyValue[] kvs = JsonConvert.DeserializeObject<StringKeyValue[]>(p);

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

                    if (iconfilebyte != null)
                    {
                        DataTable dt = new ImportFromExcel().LoadExcelData(iconfilebyte);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            var client = CreateClient<JobSiteProvider>();

                            var jss = client.GetJobSiteItems(SystemParams.CompanyID, "", true);
                            var uid = GetCurrentLoginSession().User.UID;
                            foreach (DataRow dr in dt.Rows)
                            {
                                JobSiteItem jobsite = null;
                                try
                                {
                                    jobsite = ConvertToJobSiteItem(dr, kvs, null);
                                    if (string.IsNullOrWhiteSpace(jobsite.Name))
                                        continue;

                                    long jobsiteid = client.SaveJobSite(SystemParams.CompanyID, jobsite, uid);
                                    JobSitesManagement.RefreshJobsiteAssets(session.SessionID, jobsiteid);
                                    count++;
                                }
                                catch (BusinessException e)
                                {
                                    if (jobsite != null && jss != null)
                                    {
                                        var existjs = jss.FirstOrDefault(j => j.Name.Equals(jobsite.Name));
                                        if (existjs != null)
                                        {
                                            try
                                            {
                                                existjs = ConvertToJobSiteItem(dr, kvs, existjs);
                                                client.SaveJobSite(SystemParams.CompanyID, existjs, uid);
                                                JobSitesManagement.RefreshJobsiteAssets(session.SessionID, jobsite.ID);
                                                count++;
                                            }
                                            catch { }
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                }
                            }
                        }
                    }
                }
                return count;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private JobSiteItem ConvertToJobSiteItem(DataRow dr, StringKeyValue[] kvs, JobSiteItem jobsite)
        {
            DateTime tempdt = DateTime.Now;
            double tempd = 0;
            if (jobsite == null)
                jobsite = new JobSiteItem();
            foreach (StringKeyValue kv in kvs)
            {
                if (string.IsNullOrEmpty(kv.Key) || string.IsNullOrEmpty(kv.Value))
                    continue;

                if (string.Compare(kv.Key, "Name", true) == 0)
                {
                    jobsite.Name = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "Region", true) == 0)
                {
                    string region = dr[kv.Value].ToString();
                    if (!string.IsNullOrEmpty(region))
                    {
                        int rid = 0;
                        int.TryParse(region, out rid);
                        jobsite.RegionId = rid;
                    }
                }
                else if (string.Compare(kv.Key, "Number", true) == 0)
                {
                    jobsite.Number = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "Code", true) == 0)
                {
                    jobsite.Code = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "Types", true) == 0)
                {
                    jobsite.JobSiteTypes = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "Latitude", true) == 0)
                {
                    tempd = 0;
                    if (double.TryParse(dr[kv.Value].ToString(), out tempd))
                        jobsite.Latitude = tempd;
                }
                else if (string.Compare(kv.Key, "Longitude", true) == 0)
                {
                    tempd = 0;
                    if (double.TryParse(dr[kv.Value].ToString(), out tempd))
                        jobsite.Longitude = tempd;
                }
                else if (string.Compare(kv.Key, "Color", true) == 0)
                {
                    jobsite.Color = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "Radius", true) == 0)
                {
                    tempd = 0;
                    string radisstr = dr[kv.Value].ToString();
                    if (!string.IsNullOrEmpty(radisstr))
                    {
                        string[] temps = radisstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        if (double.TryParse(temps[0].Trim(), out tempd))
                        {
                            jobsite.Radius = tempd;
                            if (temps.Length > 1)
                            {
                                if (temps[0].StartsWith("k", StringComparison.OrdinalIgnoreCase))
                                    jobsite.RadiusUOM = "Kilometre";
                                else if (temps[0].StartsWith("m", StringComparison.OrdinalIgnoreCase))
                                    jobsite.RadiusUOM = "Mile";
                                else
                                    jobsite.RadiusUOM = Helper.GetDefaultOdoUnitString();
                            }
                        }
                    }
                }
                else if (string.Compare(kv.Key, "Foreman", true) == 0)
                {
                    jobsite.Foreman = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "Manager", true) == 0)
                {
                    jobsite.Manager = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "Phone", true) == 0)
                {
                    jobsite.Phone = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "Email", true) == 0)
                {
                    jobsite.Email = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "Group", true) == 0)
                {
                    jobsite.Group = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "Delivery Address 1", true) == 0)
                {
                    jobsite.Address1 = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "Delivery Address 2", true) == 0)
                {
                    jobsite.Address2 = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "City", true) == 0)
                {
                    jobsite.City = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "State", true) == 0)
                {
                    jobsite.State = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "Zip", true) == 0)
                {
                    jobsite.Zip = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "County", true) == 0)
                {
                    jobsite.County = dr[kv.Value].ToString();
                }
                else if (string.Compare(kv.Key, "Start Date", true) == 0)
                {
                    tempdt = DateTime.Now;
                    string datestr = dr[kv.Value].ToString();
                    if (!string.IsNullOrEmpty(datestr) && DateTime.TryParse(datestr, out tempdt))
                        jobsite.StartDate = tempdt;
                }
                else if (string.Compare(kv.Key, "Projected End Date", true) == 0)
                {
                    tempdt = DateTime.Now;
                    string datestr = dr[kv.Value].ToString();
                    if (!string.IsNullOrEmpty(datestr) && DateTime.TryParse(datestr, out tempdt))
                        jobsite.ProjectedEndDate = tempdt;
                }
                else if (string.Compare(kv.Key, "End Date", true) == 0)
                {
                    tempdt = DateTime.Now;
                    string datestr = dr[kv.Value].ToString();
                    if (!string.IsNullOrEmpty(datestr) && DateTime.TryParse(datestr, out tempdt))
                        jobsite.EndDate = tempdt;
                }
                else if (string.Compare(kv.Key, "Notes", true) == 0)
                {
                    jobsite.Notes = dr[kv.Value].ToString();
                }
            }
            return jobsite;
        }

        private object GetJobsiteAutoCreateItems()
        {
            var session = GetCurrentLoginSession();
            if (session != null)
            {
                var items = CreateClient<JobSiteProvider>().GetJobsiteAutoCreateItems(SystemParams.CompanyID);

                if (items != null)
                {
                    items = items.OrderBy((t) => t.Name).ToArray();
                }
                return items;
            }

            return null;
        }
        private object SaveJobsiteAutoCreateItems()
        {
            var session = GetCurrentLoginSession();
            if (session != null)
            {
                string clientdata = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                int criteria = int.Parse(ps[0]);
                long[] itemids = JsonConvert.DeserializeObject<long[]>(ps[1]);

                CreateClient<JobSiteProvider>().SaveJobsiteAutoCreateItems(SystemParams.CompanyID, criteria, itemids);
            }

            return "OK";
        }
        private object DeleteJobsiteAutoCreateItems()
        {
            var session = GetCurrentLoginSession();
            if (session != null)
            {
                string clientdata = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                int criteria = int.Parse(ps[0]);
                long[] itemids = JsonConvert.DeserializeObject<long[]>(ps[1]);

                CreateClient<JobSiteProvider>().DeleteJobsiteAutoCreateItems(SystemParams.CompanyID, criteria, itemids);
            }

            return "OK";
        }

        public class JobSiteMahcineQueryItem
        {
            public string JobSiteID { get; set; }
            public string MachineTypeID { get; set; }
            public string SearchText { get; set; }
        }
        private JobsiteNavigateItem[] GetNavigations()
        {
            List<JobsiteNavigateItem> list = GetNavigateItems();
            Foresight.Fleet.Services.Customer.LicenseInfo license = SystemParams.GetLicense();
            if (license != null && license.Items.Count > 0)
            {
                var jsitem = license.Items.FirstOrDefault(m => m.Key == "JobSites");
                if (jsitem == null || !Helper.IsTrue(jsitem.Value))
                {
                    return new JobsiteNavigateItem[0];
                }
                var jsditem = license.Items.FirstOrDefault(m => m.Key == "JobsiteDispatch");
                if (jsditem == null || !Helper.IsTrue(jsditem.Value))
                {
                    JobsiteNavigateItem item = list.FirstOrDefault(m => m.ID == "nav_jobsiterequirements");
                    list.Remove(item);
                    item = list.FirstOrDefault(m => m.ID == "nav_dispatchrequests");
                    list.Remove(item);
                    item = list.FirstOrDefault(m => m.ID == "nav_scheduler");
                    list.Remove(item);
                }
            }

            var user = GetCurrentUser();
            if (user.UserType == Users.UserTypes.Common)
            {
                var client = CreateClient<PermissionProvider>();
                Tuple<Feature, Permissions>[] pmss = client.GetUserPermissions(SystemParams.CompanyID, user.IID);
                if (pmss.Length > 0)
                {
                    Tuple<Feature, Permissions> p = pmss.FirstOrDefault(m => m.Item1.Id == Feature.JOB_SITES_REQUIREMENTS);
                    if (p == null)
                    {
                        JobsiteNavigateItem item = list.FirstOrDefault(m => m.ID == "nav_jobsiterequirements");
                        list.Remove(item);
                    }
                    p = pmss.FirstOrDefault(m => m.Item1.Id == Feature.JOB_SITES_DISPATCHREQUESTS);
                    if (p == null)
                    {
                        JobsiteNavigateItem item = list.FirstOrDefault(m => m.ID == "nav_dispatchrequests");
                        list.Remove(item);
                    }
                    p = pmss.FirstOrDefault(m => m.Item1.Id == Feature.JOB_SITES);
                    if (p == null)
                    {
                        JobsiteNavigateItem item = list.FirstOrDefault(m => m.ID == "nav_jobsitemanage");
                        list.Remove(item);
                    }
                    p = pmss.FirstOrDefault(m => m.Item1.Id == Feature.JOB_SITES_SCHEDULER);
                    if (p == null)
                    {
                        JobsiteNavigateItem item = list.FirstOrDefault(m => m.ID == "nav_scheduler");
                        list.Remove(item);
                    }
                    //Tuple<Feature, Permissions> p = pmss.FirstOrDefault(m => m.Item1.Id == Feature.JOB_SITES);
                    //if (p == null)
                    //{
                    //    JobsiteNavigateItem item = list.FirstOrDefault(m => m.ID == "nav_jobsiterequirements");
                    //    list.Remove(item);
                    //    item = list.FirstOrDefault(m => m.ID == "nav_dispatchrequests");
                    //    list.Remove(item);
                    //    item = list.FirstOrDefault(m => m.ID == "nav_jobsitemanage");
                    //    list.Remove(item);
                    //    item = list.FirstOrDefault(m => m.ID == "nav_scheduler");
                    //    list.Remove(item);
                    //}
                }
            }
            else if (user.UserType == Users.UserTypes.Readonly)
                list.Clear();
            return list.ToArray();
        }


        private static List<JobsiteNavigateItem> GetNavigateItems()
        {
            List<JobsiteNavigateItem> list = new List<JobsiteNavigateItem>();

            JobsiteNavigateItem item1 = new JobsiteNavigateItem();
            item1.ID = "nav_jobsiterequirements";
            item1.Title = "Jobsite Requirements";
            item1.Url = "JobSiteRequirements.aspx";
            item1.IconPath = "img/jobsiterequirements.png";
            list.Add(item1);

            JobsiteNavigateItem item6 = new JobsiteNavigateItem();
            item6.ID = "nav_dispatchrequests";
            item6.Title = "Dispatch Requests";
            item6.Url = "DispatchRequests.aspx";
            item6.IconPath = "img/dispatch.png";
            list.Add(item6);

            JobsiteNavigateItem item3 = new JobsiteNavigateItem();
            item3.ID = "nav_jobsitemanage";
            item3.Title = "Jobsites";
            item3.Url = "JobSiteManage.aspx";
            item3.IconPath = "img/jobsite.png";
            list.Add(item3);

            JobsiteNavigateItem item4 = new JobsiteNavigateItem();
            item4.ID = "nav_scheduler";
            item4.Title = "Scheduler";
            item4.Url = "SchedulerManagement.aspx";
            item4.IconPath = "img/scheduler.png";
            list.Add(item4);

            return list;
        }

        public class JobsiteNavigateItem
        {
            public string ID { get; set; }
            public string Title { get; set; }
            public string Url { get; set; }
            public string IconPath { get; set; }
        }
    }
}
