void RefreshPhotoList()
        {
            //llPhotoList.RemoveViews (1, llPhotoList.ChildCount - 1);
            PhotoTable.RemoveAllViews();

            int i = 0;

            foreach (var item in Photos)
            {
                i++;

                View vPhoto = Inflater.Inflate(Resource.Layout.PhotoTableItem, null);
                vPhoto.SetTag(Resource.String.PhotoPath, item.PhotoPath);
                vPhoto.FindViewById <TextView>(Resource.Id.ptiNumTV).Text = i.ToString();
                var photoType = MainDatabase.GetItem <PhotoType>(item.PhotoType);
                vPhoto.FindViewById <TextView>(Resource.Id.ptiTypeTV).Text = photoType.name;

                string drugBrand = (photoType.isNeedBrand) ? MainDatabase.GetItem <DrugBrand>(item.Brand).name : @"<не требуется>";
                vPhoto.FindViewById <TextView>(Resource.Id.ptiSubTypeTV).Text = drugBrand;

                vPhoto.FindViewById <TextView>(Resource.Id.ptiDateTimeTV).Text = item.Stamp.ToString("G");
                vPhoto.Click += (object sender, EventArgs e) => {
                    View view = (View)sender;
                    //Toast.MakeText(Activity, view.GetTag(Resource.String.PhotoPath).ToString(), ToastLength.Short).Show();
                    Intent intent = new Intent(Intent.ActionView);
                    intent.SetDataAndType(Android.Net.Uri.Parse("file://" + view.GetTag(Resource.String.PhotoPath).ToString()), "image/*");
                    StartActivity(intent);
                };
                PhotoTable.AddView(vPhoto);
            }
        }
