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();
            };
        }
        void GenerateData_Click(object sender, EventArgs e)
        {
            var rnd = new Random();

            var step        = 7;
            var visitsCount = 10;
            var baseDate    = DateTimeOffset.Now.AddDays(-1 * visitsCount * step);

            var promotions  = MainDatabase.GetItems <Promotion>();
            var drugSKUs    = MainDatabase.GetDrugSKUs();
            var pharmacies  = MainDatabase.GetItems <Pharmacy>();
            var transaction = MainDatabase.BeginTransaction();

            MainDatabase.DeleteAttendancies();
            MainDatabase.DeleteDistributions();
            MainDatabase.DeleteFinanceData();
            MainDatabase.DeleteSaleData();

            MainDatabase.DeleteItems <CoterieData>();
            MainDatabase.DeleteItems <PresentationData>();
            MainDatabase.DeleteItems <Employee>();
            MainDatabase.DeleteItems <PromotionData>();
            MainDatabase.DeleteItems <CompetitorData>();
            MainDatabase.DeleteItems <MessageData>();
            MainDatabase.DeleteItems <ResumeData>();
            MainDatabase.DeleteItems <PhotoData>();

            transaction.Commit();

            transaction = MainDatabase.BeginTransaction();

            //int count = 0;
            foreach (var pharmacy in pharmacies)
            {
                //count++;
                // Визиты
                if (true)
                {
                    for (int i = 0; i < visitsCount; i++)
                    {
                        var attendance = MainDatabase.Create <Attendance>();
                        attendance.Pharmacy = pharmacy.UUID;
                        attendance.When     = baseDate.AddDays(i * step);

                        foreach (var SKU in drugSKUs)
                        {
                            var distribution = MainDatabase.CreateData <DistributionData>(attendance.UUID);
                            distribution.DrugSKU     = SKU.uuid;
                            distribution.IsExistence = rnd.NextDouble() > 0.5;
                            distribution.Count       = rnd.Next(0, 10);
                            distribution.Price       = (int)(rnd.NextDouble() * 200);
                            distribution.IsPresence  = rnd.NextDouble() > 0.5;
                            distribution.HasPOS      = rnd.NextDouble() > 0.5;
                            distribution.Order       = @"Order " + SKU.uuid;
                            distribution.Comment     = @"Comment " + SKU.uuid;
                        }
                    }
                }

                // Продажи
                var financesCount = 5;
                baseDate = DateTimeOffset.Now.AddMonths(-3);
                for (int i = 0; i < financesCount; i++)
                {
                    foreach (var SKU in drugSKUs)
                    {
                        var financeData = MainDatabase.Create <FinanceData>();
                        financeData.Pharmacy = pharmacy.UUID;
                        financeData.Period   = baseDate.AddMonths(i);
                        financeData.DrugSKU  = SKU.uuid;
                        financeData.Sale     = rnd.NextDouble() > 0.3 ? null : (float?)(rnd.NextDouble() * 20);
                        financeData.Purchase = rnd.NextDouble() > 0.4 ? null : (float?)(rnd.NextDouble() * 20);
                        financeData.Remain   = rnd.NextDouble() > 0.5 ? null : (float?)(rnd.NextDouble() * 20);
                    }
                }

                // Содержание визите = Презентаци
                int employeesCount = 3;
                //int presentationsCount = 5;
                var attendanceLast = MainDatabase.GetAttendaces(pharmacy.UUID).OrderByDescending(i => i.When).FirstOrDefault();
                var positions      = MainDatabase.GetItems <Position>();
                var workTypes      = MainDatabase.GetItems <WorkType>();
                var brands         = MainDatabase.GetItems <DrugBrand>();
                var employees      = MainDatabase.GetEmployees(pharmacy.UUID);

                if (employees.Count == 0)
                {
                    for (int emp = 0; emp < employeesCount; emp++)
                    {
                        var employee = MainDatabase.CreateEmployee(pharmacy.UUID);
                        employee.SetSex(Sex.Male);
                        employee.Name = (rnd.NextDouble() > 0.5 ? @"Иванов" : @"Петров") + @" "
                                        + (rnd.NextDouble() > 0.5 ? @"Иван" : @"Петр") + @" "
                                        + (rnd.NextDouble() > 0.5 ? @"Иванович" : @"Петрович");
                        employee.Position  = positions[rnd.Next(positions.Count)].uuid;
                        employee.BirthDate = DateTimeOffset.Now.AddYears(-rnd.Next(25, 40)).AddDays((rnd.NextDouble() - 0.5) * 365);
                        employees.Add(employee);
                    }
                }

                foreach (var employee in employees)
                {
                    foreach (var brand in brands)
                    {
                        if (rnd.NextDouble() > 0.5)
                        {
                            continue;
                        }

                        for (int wt = 0; wt < workTypes.Count; wt++)
                        {
                            if (rnd.NextDouble() > 0.5)
                            {
                                continue;
                            }

                            var presentationData = MainDatabase.CreateData <PresentationData>(attendanceLast.UUID);
                            presentationData.Employee = employee.UUID;
                            presentationData.Brand    = brand.uuid;
                            presentationData.WorkType = workTypes[wt].uuid;
                        }
                    }
                }

                // Содержание визите = Фарм-кружок
                foreach (var employee in employees)
                {
                    if (rnd.NextDouble() > 0.5)
                    {
                        continue;
                    }

                    foreach (var brand in brands)
                    {
                        if (rnd.NextDouble() > 0.5)
                        {
                            continue;
                        }

                        var coterieData = MainDatabase.CreateData <CoterieData>(attendanceLast.UUID);
                        coterieData.Employee = employee.UUID;
                        coterieData.Brand    = brand.uuid;
                    }
                }

                // Акция
                var promotionData = MainDatabase.CreateData <PromotionData>(attendanceLast.UUID);
                promotionData.Promotion = promotions[rnd.Next(promotions.Count - 1)].uuid;
                promotionData.Text      = @"promotionData";

                // Активность конкурентов
                var competitorData = MainDatabase.CreateData <CompetitorData>(attendanceLast.UUID);
                competitorData.Text = @"competitorData";

                // Сообщения от аптеки
                var messageTypes = MainDatabase.GetItems <MessageType>();
                foreach (var item in messageTypes)
                {
                    if (rnd.NextDouble() > 0.5)
                    {
                        continue;
                    }

                    var messageData = MainDatabase.CreateData <MessageData>(attendanceLast.UUID);
                    messageData.Type = item.uuid;
                    messageData.Text = @"messageData " + item.uuid;
                }

                // Резюме визита;
                var resumeData = MainDatabase.CreateData <ResumeData>(attendanceLast.UUID);
                resumeData.Text = @"resumeData";
            }

            transaction.Commit();

            RefreshView();
        }