protected override void OnCreate(Bundle savedInstanceState)
        {
            RequestWindowFeature(WindowFeatures.NoTitle);
            Window.AddFlags(WindowManagerFlags.KeepScreenOn);

            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.activity_screen_slide);

            PharmacyUUID = Intent.GetStringExtra("UUID");
            if (string.IsNullOrEmpty(PharmacyUUID))
            {
                return;
            }

            AttendanceLast = MainDatabase.GetAttendaces(PharmacyUUID).OrderByDescending(i => i.When).FirstOrDefault();
            var attendanceLastUUID = AttendanceLast == null ? string.Empty : AttendanceLast.UUID;

            Materials = MainDatabase.GetItems <Material>();

            FragmentTitle      = FindViewById <TextView>(Resource.Id.aaTitleTV);
            FragmentTitle.Text = @"АПТЕКА";

            Pager = FindViewById <ViewPager>(Resource.Id.aaContainerVP);
            Pager.AddOnPageChangeListener(this);
            Pager.OffscreenPageLimit = 3;
            Pager.Adapter            = new AttendancePagerAdapter(SupportFragmentManager, PharmacyUUID, attendanceLastUUID);

            var btnStartStop = FindViewById <Button>(Resource.Id.aaStartOrStopAttendanceB);

            btnStartStop.Click += (sender, e) =>
            {
                if (!IsLocationActive() || !IsInternetActive())
                {
                    return;
                }

                if (AttendanceStart == null)
                {
                    AttendanceStart = DateTimeOffset.Now;

                    // Location
                    Locations = new List <Location>();

                    LocMgr = GetSystemService(LocationService) as LocationManager;
                    var locationCriteria = new Criteria();
                    locationCriteria.Accuracy         = Accuracy.Coarse;
                    locationCriteria.PowerRequirement = Power.Medium;
                    string locationProvider = LocMgr.GetBestProvider(locationCriteria, true);
                    System.Diagnostics.Debug.Print("Starting location updates with " + locationProvider);
                    LocMgr.RequestLocationUpdates(locationProvider, 5000, 1, this);
                    // !Location

                    if (Pager.CurrentItem == 2)
                    {
                        FragmentTitle.Text = @"СОБИРАЕМАЯ ИНФОРМАЦИЯ";
                    }

                    if (Pager.CurrentItem == 3)
                    {
                        FragmentTitle.Text = @"ФОТО НА ВИЗИТЕ";
                    }

                    for (int f = 0; f < C_NUM_PAGES; f++)
                    {
                        var fragment = GetFragment(f);
                        if (fragment is IAttendanceControl)
                        {
                            (fragment as IAttendanceControl).OnAttendanceStart(AttendanceStart);
                        }
                    }

                    Close.Visibility = ViewStates.Invisible;

                    Contracts.Visibility = ViewStates.Visible;

                    Finance.Visibility = ViewStates.Visible;
                    var financeParams = Finance.LayoutParameters as RelativeLayout.LayoutParams;
                    financeParams.AddRule(LayoutRules.LeftOf, Resource.Id.aaContractsIV);

                    History.Visibility = ViewStates.Visible;
                    var historyParams = History.LayoutParameters as RelativeLayout.LayoutParams;
                    historyParams.AddRule(LayoutRules.LeftOf, Resource.Id.aaFinanceIV);

                    Material.Visibility = ViewStates.Visible;
                    var materialParams = Material.LayoutParameters as RelativeLayout.LayoutParams;
                    materialParams.AddRule(LayoutRules.LeftOf, Resource.Id.aaHistoryIV);

                    var button = sender as Button;
                    button.SetBackgroundResource(Resource.Color.Deep_Orange_500);
                    button.Text = "ЗАКОНЧИТЬ ВИЗИТ";
                    return;
                }

                if ((DateTimeOffset.Now - AttendanceStart.Value).TotalSeconds < 30)
                {
                    return;
                }

                if (CurrentFocus != null)
                {
                    var imm = (InputMethodManager)GetSystemService(InputMethodService);
                    imm.HideSoftInputFromWindow(CurrentFocus.WindowToken, HideSoftInputFlags.None);
                }

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

                var lockDialog = LockDialog.Create("Идет сохранение данных...", Resource.Color.Deep_Orange_500);
                lockDialog.Cancelable = false;
                lockDialog.Show(fragmentTransaction, LockDialog.TAG);

                LocMgr.RemoveUpdates(this);

                new Task(() => {
                    Thread.Sleep(2000);                     // иначе не успеет показаться диалог

                    RunOnUiThread(() => {
                        var transaction     = MainDatabase.BeginTransaction();
                        var attendance      = MainDatabase.Create2 <Attendance>();
                        attendance.Pharmacy = PharmacyUUID;
                        attendance.When     = AttendanceStart.Value;
                        attendance.Duration = (DateTimeOffset.Now - AttendanceStart.Value).TotalMilliseconds;

                        foreach (var location in Locations)
                        {
                            var gps                  = MainDatabase.Create2 <GPSData>();
                            gps.Attendance           = attendance.UUID;
                            gps.Accuracy             = location.Accuracy;
                            gps.Altitude             = location.Altitude;
                            gps.Bearing              = location.Bearing;
                            gps.ElapsedRealtimeNanos = location.ElapsedRealtimeNanos;
                            gps.IsFromMockProvider   = location.IsFromMockProvider;
                            gps.Latitude             = location.Latitude;
                            gps.Longitude            = location.Longitude;
                            gps.Provider             = location.Provider;
                            gps.Speed                = location.Speed;
                        }

                        // Оповещаем фрагменты о завершении визита
                        for (int f = 0; f < C_NUM_PAGES; f++)
                        {
                            var fragment = GetFragment(f);
                            if (fragment is IAttendanceControl)
                            {
                                (fragment as IAttendanceControl).OnAttendanceStop(transaction, attendance);
                            }
                        }

                        transaction.Commit();

                        //if (lockDialog != null) {
                        //	lockDialog.DismissAllowingStateLoss();
                        //}

                        Finish();
                    });
                }).Start();
            };
            // TODO: uncomment
            if (AttendanceLast != null)
            {
                if (AttendanceLast.When.Date == DateTimeOffset.UtcNow.Date)
                {
                    btnStartStop.Visibility = ViewStates.Gone;
                }
            }

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

            Contracts        = FindViewById <ImageView>(Resource.Id.aaContractsIV);
            Contracts.Click += (sender, e) => {
                var contractActivity = new Intent(this, typeof(ContractActivity));
                contractActivity.PutExtra(ContractActivity.C_PHARMACY_UUID, PharmacyUUID);
                StartActivity(contractActivity);
            };

            Finance        = FindViewById <ImageView>(Resource.Id.aaFinanceIV);
            Finance.Click += (sender, e) => {
                var financeActivity = new Intent(this, typeof(FinanceActivity));
                financeActivity.PutExtra(@"UUID", PharmacyUUID);
                financeActivity.PutExtra(FinanceActivity.C_IS_CAN_ADD, false);
                StartActivity(financeActivity);
            };

            History        = FindViewById <ImageView>(Resource.Id.aaHistoryIV);
            History.Click += (sender, e) => {
                var historyActivity = new Intent(this, typeof(HistoryActivity));
                historyActivity.PutExtra(@"UUID", PharmacyUUID);
                StartActivity(historyActivity);
            };

            Material        = FindViewById <ImageView>(Resource.Id.aaMaterialIV);
            Material.Click += (sender, e) => {
                if (Materials.Count == 0)
                {
                    return;
                }

                var materialItems = new List <MaterialItem>();
                var materialFiles = MainDatabase.GetItems <MaterialFile>();
                foreach (var mf in materialFiles)
                {
                    var file = new Java.IO.File(Helper.MaterialDir, mf.fileName);
                    if (file.Exists())
                    {
                        var found = Materials.FirstOrDefault(m => m.uuid == mf.material);
                        if (found != null)
                        {
                            materialItems.Add(new MaterialItem(found.name, file));
                        }
                    }
                }

                if (materialItems.Count == 0)
                {
                    return;
                }

                new AlertDialog.Builder(this)
                .SetTitle("Выберите материал для показа:")
                .SetCancelable(true)
                .SetItems(
                    materialItems.Select(item => item.MaterialName).ToArray(),
                    (caller, arguments) => {
                    var intent = new Intent(Intent.ActionView);
                    var uri    = Android.Net.Uri.FromFile(materialItems[arguments.Which].FilePath);
                    intent.SetDataAndType(uri, "application/pdf");
                    intent.SetFlags(ActivityFlags.NoHistory);
                    StartActivity(intent);
                })
                .Show();
            };
        }
        //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();
        }
        public override void OnPause()
        {
            base.OnPause();
            var transaction = MainDatabase.BeginTransaction();

            Pharmacy item;

            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      = View.FindViewById <EditText>(Resource.Id.pfBrandET).Text;
            item.NumberName = View.FindViewById <EditText>(Resource.Id.pfNumberNameET).Text;
            item.LegalName  = View.FindViewById <EditText>(Resource.Id.pfLegalNameET).Text;

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

            var address = View.FindViewById <AutoCompleteTextView>(Resource.Id.pfAddressACTV);

            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 = View.FindViewById <EditText>(Resource.Id.pfPhoneET).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(View.FindViewById <EditText>(Resource.Id.pfTurnOverET).Text);
            item.Comment  = View.FindViewById <EditText>(Resource.Id.pfCommentET).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"));
            Activity.GetSharedPreferences(MainActivity.C_MAIN_PREFS, FileCreationMode.Private)
            .Edit()
            .PutString(MainActivity.C_SAVED_PHARMACY_UUID, item.UUID)
            .Commit();
        }
        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 #5
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);
        }