Exemple #2
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Use this to return your custom view for this Fragment
            // return inflater.Inflate(Resource.Layout.YourFragment, container, false);

            Dialog.SetCanceledOnTouchOutside(true);
            Dialog.SetTitle(@"Настройка фильтра");
            Dialog.Window.RequestFeature(WindowFeatures.NoTitle);

            View view = inflater.Inflate(Resource.Layout.FilterDialog, container, false);

            var prefs = Activity.GetSharedPreferences(C_FILTER_PREFS, FileCreationMode.Private);

            Subway = view.FindViewById <AutoCompleteTextView>(Resource.Id.fdSubwayACTV);
            string subwayUUID = prefs.GetString(@"SUBWAY", string.Empty);

            if (!string.IsNullOrEmpty(subwayUUID))
            {
                Subway.Text = MainDatabase.GetItem <Subway>(subwayUUID).name;
                Subway.SetTag(Resource.String.SubwayUUID, subwayUUID);
            }
            Region = view.FindViewById <AutoCompleteTextView>(Resource.Id.fdRegionACTV);
            string regionUUID = prefs.GetString(@"REGION", string.Empty);

            if (!string.IsNullOrEmpty(regionUUID))
            {
                Region.Text = MainDatabase.GetItem <Region>(regionUUID).name;
                Region.SetTag(Resource.String.RegionUUID, regionUUID);
            }
            Net = view.FindViewById <AutoCompleteTextView>(Resource.Id.fdNetACTV);
            string netUUID = prefs.GetString(@"NET", string.Empty);

            if (!string.IsNullOrEmpty(netUUID))
            {
                Net.Text = MainDatabase.GetItem <Net>(netUUID).name;
                Net.SetTag(Resource.String.NetUUID, netUUID);
            }
            Address      = view.FindViewById <EditText>(Resource.Id.fdAddressET);
            Address.Text = prefs.GetString(@"ADDRESS", string.Empty);

            InitViews();

            var close = view.FindViewById <Button>(Resource.Id.Close);

            close.Click += (sender, e) => {
                Dismiss();
            };

            var save = view.FindViewById <Button>(Resource.Id.Save);

            save.Click += Save_Click;

            return(view);
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.Material);

            var materialUUID = Intent.GetStringExtra(C_MATERIAL_UUID);

            if (string.IsNullOrEmpty(materialUUID))
            {
                return;
            }

            var material = MainDatabase.GetItem <Material>(materialUUID);

            FindViewById <TextView>(Resource.Id.mMaterialTV).Text = material.name;
        }
        //SuggestClient Api;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            RequestWindowFeature(WindowFeatures.NoTitle);
            Window.AddFlags(WindowManagerFlags.KeepScreenOn);

            // Create your application here
            SetContentView(Resource.Layout.Pharmacy);

            FindViewById <Button>(Resource.Id.paCloseB).Click += (s, e) => {
                Finish();
            };

            FindViewById <Button>(Resource.Id.paSaveB).Click += (s, e) => {
                var transaction = MainDatabase.BeginTransaction();

                Pharmacy item;
                if (Pharmacy == null)
                {
                    item           = MainDatabase.Create2 <Pharmacy>();
                    item.CreatedAt = DateTimeOffset.Now;

                    /* Contracts */
                    if (!string.IsNullOrEmpty(ContractsNames.Text))
                    {
                        var ll            = ContractsNames.Parent as LinearLayout;
                        var contractUUIDs = (string)ll.GetTag(Resource.String.ContractUUIDs);
                        if (!string.IsNullOrEmpty(contractUUIDs))
                        {
                            foreach (var contract in contractUUIDs.Split(';'))
                            {
                                var contractData = MainDatabase.Create <ContractData>();
                                contractData.Pharmacy = item.UUID;
                                contractData.Contract = contract;
                            }
                        }
                    }
                    /* ./Contracts */
                }
                else
                {
                    item = Pharmacy;

                    /* Contracts */
                    if (string.IsNullOrEmpty(ContractsNames.Text))
                    {
                        var contractDatas = MainDatabase.GetPharmacyDatas <ContractData>(item.UUID);
                        foreach (var contractData in contractDatas)
                        {
                            MainDatabase.DeleteEntity(transaction, contractData);;
                        }
                        contractDatas = null;
                    }
                    else
                    {
                        var ll            = ContractsNames.Parent as LinearLayout;
                        var contractUUIDs = (string)ll.GetTag(Resource.String.ContractUUIDs);
                        if (!string.IsNullOrEmpty(contractUUIDs))
                        {
                            var contracts     = contractUUIDs.Split(';');
                            var contractDatas = MainDatabase.GetPharmacyDatas <ContractData>(item.UUID);
                            foreach (var contractData in contractDatas)
                            {
                                MainDatabase.DeleteEntity(transaction, contractData);
                            }
                            contractDatas = null;
                            foreach (var contract in contractUUIDs.Split(';'))
                            {
                                var contractData = MainDatabase.Create2 <ContractData>();
                                contractData.Pharmacy = item.UUID;
                                contractData.Contract = contract;
                            }
                        }
                    }
                    /* ./Contracts */
                }

                item.UpdatedAt = DateTimeOffset.Now;
                item.IsSynced  = false;
                item.SetState((PharmacyState)State.SelectedItemPosition);
                item.Brand      = FindViewById <EditText>(Resource.Id.paBrandET).Text;
                item.NumberName = FindViewById <EditText>(Resource.Id.paNumberNameET).Text;
                item.LegalName  = FindViewById <EditText>(Resource.Id.paLegalNameET).Text;

                if (string.IsNullOrEmpty(NetName.Text))
                {
                    item.Net = string.Empty;
                }
                else
                {
                    item.Net = NetUUID;
                }

                var address = FindViewById <AutoCompleteTextView>(Resource.Id.paAddressACTV);
                item.Address = address.Text;
                bool isChanged = (bool)address.GetTag(Resource.String.IsChanged);
                if (isChanged)
                {
                    item.AddressFiasId = (string)address.GetTag(Resource.String.fias_id);
                    item.AddressQCGeo  = (string)address.GetTag(Resource.String.qc_geo);
                    item.AddressGeoLat = (string)address.GetTag(Resource.String.geo_lat);
                    item.AddressGeoLon = (string)address.GetTag(Resource.String.geo_lon);
                }

                if (string.IsNullOrEmpty(Subway.Text))
                {
                    item.Subway = string.Empty;
                }
                else
                {
                    var subwayUUID = (string)Subway.GetTag(Resource.String.SubwayUUID);
                    if (!string.IsNullOrEmpty(subwayUUID))
                    {
                        item.Subway = subwayUUID;
                    }
                }

                if (string.IsNullOrEmpty(Region.Text))
                {
                    item.Region = string.Empty;
                }
                else
                {
                    var regionUUID = (string)Region.GetTag(Resource.String.RegionUUID);
                    if (!string.IsNullOrEmpty(regionUUID))
                    {
                        item.Region = regionUUID;
                    }
                }

                item.Phone = FindViewById <EditText>(Resource.Id.paPhoneET).Text;

                if (string.IsNullOrEmpty(Place.Text))
                {
                    item.Place = string.Empty;
                }
                else
                {
                    var placeUUID = (string)Place.GetTag(Resource.String.PlaceUUID);
                    if (!string.IsNullOrEmpty(placeUUID))
                    {
                        item.Place = placeUUID;
                    }
                }

                if (Category.SelectedItemPosition > 0)
                {
                    item.Category = Categories[Category.SelectedItemPosition].uuid;
                }
                else
                {
                    item.Category = string.Empty;
                }
                //if (string.IsNullOrEmpty(Category.Text)) {
                //	item.Category = string.Empty;
                //} else {
                //	var categoryUUID = (string)Category.GetTag(Resource.String.CategoryUUID);
                //	if (!string.IsNullOrEmpty(categoryUUID)) {
                //		item.Category = categoryUUID;
                //	}
                //}
                item.TurnOver = Helper.ToInt(FindViewById <EditText>(Resource.Id.paTurnOverET).Text);
                item.Comment  = FindViewById <EditText>(Resource.Id.paCommentET).Text;

                if (!item.IsManaged)
                {
                    MainDatabase.SaveEntity(transaction, item);
                }

                transaction.Commit();

                //var sync = new SyncItem() {
                //	Path = @"Pharmacy",
                //	ObjectUUID = Pharmacy.UUID,
                //	JSON = JsonConvert.SerializeObject(Pharmacy)
                //};

                //MainDatabase.AddToQueue(sync);

                //StartService(new Intent("com.xamarin.SyncService"));
                GetSharedPreferences(MainActivity.C_MAIN_PREFS, FileCreationMode.Private)
                .Edit()
                .PutString(MainActivity.C_SAVED_PHARMACY_UUID, item.UUID)
                .Commit();

                Finish();
            };

            //Api = new SuggestClient(Secret.DadataApiToken, Secret.DadataApiURL);


            #region State
            State  = FindViewById <Spinner>(Resource.Id.paStateS);
            States = MainDatabase.GetStates();
            var stateAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, States.ToArray());
            stateAdapter.SetDropDownViewResource(Resource.Layout.SpinnerItem);
            State.Adapter = stateAdapter;
            #endregion

            #region Net
            Nets    = MainDatabase.GetNets();
            NetName = FindViewById <AutoCompleteTextView>(Resource.Id.paNetACTV);
            var netChoiceButton = FindViewById <Button>(Resource.Id.paNetB);
            netChoiceButton.Click += (object sender, EventArgs e) => {
                new AlertDialog.Builder(this)
                .SetTitle("Аптечная сеть")
                .SetCancelable(true)
                .SetItems(Nets.Select(item => item.name).ToArray(), (caller, arguments) => {
                    SetNet(arguments.Which);
                    //Toast.MakeText(this, @"Selected " + arguments.Which, ToastLength.Short).Show();
                })
                .Show();
            };
            #endregion

            ContractsNames         = FindViewById <AutoCompleteTextView>(Resource.Id.paContractsACTV);
            ContractsChoice        = FindViewById <Button>(Resource.Id.paContractsB);
            ContractsChoice.Click += ContractsChoice_Click;

            Address = FindViewById <AutoCompleteTextView>(Resource.Id.paAddressACTV);
            Address.SetTag(Resource.String.IsChanged, false);

            Subway = FindViewById <AutoCompleteTextView>(Resource.Id.paSubwayACTV);

            Region = FindViewById <AutoCompleteTextView>(Resource.Id.paRegionACTV);

            Place = FindViewById <AutoCompleteTextView>(Resource.Id.paPlaceACTV);

            //Category = FindViewById<AutoCompleteTextView>(Resource.Id.paCategoryACTV);

            #region Category
            Category   = FindViewById <Spinner>(Resource.Id.paCategoryS);
            Categories = new List <Category>();
            Categories.Add(new Category {
                name = @"Выберите категорию!", uuid = Guid.Empty.ToString()
            });
            Categories.AddRange(MainDatabase.GetItems <Category>());;
            var categoryAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, Categories.Select(cat => cat.name).ToArray());
            categoryAdapter.SetDropDownViewResource(Resource.Layout.SpinnerItem);
            Category.Adapter = categoryAdapter;
            #endregion

            var pharmacyUUID = Intent.GetStringExtra("UUID");
            if (string.IsNullOrEmpty(pharmacyUUID))
            {
                var shared    = GetSharedPreferences(MainActivity.C_MAIN_PREFS, FileCreationMode.Private);
                var agentUUID = shared.GetString(SigninDialog.C_AGENT_UUID, string.Empty);
                try {
                    var agent = MainDatabase.GetItem <Agent>(agentUUID);
                    Address.Text = agent.city;
                } catch (Exception ex) {
                    Console.WriteLine(ex.Message);
                }

                FindViewById <TextView>(Resource.Id.paInfoTV).Text = @"ДОБАВЛЕНИЕ НОВОЙ АПТЕКИ";
                FindViewById <TableRow>(Resource.Id.paRowLastAttendance).Visibility     = ViewStates.Gone;
                FindViewById <TableRow>(Resource.Id.paRowNextAttendanceDate).Visibility = ViewStates.Gone;

                InitViews();
                return;
            }

            Pharmacy = MainDatabase.GetEntity <Pharmacy>(pharmacyUUID);

            FindViewById <TextView>(Resource.Id.paInfoTV).Text = "АПТЕКА : " + Pharmacy.GetName();

            FindViewById <TextView>(Resource.Id.paUUIDTV).Text = Pharmacy.UUID;

            State.SetSelection((int)Pharmacy.GetState());
            FindViewById <EditText>(Resource.Id.paBrandET).Text      = Pharmacy.Brand;
            FindViewById <EditText>(Resource.Id.paNumberNameET).Text = Pharmacy.NumberName;
            FindViewById <EditText>(Resource.Id.paLegalNameET).Text  = Pharmacy.LegalName;

            //NetName.Text = string.IsNullOrEmpty(Pharmacy.Net) ?
            //	string.Empty : MainDatabase.GetNet(Pharmacy.Net).name;
            //NetUUID = Pharmacy.Net;

            if (!string.IsNullOrEmpty(Pharmacy.Net))
            {
                SetNet(Nets.FindIndex(net => string.Compare(net.uuid, Pharmacy.Net) == 0));
            }

            ContractDatas = MainDatabase.GetPharmacyDatas <ContractData>(Pharmacy.UUID);
            if (ContractDatas.Count > 0)
            {
                ContractsNames.Text = string.Join(", ", ContractDatas.Select(cd => MainDatabase.GetItem <Contract>(cd.Contract).name).ToArray());
                var ll = ContractsNames.Parent as LinearLayout;
                ll.SetTag(Resource.String.ContractUUIDs,
                          string.Join(@";", ContractDatas.Select(cd => cd.Contract).ToArray())
                          );
            }
            Address.Text = Pharmacy.Address;

            Subway.Text = string.IsNullOrEmpty(Pharmacy.Subway) ?
                          string.Empty : MainDatabase.GetItem <Subway>(Pharmacy.Subway).name;

            Region.Text = string.IsNullOrEmpty(Pharmacy.Region) ?
                          string.Empty : MainDatabase.GetItem <Region>(Pharmacy.Region).name;

            FindViewById <EditText>(Resource.Id.paPhoneET).Text = Pharmacy.Phone;

            Place.Text = string.IsNullOrEmpty(Pharmacy.Place) ?
                         string.Empty : MainDatabase.GetItem <Place>(Pharmacy.Place).name;

            //Category.Text = string.IsNullOrEmpty(Pharmacy.Category) ?
            //	string.Empty : MainDatabase.GetItem<Category>(Pharmacy.Category).name;
            if (!string.IsNullOrEmpty(Pharmacy.Category))
            {
                Category.SetSelection(Categories.FindIndex(cat => string.Compare(cat.uuid, Pharmacy.Category) == 0));
            }

            FindViewById <EditText>(Resource.Id.paTurnOverET).Text = Pharmacy.TurnOver.HasValue ?
                                                                     Pharmacy.TurnOver.Value.ToString() : string.Empty;

            FindViewById <TextView>(Resource.Id.paLastAttendanceTV).Text = Pharmacy.LastAttendanceDate.HasValue ?
                                                                           Pharmacy.LastAttendanceDate.Value.ToString(@"dd.MM.yyyy") : @"<нет визита>";

            FindViewById <TextView>(Resource.Id.paNextAttendanceDateTV).Text = Pharmacy.NextAttendanceDate.HasValue ?
                                                                               Pharmacy.NextAttendanceDate.Value.ToString(@"dd.MM.yyyy") : DateTimeOffset.Now.ToString(@"dd.MM.yyyy");

            FindViewById <EditText>(Resource.Id.paCommentET).Text = Pharmacy.Comment;


            InitViews();
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            RequestWindowFeature(WindowFeatures.NoTitle);
            Window.AddFlags(WindowManagerFlags.KeepScreenOn);

            // Create your application here
            SetContentView(Resource.Layout.Route);

            FindViewById <Button>(Resource.Id.raCloseB).Click += (s, e) => {
                MainDatabase.Dispose();
                Finish();
            };

            PharmacyTable            = FindViewById <ListView>(Resource.Id.raPharmacyTable);
            PharmacyTable.ItemClick += (sender, e) => {
                var ll      = (ListView)sender;
                var adapter = (RoutePharmacyAdapter)ll.Adapter;
                adapter.SwitchVisibility(e.Position);

                var row = LayoutInflater.Inflate(Resource.Layout.RouteItem, RouteTable, false);
                row.SetTag(Resource.String.Position, e.Position);

                RouteSearchItem item;
                if (string.IsNullOrEmpty(SearchEditor.Text))
                {
                    item = RouteSearchItems[e.Position];
                }
                else
                {
                    item = SearchedItems[e.Position];
                }

                //TODO: rename vars
                using (var trans = MainDatabase.BeginTransaction()){
                    var newRouteItem = MainDatabase.Create2 <RouteItem>();
                    newRouteItem.Pharmacy = item.UUID;
                    newRouteItem.Order    = RouteTable.ChildCount;
                    newRouteItem.Date     = SelectedDate;
                    trans.Commit();
                    row.SetTag(Resource.String.RouteItemUUID, newRouteItem.UUID);
                }
                row.SetTag(Resource.String.PharmacyUUID, item.UUID);

                row.FindViewById <TextView>(Resource.Id.riPharmacyTV).Text = item.Name;
                row.SetTag(Resource.String.RouteItemOrder, RouteTable.ChildCount);
                row.FindViewById <TextView>(Resource.Id.riOrderTV).Text = (RouteTable.ChildCount + 1).ToString();

                row.FindViewById <ImageView>(Resource.Id.riDeleteIV).Click += RowDelete_Click;
                row.LongClick += Row_LongClick;
                row.Drag      += Row_Drag;

                RouteTable.AddView(row);
            };

            RouteSearchItemsSource = new List <RouteSearchItem>();
            var pharmacies = MainDatabase.GetItems <Pharmacy>();

            foreach (var item in pharmacies)
            {
                RouteSearchItemsSource.Add(
                    new RouteSearchItem(
                        item.UUID,
                        string.IsNullOrEmpty(item.GetName()) ? string.Empty : item.GetName(),
                        string.IsNullOrEmpty(item.Subway) ? string.Empty : MainDatabase.GetItem <Subway>(item.Subway).name,
                        string.IsNullOrEmpty(item.Region) ? string.Empty : MainDatabase.GetItem <Region>(item.Region).name,
                        string.IsNullOrEmpty(item.Brand) ? string.Empty : item.Brand,
                        string.IsNullOrEmpty(item.Address) ? string.Empty : item.Address
                        )
                    );
            }
            SearchedItems  = new List <RouteSearchItem>();
            SearchSwitcher = FindViewById <ViewSwitcher>(Resource.Id.raSearchVS);
            SearchSwitcher.SetInAnimation(this, Android.Resource.Animation.SlideInLeft);
            SearchSwitcher.SetOutAnimation(this, Android.Resource.Animation.SlideOutRight);

            SearchImage        = FindViewById <ImageView>(Resource.Id.raSearchIV);
            SearchImage.Click += (sender, e) => {
                if (CurrentFocus != null)
                {
                    var imm = (InputMethodManager)GetSystemService(InputMethodService);
                    imm.HideSoftInputFromWindow(CurrentFocus.WindowToken, HideSoftInputFlags.None);
                }

                SearchSwitcher.ShowNext();
            };

            SearchEditor = FindViewById <EditText>(Resource.Id.raSearchET);

            SearchEditor.AfterTextChanged += (sender, e) => {
                var text = e.Editable.ToString();

                if (string.IsNullOrEmpty(text))
                {
                    foreach (var item in RouteSearchItems)
                    {
                        item.Match = string.Empty;
                    }
                    PharmacyTable.Adapter = new RoutePharmacyAdapter(this, RouteSearchItems);
                    return;
                }

                var w = new SDiag.Stopwatch();
                w.Start();
                SearchedItems = new List <RouteSearchItem>();
                var matchFormat = @"Совпадение: {0}";
                var culture     = CultureInfo.GetCultureInfo("ru-RU");
                // 2 поиск
                foreach (var item in RouteSearchItems)
                {
                    if (item.IsVisible)
                    {
                        //item.Subway = null;
                        if (culture.CompareInfo.IndexOf(item.Subway, text, CompareOptions.IgnoreCase) >= 0)
                        {
                            item.Match = string.Format(matchFormat, @"метро=" + item.Subway);
                            SearchedItems.Add(item);
                            //if (SearchedItems.Count > C_ITEMS_IN_RESULT) break;
                            continue;
                        }

                        if (culture.CompareInfo.IndexOf(item.Region, text, CompareOptions.IgnoreCase) >= 0)
                        {
                            item.Match = string.Format(matchFormat, @"район=" + item.Region);
                            SearchedItems.Add(item);
                            //if (SearchedItems.Count > C_ITEMS_IN_RESULT) break;
                            continue;
                        }

                        if (culture.CompareInfo.IndexOf(item.Brand, text, CompareOptions.IgnoreCase) >= 0)
                        {
                            item.Match = string.Format(matchFormat, @"бренд=" + item.Brand);
                            SearchedItems.Add(item);
                            //if (SearchedItems.Count > C_ITEMS_IN_RESULT) break;
                            continue;
                        }

                        if (culture.CompareInfo.IndexOf(item.Address, text, CompareOptions.IgnoreCase) >= 0)
                        {
                            item.Match = string.Format(matchFormat, @"адрес");
                            SearchedItems.Add(item);
                            //if (SearchedItems.Count > C_ITEMS_IN_RESULT) break;
                            continue;
                        }
                    }
                }
                w.Stop();
                SDiag.Debug.WriteLine(@"Search: поиск={0}", w.ElapsedMilliseconds);

                PharmacyTable.Adapter = new RoutePharmacyAdapter(this, SearchedItems);
            };

            RouteTable = FindViewById <LinearLayout>(Resource.Id.raRouteTable);

            FindViewById <Button>(Resource.Id.raSelectDateB).Click += (sender, e) => {
                DatePickerFragment frag = DatePickerFragment.NewInstance(delegate(DateTime date) {
                    SDiag.Debug.WriteLine("DatePicker:{0}", date.ToLongDateString());
                    SDiag.Debug.WriteLine("DatePicker:{0}", new DateTimeOffset(date));
                    SelectedDate = new DateTimeOffset(date, new TimeSpan(0, 0, 0));;
                    RefreshTables();
                });
                frag.Show(FragmentManager, DatePickerFragment.TAG);
            };

            Info      = FindViewById <TextView>(Resource.Id.raInfoTV);
            Info.Text = string.Format(@"Период планирования: {0} недели ({1} дней)", Helper.WeeksInRoute, Helper.WeeksInRoute * 5);

            var switcher = FindViewById <ViewSwitcher>(Resource.Id.raSwitchViewVS);

            FindViewById <ImageView>(Resource.Id.raSwitchIV).Click += (sender, e) => {
                SDiag.Debug.WriteLine(@"switcher:{0}; Resource{1}", switcher.CurrentView.Id, Resource.Id.raContainerVP);
                if (switcher.CurrentView.Id != Resource.Id.raContainerVP)
                {
                    Info.Text = string.Format(
                        @"Период планирования: {0} недели ({1} дней). Номер недели: {2}",
                        Helper.WeeksInRoute, Helper.WeeksInRoute * 5, 1
                        );
                    var pager = FindViewById <ViewPager>(Resource.Id.raContainerVP);
                    pager.AddOnPageChangeListener(this);
                    pager.Adapter = new RoutePagerAdapter(SupportFragmentManager);
                }
                else
                {
                    Info.Text = string.Format(@"Период планирования: {0} недели ({1} дней)", Helper.WeeksInRoute, Helper.WeeksInRoute * 5);
                }
                switcher.ShowNext();
            };
        }
Exemple #6
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            RequestWindowFeature(WindowFeatures.NoTitle);
            Window.AddFlags(WindowManagerFlags.KeepScreenOn);

            // Create your application here
            SetContentView(Resource.Layout.Profile);

            FindViewById <Button>(Resource.Id.paCloseB).Click += (sender, e) => {
                Finish();
            };

            FindViewById <Button>(Resource.Id.paExitAppB).Click += (sender, e) => {
                int count = 0;

                count += MainDatabase.CountItemsToSync <Attendance>();
                count += MainDatabase.CountItemsToSync <CompetitorData>();
                count += MainDatabase.CountItemsToSync <ContractData>();
                count += MainDatabase.CountItemsToSync <CoterieData>();
                count += MainDatabase.CountItemsToSync <DistributionData>();
                count += MainDatabase.CountItemsToSync <Pharmacy>();
                count += MainDatabase.CountItemsToSync <Employee>();

                count += MainDatabase.CountItemsToSync <GPSData>();

                count += MainDatabase.CountItemsToSync <Hospital>();
                count += MainDatabase.CountItemsToSync <HospitalData>();

                //var monthFinanceDatas = MainDatabase.GetItemsToSync<FinanceDataByMonth>();
                //var quarterFinanceDatas = MainDatabase.GetItemsToSync<FinanceDataByQuarter>();
                //var monthSaleDatas = MainDatabase.GetItemsToSync<SaleDataByMonth>();
                //var quarterSaleDatas = MainDatabase.GetItemsToSync<SaleDataByQuarter>();

                count += MainDatabase.CountItemsToSync <MessageData>();

                count += MainDatabase.CountItemsToSync <PresentationData>();
                count += MainDatabase.CountItemsToSync <PromotionData>();
                count += MainDatabase.CountItemsToSync <ResumeData>();
                count += MainDatabase.CountItemsToSync <RouteItem>();

                count += MainDatabase.CountItemsToSync <RouteItem>();

                count += MainDatabase.CountItemsToSync <PhotoData>();

                if (count > 0)
                {
                    new AlertDialog.Builder(this)
                    .SetTitle(Resource.String.warning_caption)
                    .SetMessage("Перед выходом необходимо синхронизировать все данные!!!")
                    .SetCancelable(true)
                    .SetPositiveButton("OK", (caller, arguments) => {
                        if (caller is Dialog)
                        {
                            (caller as Dialog).Dismiss();
                        }
                    })
                    .Show();
                }
                else
                {
                    GetSharedPreferences(MainActivity.C_MAIN_PREFS, FileCreationMode.Private)
                    .Edit()
                    .PutString(SigninDialog.C_USERNAME, string.Empty)
                    .Commit();
                    MainDatabase.Dispose();
                    Finish();
                }
            };

            Content = FindViewById <LinearLayout>(Resource.Id.paAttendanceByWeekLL);
            Table   = FindViewById <ListView>(Resource.Id.paAttendanceByWeekTable);

            int weeksCount = 14;

            Dates = new DateTimeOffset[weeksCount];
            var header = (LinearLayout)LayoutInflater.Inflate(Resource.Layout.AttendanceByWeekTableHeader, Table, false);

            (header.GetChildAt(0) as TextView).Text = @"Недели";
            for (int w = 0; w < weeksCount; w++)
            {
                Dates[w] = DateTimeOffset.UtcNow.AddDays(-7 * (weeksCount - 1 - w));
                var hView = header.GetChildAt(w + 1);
                if (hView is TextView)
                {
                    (hView as TextView).Text = Helper.GetIso8601WeekOfYear(Dates[w].UtcDateTime.Date).ToString();
                }
            }
            Content.AddView(header, 1);

            var shared = GetSharedPreferences(MainActivity.C_MAIN_PREFS, FileCreationMode.Private);

            FindViewById <TextView>(Resource.Id.paUsernameTV).Text = shared.GetString(SigninDialog.C_USERNAME, string.Empty);

            var agentUUID = shared.GetString(SigninDialog.C_AGENT_UUID, string.Empty);

            try {
                var agent = MainDatabase.GetItem <Agent>(agentUUID);
                FindViewById <TextView>(Resource.Id.paShortNameTV).Text = agent.shortName;
            } catch (Exception ex) {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            SearchSwitcher = FindViewById <ViewSwitcher>(Resource.Id.paSearchVS);
            SearchSwitcher.SetInAnimation(this, Android.Resource.Animation.SlideInLeft);
            SearchSwitcher.SetOutAnimation(this, Android.Resource.Animation.SlideOutRight);

            SearchImage        = FindViewById <ImageView>(Resource.Id.paSearchIV);
            SearchImage.Click += (sender, e) => {
                if (CurrentFocus != null)
                {
                    var imm = (InputMethodManager)GetSystemService(InputMethodService);
                    imm.HideSoftInputFromWindow(CurrentFocus.WindowToken, HideSoftInputFlags.None);
                }

                SearchSwitcher.ShowNext();
            };

            SearchEditor = FindViewById <EditText>(Resource.Id.paSearchET);

            SearchEditor.AfterTextChanged += (sender, e) => {
                var text = e.Editable.ToString();

                (Table.Adapter as AttendanceByWeekAdapter).SetSearchText(text);
            };
        }
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Use this to return your custom view for this Fragment
            // return inflater.Inflate(Resource.Layout.YourFragment, container, false);

            base.OnCreateView(inflater, container, savedInstanceState);

            View view = inflater.Inflate(Resource.Layout.PharmacyFragment, container, false);

            //Api = new SuggestClient(Secret.DadataApiToken, Secret.DadataApiURL);


            var pharmacyUUID = Arguments.GetString(C_PHARMACY_UUID);

            if (string.IsNullOrEmpty(pharmacyUUID))
            {
                return(view);
            }

            Pharmacy = MainDatabase.GetPharmacy(pharmacyUUID);

            var shared = Activity.GetSharedPreferences(MainActivity.C_MAIN_PREFS, FileCreationMode.Private);

            var agentUUID = shared.GetString(SigninDialog.C_AGENT_UUID, string.Empty);

            try {
                Agent = MainDatabase.GetItem <Agent>(agentUUID);
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
                Agent = null;
            }

            #region State
            State  = view.FindViewById <Spinner>(Resource.Id.pfStateS);
            States = MainDatabase.GetStates();
            var stateAdapter = new ArrayAdapter(Activity, Android.Resource.Layout.SimpleSpinnerItem, States.ToArray());
            stateAdapter.SetDropDownViewResource(Resource.Layout.SpinnerItem);
            State.Adapter = stateAdapter;
            #endregion

            #region Net
            Nets    = MainDatabase.GetNets();
            NetName = view.FindViewById <AutoCompleteTextView>(Resource.Id.pfNetACTV);
            var netChoiceButton = view.FindViewById <Button>(Resource.Id.pfNetB);
            netChoiceButton.Click += (object sender, EventArgs e) => {
                new Android.App.AlertDialog.Builder(Activity)
                .SetTitle("Аптечная сеть")
                .SetCancelable(true)
                .SetItems(Nets.Select(item => item.name).ToArray(), (caller, arguments) => {
                    SetNet(arguments.Which);
                    //Toast.MakeText(this, @"Selected " + arguments.Which, ToastLength.Short).Show();
                })
                .Show();
            };
            #endregion

            ContractsNames         = view.FindViewById <AutoCompleteTextView>(Resource.Id.pfContractsACTV);
            ContractsChoice        = view.FindViewById <Button>(Resource.Id.pfContractsB);
            ContractsChoice.Click += ContractsChoice_Click;

            Address = view.FindViewById <AutoCompleteTextView>(Resource.Id.pfAddressACTV);
            Address.SetTag(Resource.String.IsChanged, false);

            Subway = view.FindViewById <AutoCompleteTextView>(Resource.Id.pfSubwayACTV);

            Region = view.FindViewById <AutoCompleteTextView>(Resource.Id.pfRegionACTV);

            Place = view.FindViewById <AutoCompleteTextView>(Resource.Id.pfPlaceACTV);

            //Category = FindViewById<AutoCompleteTextView>(Resource.Id.paCategoryACTV);

            #region Category
            Category   = view.FindViewById <Spinner>(Resource.Id.pfCategoryS);
            Categories = new List <Category>();
            Categories.Add(new Category {
                name = @"Выберите категорию!", uuid = Guid.Empty.ToString()
            });
            Categories.AddRange(MainDatabase.GetItems <Category>());
            var categoryAdapter = new ArrayAdapter(Activity, Android.Resource.Layout.SimpleSpinnerItem, Categories.Select(cat => cat.name).ToArray());
            categoryAdapter.SetDropDownViewResource(Resource.Layout.SpinnerItem);
            Category.Adapter = categoryAdapter;
            #endregion

            view.FindViewById <TextView>(Resource.Id.pfUUIDTV).Text = Pharmacy.UUID;

            State.SetSelection((int)Pharmacy.GetState());
            view.FindViewById <EditText>(Resource.Id.pfBrandET).Text      = Pharmacy.Brand;
            view.FindViewById <EditText>(Resource.Id.pfNumberNameET).Text = Pharmacy.NumberName;
            view.FindViewById <EditText>(Resource.Id.pfLegalNameET).Text  = Pharmacy.LegalName;

            //NetName.Text = string.IsNullOrEmpty(Pharmacy.Net) ?
            //	string.Empty : MainDatabase.GetNet(Pharmacy.Net).name;
            //NetUUID = Pharmacy.Net;

            if (!string.IsNullOrEmpty(Pharmacy.Net))
            {
                SetNet(Nets.FindIndex(net => string.Compare(net.uuid, Pharmacy.Net) == 0));
            }

            ContractDatas = MainDatabase.GetPharmacyDatas <ContractData>(Pharmacy.UUID);
            if (ContractDatas.Count > 0)
            {
                ContractsNames.Text = string.Join(", ", ContractDatas.Select(cd => MainDatabase.GetItem <Contract>(cd.Contract).name).ToArray());
                var ll = ContractsNames.Parent as LinearLayout;
                ll.SetTag(Resource.String.ContractUUIDs,
                          string.Join(@";", ContractDatas.Select(cd => cd.Contract).ToArray())
                          );
            }
            Address.Text = Pharmacy.Address;

            Subway.Text = string.IsNullOrEmpty(Pharmacy.Subway) ?
                          string.Empty : MainDatabase.GetItem <Subway>(Pharmacy.Subway).name;

            Region.Text = string.IsNullOrEmpty(Pharmacy.Region) ?
                          string.Empty : MainDatabase.GetItem <Region>(Pharmacy.Region).name;

            view.FindViewById <EditText>(Resource.Id.pfPhoneET).Text = Pharmacy.Phone;

            Place.Text = string.IsNullOrEmpty(Pharmacy.Place) ?
                         string.Empty : MainDatabase.GetItem <Place>(Pharmacy.Place).name;

            //Category.Text = string.IsNullOrEmpty(Pharmacy.Category) ?
            //	string.Empty : MainDatabase.GetItem<Category>(Pharmacy.Category).name
            if (!string.IsNullOrEmpty(Pharmacy.Category))
            {
                Category.SetSelection(Categories.FindIndex(cat => string.Compare(cat.uuid, Pharmacy.Category) == 0));
            }

            view.FindViewById <EditText>(Resource.Id.pfTurnOverET).Text = Pharmacy.TurnOver.HasValue ?
                                                                          Pharmacy.TurnOver.Value.ToString() : string.Empty;

            view.FindViewById <TextView>(Resource.Id.pfLastAttendanceTV).Text = Pharmacy.LastAttendanceDate.HasValue ?
                                                                                Pharmacy.LastAttendanceDate.Value.ToString(@"dd.MM.yyyy") : @"<нет визита>";

            view.FindViewById <TextView>(Resource.Id.pfNextAttendanceDateTV).Text = Pharmacy.NextAttendanceDate.HasValue ?
                                                                                    Pharmacy.NextAttendanceDate.Value.ToString(@"dd.MM.yyyy") : DateTimeOffset.Now.ToString(@"dd.MM.yyyy");

            view.FindViewById <EditText>(Resource.Id.pfCommentET).Text = Pharmacy.Comment;


            InitViews();

            return(view);
        }
Exemple #8
0
        protected override void OnResume()
        {
            base.OnResume();

            //Start Tracking usage in this activit
            Tracking.StartUsage(this);

            var shared = GetSharedPreferences(C_MAIN_PREFS, FileCreationMode.Private);

            string username = shared.GetString(SigninDialog.C_USERNAME, string.Empty);

            if (string.IsNullOrEmpty(username))
            {
                Pharmacies            = new List <Pharmacy>();     //.Take(14).ToList();
                PharmacyTable.Adapter = new PharmacyAdapter(this, Pharmacies);

                var fragmentTransaction = FragmentManager.BeginTransaction();
                var prev = FragmentManager.FindFragmentByTag(SigninDialog.TAG);
                if (prev != null)
                {
                    fragmentTransaction.Remove(prev);
                }
                fragmentTransaction.AddToBackStack(null);

                var signinDialog = new SigninDialog(this);
                signinDialog.Show(fragmentTransaction, SigninDialog.TAG);
                signinDialog.SuccessSignedIn += (caller, arguments) => {
                    //Toast.MakeText(this, @"SuccessSignedIn", ToastLength.Short).Show();
                    RunOnUiThread(() => {
                        OnResume();
                        SDiag.Debug.WriteLine(@"DBPath = {0}", MainDatabase.DBPath);
                    });
                };

                SDiag.Debug.WriteLine(@"username = IsNullOrEmpty");
                return;
            }

            var ft = FragmentManager.BeginTransaction();
            var sd = FragmentManager.FindFragmentByTag(SigninDialog.TAG);

            if (sd != null)
            {
                ft.Remove(sd);
            }
            ft.Commit();

            if (!IsLocationActive() || !IsInternetActive())
            {
                return;
            }

            MainDatabase.Username = username;
            Helper.Username       = username;

            var agentUUID = shared.GetString(SigninDialog.C_AGENT_UUID, string.Empty);

            try {
                var agent = MainDatabase.GetItem <Agent>(agentUUID);
                MainDatabase.AgentUUID = agent.uuid;
                Helper.WeeksInRoute    = agent.weeksInRout;
                Helper.WorkMode        = agent.GetWorkMode();
                Helper.AndroidId       = Helper.GetAndroidId(this);
            } catch (Exception ex) {
                SDiag.Debug.WriteLine(ex.Message);
            }


            var packageInfo = ApplicationContext.PackageManager.GetPackageInfo(ApplicationContext.PackageName, 0);
            var version     = string.Format("Версия: {0} ({1})", packageInfo.VersionName, packageInfo.VersionCode);

            FindViewById <TextView>(Resource.Id.maVersionTV).Text = version;

            var w = new SDiag.Stopwatch();

            w.Restart();
            var currentRouteItems = MainDatabase.GetRouteItems(DateTimeOffset.Now);

            if (currentRouteItems.Count() > 0)
            {
                var nextDate      = DateTimeOffset.Now.AddDays(Helper.WeeksInRoute * 7);
                var date          = new DateTimeOffset(nextDate.Year, nextDate.Month, nextDate.Day, 0, 0, 0, new TimeSpan(0, 0, 0));
                var nextRoutItems = MainDatabase.GetRouteItems(date);

                if (nextRoutItems.Count() == 0)
                {
                    using (var trans = MainDatabase.BeginTransaction()){
                        foreach (var oldItem in currentRouteItems)
                        {
                            var newItem = MainDatabase.Create2 <RouteItem>();
                            newItem.Pharmacy = oldItem.Pharmacy;
                            newItem.Date     = date;
                            newItem.Order    = oldItem.Order;
                        }
                        trans.Commit();
                    }
                }
            }
            w.Stop();
            SDiag.Debug.WriteLine(@"Route: копирование={0}", w.ElapsedMilliseconds);

            w.Restart();
            int count = MainDatabase.GetItems <Attendance>()
                        .Count(att => att.When.LocalDateTime.Date == DateTimeOffset.Now.Date);

            AttendanceCount.Text = string.Format(
                @"РЕЖИМ РАБОТЫ: {0};  СЕГОДНЯ ВИЗИТОВ: {1}", Helper.GetWorkModeDesc(Helper.WorkMode), count
                );
            w.Stop();
            SDiag.Debug.WriteLine(@"OnResume: подсчет визитов={0}", w.ElapsedMilliseconds);

            var  sparseArray = SearchTable.CheckedItemPositions;
            bool hasCheckedItemInSearchTable = false;

            for (var i = 0; i < sparseArray.Size(); i++)
            {
                if (sparseArray.ValueAt(i))
                {
                    hasCheckedItemInSearchTable = true;
                    break;
                }
            }

            if (!hasCheckedItemInSearchTable)
            {
                RecreateAdapter();
            }

            var prefs = GetSharedPreferences(C_MAIN_PREFS, FileCreationMode.Private);
            var uuid  = prefs.GetString(C_SAVED_PHARMACY_UUID, string.Empty);

            if (string.IsNullOrEmpty(uuid))
            {
                return;
            }

            if (SearchItems == null)
            {
                return;
            }

            if (SearchItems.ContainsKey(uuid))
            {
                w.Start();
                var pharmacy = MainDatabase.GetEntity <Pharmacy>(uuid);
                SearchItems[uuid] = new SearchItem(
                    pharmacy.UUID,
                    pharmacy.GetName(),
                    string.IsNullOrEmpty(pharmacy.Subway) ? string.Empty : MainDatabase.GetItem <Subway>(pharmacy.Subway).name,
                    string.IsNullOrEmpty(pharmacy.Region) ? string.Empty : MainDatabase.GetItem <Region>(pharmacy.Region).name,
                    string.IsNullOrEmpty(pharmacy.Brand) ? string.Empty : pharmacy.Brand
                    );
            }
            prefs.Edit().PutString(C_SAVED_PHARMACY_UUID, string.Empty).Commit();
            w.Stop();
            SDiag.Debug.WriteLine(@"Search: обновление={0}", w.ElapsedMilliseconds);
        }
Exemple #9
0
        void Search(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                SearchTable.Adapter = null;
                RecreateAdapter();
                return;
            }

            //SDiag.Debug.WriteLine(@"Search: startmemory{0}", System.Diagnostics.Process.GetCurrentProcess().WorkingSet64);

            var w = new SDiag.Stopwatch();

            w.Start();
            // 1 насыщениe
            //var searchItems = new List<SearchItem>()
            if (SearchItems == null)
            {
                SearchItems = new Dictionary <string, SearchItem>();
                var pharmacies = MainDatabase.GetItems <Pharmacy>();
                foreach (var pharmacy in pharmacies)
                {
                    SearchItems.Add(
                        pharmacy.UUID,
                        new SearchItem(
                            pharmacy.UUID,
                            pharmacy.GetName(),
                            string.IsNullOrEmpty(pharmacy.Subway) ? string.Empty : MainDatabase.GetItem <Subway>(pharmacy.Subway).name,
                            string.IsNullOrEmpty(pharmacy.Region) ? string.Empty : MainDatabase.GetItem <Region>(pharmacy.Region).name,
                            string.IsNullOrEmpty(pharmacy.Brand) ? string.Empty : pharmacy.Brand
                            )
                        );
                }
            }
            w.Stop();
            SDiag.Debug.WriteLine(@"Search: насыщение={0}", w.ElapsedMilliseconds);

            w.Restart();
            var matchFormat = @"Совпадение: {0}";
            var result      = new List <SearchItem>();
            var culture     = CultureInfo.GetCultureInfo("ru-RU");

            // 2 поиск
            foreach (var item in SearchItems)
            {
                if (culture.CompareInfo.IndexOf(item.Value.Subway, text, CompareOptions.IgnoreCase) >= 0)
                {
                    item.Value.Match = string.Format(matchFormat, @"метро=" + item.Value.Subway);
                    result.Add(item.Value);
                    if (result.Count > C_ITEMS_IN_RESULT)
                    {
                        break;
                    }
                    continue;
                }

                if (culture.CompareInfo.IndexOf(item.Value.Region, text, CompareOptions.IgnoreCase) >= 0)
                {
                    item.Value.Match = string.Format(matchFormat, @"район=" + item.Value.Region);
                    result.Add(item.Value);
                    if (result.Count > C_ITEMS_IN_RESULT)
                    {
                        break;
                    }
                    continue;
                }

                if (culture.CompareInfo.IndexOf(item.Value.Brand, text, CompareOptions.IgnoreCase) >= 0)
                {
                    item.Value.Match = string.Format(matchFormat, @"бренд=" + item.Value.Brand);
                    result.Add(item.Value);
                    if (result.Count > C_ITEMS_IN_RESULT)
                    {
                        break;
                    }
                    continue;
                }
            }
            w.Stop();
            SDiag.Debug.WriteLine(@"Search: поиск={0}", w.ElapsedMilliseconds);

            w.Restart();
            // 3 показ
            SearchTable.Adapter = new SearchResultAdapter(this, result);
            //SearchTable.Adapter = new ArrayAdapter<string>(
            //	this, Android.Resource.Layout.SimpleListItemMultipleChoice, result.Select(si => si.Name).ToArray()
            //);
            w.Stop();
            SDiag.Debug.WriteLine(@"Search: показ={0}", w.ElapsedMilliseconds);
            //SDiag.Debug.WriteLine(@"Search: endmemory{0}", System.Diagnostics.Process.GetCurrentProcess().WorkingSet64);
        }
Exemple #10
0
        void RecreateAdapter(List <Pharmacy> inputList = null)
        {
            // ветка для фильтра
            if (inputList != null)
            {
                if (inputList.Count > 0)
                {
                    Pharmacies            = inputList;
                    PharmacyTable.Adapter = new PharmacyAdapter(this, Pharmacies);
                    //if (!string.IsNullOrEmpty(SelectedPharmacyUUID)) {
                    //	int index = Pharmacies.FindIndex(ph => ph.UUID == SelectedPharmacyUUID);
                    //	if (index > -1) {
                    //		PharmacyTable.SetSelection(index);
                    //	}
                    //}
                    return;
                }
            }

            var list = MainDatabase.GetItems <Pharmacy>();

            string[] pharmaciesInRoute = null;

            var    prefs   = GetSharedPreferences(FilterDialog.C_FILTER_PREFS, FileCreationMode.Private);
            bool   isOn    = prefs.GetBoolean(@"IS_ON", false);
            string subway  = prefs.GetString(@"SUBWAY", string.Empty);
            string region  = prefs.GetString(@"REGION", string.Empty);
            string net     = prefs.GetString(@"NET", string.Empty);
            string address = prefs.GetString(@"ADDRESS", string.Empty);

            if (isOn)
            {
                Filter.SetBackgroundColor(Android.Graphics.Color.LightGreen);

                var filters = new List <string>();
                if (!string.IsNullOrEmpty(subway))
                {
                    list = list.Where(ph => ph.Subway == subway).ToList();
                    filters.Add(string.Format(@"Метро=""{0}""", MainDatabase.GetItem <Subway>(subway).name));
                }

                if (!string.IsNullOrEmpty(region))
                {
                    list = list.Where(ph => ph.Region == region).ToList();
                    filters.Add(string.Format(@"Район=""{0}""", MainDatabase.GetItem <Region>(region).name));
                }

                if (!string.IsNullOrEmpty(net))
                {
                    list = list.Where(ph => ph.Net == net).ToList();
                    filters.Add(string.Format(@"Аптечная сеть=""{0}""", MainDatabase.GetItem <Net>(net).name));
                }
                if (!string.IsNullOrEmpty(address))
                {
                    var culture = CultureInfo.GetCultureInfo("ru-RU");
                    list = list.Where(ph => culture.CompareInfo.IndexOf(ph.Address, address, CompareOptions.IgnoreCase) >= 0
                                      ).ToList();
                    filters.Add(string.Format(@"Адрес=""{0}""", address));
                }

                FilterContent.Text       = @"ФИЛЬТР: " + string.Join("; ", filters);
                FilterContent.Visibility = ViewStates.Visible;
                FilterContent.RequestFocus();
            }
            else
            {
                FilterContent.Visibility = ViewStates.Gone;
                Filter.SetBackgroundColor(Android.Graphics.Color.Transparent);


                var orderMapState = new Dictionary <string, int> {
                    { PharmacyState.psActive.ToString("G"), 0 },
                    { PharmacyState.psReserve.ToString("G"), 1 },
                    { PharmacyState.psClose.ToString("G"), 2 },
                };

                // TODO: optimize work with route
                var now        = DateTime.Now;
                var date       = new DateTimeOffset(now.Year, now.Month, now.Day, 0, 0, 0, new TimeSpan(0, 0, 0));
                var routeItems = MainDatabase.GetRouteItems(date);

                //Проверка правильности маршрута
                routeItems = FixRoute(routeItems);

                pharmaciesInRoute = routeItems.Select(ri => ri.Pharmacy).ToArray();
                // wmOnlyRoute, wmRouteAndRecommendations, wmOnlyRecommendations
                switch (Helper.WorkMode)
                {
                case WorkMode.wmOnlyRoute:
                    if (routeItems.Count == 0)
                    {
                        list = new List <Pharmacy>();
                    }
                    else
                    {
                        list = list.Where(ph => pharmaciesInRoute.Contains(ph.UUID)).ToList();
                    }
                    break;

                case WorkMode.wmRouteAndRecommendations:
                    if (routeItems.Count == 0)
                    {
                        list = list.OrderBy(ph => orderMapState[ph.State]).ThenBy(ph => ph.NextAttendanceDate).ToList();
                    }
                    else
                    {
                        var orderMapRoute = routeItems.ToDictionary(ri => ri.Pharmacy, ri => ri.Order);
                        var routeList     = list.Where(ph => pharmaciesInRoute.Contains(ph.UUID))
                                            .OrderBy(ph => orderMapRoute[ph.UUID])
                                            .ToList();

                        var nonRouteList = list.Where(ph => !pharmaciesInRoute.Contains(ph.UUID))
                                           .OrderBy(ph => orderMapState[ph.State])
                                           .ThenBy(ph => ph.NextAttendanceDate)
                                           .ToList();
                        list = new List <Pharmacy>();
                        list.AddRange(routeList);
                        list.AddRange(nonRouteList);
                    }
                    break;

                case WorkMode.wmOnlyRecommendations:
                    list = list.OrderBy(ph => orderMapState[ph.State]).ThenBy(ph => ph.NextAttendanceDate).ToList();
                    break;
                }

                //Pharmacies = list; //.Take(14).ToList();
                //PharmacyTable.Adapter = new PharmacyAdapter(this, Pharmacies, pharmaciesInRout);
                //return;
            }
            Filter.Invalidate();


            Pharmacies            = list;  //.Take(14).ToList();
            PharmacyTable.Adapter = new PharmacyAdapter(this, Pharmacies, pharmaciesInRoute);
            if (!string.IsNullOrEmpty(SelectedPharmacyUUID))
            {
                int index = Pharmacies.FindIndex(ph => ph.UUID == SelectedPharmacyUUID);
                if (index > -1)
                {
                    PharmacyTable.SetSelection(index);
                }
            }
        }