diff --git a/.idea/deploymentTargetDropDown.xml b/.idea/deploymentTargetDropDown.xml index 70901d2..52814fd 100644 --- a/.idea/deploymentTargetDropDown.xml +++ b/.idea/deploymentTargetDropDown.xml @@ -7,11 +7,11 @@ - + - + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index 773fe0f..1e1b85f 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -6,4 +6,11 @@ + + + \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle index 6d5baed..5441837 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,8 +1,8 @@ plugins { + id 'kotlin-kapt' id 'com.android.application' id 'org.jetbrains.kotlin.android' - id 'kotlin-kapt' - + id 'com.google.gms.google-services' } android { @@ -42,10 +42,17 @@ dependencies { implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.6.1' implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.1' + implementation platform('com.google.firebase:firebase-bom:31.2.0') + implementation 'com.google.firebase:firebase-database-ktx:20.2.2' + implementation 'com.google.firebase:firebase-auth-ktx:22.1.0' + implementation 'com.google.firebase:firebase-analytics' + implementation 'com.google.firebase:firebase-messaging' + implementation 'com.google.firebase:firebase-messaging-ktx:23.2.0' + kapt 'androidx.room:room-compiler:2.5.2' implementation 'androidx.fragment:fragment-ktx:1.5.5' - + implementation 'pl.droidsonroids.gif:android-gif-drawable:1.1.17' implementation 'androidx.core:core-ktx:1.7.0' implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.google.android.material:material:1.9.0' @@ -54,4 +61,23 @@ dependencies { testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.5' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' + + implementation 'org.apache.poi:poi:5.2.3' + + implementation group: 'org.apache.poi', name: 'poi-ooxml', version: '5.2.3' + implementation group: 'org.apache.poi', name: 'poi', version: '5.2.3' + + //Календарь + // implementation 'com.github.appmonkey8010:amcalendar:[RELEASE]' //e.g.: 1.0.0 + //implementation 'ru.cleverpumpkin:crunchycalendar:2.6.0' + //implementation 'com.applandeo:material-calendar-view:1.9.0-rc03' + //implementation 'com.github.tejpratap46:RecyclerCalendarAndroid:LATEST_RELEASE_TAG' + //implementation 'com.github.tejpratap46:RecyclerCalendarAndroid:LATEST_RELEASE_TAG' + + + //implementation 'com.sun.mail:android-mail:1.6.2' + //implementation 'com.sun.mail:android-activation:1.6.2' + //implementation 'com.archit.calendar:awesome-calendar:2.0.0' + //implementation 'com.andrewjapar.rangedatepicker:rangedatepicker:0.3' + } \ No newline at end of file diff --git a/app/google-services.json b/app/google-services.json new file mode 100644 index 0000000..cb6c3b8 --- /dev/null +++ b/app/google-services.json @@ -0,0 +1,69 @@ +{ + "project_info": { + "project_number": "1027818028999", + "firebase_url": "https://rehabilitationtest-default-rtdb.europe-west1.firebasedatabase.app", + "project_id": "rehabilitationtest", + "storage_bucket": "rehabilitationtest.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:1027818028999:android:a97724d7840d06fdada3e2", + "android_client_info": { + "package_name": "com.example.rehabilitation" + } + }, + "oauth_client": [ + { + "client_id": "1027818028999-a75qvvvqqb81ber25k6eeq1fqpr60oam.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyAHvjzE2QIaIrCD9NOD1f_rShI4eXPyFVo" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "1027818028999-a75qvvvqqb81ber25k6eeq1fqpr60oam.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + }, + { + "client_info": { + "mobilesdk_app_id": "1:1027818028999:android:1459bab345b4bf66ada3e2", + "android_client_info": { + "package_name": "com.example.user" + } + }, + "oauth_client": [ + { + "client_id": "1027818028999-a75qvvvqqb81ber25k6eeq1fqpr60oam.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyAHvjzE2QIaIrCD9NOD1f_rShI4eXPyFVo" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "1027818028999-a75qvvvqqb81ber25k6eeq1fqpr60oam.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index f590832..805b52f 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,32 +2,79 @@ + + + + + + + + + + + + + + + + + + + + + + android:exported="false" + android:screenOrientation="portrait" /> + android:exported="false" + android:screenOrientation="portrait" /> + android:exported="false" + android:screenOrientation="portrait" /> + + + diff --git a/app/src/main/assets/ReabilitationV4.db b/app/src/main/assets/ReabilitationV4.db new file mode 100644 index 0000000..69677dc Binary files /dev/null and b/app/src/main/assets/ReabilitationV4.db differ diff --git a/app/src/main/ic_launcher-playstore.png b/app/src/main/ic_launcher-playstore.png index c15e36a..572be4f 100644 Binary files a/app/src/main/ic_launcher-playstore.png and b/app/src/main/ic_launcher-playstore.png differ diff --git a/app/src/main/java/com/example/rehabilitation/Admin/activityAdmin/FeedbackActivity.kt b/app/src/main/java/com/example/rehabilitation/Admin/activityAdmin/FeedbackActivity.kt index ea8a4fa..4e49d76 100644 --- a/app/src/main/java/com/example/rehabilitation/Admin/activityAdmin/FeedbackActivity.kt +++ b/app/src/main/java/com/example/rehabilitation/Admin/activityAdmin/FeedbackActivity.kt @@ -1,12 +1,15 @@ package com.example.rehabilitation.Admin.activityAdmin -import androidx.appcompat.app.AppCompatActivity +import android.content.Intent +import android.net.Uri import android.os.Bundle -import com.example.rehabilitation.R +import android.widget.Toast +import androidx.appcompat.app.AppCompatActivity +import com.example.rehabilitation.MainActivity import com.example.rehabilitation.databinding.ActivityFeedbackBinding -import com.example.rehabilitation.databinding.FragmentFeedbackBinding class FeedbackActivity : AppCompatActivity() { + var backPressedTime: Long = 0 private lateinit var binding: ActivityFeedbackBinding override fun onCreate(savedInstanceState: Bundle?) { @@ -18,5 +21,50 @@ class FeedbackActivity : AppCompatActivity() { binding.btnExit.setOnClickListener{ finish() } + + //Переход по ссылке на сайт + binding.txtUrlVmeda.setOnClickListener{ + val i = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.vmeda.org/")) + startActivity(i) + } +// +// //Переход на почту +// binding.txtEmailDoctor.setOnClickListener{ +// val intent = Intent(Intent.ACTION_SEND) +// intent.data = Uri.parse("mailto:") +// intent.type = "text/plain" +// intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(binding.txtEmailDoctor.text.toString()))// herer adresses is already string +// +// try{ +// startActivity(Intent.createChooser(intent,"Choose Email Client...")) +// } +// catch (e:Exception){ +// Toast.makeText(this,e.message, Toast.LENGTH_LONG).show() +// } +// } + +// //Номер врача +// binding.txtNumberDoctor.setOnClickListener{ +// val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + binding.txtNumberDoctor.text.toString())) +// startActivity(intent) +// } + + //Номер регистратуры + binding.txtNumberRegister.setOnClickListener{ + val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "+78122923286")) + startActivity(intent) + } + + //Номер ДМС + binding.txtNumberDMS.setOnClickListener{ + val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "+78122923412")) + startActivity(intent) + } + } + + override fun onBackPressed() { + val intetn = Intent(this, MainActivity::class.java) + startActivity(intetn) + finish() } } \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Admin/activityAdmin/StatisticsActivity.kt b/app/src/main/java/com/example/rehabilitation/Admin/activityAdmin/StatisticsActivity.kt index 0eb43f7..0e0c9bd 100644 --- a/app/src/main/java/com/example/rehabilitation/Admin/activityAdmin/StatisticsActivity.kt +++ b/app/src/main/java/com/example/rehabilitation/Admin/activityAdmin/StatisticsActivity.kt @@ -1,12 +1,14 @@ package com.example.rehabilitation.Admin.activityAdmin +import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle +import com.example.rehabilitation.MainActivity import com.example.rehabilitation.R import com.example.rehabilitation.databinding.ActivityFeedbackBinding -import com.example.rehabilitation.databinding.FragmentStatisticsBinding class StatisticsActivity : AppCompatActivity() { + var backPressedTime: Long = 0 private lateinit var binding: ActivityFeedbackBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -18,4 +20,10 @@ class StatisticsActivity : AppCompatActivity() { finish() } } + + override fun onBackPressed() { + val intetn = Intent(this, MainActivity::class.java) + startActivity(intetn) + finish() + } } \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Admin/activityAdmin/UserSettingActivity.kt b/app/src/main/java/com/example/rehabilitation/Admin/activityAdmin/UserSettingActivity.kt index 2919917..de4b647 100644 --- a/app/src/main/java/com/example/rehabilitation/Admin/activityAdmin/UserSettingActivity.kt +++ b/app/src/main/java/com/example/rehabilitation/Admin/activityAdmin/UserSettingActivity.kt @@ -1,475 +1,128 @@ package com.example.rehabilitation.Admin.activityAdmin +import android.annotation.SuppressLint +import android.content.Context +import android.content.Intent +import android.content.SharedPreferences import androidx.appcompat.app.AppCompatActivity import android.os.Bundle +import android.util.Log import android.view.View +import android.widget.EditText +import android.widget.Toast import androidx.activity.viewModels +import androidx.appcompat.app.AlertDialog +import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.asLiveData +import androidx.recyclerview.widget.GridLayoutManager +import com.example.admin.Toast.showCustomInfoToast +import com.example.admin.Toast.showCustomNiceToast +import com.example.rehabilitation.Admin.fragmrntAdmin.SettingDoctor.MainSettingDoctorFragment +import com.example.rehabilitation.Auth.AuthorizationActivity +import com.example.rehabilitation.FIO +import com.example.rehabilitation.MainActivity import com.example.rehabilitation.R + +import com.example.rehabilitation.SettingActivity +import com.example.rehabilitation.countCategory import com.example.rehabilitation.databinding.ActivityUserSettingBinding -import com.example.rehabilitation.db.Item -import com.example.rehabilitation.db.ItemDaySport -import com.example.rehabilitation.db.ItemImage -import com.example.rehabilitation.db.ItemSportCategory -import com.example.rehabilitation.db.MainDB -import com.example.rehabilitation.dip.Day.DayAdapter -import com.example.rehabilitation.dip.Day.DayModel +import com.example.rehabilitation.Room.Item +import com.example.rehabilitation.Room.ItemDaySport +import com.example.rehabilitation.Room.ItemImage +import com.example.rehabilitation.Room.ItemSportCategory +import com.example.rehabilitation.Room.MainDB +import com.example.rehabilitation.Room.dbUser.dbPatient.ItemPatient +import com.example.rehabilitation.User.fragmentUser.HomeFragment +import com.example.rehabilitation.UserDoctorToken +import com.example.rehabilitation.counter2 +import com.example.rehabilitation.model_adapter.Day.DayAdapter +import com.example.rehabilitation.model_adapter.Day.DayListModel +import com.example.rehabilitation.model_adapter.Doctor.DoctorModel +import com.example.rehabilitation.model_adapter.Edit.EditSportAdapter +import com.example.rehabilitation.model_adapter.Edit.EditSportModel +import com.example.rehabilitation.model_adapter.Image.Category.CountNameCategoryModel import com.example.sqlitework.dip.MainViewModel -import com.example.rehabilitation.dip.Month.MonthModel -import com.example.rehabilitation.dip.Month.MonthAdapter +import com.example.rehabilitation.model_adapter.Month.MonthModel +import com.example.rehabilitation.model_adapter.Month.MonthAdapter +import com.example.rehabilitation.model_adapter.Patient.PatientModel +import com.example.rehabilitation.prefDoctor +import com.example.rehabilitation.prefFIO +import com.example.rehabilitation.prefUserDoctorToken +import com.example.rehabilitation.questionnaire_before +import com.example.rehabilitation.tokenClassDoctor + import java.time.LocalDate -class UserSettingActivity : AppCompatActivity(), MonthAdapter.Listener,DayAdapter.Listener { +class UserSettingActivity : AppCompatActivity(), MonthAdapter.Listener, DayAdapter.Listener,EditSportAdapter.Listener,EditSportAdapter.ListenerEdit { + var backPressedTime: Long = 0 private lateinit var binding: ActivityUserSettingBinding private val model: MainViewModel by viewModels()//Инициализировали класс lateinit var adapterMonth: MonthAdapter lateinit var adapterDay: DayAdapter + lateinit var editAdapter: EditSportAdapter - + var loginPatient = "" + var loginDoctor = "" + var prefSport: SharedPreferences? = null + var SportUserTrue = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityUserSettingBinding.inflate(layoutInflater) setContentView(binding.root) -// initRcView() -// initRcViewDay() -// model.liveListList.observe(lifeCy) {//viewLifecycleOwner - следит за циклом жизни fragment -// adapterMonth.submitList(it)//Напрямую переадем созданный список в adapter(ProductAdapter) -// } -// -// model.liveDayList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment -// adapterDay.submitList(it)//Напрямую переадем созданный список в adapter(ProductAdapter) -// } + //Вывод фрагмента на активити при первоначальной загрузке + supportFragmentManager.beginTransaction().replace(R.id.CLMainSettinDoctor, MainSettingDoctorFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем - //Выход - binding.btnExit.setOnClickListener{ - finish() - } + prefUserDoctorToken = getSharedPreferences("UserDoctorToken", Context.MODE_PRIVATE) + UserDoctorToken = prefUserDoctorToken?.getString("userdoctortoken", "")!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0 - //Выход из добавленеия - binding.btnExitAdd.setOnClickListener{ - binding.CLAdd.visibility = View.GONE - binding.CLCreateDeleteUser.visibility = View.VISIBLE - } - - //Выход из добавленеия - binding.btnCreate.setOnClickListener{ - binding.CLAdd.visibility = View.VISIBLE - binding.CLCreateDeleteUser.visibility = View.GONE - } - - binding.cvClearDayUser.setOnClickListener{ - val db = MainDB.getDB(this) - Thread { - db.getDaoDaySport().deleteItemDaySport() - db.getDao().deleteItem() - }.start() - } - - //addListModelCards() - - //addDayModelCards() - - - binding.btnImage.setOnClickListener{ - createImageBD() - } - - binding.btnCategorySport.setOnClickListener { - createSportCategory() - } - - binding.btnCardC.setOnClickListener { - val db = MainDB.getDB(this) - for(i in 1..30){ - val item = Item(null, - getDateTomorrow(i, "c"),//"11/11/2023", - i.toString(), - 0 - ) - Thread { - db.getDao().insertItem(item) - }.start() - } - } - binding.btnCardB.setOnClickListener { - val db = MainDB.getDB(this) - for(i in 1..30){ - val item = Item(null, - getDateTomorrow(i, "b"),//"11/11/2023", - i.toString(), - 0 - ) - Thread { - db.getDao().insertItem(item) - }.start() - } - } - binding.btnCardJ.setOnClickListener { - val db = MainDB.getDB(this) - for(i in 1..30){ - val item = Item(null, - getDateTomorrow(i, "j"),//"11/11/2023", - i.toString(), - 0 - ) - Thread { - db.getDao().insertItem(item) - }.start() - } - } + prefFIO = getSharedPreferences("FIO", Context.MODE_PRIVATE) + FIO = prefFIO?.getString("fio", "")!! } - private fun createImageBD() { - val db = MainDB.getDB(this) - - val itemС1_1 = ItemImage(null, "${R.drawable.c1_1}", "c1","c") - val itemС1_2 = ItemImage(null, "${R.drawable.c1_2}", "c1","c") - val itemС2_1 = ItemImage(null, "${R.drawable.c2_1}", "c2","c") - val itemС2_2 = ItemImage(null, "${R.drawable.c2_2}", "c2","c") - val itemС3_1 = ItemImage(null, "${R.drawable.c3_1}", "c3","c") - val itemС3_2 = ItemImage(null, "${R.drawable.c3_2}", "c3","c") - val itemС4_1 = ItemImage(null, "${R.drawable.c4_1}", "c4","c") - val itemС4_2 = ItemImage(null, "${R.drawable.c4_1}", "c4","c") - val itemС5_1 = ItemImage(null, "${R.drawable.c5_1}", "c5","c") - val itemС5_2 = ItemImage(null, "${R.drawable.c5_2}", "c5","c") - val itemС6_1 = ItemImage(null, "${R.drawable.c6_1}", "c6","c") - val itemС6_2 = ItemImage(null, "${R.drawable.c6_2}", "c6","c") - val itemС6_3 = ItemImage(null, "${R.drawable.c6_3}", "c6","c") - val itemС7_1 = ItemImage(null, "${R.drawable.c7_1}", "c7","c") - val itemС8_1 = ItemImage(null, "${R.drawable.c8_1}", "c8","c") - val itemС8_2 = ItemImage(null, "${R.drawable.c8_2}", "c8","c") - val itemС9_1 = ItemImage(null, "${R.drawable.c9_1}", "c9","c") - val itemС9_2 = ItemImage(null, "${R.drawable.c9_2}", "c9","c") - val itemС9_3 = ItemImage(null, "${R.drawable.c9_3}", "c9","c") - val itemС10_1 = ItemImage(null, "${R.drawable.c10_1}", "c10","c") - val itemС10_2 = ItemImage(null, "${R.drawable.c10_2}", "c10","c") - val itemС10_3 = ItemImage(null, "${R.drawable.c10_3}", "c10","c") - val itemС11_1 = ItemImage(null, "${R.drawable.c11_1}", "c11","c") - val itemС12_1 = ItemImage(null, "${R.drawable.c12_1}", "c12","c") - val itemС12_2 = ItemImage(null, "${R.drawable.c12_2}", "c12","c") - val itemС13_1 = ItemImage(null, "${R.drawable.c13_1}", "c13","c") - val itemС13_2 = ItemImage(null, "${R.drawable.c13_2}", "c13","c") - val itemС14_1 = ItemImage(null, "${R.drawable.c14_1}", "c14","c") - val itemС14_2 = ItemImage(null, "${R.drawable.c14_2}", "c14","c") - val itemС15_1 = ItemImage(null, "${R.drawable.c15_1}", "c15","c") - val itemС15_2 = ItemImage(null, "${R.drawable.c15_2}", "c15","c") - val itemС16_1 = ItemImage(null, "${R.drawable.c16_1}", "c16","c") - val itemС16_2 = ItemImage(null, "${R.drawable.c16_2}", "c16","c") - val itemС17_1 = ItemImage(null, "${R.drawable.c17_1}", "c17","c") - val itemС17_2 = ItemImage(null, "${R.drawable.c17_2}", "c17","c") - val itemС18_1 = ItemImage(null, "${R.drawable.c18_1}", "c18","c") - val itemС18_2 = ItemImage(null, "${R.drawable.c18_2}", "c18","c") - val itemС18_3 = ItemImage(null, "${R.drawable.c18_3}", "c18","c") - - val itemB1_1 = ItemImage(null, "${R.drawable.b1_1}", "b1", "b") - val itemB1_2 = ItemImage(null, "${R.drawable.b1_2}", "b1", "b") - val itemB2_1 = ItemImage(null, "${R.drawable.b2_1}", "b2", "b") - val itemB2_2 = ItemImage(null, "${R.drawable.b2_2}", "b2", "b") - val itemB3_1 = ItemImage(null, "${R.drawable.b3_1}", "b3", "b") - val itemB3_2 = ItemImage(null, "${R.drawable.b3_2}", "b3", "b") - val itemB3_3 = ItemImage(null, "${R.drawable.b3_3}", "b3", "b") - val itemB4_1 = ItemImage(null, "${R.drawable.b4_1}", "b4", "b") - val itemB4_2 = ItemImage(null, "${R.drawable.b4_2}", "b4", "b") - - val itemJ1_1 = ItemImage(null, "${R.drawable.j1_1}", "j1","j") - val itemJ1_2 = ItemImage(null, "${R.drawable.j1_2}", "j1","j") - val itemJ2_1 = ItemImage(null, "${R.drawable.j2_1}", "j2","j") - val itemJ2_2 = ItemImage(null, "${R.drawable.j2_2}", "j2","j") - val itemJ3_1 = ItemImage(null, "${R.drawable.j3_1}", "j3","j") - val itemJ3_2 = ItemImage(null, "${R.drawable.j3_2}", "j3","j") - val itemJ4_1 = ItemImage(null, "${R.drawable.j4_1}", "j4","j") - val itemJ4_2 = ItemImage(null, "${R.drawable.j4_2}", "j4","j") - val itemJ4_3 = ItemImage(null, "${R.drawable.j4_3}", "j4","j") - val itemJ5_1 = ItemImage(null, "${R.drawable.j5_1}", "j5","j") - val itemJ6_1 = ItemImage(null, "${R.drawable.j6_1}", "j6","j") - val itemJ6_2 = ItemImage(null, "${R.drawable.j6_2}", "j6","j") - val itemJ6_3 = ItemImage(null, "${R.drawable.j6_3}", "j6","j") - val itemJ6_4 = ItemImage(null, "${R.drawable.j6_4}", "j6","j") - val itemJ7_1 = ItemImage(null, "${R.drawable.j7_1}", "j7","j") - val itemJ7_2 = ItemImage(null, "${R.drawable.j7_2}", "j7","j") - val itemJ7_3 = ItemImage(null, "${R.drawable.j7_3}", "j7","j") - val itemJ7_4 = ItemImage(null, "${R.drawable.j7_4}", "j7","j") - val itemJ7_5 = ItemImage(null, "${R.drawable.j7_5}", "j7","j") - val itemJ7_6 = ItemImage(null, "${R.drawable.j7_6}", "j7","j") - val itemJ7_7 = ItemImage(null, "${R.drawable.j7_7}", "j7","j") - val itemJ8_1 = ItemImage(null, "${R.drawable.j8_1}", "j8","j") - val itemJ8_2 = ItemImage(null, "${R.drawable.j8_2}", "j8","j") - val itemJ8_3 = ItemImage(null, "${R.drawable.j8_3}", "j8","j") - val itemJ9_1 = ItemImage(null, "${R.drawable.j9_1}", "j9","j") - val itemJ10_1 = ItemImage(null, "${R.drawable.j10_1}", "j10","j") - val itemJ10_2 = ItemImage(null, "${R.drawable.j10_2}", "j10","j") - val itemJ10_3 = ItemImage(null, "${R.drawable.j10_2}", "j10","j") - val itemJ11_1 = ItemImage(null, "${R.drawable.j11_1}", "j11","j") - val itemJ11_2 = ItemImage(null, "${R.drawable.j11_2}", "j11","j") - val itemJ11_3 = ItemImage(null, "${R.drawable.j11_3}", "j11","j") - val itemJ11_4 = ItemImage(null, "${R.drawable.j11_4}", "j11","j") - val itemJ12_1 = ItemImage(null, "${R.drawable.j12_1}", "j12","j") - val itemJ12_2 = ItemImage(null, "${R.drawable.j12_2}", "j12","j") - - Thread { - db.getDaoImage().insertItemImage(itemС1_1) - db.getDaoImage().insertItemImage(itemС1_2) - db.getDaoImage().insertItemImage(itemС2_1) - db.getDaoImage().insertItemImage(itemС2_2) - db.getDaoImage().insertItemImage(itemС3_1) - db.getDaoImage().insertItemImage(itemС3_2) - db.getDaoImage().insertItemImage(itemС4_1) - db.getDaoImage().insertItemImage(itemС4_2) - db.getDaoImage().insertItemImage(itemС5_1) - db.getDaoImage().insertItemImage(itemС5_2) - db.getDaoImage().insertItemImage(itemС6_1) - db.getDaoImage().insertItemImage(itemС6_2) - db.getDaoImage().insertItemImage(itemС6_3) - db.getDaoImage().insertItemImage(itemС7_1) - db.getDaoImage().insertItemImage(itemС8_1) - db.getDaoImage().insertItemImage(itemС8_2) - db.getDaoImage().insertItemImage(itemС9_1) - db.getDaoImage().insertItemImage(itemС9_2) - db.getDaoImage().insertItemImage(itemС9_3) - db.getDaoImage().insertItemImage(itemС10_1) - db.getDaoImage().insertItemImage(itemС10_2) - db.getDaoImage().insertItemImage(itemС10_3) - db.getDaoImage().insertItemImage(itemС11_1) - db.getDaoImage().insertItemImage(itemС12_1) - db.getDaoImage().insertItemImage(itemС12_2) - db.getDaoImage().insertItemImage(itemС13_1) - db.getDaoImage().insertItemImage(itemС13_2) - db.getDaoImage().insertItemImage(itemС14_1) - db.getDaoImage().insertItemImage(itemС14_2) - db.getDaoImage().insertItemImage(itemС15_1) - db.getDaoImage().insertItemImage(itemС15_2) - db.getDaoImage().insertItemImage(itemС16_1) - db.getDaoImage().insertItemImage(itemС16_2) - db.getDaoImage().insertItemImage(itemС17_1) - db.getDaoImage().insertItemImage(itemС17_2) - db.getDaoImage().insertItemImage(itemС18_1) - db.getDaoImage().insertItemImage(itemС18_2) - db.getDaoImage().insertItemImage(itemС18_3) - - db.getDaoImage().insertItemImage(itemB1_1) - db.getDaoImage().insertItemImage(itemB1_2) - db.getDaoImage().insertItemImage(itemB2_1) - db.getDaoImage().insertItemImage(itemB2_2) - db.getDaoImage().insertItemImage(itemB3_1) - db.getDaoImage().insertItemImage(itemB3_2) - db.getDaoImage().insertItemImage(itemB3_3) - db.getDaoImage().insertItemImage(itemB4_1) - db.getDaoImage().insertItemImage(itemB4_2) - - db.getDaoImage().insertItemImage(itemJ1_1) - db.getDaoImage().insertItemImage(itemJ1_2) - db.getDaoImage().insertItemImage(itemJ2_1) - db.getDaoImage().insertItemImage(itemJ2_2) - db.getDaoImage().insertItemImage(itemJ3_1) - db.getDaoImage().insertItemImage(itemJ3_2) - db.getDaoImage().insertItemImage(itemJ4_1) - db.getDaoImage().insertItemImage(itemJ4_2) - db.getDaoImage().insertItemImage(itemJ4_3) - db.getDaoImage().insertItemImage(itemJ5_1) - db.getDaoImage().insertItemImage(itemJ6_1) - db.getDaoImage().insertItemImage(itemJ6_2) - db.getDaoImage().insertItemImage(itemJ6_3) - db.getDaoImage().insertItemImage(itemJ6_4) - db.getDaoImage().insertItemImage(itemJ7_1) - db.getDaoImage().insertItemImage(itemJ7_2) - db.getDaoImage().insertItemImage(itemJ7_3) - db.getDaoImage().insertItemImage(itemJ7_4) - db.getDaoImage().insertItemImage(itemJ7_5) - db.getDaoImage().insertItemImage(itemJ7_6) - db.getDaoImage().insertItemImage(itemJ7_7) - db.getDaoImage().insertItemImage(itemJ8_1) - db.getDaoImage().insertItemImage(itemJ8_2) - db.getDaoImage().insertItemImage(itemJ8_3) - db.getDaoImage().insertItemImage(itemJ9_1) - db.getDaoImage().insertItemImage(itemJ10_1) - db.getDaoImage().insertItemImage(itemJ10_2) - db.getDaoImage().insertItemImage(itemJ10_3) - db.getDaoImage().insertItemImage(itemJ11_1) - db.getDaoImage().insertItemImage(itemJ11_2) - db.getDaoImage().insertItemImage(itemJ11_3) - db.getDaoImage().insertItemImage(itemJ11_4) - db.getDaoImage().insertItemImage(itemJ12_1) - db.getDaoImage().insertItemImage(itemJ12_2) - - }.start() - - + override fun onDestroy() { + super.onDestroy() + clearUserDoctorToken() + finish() + } + //Функция очистки данных + fun clearUserDoctorToken() { + val edit = prefUserDoctorToken?.edit() + edit?.clear() + edit?.apply() + UserDoctorToken = "" } - fun createSportCategory(){ - getDaySport(1, C1,"c","c1") - getDaySport(2, C2,"c","c2") - getDaySport(3, C3,"c","c3") - getDaySport(4, C4,"c","c4") - getDaySport(5, C5,"c","c5") - getDaySport(6, C6,"c","c6") - getDaySport(7, C7,"c","c7") - getDaySport(8, C8,"c","c8") - getDaySport(9, C9,"c","c9") - getDaySport(10, C10,"c","c10") - getDaySport(11, C11,"c","c11") - getDaySport(12, C12,"c","c12") - getDaySport(13, C13,"c","c13") - getDaySport(14, C14,"c","c14") - getDaySport(15, C15,"c","c15") - getDaySport(16, C16,"c","c16") - getDaySport(17, C17,"c","c17") - getDaySport(18, C18,"c","c18") - - - getDaySport(19, B1,"b","b1") - getDaySport(20, B2,"b","b2") - getDaySport(21, B3,"b","b3") - getDaySport(22, B4,"b","b4") - - getDaySport(23, J1,"j","j1" ) - getDaySport(24, J2,"j","j2" ) - getDaySport(25, J3,"j","j3" ) - getDaySport(26, C4,"j","j4" ) - getDaySport(27, J5,"j","j5" ) - getDaySport(28, J6,"j","j6" ) - getDaySport(29, J7,"j","j7" ) - getDaySport(30, J8,"j","j8" ) - getDaySport(31, J9,"j","j9" ) - getDaySport(32, J10,"j","j10" ) - getDaySport(33, J11,"j","j11" ) - getDaySport(34, J12,"j","j12" ) - + fun saveFIO(fio: String) { + val edit = prefFIO?.edit() + edit?.putString("fio", fio) + edit?.apply() + FIO = fio + } + fun clearFIO() { + val edit = prefFIO?.edit() + edit?.clear() + edit?.apply() + FIO = "" } - - //Заполнения модели и списка - private fun addListModelCards(){ - val db = MainDB.getDB(this) - val list = ArrayList() - db.getDao().getAllItems().asLiveData().observe(this){itList-> - itList.forEach{ - //val text = "Id: ${it.id} Name: ${it.name} Proce: ${it.price}" - //binding.txtList.append(text) - val item = MonthModel( - it.id.toString(), - it.day.toString(), - it.date.toString(), - it.check.toString() - ) - //model.liveZakazCurrent.value = item//Передаем в liveDataCurrent один из продуктов, чтобы дальше эти данные использовать и передавать их в пробную ячейку - list.add(item)//Передали заполненый список - } - model.liveListList.value = list - } - - - - - binding.btnSaveList.setOnClickListener{ -// for(i in 1..30){ -// val item = Item(null, -// getDateTomorrow(i, ),//"11/11/2023", -// 0 -// ) -// Thread { -// db.getDao().insertItem(item) -// }.start() -// } - } - - - - } - - fun getDaySport(i:Int, description:String, categoryImage:String, categorySport:String): String { - val db = MainDB.getDB(this) - val tomorrow = LocalDate.now().plusDays(i.toLong()) - val item = ItemSportCategory(null, i.toString(), description,"3",categoryImage, categorySport) - Thread { - db.getDaoSportCategory().insertItemSportCategory(item) - }.start() - - return tomorrow.toString() - } - - - fun getDateTomorrow(i:Int,categorySport:String): String { - val db = MainDB.getDB(this) - - val DATE_PATTERN = "MM/dd/yyyy" - val tomorrow = LocalDate.now().plusDays(i.toLong()) - val item = ItemDaySport(null, - tomorrow.toString(), - categorySport, - 0 - ) - Thread { - db.getDaoDaySport().insertItemDaySport(item) - }.start() - - return tomorrow.toString() - } - //Заполнения модели и списка -// private fun addDayModelCards(){ -// val db = MainDB.getDB(this) -// val list = ArrayList() -// db.getDaoDaySport().getAllItemDaySport().asLiveData().observe(this){itList-> -// itList.forEach{ -// //val text = "Id: ${it.id} Name: ${it.name} Proce: ${it.price}" -// //binding.txtList.append(text) -// val itemDay = DayModel( -// it.id.toString(), -// it.day.toString(), -// it.category.toString(), -// it.check.toString(), -// ) -// //model.liveZakazCurrent.value = item//Передаем в liveDataCurrent один из продуктов, чтобы дальше эти данные использовать и передавать их в пробную ячейку -// list.add(itemDay)//Передали заполненый список -// } -// model.liveDayList.value = list -// } -// -// binding.btnSaveDay.setOnClickListener{ -//// val item = ItemDaySport(null, -//// binding.edName.text.toString(), -//// binding.edDesc.text.toString(), -//// binding.edDayCard.text.toString(), -//// binding.edCount.text.toString(), -//// binding.edImage.text.toString(), -//// 0 -//// ) -//// Thread { -//// db.getDaoDaySport().insertItemDaySport(item) -//// }.start() -// } -// } - - -// //Инициализация списка -// private fun initRcView() = with(binding) { -// todoListRecycleView.layoutManager = GridLayoutManager(this@UserSettingActivity,1)//По вертикали будет выводить по умолчанию -// adapterMonth = MonthAdapter(this@UserSettingActivity) -// todoListRecycleView.adapter = adapterMonth -// } -// -// //Инициализация списка -// private fun initRcViewDay() = with(binding) { -// todoDayListRecycleView.layoutManager = GridLayoutManager(this@UserSettingActivity,1)//По вертикали будет выводить по умолчанию -// adapterDay = DayAdapter(this@UserSettingActivity) -// todoDayListRecycleView.adapter = adapterDay -// } - - override fun onClickDay(item: DayModel) { - + override fun onBackPressed() { + val intetn = Intent(this, SettingActivity::class.java) + startActivity(intetn) + finish() } override fun onClickExceptionOrder(item: MonthModel) { } + //Спина val c1 = arrayOf("c1_1", "c1_2") val c2 = arrayOf("c2_1", "c2_2") val c3 = arrayOf("c3_1", "c3_2") val c4 = arrayOf("c4_1", "c4_2") val c5 = arrayOf("c5_1", "c5_2") - val c6 = arrayOf("c6_1", "c6_2","c6_3") + val c6 = arrayOf("c6_1", "c6_2", "c6_3") val c7 = arrayOf("c7_1") val c8 = arrayOf("c8_1", "c8_2") val c9 = arrayOf("c9_1", "c9_2", "c9_3") @@ -527,62 +180,71 @@ class UserSettingActivity : AppCompatActivity(), MonthAdapter.Listener,DayAdapte "2-3 – удерживать в напряжении;\n" + "4 - расслабиться.\n" + "Повторить 6-10 раз. Дыхание произвольное. При ампутации на уровне голени можно подложить под нижнюю треть бедра валик, если есть сгибательная контрактура колена, или если пациент так лучше ощущает работу мышц.\n" - val C5 = "Исходное положение, руки лежат вниз вдоль туловища, под культю и под аналогичный сегмент сохранной конечности подложить мячи. \n" + - "Счет\n" + - "1 — опереться на ноги, поднять таз вверх;\n" + - "2-3 — удерживать это положение;\n" + - "4 — опуститься в исходное положение. \n" + - "Повторить 4-8 раз. Дыхание произвольное, или подъем таза осуществлять на выдохе через рот, губы сложены «трубочкой».\n" - val C6 = "Исходное положение, руки лежат вниз вдоль туловища, под культю и под аналогичный сегмент сохранной конечности подложить мячи. \n" + - "Счет\n" + - "1 — опереться на ноги и поднять таз вверх;\n" + - " 2 — поднять одну прямую ногу вверх на 30°—45% \n" + - "3 — опустить ногу на мяч;\n" + - " 4 — опустить таз и вернуться в исходное положение. Повторить упражнение по 4-8 раз с каждой ноги. Дыхание произвольное. При значительных трудностях с удержанием баланса на мячах данное упражнение можно выполнять на валике или любых стабильных опорах.\n" + val C5 = + "Исходное положение, руки лежат вниз вдоль туловища, под культю и под аналогичный сегмент сохранной конечности подложить мячи. \n" + + "Счет\n" + + "1 — опереться на ноги, поднять таз вверх;\n" + + "2-3 — удерживать это положение;\n" + + "4 — опуститься в исходное положение. \n" + + "Повторить 4-8 раз. Дыхание произвольное, или подъем таза осуществлять на выдохе через рот, губы сложены «трубочкой».\n" + val C6 = + "Исходное положение, руки лежат вниз вдоль туловища, под культю и под аналогичный сегмент сохранной конечности подложить мячи. \n" + + "Счет\n" + + "1 — опереться на ноги и поднять таз вверх;\n" + + " 2 — поднять одну прямую ногу вверх на 30°—45% \n" + + "3 — опустить ногу на мяч;\n" + + " 4 — опустить таз и вернуться в исходное положение. Повторить упражнение по 4-8 раз с каждой ноги. Дыхание произвольное. При значительных трудностях с удержанием баланса на мячах данное упражнение можно выполнять на валике или любых стабильных опорах.\n" val C7 = "Дыхательное упражнение — диафрагмальное дыхание. \n" + "Сохранную ногу поставить согнутую, вторая нога или свободно лежит на полу, или бедро закинуто на другое бедро (фото), одна ладонь лежит на животе, а другая — на груди. На вдох носом надуть животом «шарик», на выдох через рот опустить переднюю стенку живота (и втянуть ее) и расслабиться. \n" + "Повторить дыхательный цикл не более 4-6 раз. Дышать глубоко, в комфортном темпе.\n" - val C8 = "Исходное положение, руки лежат вниз вдоль туловища, под ноги подложен большой гимнастический мяч.\n" + - "Счет\n" + - "1 – упереться ногами в мяч, поднять таз вверх;\n" + - "2-3 — удерживать это положение;\n" + - "4 - опустить таз и вернуться B исходное положение.\n" + - "Дыхание произвольное. Повторить упражнение 6-8 раз.\n" - val C9 = "Исходное положение, руки лежат вниз вдоль туловища, под ноги подложен большой гимнастический мяч. \n" + - "Счет\n" + - "1 - поднять таз с опорой на обе ноги;\n" + - "2 - поднять сохранную ногу вверх от опоры и остаться стоять на одной культе;\n" + - "3 - опустить на опору сохранную ногу;\n" + - "4 - опустить таз и вернуться в исходное положение. Повторить упражнение для каждой ноги по 4—6 раз. Дыхание произвольное.\n" - val C10 = "Исходное положение, руки лежат вниз вдоль туловища или под головой (усложненный вариант). \n" + - "Имитация велосипедных движений. По 6-10 движений сначала одной ногой, затем второй. Усложненный вариант упражнения (фото) — выполнение упражнения одновременно двумя ногами.\n" + - "Сначала движение ногами выполняется в направлении движения вперед, а затем — назад. \n" + - "Следить за дыханием и за тем, чтобы поясница была прижата к полу.\n" + val C8 = + "Исходное положение, руки лежат вниз вдоль туловища, под ноги подложен большой гимнастический мяч.\n" + + "Счет\n" + + "1 – упереться ногами в мяч, поднять таз вверх;\n" + + "2-3 — удерживать это положение;\n" + + "4 - опустить таз и вернуться B исходное положение.\n" + + "Дыхание произвольное. Повторить упражнение 6-8 раз.\n" + val C9 = + "Исходное положение, руки лежат вниз вдоль туловища, под ноги подложен большой гимнастический мяч. \n" + + "Счет\n" + + "1 - поднять таз с опорой на обе ноги;\n" + + "2 - поднять сохранную ногу вверх от опоры и остаться стоять на одной культе;\n" + + "3 - опустить на опору сохранную ногу;\n" + + "4 - опустить таз и вернуться в исходное положение. Повторить упражнение для каждой ноги по 4—6 раз. Дыхание произвольное.\n" + val C10 = + "Исходное положение, руки лежат вниз вдоль туловища или под головой (усложненный вариант). \n" + + "Имитация велосипедных движений. По 6-10 движений сначала одной ногой, затем второй. Усложненный вариант упражнения (фото) — выполнение упражнения одновременно двумя ногами.\n" + + "Сначала движение ногами выполняется в направлении движения вперед, а затем — назад. \n" + + "Следить за дыханием и за тем, чтобы поясница была прижата к полу.\n" val C11 = "Дыхательное упражнение — диафрагмальное дыхание.\n" + "Повторить дыхательный цикл не более 4-6 раз. В необходимости повторения дыхательного упражнения — ориентироваться на самочувствие пациента.\n" - val C12 = "Исходное положение, руки вытянуты перед собой, B руках — резиновая лента-амортизатор.\n" + - "Счет\n" + - "1 - развести в стороны прямые руки и коснуться кулачками пола, свести лопатки;\n" + - "2-3 — удерживать это положение;\n" + - "4 — свести руки перед собой и вернуться в исходное положение.\n" + - "При выполнении упражнения акцент делать на сведение лопаток в момент растяжения резинового амортизатора.\n" - val C13 = "Исходное положение, в руках — резиновый амортизатор; одна рука лежит вниз вдоль туловища, вторая согнута в локте на 90° и отведена от туловища (локоть на уровне плеча), ее плечо лежит на полу. \n" + - "Счет\n" + - "1 - не разгибая локтя, разворачивая лопатку, положить кисть согнутой руки на пол;\n" + - "2-3 — удерживать это положение;\n" + - "4 - вернуться в исходное положение. Повторить 10—15-20 раз. Не меняя длины хвата амортизатора, повторить с другой руки. Дыхание произвольное.\n" - val C14 = "Исходное положение, поставить руки B упоре на локти, немного отведя их от туловища.\n" + - "1 - надавить локтями на пол, свести лопатки прогнуть грудную клетку;\n" + - "2-3 — удерживать это напряжение;\n" + - "4 - расслабиться и вернуться в исходное положение \n" + - "Повторить 4-8 раз. Дыхание ровное, без задержек.\n" - val C15 = "Исходное положение, на бедра надета резиновая петля, ногу со стороны ампутации ротировать внутрь (cкосолапить). \n" + - "Счет\n" + - "1 - скользя по поверхности, отвести ногу со стороны ампутации в сторону; \n" + - "2-3 - удерживать ногу в этом положении;\n" + - "4 - вернуть ногу в исходное положение.\n" + - "Повторить упражнение 10-15-20 раз.\n" + - "Повторить 10-15-20 раз. После короткого отдыха сделать второй подход. Дыхание произвольное. Следить, чтобы мышцы плечевого пояса не вовлекались в напряжение, а таз оставался неподвижным. Для улучшения самоконтроля можно руки ставить на пояс и таким 0бразом следить за неподвижностью таза.\n" + val C12 = + "Исходное положение, руки вытянуты перед собой, B руках — резиновая лента-амортизатор.\n" + + "Счет\n" + + "1 - развести в стороны прямые руки и коснуться кулачками пола, свести лопатки;\n" + + "2-3 — удерживать это положение;\n" + + "4 — свести руки перед собой и вернуться в исходное положение.\n" + + "При выполнении упражнения акцент делать на сведение лопаток в момент растяжения резинового амортизатора.\n" + val C13 = + "Исходное положение, в руках — резиновый амортизатор; одна рука лежит вниз вдоль туловища, вторая согнута в локте на 90° и отведена от туловища (локоть на уровне плеча), ее плечо лежит на полу. \n" + + "Счет\n" + + "1 - не разгибая локтя, разворачивая лопатку, положить кисть согнутой руки на пол;\n" + + "2-3 — удерживать это положение;\n" + + "4 - вернуться в исходное положение. Повторить 10—15-20 раз. Не меняя длины хвата амортизатора, повторить с другой руки. Дыхание произвольное.\n" + val C14 = + "Исходное положение, поставить руки B упоре на локти, немного отведя их от туловища.\n" + + "1 - надавить локтями на пол, свести лопатки прогнуть грудную клетку;\n" + + "2-3 — удерживать это напряжение;\n" + + "4 - расслабиться и вернуться в исходное положение \n" + + "Повторить 4-8 раз. Дыхание ровное, без задержек.\n" + val C15 = + "Исходное положение, на бедра надета резиновая петля, ногу со стороны ампутации ротировать внутрь (cкосолапить). \n" + + "Счет\n" + + "1 - скользя по поверхности, отвести ногу со стороны ампутации в сторону; \n" + + "2-3 - удерживать ногу в этом положении;\n" + + "4 - вернуть ногу в исходное положение.\n" + + "Повторить упражнение 10-15-20 раз.\n" + + "Повторить 10-15-20 раз. После короткого отдыха сделать второй подход. Дыхание произвольное. Следить, чтобы мышцы плечевого пояса не вовлекались в напряжение, а таз оставался неподвижным. Для улучшения самоконтроля можно руки ставить на пояс и таким 0бразом следить за неподвижностью таза.\n" val C16 = "Исходное положение, бедрами удерживать мяч.\n" + "Счет\n" + "1 - сжать мяч между бедрами; \n" + @@ -590,27 +252,29 @@ class UserSettingActivity : AppCompatActivity(), MonthAdapter.Listener,DayAdapte "4 - расслабиться.\n" + "Повторить упражнение 10-15-20 раз. \n" + "Со временем возможно усложнение упражнения: удерживать сжатие не на счет 2-3, а на 2-3-4-5-6-7, и только на счет 8 — расслабиться. Дыхание произвольное. Следить, чтобы мышцы плечевого пояса не вовлекались B напряжение, и пациент не затаивал дыхание.\n" - val C17 = "Исходное положение, руки лежат под головой, на ногу со стороны ампутации надета манжета-утяжелитель.\n" + - "Счет\n" + - "1 - поднять прямую ногу на 45°; \n" + - "2-3 - удерживать ногу в этом положении; \n" + - "4 - опустить ногу и вернуться в исходное положение. \n" + - "Повторить 10—15—20 раз.\n" + - "Усложнение упражнения:\n" + - "1 - поднять ногу; \n" + - "2-3-4-5-6-7 - держать ногу; \n" + - "8 - опустить ногу и вернуться в исходное положение.\n" + - "Со временем можно выполнять два подхода к упражнению.\n" - val C18 = "Исходное положение, руки лежат под головой, на ногу со стороны ампутации надета манжета-утяжелитель. \n" + - "Счет\n" + - "1 - поднять прямую ногу на 45°;\n" + - "2 - согнуть ногу в бедре и колене до 90°; \n" + - "3 - выпрямить ногу обратно; \n" + - "4 - опустить ногу и вернуться в исходное положение. \n" + - "Повторить упражнение 10—15 раз. \n" + - "Усложнение упражнения: \n" + - "сгибание и разгибание колена и бедра можно осуществлять не один, а несколько раз подряд, и только потом. опускать ногу. Также можно делать имитацию велосипедных движений вперед, а потом B обратную сторону. \n" + - "Со временем весь комплекс упражнений можно выполнять с утяжелителем в постоянном режиме. Со стороны ампутации делать больше подходов и количество повторений предлагаемых упражнений.\n" + val C17 = + "Исходное положение, руки лежат под головой, на ногу со стороны ампутации надета манжета-утяжелитель.\n" + + "Счет\n" + + "1 - поднять прямую ногу на 45°; \n" + + "2-3 - удерживать ногу в этом положении; \n" + + "4 - опустить ногу и вернуться в исходное положение. \n" + + "Повторить 10—15—20 раз.\n" + + "Усложнение упражнения:\n" + + "1 - поднять ногу; \n" + + "2-3-4-5-6-7 - держать ногу; \n" + + "8 - опустить ногу и вернуться в исходное положение.\n" + + "Со временем можно выполнять два подхода к упражнению.\n" + val C18 = + "Исходное положение, руки лежат под головой, на ногу со стороны ампутации надета манжета-утяжелитель. \n" + + "Счет\n" + + "1 - поднять прямую ногу на 45°;\n" + + "2 - согнуть ногу в бедре и колене до 90°; \n" + + "3 - выпрямить ногу обратно; \n" + + "4 - опустить ногу и вернуться в исходное положение. \n" + + "Повторить упражнение 10—15 раз. \n" + + "Усложнение упражнения: \n" + + "сгибание и разгибание колена и бедра можно осуществлять не один, а несколько раз подряд, и только потом. опускать ногу. Также можно делать имитацию велосипедных движений вперед, а потом B обратную сторону. \n" + + "Со временем весь комплекс упражнений можно выполнять с утяжелителем в постоянном режиме. Со стороны ампутации делать больше подходов и количество повторений предлагаемых упражнений.\n" val B1 = "Исходное положение. \n" + "Счет\n" + @@ -663,7 +327,8 @@ class UserSettingActivity : AppCompatActivity(), MonthAdapter.Listener,DayAdapte "2-3 - удерживать это положение; \n" + "4 — опуститься в исходное положение. \n" + "С каждой стороны повторить упражнение по 4-8 раз. Следить за дыханием.\n" - val J5 = "Дыхательное упражнение. Исходное положение, голова опирается на лоб, руки под толовой. Глубокий вдох HOCOM, долгий выдох через рот, губы сложены «трубочкой». Повторить 4-6 раз.\n" + val J5 = + "Дыхательное упражнение. Исходное положение, голова опирается на лоб, руки под толовой. Глубокий вдох HOCOM, долгий выдох через рот, губы сложены «трубочкой». Повторить 4-6 раз.\n" val J6 = "Исходное положение, голова опирается на лоб. Рисуем ногой медленно букву «П».\n" + "Счет\n" + "1 – поднять прямую правую ногу вверх;\n" + @@ -694,25 +359,40 @@ class UserSettingActivity : AppCompatActivity(), MonthAdapter.Listener,DayAdapte "3 - развести ноги в стороны;\n" + "4 - свести ноги и перекрестить их, поменяв верхнюю и нижнюю ноги.\n" + "Упражнение сделать по 4-8 раз на каждую ногу. Следить за дыханием.\n" - val J9 = "Дыхательное упражнение. Исходное положение, голова опирается на лоб, руки под головой. Глубокий вдох носом, долгий выдох через POT, губы сложены «трубочкой». Повторить 4-6 раз.\n" - val J10 = "Исходное положение, голова опирается на лоб, руки лежат наверху на ширине, в руках — резиновый амортизатор. \n" + - "1 — поднять туловище, руки и голову вверх; \n" + - "2 — развести руки в стороны так, чтобы амортизатор лег на лопатки; \n" + - "3 — свести руки наверху до ширины плеч; \n" + - "4 — опуститься в исходное положение. \n" + - "Повторить упражнение 6-10 раз. Дыхание произвольное.\n" + - " Со временем можно усложнить упражнение: разводить руки в стороны не один раз, а несколько раз подряд; также можно сделать паузу в момент, когда руки разведены в стороны. Дыхание произвольное. Можно одновременно с подъемом туловища поднимать поочередно то одну, то вторую ногу.\n" - val J11 = "Исходное положение, руки под головой. Поднять плечевой пояс и согнутые к плечам руки. Имитация плавания брассом. Дыхание ровное. \n" + - "Два подхода по 10-15-20 движений. Следить за полным выпрямлением рук наверх, разведением прямых рук B стороны, сведением лопаток B момент приведения плеч, а также за тем, чтобы корпус при выпрямлении рук наверх не опускался. Дыхание произвольное.\n" - val J12 = "Исходное положение, руки лежат под головой, голова опирается на лоб. На ноге со стороны ампутации надета манжета с утяжелителем.\n" + - "Счет\n" + - "1 - поднять ногу с утяжелителем;\n" + - "2-3 — удерживать ногу; \n" + - "4 — опустить ногу в исходное положение. \n" + - "Повторить 10-15-20 раз.\n" + - "Усложнение: можно на счет 2 - отвести ногу в сторону, на счет 3 - вернуть ногу к центру, счет 4 — опуститься в исходное положение. Также можно отводить в сторону не один раз, а несколько раз подряд. Дыхание свободное. \n" + - "Со временем все упражнения можно выполнять с утяжелителем." + val J9 = + "Дыхательное упражнение. Исходное положение, голова опирается на лоб, руки под головой. Глубокий вдох носом, долгий выдох через POT, губы сложены «трубочкой». Повторить 4-6 раз.\n" + val J10 = + "Исходное положение, голова опирается на лоб, руки лежат наверху на ширине, в руках — резиновый амортизатор. \n" + + "1 — поднять туловище, руки и голову вверх; \n" + + "2 — развести руки в стороны так, чтобы амортизатор лег на лопатки; \n" + + "3 — свести руки наверху до ширины плеч; \n" + + "4 — опуститься в исходное положение. \n" + + "Повторить упражнение 6-10 раз. Дыхание произвольное.\n" + + " Со временем можно усложнить упражнение: разводить руки в стороны не один раз, а несколько раз подряд; также можно сделать паузу в момент, когда руки разведены в стороны. Дыхание произвольное. Можно одновременно с подъемом туловища поднимать поочередно то одну, то вторую ногу.\n" + val J11 = + "Исходное положение, руки под головой. Поднять плечевой пояс и согнутые к плечам руки. Имитация плавания брассом. Дыхание ровное. \n" + + "Два подхода по 10-15-20 движений. Следить за полным выпрямлением рук наверх, разведением прямых рук B стороны, сведением лопаток B момент приведения плеч, а также за тем, чтобы корпус при выпрямлении рук наверх не опускался. Дыхание произвольное.\n" + val J12 = + "Исходное положение, руки лежат под головой, голова опирается на лоб. На ноге со стороны ампутации надета манжета с утяжелителем.\n" + + "Счет\n" + + "1 - поднять ногу с утяжелителем;\n" + + "2-3 — удерживать ногу; \n" + + "4 — опустить ногу в исходное положение. \n" + + "Повторить 10-15-20 раз.\n" + + "Усложнение: можно на счет 2 - отвести ногу в сторону, на счет 3 - вернуть ногу к центру, счет 4 — опуститься в исходное положение. Также можно отводить в сторону не один раз, а несколько раз подряд. Дыхание свободное. \n" + + "Со временем все упражнения можно выполнять с утяжелителем." + override fun onClickDay(item: DayListModel) { + + } + + override fun onClickExceptionOrder(item: EditSportModel) { + + } + + override fun onClickEditCard(item: EditSportModel) { + TODO("Not yet implemented") + } } \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/FeedbackFragment.kt b/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/FeedbackFragment.kt deleted file mode 100644 index 7cf5dc8..0000000 --- a/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/FeedbackFragment.kt +++ /dev/null @@ -1,26 +0,0 @@ -package com.example.rehabilitation.Admin.fragmrntAdmin - -import android.os.Bundle -import androidx.fragment.app.Fragment -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import com.example.rehabilitation.R -import com.example.rehabilitation.databinding.FragmentFeedbackBinding - -class FeedbackFragment : Fragment() { - private lateinit var binding: FragmentFeedbackBinding - - override fun onCreateView( - inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle? - ): View? { - binding = FragmentFeedbackBinding.inflate(layoutInflater, container,false) - return inflater.inflate(R.layout.fragment_feedback, container, false) - } - - companion object { - - fun newInstance() = FeedbackFragment() - } -} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/MainSettingFragment.kt b/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/MainSettingFragment.kt deleted file mode 100644 index 17680e6..0000000 --- a/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/MainSettingFragment.kt +++ /dev/null @@ -1,49 +0,0 @@ -package com.example.rehabilitation.Admin.fragmrntAdmin - -import android.os.Binder -import android.os.Bundle -import androidx.fragment.app.Fragment -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import com.example.rehabilitation.R -import com.example.rehabilitation.databinding.FragmentMainSettingBinding - - -class MainSettingFragment : Fragment() { - private lateinit var binding: FragmentMainSettingBinding - - override fun onCreateView( - inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle? - ): View? { - binding = FragmentMainSettingBinding.inflate(layoutInflater,container,false) - return binding.root - } - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - - //Выход на основную часть - binding.btnExitSetting.setOnClickListener { - activity?.finish() - } - - binding.cvSettingUser.setOnClickListener{ - - } - - binding.cvFeedback.setOnClickListener{ - - } - - binding.cvStatistics.setOnClickListener{ - - } - } - - companion object { - - fun newInstance() = MainSettingFragment() - } -} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/SettingDoctor/CreatePatientFragment.kt b/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/SettingDoctor/CreatePatientFragment.kt new file mode 100644 index 0000000..df2a864 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/SettingDoctor/CreatePatientFragment.kt @@ -0,0 +1,503 @@ +package com.example.rehabilitation.Admin.fragmrntAdmin.SettingDoctor + +import android.content.Context +import android.os.Binder +import android.os.Bundle +import android.util.Log +import androidx.fragment.app.Fragment +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.EditText +import android.widget.Toast +import androidx.appcompat.app.AlertDialog +import androidx.fragment.app.activityViewModels +import androidx.lifecycle.asLiveData +import com.example.admin.Toast.showCustomInfoToast +import com.example.admin.Toast.showCustomNiceToast +import com.example.rehabilitation.Block +import com.example.rehabilitation.CursDayNull +import com.example.rehabilitation.DayAfter +import com.example.rehabilitation.DayBefore +import com.example.rehabilitation.EmailPatient +import com.example.rehabilitation.FIO +import com.example.rehabilitation.PatientDoctorNew +import com.example.rehabilitation.PauseDay +import com.example.rehabilitation.R +import com.example.rehabilitation.Room.MainDB +import com.example.rehabilitation.Room.dbUser.dbPatient.ItemPatient +import com.example.rehabilitation.SportCursDay +import com.example.rehabilitation.SportCursDayDangerAfter +import com.example.rehabilitation.SportCursDayDangerBefore +import com.example.rehabilitation.SportCursDayNumber +import com.example.rehabilitation.SportDateStart +import com.example.rehabilitation.SportMaxCount +import com.example.rehabilitation.SportPlusCount +import com.example.rehabilitation.SportUserTrue +import com.example.rehabilitation.UserPatientToken +import com.example.rehabilitation.databinding.FragmentCreatePatientBinding +import com.example.rehabilitation.model_adapter.Patient.PatientModel +import com.example.rehabilitation.prefBlock +import com.example.rehabilitation.prefCursDangerDayAfter +import com.example.rehabilitation.prefCursDangerDayBefore +import com.example.rehabilitation.prefCursDay +import com.example.rehabilitation.prefCursDayNull +import com.example.rehabilitation.prefDayAfter +import com.example.rehabilitation.prefDayBefore +import com.example.rehabilitation.prefEmailPatient +import com.example.rehabilitation.prefFIO +import com.example.rehabilitation.prefPatientDoctorNew +import com.example.rehabilitation.prefPauseDay +import com.example.rehabilitation.prefSport +import com.example.rehabilitation.prefSportCursDayNumber +import com.example.rehabilitation.prefSportDateStart +import com.example.rehabilitation.prefSportMaxCount +import com.example.rehabilitation.prefSportPlusCount +import com.example.rehabilitation.prefUserPatientToken +import com.example.sqlitework.dip.MainViewModel + + +class CreatePatientFragment : Fragment() { + private lateinit var binding: FragmentCreatePatientBinding + private val model: MainViewModel by activityViewModels()//Инициализировали класс + + var addSave = 0 + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + binding = FragmentCreatePatientBinding.inflate(layoutInflater,container,false) + return binding.root + } + + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + //Выход из создания пациента + binding.btnBackCreatePatient.setOnClickListener { + visible3() + } + createBtnPatient() + deleteBtnPatient() + liveLookPatientCurrent() + + prefUserPatientToken = activity?.getSharedPreferences("UserPatientToken", Context.MODE_PRIVATE) + UserPatientToken = prefUserPatientToken?.getString("userpatienttoken", "")!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0 + + prefFIO = activity?.getSharedPreferences("FIO", Context.MODE_PRIVATE) + FIO = prefFIO?.getString("fio", "")!! + + prefEmailPatient = activity?.getSharedPreferences("EmailPatient", Context.MODE_PRIVATE) + EmailPatient = prefEmailPatient?.getString("emailPatient", "")!! + + prefSport = activity?.getSharedPreferences("SportUserTrue", Context.MODE_PRIVATE) + SportUserTrue = prefSport?.getInt("spt", 0)!! + + //Какой сегодня курс + prefSportCursDayNumber = activity?.getSharedPreferences("SportCursDayNumber", Context.MODE_PRIVATE) + SportCursDayNumber = prefSportCursDayNumber?.getInt("scdn", 0)!! + + + prefCursDay = activity?.getSharedPreferences("SportCursDay", Context.MODE_PRIVATE) + SportCursDay = prefCursDay?.getInt("scd", 0)!! + + prefCursDangerDayBefore = activity?.getSharedPreferences("CursDangerDayBefore", Context.MODE_PRIVATE) + SportCursDayDangerBefore = prefCursDangerDayBefore?.getInt("cddb", 0)!! + prefCursDangerDayAfter = activity?.getSharedPreferences("CursDangerDayAfter", Context.MODE_PRIVATE) + SportCursDayDangerAfter = prefCursDangerDayAfter?.getInt("cdda", 0)!! + + prefCursDayNull = activity?.getSharedPreferences("CursDayNull", Context.MODE_PRIVATE) + CursDayNull = prefCursDayNull?.getString("cdn", "")!! + + //Для пауз и блоков + prefPauseDay = activity?.getSharedPreferences("PauseDay", Context.MODE_PRIVATE) + PauseDay = prefPauseDay?.getString("pd", "")!! + prefBlock = activity?.getSharedPreferences("Block", Context.MODE_PRIVATE) + Block = prefBlock?.getString("b", "")!! + + //ДАнные пациента + prefFIO = activity?.getSharedPreferences("FIO", Context.MODE_PRIVATE) + FIO = prefFIO?.getString("fio", "")!! + + //Дата старта тренировки + prefSportDateStart = activity?.getSharedPreferences("SportDateStart", Context.MODE_PRIVATE) + SportDateStart = prefSportDateStart?.getString("sportdatestart", "")!! + + //Есть ли аакаунт у пациента + prefPatientDoctorNew = activity?.getSharedPreferences("PatientDoctorNew", Context.MODE_PRIVATE) + PatientDoctorNew = prefPatientDoctorNew?.getInt("patientdoctornew", 0)!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0 + + + } + + + fun savePatientDoctorNew(patientdoctornew: Int) { + val edit = prefPatientDoctorNew?.edit() + edit?.putInt("patientdoctornew", patientdoctornew) + edit?.apply() + PatientDoctorNew = patientdoctornew + } + fun clearPatientDoctorNew() { + val edit = prefPatientDoctorNew?.edit() + edit?.clear() + edit?.apply() + PatientDoctorNew = 0 + } + + fun saveFIO(fio: String) { + val edit = prefFIO?.edit() + edit?.putString("fio", fio) + edit?.apply() + FIO = fio + } + fun clearFIO() { + val edit = prefFIO?.edit() + edit?.clear() + edit?.apply() + FIO = "" + } + fun saveEmailPatient(emailPatient: String) { + val edit = prefEmailPatient?.edit() + edit?.putString("emailPatient", emailPatient) + edit?.apply() + EmailPatient = emailPatient + } + fun clearEmailPatient() { + val edit = prefEmailPatient?.edit() + edit?.clear() + edit?.apply() + EmailPatient = "" + } + + //Экран о пациенте + fun visible3() { + activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLMainSettinDoctor,MainPatientFragment.newInstance())?.addToBackStack(null)?.commit() + } + + //Диалоговое окно + private fun createAlеrtDialogCreate( + nameCreate: String, + surnameCreate: String, + //patronymicCreate: String, + diagnosisCreate: String, + //emailCreate: String, + loginCreate: String, + passwordCreate: String + ) { + val builder = AlertDialog.Builder(requireContext()) + builder.setTitle("Создание") + builder.setMessage("Вы уверены что хотите создать пользователя") + builder.setNegativeButton("Назад") { dialogInterface, i -> + + } + builder.setPositiveButton("Подтвердить") { dialogInterface, i -> + createPatient( + nameCreate, + surnameCreate, + //patronymicCreate, + diagnosisCreate, + //emailCreate, + loginCreate, + passwordCreate + ) + } + builder.show() + } + + //Создание нового пациента + private fun createPatient( + nameCreate: String, + surnameCreate: String, + //patronymicCreate: String, + diagnosisCreate: String, + //emailCreate: String, + loginCreate: String, + passwordCreate: String + ) { + val db = MainDB.getDB(requireContext()) + val item = ItemPatient( + null, + nameCreate, + surnameCreate, + "", + diagnosisCreate, + //emailCreate, + 0, + loginCreate, + passwordCreate, + ) + Thread { + db.getDaoPatient().insertItemPatient(item) + }.start() + visible3() + savePatientDoctorNew(1) + clearPatientED() + Toast(requireContext()).showCustomNiceToast("Пользователь создан", requireActivity()) + //Сохраняем то что пациент создан + + } + + + //Функция для очистки полей + private fun clearPatientED() = with(binding) { + edCreateName.setText("") + edCreateSurname.setText("") + edDiagnosis.setText("") + edCreateEmail.setText("") + edCreateLogin.setText("") + edCreatePassword.setText("") + } + //Удаление определенного пациента + private fun deleteBtnPatient() = with(binding) { + binding.btnDeletePatient.setOnClickListener { + createAlеrtDialogDelete() + } + } + private fun createAlеrtDialogDelete() { + val db = MainDB.getDB(requireContext()) + + val edException = EditText(requireContext()) + val builder = AlertDialog.Builder(requireContext()) + builder.setTitle("Удаление") + builder.setMessage("Введите login пользователя для удаления") + builder.setView(edException) + builder.setNegativeButton("Назад") { dialogInterface, i -> + + } + builder.setPositiveButton("Подтвердить") { dialogInterface, i -> + if(EmailPatient == edException.text.toString()){ + deletePatient(edException.text.toString()) + clearFIO() + clearEmailPatient() + clearDate() + clearSportCursDay() + clearSportCursDayDangerBefore() + clearSportCursDayDangerAfter() + clearPauseDay() + clearBlock() + clearDayBefore() + clearDayAfter() + clearSportPlusCount() + clearSportMaxCount() + clearSportDateStart() + clearCursDayNumber() + //Сохраняем то что пациент создан + clearPatientDoctorNew() + clearUserPatientToken() + Thread { + db.getDaoDaySport().deleteItemDaySport() + db.getDao().deleteItem() + db.getDaoQB().deleteBQ() + db.getDaoQA().deleteAQ() + }.start() + } + else{ + Toast(requireContext()).showCustomInfoToast("Такого пользователя нету", requireActivity()) + } + + } + builder.show() + } + + //Функция удаления пользователя + private fun deletePatient(login: String) { + val db = MainDB.getDB(requireContext()) + Thread { + db.getDaoPatient().deletePatient(login) + }.start() + Toast(requireContext()).showCustomInfoToast("Аккаунт пациента был удален", requireActivity()) + + } + + //Создание пациеанта + private fun createBtnPatient() { + + binding.btnSaveCreatePatient.setOnClickListener { + addSave = 1 + val db = MainDB.getDB(requireContext()) + db.getDaoPatient().getAllItemPatient().asLiveData().observe(requireActivity()){ + val listPatient = it.size + if(listPatient == 0){ + val item = PatientModel( + "", + "", + "", + "", + "", + "", + "", + "", + ) + + model.liveLookPatientCurrent.value = item + } + else{ + it.forEach(){ + val item = PatientModel( + it.id.toString(), + "", + "", + "", + "", + "", + "", + "", + ) + + model.liveLookPatientCurrent.value = item + } + } + + } + } + } + + + private fun liveLookPatientCurrent() = with(binding) { + model.liveLookPatientCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + if(addSave == 1){ + Log.d("id","id123 = ${it.id}") + + if(it.id != "" || it.id == null || it.id.isNotBlank()){ + Toast(requireContext()).showCustomInfoToast("Аккаунт присутсвует", requireActivity()) + } + else{ + val nameCreate = binding.edCreateName.text.toString() + val surnameCreate = binding.edCreateSurname.text.toString() + val diagnosisCreate = binding.edDiagnosis.text.toString() + val emailCreate = binding.edCreateEmail.text.toString() + val loginCreate = binding.edCreateLogin.text.toString() + val passwordCreate = binding.edCreatePassword.text.toString() + + + if (nameCreate != "" && surnameCreate != "" && diagnosisCreate != "" && loginCreate != "" && passwordCreate != "") { + createAlеrtDialogCreate( + nameCreate, + surnameCreate, + //patronymicCreate, + diagnosisCreate, + //emailCreate, + loginCreate, + passwordCreate + ) + saveFIO(surnameCreate+" "+nameCreate) + saveEmailPatient(loginCreate) + + } else { + Toast(requireContext()).showCustomInfoToast("Не все поля заполнены", requireActivity()) + } + } + + //Сбрасываем нажатие + addSave=0 + } + + } + + } + + fun clearUserPatientToken() { + val edit = prefUserPatientToken?.edit() + edit?.clear() + edit?.apply() + UserPatientToken = "" + } + fun clearCursDayNumber() { + val edit = prefSportCursDayNumber?.edit() + edit?.clear() + edit?.apply() + SportCursDayNumber = 0 + } + + + fun clearSportDateStart() { + val edit = prefSportDateStart?.edit() + edit?.clear() + edit?.apply() + SportDateStart = "0" + } + + + fun clearSportPlusCount() { + val edit = prefSportPlusCount?.edit() + edit?.clear() + edit?.apply() + SportPlusCount = 0 + } + + + + + fun clearSportMaxCount() { + val edit = prefSportMaxCount?.edit() + edit?.clear() + edit?.apply() + SportMaxCount = 0 + } + + fun clearDayBefore() { + val edit = prefDayBefore?.edit() + edit?.clear() + edit?.apply() + DayBefore = "" + } + fun clearDayAfter() { + val edit = prefDayAfter?.edit() + edit?.clear() + edit?.apply() + DayAfter = "" + } + + + fun clearBlock() { + val edit = prefBlock?.edit() + edit?.clear() + edit?.apply() + Block = "" + } + + fun clearPauseDay() { + val edit = prefPauseDay?.edit() + edit?.clear() + edit?.apply() + PauseDay = "" + } + + + fun clearDate() { + val edit = prefSport?.edit() + edit?.clear() + edit?.apply() + SportUserTrue = 0 + } + + fun clearSportCursDay() { + val edit = prefCursDay?.edit() + edit?.clear() + edit?.apply() + SportCursDay = 0 + } + + + fun clearSportCursDayDangerBefore() { + val edit = prefCursDangerDayBefore?.edit() + edit?.clear() + edit?.apply() + SportCursDayDangerBefore = 0 + } + + + fun clearSportCursDayDangerAfter() { + val edit = prefCursDangerDayAfter?.edit() + edit?.clear() + edit?.apply() + SportCursDayDangerAfter = 0 + } + + + companion object { + + fun newInstance() = CreatePatientFragment() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/SettingDoctor/EditPatientFragment.kt b/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/SettingDoctor/EditPatientFragment.kt new file mode 100644 index 0000000..9a06032 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/SettingDoctor/EditPatientFragment.kt @@ -0,0 +1,219 @@ +package com.example.rehabilitation.Admin.fragmrntAdmin.SettingDoctor + +import android.content.Context +import android.os.Bundle +import android.util.Log +import androidx.fragment.app.Fragment +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.fragment.app.activityViewModels +import androidx.lifecycle.asLiveData +import com.example.admin.Toast.showCustomInfoToast +import com.example.admin.Toast.showCustomNiceToast +import com.example.rehabilitation.DayBefore +import com.example.rehabilitation.EmailPatient +import com.example.rehabilitation.FIO +import com.example.rehabilitation.R +import com.example.rehabilitation.Room.MainDB +import com.example.rehabilitation.SportCursDayDangerBefore +import com.example.rehabilitation.databinding.FragmentEditPatientBinding +import com.example.rehabilitation.model_adapter.Patient.PatientModel +import com.example.rehabilitation.prefCursDangerDayBefore +import com.example.rehabilitation.prefDayBefore +import com.example.rehabilitation.prefEmailPatient +import com.example.rehabilitation.prefFIO +import com.example.sqlitework.dip.MainViewModel + + +class EditPatientFragment : Fragment() { + private lateinit var binding: FragmentEditPatientBinding + private val model: MainViewModel by activityViewModels()//Инициализировали класс + + var loginPatient = "" + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + binding = FragmentEditPatientBinding.inflate(layoutInflater,container,false) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + enabledPatient() + editBtnSavePatient() + liveSettingPatientCurrent() + + outputOfDataParient() + //Выход из редактирвоания данных пациента + binding.btnBackPatientSetting.setOnClickListener { + visible3() + } + + prefFIO = activity?.getSharedPreferences("FIO", Context.MODE_PRIVATE) + FIO = prefFIO?.getString("fio", "")!! + + prefEmailPatient = activity?.getSharedPreferences("EmailPatient", Context.MODE_PRIVATE) + EmailPatient = prefEmailPatient?.getString("emailPatient", "")!! + + } + + override fun onResume() { + super.onResume() + + } + fun saveFIO(fio: String) { + val edit = prefFIO?.edit() + edit?.putString("fio", fio) + edit?.apply() + FIO = fio + } + fun clearFIO() { + val edit = prefFIO?.edit() + edit?.clear() + edit?.apply() + FIO = "" + } + + fun saveEmailPatient(emailPatient: String) { + val edit = prefEmailPatient?.edit() + edit?.putString("emailPatient", emailPatient) + edit?.apply() + EmailPatient = emailPatient + } + fun clearEmailPatient() { + val edit = prefEmailPatient?.edit() + edit?.clear() + edit?.apply() + EmailPatient = "" + } + + //Экран о пациенте + fun visible3() { + activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLMainSettinDoctor,MainPatientFragment.newInstance())?.addToBackStack(null)?.commit() + } + + //Функция отключающая поля для ввода редактирования пациента + private fun enabledPatient() = with(binding) { + edEditNamePatient.setEnabled(false) + edEditSurnamePatient.setEnabled(false) + //edEditPatronymicPatient.setEnabled(false) + edEditDiagnosisPatient.setEnabled(false) + edEditLoginPatient.setEnabled(false) + //edEditEmailPatient.setEnabled(false) + edEditPasswordPatient.setEnabled(false) + enabledPatientBtn() + } + + //Функция активации полей при редактирование пациента + private fun enabledPatientBtn() = with(binding) { + btnEditNamePatient.setOnClickListener { edEditNamePatient.setEnabled(true) } + btnEditSurnamePatient.setOnClickListener { edEditSurnamePatient.setEnabled(true) } + //btnEditPatronymicPatient.setOnClickListener { edEditPatronymicPatient.setEnabled(true) } + btnEditDiagnosisPatient.setOnClickListener { edEditDiagnosisPatient.setEnabled(true) } + btnEditLoginPatient.setOnClickListener { edEditLoginPatient.setEnabled(true) } + //btnEditEmailPatient.setOnClickListener { edEditEmailPatient.setEnabled(true) } + btnEditPasswordPatient.setOnClickListener { edEditPasswordPatient.setEnabled(true) } + } + + //Сохранение измененных данных для пациента + private fun editBtnSavePatient() = with(binding) { + binding.btnSaveEditPatient.setOnClickListener { + val name = edEditNamePatient.text.toString() + val surname = edEditSurnamePatient.text.toString() + // val patronymic = edEditPatronymicPatient.text.toString() + val diagnosis = edEditDiagnosisPatient.text.toString() + val login = edEditLoginPatient.text.toString() + //val email = edEditEmailPatient.text.toString() + val password = edEditPasswordPatient.text.toString() + if (name != "" && surname != "" && login != "" && password != "" && diagnosis != "") { + saveFIO(surname +" "+ name) + saveEmailPatient(login) + val db = MainDB.getDB(requireContext()) + Thread { + db.getDaoPatient().updatePatient( + loginPatient, + name, + surname, + "", + diagnosis, + login, + password + ) + }.start() + Toast(requireContext()).showCustomNiceToast( + "Данные обновлены", + requireActivity() + ) + + } else { + Toast(requireContext()).showCustomInfoToast( + "Не все поля заполнены", + requireActivity() + ) + } + } + } + + private fun liveSettingPatientCurrent() = with(binding) { + model.liveSettingPatientCurrent.observe(viewLifecycleOwner) { + //viewLifecycleOwner - следит за циклом жизни fragment + Log.i("liveSettingPatientCurrent","liveSettingPatientCurrent") + binding.edEditNamePatient.setText(it.name) + binding.edEditSurnamePatient.setText(it.surname) + //binding.edEditPatronymicPatient.setText(it.patronymic) + binding.edEditDiagnosisPatient.setText(it.diagnosis) + //binding.edEditEmailPatient.setText("") + binding.edEditLoginPatient.setText(it.login) + binding.edEditPasswordPatient.setText(it.password) + loginPatient = it.login + visible5() + } + + + } + + //Экран редактировани данных пациента + fun visible5() { + Log.i("visible5","visible5") + binding.CLLoad.visibility = View.GONE + + binding.CLEditPatien.visibility = View.VISIBLE + } + + private fun outputOfDataParient() { + Log.i("outputOfDataParient","outputOfDataParient") + visibleLoad() + val db = MainDB.getDB(requireContext()) + db.getDaoPatient().getAuthItemPatientOutput(EmailPatient).asLiveData().observe(requireActivity()) { itList -> + itList.forEach { + val item = PatientModel( + it.id.toString(), + it.name.toString(), + it.surname.toString(), + it.patronymic.toString(), + it.diagnosis.toString(), + it.number_of_courses.toString(), + it.login.toString(), + it.password.toString(), + ) + model.liveSettingPatientCurrent.value = item + } + } + } + + + + //Экран создания пациенат + fun visibleLoad() { + binding.CLLoad.visibility = View.VISIBLE + binding.CLEditPatien.visibility = View.GONE + } + + companion object { + + fun newInstance() = EditPatientFragment() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/SettingDoctor/MainPatientFragment.kt b/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/SettingDoctor/MainPatientFragment.kt new file mode 100644 index 0000000..ac09f84 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/SettingDoctor/MainPatientFragment.kt @@ -0,0 +1,153 @@ +package com.example.rehabilitation.Admin.fragmrntAdmin.SettingDoctor + +import android.content.Context +import android.os.Bundle +import androidx.fragment.app.Fragment +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.lifecycle.asLiveData +import com.example.admin.Toast.showCustomInfoToast +import com.example.admin.Toast.showCustomNiceToast +import com.example.rehabilitation.EmailPatient +import com.example.rehabilitation.FIO +import com.example.rehabilitation.MainActivity +import com.example.rehabilitation.R +import com.example.rehabilitation.Room.MainDB +import com.example.rehabilitation.databinding.FragmentMainPatientBinding +import com.example.rehabilitation.fragment.InfoFragment.MedicalReabilitationFragment +import com.example.rehabilitation.model_adapter.Patient.PatientModel +import com.example.rehabilitation.prefEmailPatient +import com.example.rehabilitation.prefFIO + + +class MainPatientFragment : Fragment()/*, MainActivity.IOnBackPressed*/ { + private lateinit var binding: FragmentMainPatientBinding +// override fun onBackPressed(): Boolean { +// return if (true) { +// Toast(requireContext()).showCustomInfoToast("123123213", requireActivity()) +// true +// } else { +// false +// } +// } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + binding = FragmentMainPatientBinding.inflate(layoutInflater,container,false) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + prefFIO = activity?.getSharedPreferences("FIO", Context.MODE_PRIVATE) + FIO = prefFIO?.getString("fio", "")!! + + prefEmailPatient = activity?.getSharedPreferences("EmailPatient", Context.MODE_PRIVATE) + EmailPatient = prefEmailPatient?.getString("emailPatient", "")!! + + + //Выход из мею настроек пациента + binding.btnExitMainPAtient.setOnClickListener { + visible1() + } + + binding.btnSportPatient.setOnClickListener { + if(FIO !=""){ + visible4() + } + else{ + Toast(requireContext()).showCustomInfoToast("Создайте аккаунт пациенту", requireActivity()) + } + + } + + binding.btnCreatePatient.setOnClickListener { + visible7() + } + binding.btnEditPatient.setOnClickListener { + if(FIO !=""){ + visible5() + } + else{ + Toast(requireContext()).showCustomInfoToast("Создайте аккаунт пациенту", requireActivity()) + } + } + + } + + +// override fun onBackPressed(): Boolean { +// return if (myCondition) { +// //action not popBackStack +// true +// } else { +// false +// } +// } + + + fun saveFIO(fio: String) { + val edit = prefFIO?.edit() + edit?.putString("fio", fio) + edit?.apply() + FIO = fio + } + fun clearFIO() { + val edit = prefFIO?.edit() + edit?.clear() + edit?.apply() + FIO = "" + } + + fun saveEmailPatient(emailPatient: String) { + val edit = prefEmailPatient?.edit() + edit?.putString("emailPatient", emailPatient) + edit?.apply() + EmailPatient = emailPatient + } + fun clearEmailPatient() { + val edit = prefEmailPatient?.edit() + edit?.clear() + edit?.apply() + EmailPatient = "" + } + //Экран создания пациенат + fun visibleLoad() { + binding.CLLoad.visibility = View.VISIBLE + binding.CLMainPatient.visibility = View.GONE + } + + //Основной экран + fun visible1() { + activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLMainSettinDoctor,MainSettingDoctorFragment.newInstance())?.addToBackStack(null)?.commit() + } + //Экран тренировок пациента + fun visible4() { + activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLMainSettinDoctor,PatientSportFragment.newInstance())?.addToBackStack(null)?.commit() +// val infoFrag = activity?.supportFragmentManager?.beginTransaction() +// infoFrag?.replace(R.id.CLMainSettinDoctor, PatientSportFragment.newInstance()) +// infoFrag?.addToBackStack(null) +// infoFrag?.commit() + + } + //Экран редактировани данных пациента + fun visible5() { + activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLMainSettinDoctor,EditPatientFragment.newInstance())?.addToBackStack(null)?.commit() + + } + + + //Экран создания пациенат + fun visible7() { + activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLMainSettinDoctor,CreatePatientFragment.newInstance())?.addToBackStack(null)?.commit() + } + companion object { + + fun newInstance() = MainPatientFragment() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/SettingDoctor/MainSettingDoctorFragment.kt b/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/SettingDoctor/MainSettingDoctorFragment.kt new file mode 100644 index 0000000..d3a1273 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/SettingDoctor/MainSettingDoctorFragment.kt @@ -0,0 +1,336 @@ +package com.example.rehabilitation.Admin.fragmrntAdmin.SettingDoctor + +import android.content.Context +import android.content.Intent +import android.graphics.Color +import android.os.Bundle +import android.util.Log +import androidx.fragment.app.Fragment +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.appcompat.app.AlertDialog +import androidx.fragment.app.activityViewModels +import androidx.lifecycle.asLiveData +import com.example.admin.Toast.showCustomInfoToast +import com.example.rehabilitation.Auth.AuthDoctorActivity +import com.example.rehabilitation.Auth.AuthorizationActivity +import com.example.rehabilitation.Block +import com.example.rehabilitation.EmailPatient +import com.example.rehabilitation.FIO +import com.example.rehabilitation.PauseDay +import com.example.rehabilitation.R +import com.example.rehabilitation.Room.MainDB +import com.example.rehabilitation.SettingActivity +import com.example.rehabilitation.SportDateStart +import com.example.rehabilitation.SportPlusCount +import com.example.rehabilitation.User.fragmentUser.SceduleFragment +import com.example.rehabilitation.UserDoctorToken +import com.example.rehabilitation.counter2 +import com.example.rehabilitation.databinding.FragmentMainSettingDoctorBinding +import com.example.rehabilitation.model_adapter.Patient.PatientModel +import com.example.rehabilitation.prefBlock +import com.example.rehabilitation.prefDoctor +import com.example.rehabilitation.prefEmailPatient +import com.example.rehabilitation.prefFIO +import com.example.rehabilitation.prefPauseDay +import com.example.rehabilitation.prefSportDateStart +import com.example.rehabilitation.prefUserDoctorToken +import com.example.rehabilitation.tokenClassDoctor +import com.example.sqlitework.dip.MainViewModel +import java.time.LocalDate + +class MainSettingDoctorFragment : Fragment() { + private lateinit var binding: FragmentMainSettingDoctorBinding + private val model: MainViewModel by activityViewModels()//Инициализировали класс + + private var addPatient = false + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + binding = FragmentMainSettingDoctorBinding.inflate(layoutInflater,container,false) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + prefFIO = activity?.getSharedPreferences("FIO", Context.MODE_PRIVATE) + FIO = prefFIO?.getString("fio", "")!! + + prefEmailPatient = activity?.getSharedPreferences("EmailPatient", Context.MODE_PRIVATE) + EmailPatient = prefEmailPatient?.getString("emailPatient", "")!! + + prefSportDateStart = activity?.getSharedPreferences("SportDateStart", Context.MODE_PRIVATE) + SportDateStart = prefSportDateStart?.getString("sportdatestart", "")!! + + //Для пауз и блоков + prefPauseDay = activity?.getSharedPreferences("PauseDay", Context.MODE_PRIVATE) + PauseDay = prefPauseDay?.getString("pd", "")!! + prefBlock = activity?.getSharedPreferences("Block", Context.MODE_PRIVATE) + Block = prefBlock?.getString("b", "")!! + + data_prefDoctorPatientToken() + + //Вызываем вывод данных пациента + outputOfDataPatient() + + //Получаем данные пациента + liveSettingPatientCurrent() + + binding.btnPatient.setOnClickListener { + visible3() + } + + //Выход из раздела врача + binding.btnExitDoctorProfil.setOnClickListener { + clearUserDoctorToken() + val intetn = Intent(requireContext(), SettingActivity::class.java) + activity?.finish() + startActivity(intetn) + } + + //Выход из аккаунта врача + binding.btnExitAuthDoctor.setOnClickListener { + createAlеrtDialogExitAuth() + } + + if(SportDateStart !=""){ + binding.txtDateSport.setText("Дата назначения: ${SportDateStart}") + binding.cardViewSportDay.setCardBackgroundColor(Color.parseColor("#9CD57E")) + + } + else{ + binding.txtDateSport.setText("Курс отсуствует") + binding.cardViewSportDay.setCardBackgroundColor(Color.parseColor("#D57E7E")) + + } + + if(FIO ==""){ + visibleLoad() + binding.txtSurname.setText("") + binding.txtName.setText("") + binding.txtPatronymic.setText("") + binding.txtEmail.setText("") + binding.txtDiagnoz.setText("") + } + + //Цвет кнопок в зависимоти паузы и блока + colorBtnBlockPause() + + binding.cardViewBan.setOnClickListener { + if(FIO !=""){ + if(Block <= LocalDate.now().toString() || Block == ""){ + saveBlock(LocalDate.now().plusDays(3).toString()) + Toast(requireContext()).showCustomInfoToast("Курс заблокирован", requireActivity()) + binding.cardViewBan.setCardBackgroundColor(Color.parseColor("#FF3F3F")) + } + else{ + clearBlock() + Toast(requireContext()).showCustomInfoToast("Курс разблокирован", requireActivity()) + binding.cardViewBan.setCardBackgroundColor(Color.parseColor("#8FF174")) + + } + } + else{ + Toast(requireContext()).showCustomInfoToast("Создайте аккаунт пациенту", requireActivity()) + } + + } + + binding.cardViewPause.setOnClickListener { + if(FIO !=""){ + if(PauseDay <= LocalDate.now().toString() || PauseDay == ""){ + savePauseDay(LocalDate.now().plusDays(1).toString()) + Toast(requireContext()).showCustomInfoToast("Пауза на 3 дня", requireActivity()) + binding.cardViewPause.setCardBackgroundColor(Color.parseColor("#FF3F3F")) + } + else{ + clearPauseDay() + Toast(requireContext()).showCustomInfoToast("Пауза снята", requireActivity()) + binding.cardViewPause.setCardBackgroundColor(Color.parseColor("#8FF174")) + } + } + else{ + Toast(requireContext()).showCustomInfoToast("Создайте аккаунт пациенту", requireActivity()) + } + + } + + + } + + + private fun colorBtnBlockPause() { + //Цвет кнопки в зависимоти от включен ли блок + if(Block==""){ + binding.cardViewBan.setCardBackgroundColor(Color.parseColor("#8FF174")) + } + else{ + binding.cardViewBan.setCardBackgroundColor(Color.parseColor("#FF3F3F")) + } + + //Цвет кнопки в зависимоти от включена ли пацза + if(PauseDay==""){ + binding.cardViewPause.setCardBackgroundColor(Color.parseColor("#8FF174")) + } + else{ + binding.cardViewPause.setCardBackgroundColor(Color.parseColor("#FF3F3F")) + } + } + + fun saveBlock(b: String) { + val edit = prefBlock?.edit() + edit?.putString("b", b) + edit?.apply() + Block = b + } + + fun clearBlock() { + val edit = prefBlock?.edit() + edit?.clear() + edit?.apply() + SportPlusCount = 0 + } + fun savePauseDay(pd: String) { + val edit = prefPauseDay?.edit() + edit?.putString("pd", pd) + edit?.apply() + PauseDay = pd + } + fun clearPauseDay() { + val edit = prefPauseDay?.edit() + edit?.clear() + edit?.apply() + PauseDay = "" + } + + override fun onDestroy() { + super.onDestroy() + + clearUserDoctorToken() + } + + + + override fun onResume() { + super.onResume() + if(FIO ==""){ + visibleLoad() + binding.txtSurname.setText("") + binding.txtName.setText("") + binding.txtPatronymic.setText("") + binding.txtEmail.setText("") + binding.txtDiagnoz.setText("") + } + //Цвет кнопок в зависимоти паузы и блока + colorBtnBlockPause() + } + + //Диалоговое окно + private fun createAlеrtDialogExitAuth() { + val builder = AlertDialog.Builder(requireContext()) + builder.setTitle("Выход") + builder.setMessage("Вы уверены что хотите выйти из аккаунта") + builder.setNegativeButton("Назад") { dialogInterface, i -> + + } + builder.setPositiveButton("Подтвердить") { dialogInterface, i -> + clearUserDoctorToken() + val intetn = Intent(requireContext(), SettingActivity::class.java) + activity?.finish() + startActivity(intetn) + } + builder.show() + } + //Фиксируем токен врача + private fun data_prefDoctorPatientToken() { + prefUserDoctorToken = activity?.getSharedPreferences("UserDoctorToken", Context.MODE_PRIVATE) + UserDoctorToken = prefUserDoctorToken?.getString("userdoctortoken", "")!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0 + if(UserDoctorToken == ""){ + val intetn = Intent(requireContext(), AuthDoctorActivity::class.java) + activity?.finish() + startActivity(intetn) + } + } + + //Записываем число + fun saveUserDoctorToken(userdoctortoken: String) { + val editer = prefUserDoctorToken?.edit() + editer?.putString("userdoctortoken", userdoctortoken) + editer?.apply() + UserDoctorToken = userdoctortoken + } + //Функция очистки данных + fun clearUserDoctorToken() { + val edit = prefUserDoctorToken?.edit() + edit?.clear() + edit?.apply() + UserDoctorToken = "" + } + + //Получение из базы данных пациента + private fun outputOfDataPatient() { + Log.i("111","111") + visibleLoad() + Log.i("122","122") + val db = MainDB.getDB(requireContext()) + db.getDaoPatient().getAuthItemPatientOutput(EmailPatient).asLiveData().observe(requireActivity()) { itList -> + itList.forEach { + val item = PatientModel( + it.id.toString(), + it.name, + it.surname, + it.patronymic, + it.diagnosis, + it.number_of_courses.toString(), + it.login, + it.password, + ) + model.liveSettingPatientCurrent.value = item + } + } + } + + //ВЫводим данные пациента + private fun liveSettingPatientCurrent() = with(binding) { + model.liveSettingPatientCurrent.observe(viewLifecycleOwner) { + Log.i("333","333") + binding.txtSurname.setText(it.surname) + binding.txtName.setText(it.name) + binding.txtPatronymic.setText(it.patronymic) + binding.txtEmail.setText(it.login) + binding.txtDiagnoz.setText(it.diagnosis) + visible5() + } + + + } + + //Экран загрузки + fun visibleLoad() { + Log.i("222","222") + binding.cardLoad.visibility = View.VISIBLE + binding.CLMainSetting.visibility = View.VISIBLE + } + //Экран с данными пациента и кнопками + fun visible5() { + Log.i("444","444") + binding.cardLoad.visibility = View.GONE + binding.CLMainSetting.visibility = View.VISIBLE + } + + + + //Экран о пациенте + fun visible3() { + activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLMainSettinDoctor,MainPatientFragment.newInstance())?.addToBackStack(null)?.commit() + } + + companion object { + fun newInstance() = MainSettingDoctorFragment() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/SettingDoctor/PatientSportFragment.kt b/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/SettingDoctor/PatientSportFragment.kt new file mode 100644 index 0000000..81e4991 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/SettingDoctor/PatientSportFragment.kt @@ -0,0 +1,1435 @@ +package com.example.rehabilitation.Admin.fragmrntAdmin.SettingDoctor + +import android.annotation.SuppressLint +import android.content.Context +import android.content.SharedPreferences +import android.graphics.Color +import android.os.Bundle +import android.util.Log +import androidx.fragment.app.Fragment +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.fragment.app.activityViewModels +import androidx.lifecycle.asLiveData +import androidx.recyclerview.widget.GridLayoutManager +import com.example.admin.Toast.showCustomInfoToast +import com.example.admin.Toast.showCustomNiceToast +import com.example.rehabilitation.Block +import com.example.rehabilitation.CursDayNull +import com.example.rehabilitation.DayAfter +import com.example.rehabilitation.DayBefore +import com.example.rehabilitation.FIO +import com.example.rehabilitation.PauseDay +import com.example.rehabilitation.R +import com.example.rehabilitation.Room.Item +import com.example.rehabilitation.Room.ItemDaySport +import com.example.rehabilitation.Room.ItemImage +import com.example.rehabilitation.Room.ItemSportCategory +import com.example.rehabilitation.Room.MainDB +import com.example.rehabilitation.SportCursDay +import com.example.rehabilitation.SportCursDayNumber +import com.example.rehabilitation.SportDateStart +import com.example.rehabilitation.SportMaxCount +import com.example.rehabilitation.SportPlusCount +import com.example.rehabilitation.SportUserTrue +import com.example.rehabilitation.countCategory +import com.example.rehabilitation.databinding.FragmentPatientSportBinding +import com.example.rehabilitation.model_adapter.Day.DayListModel +import com.example.rehabilitation.model_adapter.Day.DayListOneModel +import com.example.rehabilitation.model_adapter.Edit.EditSportAdapter +import com.example.rehabilitation.model_adapter.Edit.EditSportModel +import com.example.rehabilitation.model_adapter.Image.Category.CountNameCategoryModel +import com.example.rehabilitation.prefBlock +import com.example.rehabilitation.prefCursDangerDayAfter +import com.example.rehabilitation.prefCursDangerDayBefore +import com.example.rehabilitation.prefCursDay +import com.example.rehabilitation.prefCursDayNull +import com.example.rehabilitation.prefDayAfter +import com.example.rehabilitation.prefDayBefore +import com.example.rehabilitation.prefFIO +import com.example.rehabilitation.prefPauseDay +import com.example.rehabilitation.prefSport +import com.example.rehabilitation.prefSportCursDayNumber +import com.example.rehabilitation.prefSportDateStart +import com.example.rehabilitation.prefSportMaxCount +import com.example.rehabilitation.prefSportPlusCount +import com.example.sqlitework.dip.MainViewModel +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.launch +import java.time.LocalDate + + +class PatientSportFragment : Fragment(), EditSportAdapter.Listener, EditSportAdapter.ListenerEdit { + private lateinit var binding: FragmentPatientSportBinding + + private val model: MainViewModel by activityViewModels()//Инициализировали класс + lateinit var editAdapter: EditSportAdapter + + var SportCursDayDangerBefore = 0 + var SportCursDayDangerAfter = 0 + + var visibleListCyrs = false + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + binding = FragmentPatientSportBinding.inflate(layoutInflater, container, false) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + liveListDaySportOneCurrent() + + prefSport = activity?.getSharedPreferences("SportUserTrue", Context.MODE_PRIVATE) + SportUserTrue = prefSport?.getInt("spt", 0)!! + + //Какой сегодня курс + prefSportCursDayNumber = activity?.getSharedPreferences("SportCursDayNumber", Context.MODE_PRIVATE) + SportCursDayNumber = prefSportCursDayNumber?.getInt("scdn", 0)!! + + + prefCursDay = activity?.getSharedPreferences("SportCursDay", Context.MODE_PRIVATE) + SportCursDay = prefCursDay?.getInt("scd", 0)!! + + prefCursDangerDayBefore = activity?.getSharedPreferences("CursDangerDayBefore", Context.MODE_PRIVATE) + SportCursDayDangerBefore = prefCursDangerDayBefore?.getInt("cddb", 0)!! + prefCursDangerDayAfter = activity?.getSharedPreferences("CursDangerDayAfter", Context.MODE_PRIVATE) + SportCursDayDangerAfter = prefCursDangerDayAfter?.getInt("cdda", 0)!! + + prefCursDayNull = activity?.getSharedPreferences("CursDayNull", Context.MODE_PRIVATE) + CursDayNull = prefCursDayNull?.getString("cdn", "")!! + + //Для пауз и блоков + prefPauseDay = activity?.getSharedPreferences("PauseDay", Context.MODE_PRIVATE) + PauseDay = prefPauseDay?.getString("pd", "")!! + prefBlock = activity?.getSharedPreferences("Block", Context.MODE_PRIVATE) + Block = prefBlock?.getString("b", "")!! + + //ДАнные пациента + prefFIO = activity?.getSharedPreferences("FIO", Context.MODE_PRIVATE) + FIO = prefFIO?.getString("fio", "")!! + + //Дата старта тренировки + prefSportDateStart = activity?.getSharedPreferences("SportDateStart", Context.MODE_PRIVATE) + SportDateStart = prefSportDateStart?.getString("sportdatestart", "")!! + + + binding.txtPatientSportandFIO.setText("Настройка курса для \n ${FIO}") + + //Выход из настроек спорта пациента + binding.btnExitPatientSport.setOnClickListener { + visible3() + } + + binding.btnExitEditSportPatient.setOnClickListener { + visible4() + } + + binding.btnExitEditSportVisible.setOnClickListener { + visible4() + } + + binding.btnEdit.setOnClickListener { + itemDAySportOne() + } + + //Цвет кнопок в зависимоти паузы и блока + colorBtnBlockPause() + + binding.btnBlockFalse.setOnClickListener { + if(FIO !=""){ + if(Block<=LocalDate.now().toString() || Block == ""){ + saveBlock(LocalDate.now().plusDays(3).toString()) + Toast(requireContext()).showCustomInfoToast("Курс заблокирован", requireActivity()) + binding.btnBlockFalse.setCardBackgroundColor(Color.parseColor("#FF3F3F")) + } + else{ + clearBlock() + Toast(requireContext()).showCustomInfoToast("Курс разблокирован", requireActivity()) + binding.btnBlockFalse.setCardBackgroundColor(Color.parseColor("#8FF174")) + + } + } + else{ + Toast(requireContext()).showCustomInfoToast("Создайте аккаунт пациенту", requireActivity()) + } + + } + + binding.btnPauseFalse.setOnClickListener { + if(FIO !=""){ + if(PauseDay<=LocalDate.now().toString() || PauseDay == ""){ + savePauseDay(LocalDate.now().plusDays(1).toString()) + Toast(requireContext()).showCustomInfoToast("Пауза на 3 дня", requireActivity()) + binding.btnPauseFalse.setCardBackgroundColor(Color.parseColor("#FF3F3F")) + } + else{ + clearPauseDay() + Toast(requireContext()).showCustomInfoToast("Пауза снята", requireActivity()) + binding.btnPauseFalse.setCardBackgroundColor(Color.parseColor("#8FF174")) + } + } + else{ + Toast(requireContext()).showCustomInfoToast("Создайте аккаунт пациенту", requireActivity()) + } + + } + + + sportAddPacient() + createCyrs() + liveCountNameCategoryCurrent() + + model.liveEditSportList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + editAdapter.submitList(it)//Напрямую переадем созданный список в adapter(ProductAdapter) + } + initRcViewDay() + liveEditSportCurrent() + } + + override fun onResume() { + super.onResume() + //Цвет кнопок в зависимоти паузы и блока + colorBtnBlockPause() + } + + private fun colorBtnBlockPause() { + //Цвет кнопки в зависимоти от включен ли блок + if(Block==""){ + binding.btnBlockFalse.setCardBackgroundColor(Color.parseColor("#8FF174")) + } + else{ + binding.btnBlockFalse.setCardBackgroundColor(Color.parseColor("#FF3F3F")) + } + + //Цвет кнопки в зависимоти от включена ли пацза + if(PauseDay==""){ + binding.btnPauseFalse.setCardBackgroundColor(Color.parseColor("#8FF174")) + } + else{ + binding.btnPauseFalse.setCardBackgroundColor(Color.parseColor("#FF3F3F")) + } + } + + private fun addSportCyrs() { + +// if (SportUserTrue == 0) { +// visibleLoad() +// val db = MainDB.getDB(requireContext()) +// db.getDaoSportCategory().getAllItemsSportCategoryCountSport(category).asLiveData() +// .observe(requireActivity()) { itCount -> +// itCount.forEach() { +// val item = CountNameCategoryModel( +// it.count.toString(), +// it.image.toString() +// ) +// model.liveCountNameCategoryCurrent.value = item +// } +// } +// Thread { +// //Создаем карточки на 30 дней +// for (i in 1..30) { +// val item = Item( +// null, +// LocalDate.now().plusDays(i.toLong()).toString(), +// //getDateTomorrow(i, "c"),//"11/11/2023", +// i.toString(), +// 0 +// ) +// db.getDao().insertItem(item) +// } +// }.start() +// +// } else { +// Toast(requireContext()).showCustomInfoToast("Удалите предыдуший курс", requireActivity()) +// } + + } + + fun itemDAySportOne() { +// visibleLoad() +// val db = MainDB.getDB(requireContext()) +// db.getDaoDaySport().getItemDaySportRandomOne().asLiveData() +// .observe(requireActivity()) { itCount -> +// itCount.forEach() { +// val item = DayListOneModel( +// it.day, +// ) +// model.liveListDaySportOneCurrent.value = item +// } +// } + } + + + private fun liveListDaySportOneCurrent() = with(binding) { + model.liveListDaySportOneCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + addSportList(it.day) + } + } + + //Функции для добавления курса тренеровок пациенту и офиска старого или неудачного курса + @SuppressLint("SuspiciousIndentation") + private fun sportAddPacient() { + binding.btnCardC.setOnClickListener { + //visible8() + //addSportCategory("b") + addSportCategory("c") + } + binding.btnCardB.setOnClickListener { + + //addSportCategory("b") + addSportCategory("b") + } + binding.btnCardJ.setOnClickListener { +// visible8() +// //addSportCategory("j") + addSportCategory("j") + } + + binding.btnAddCyrc1.setOnClickListener { + if(FIO !=""){ + addSportCategoryDay() + } + else{ + Toast(requireContext()).showCustomInfoToast("Создайте аккаунт пациенту", requireActivity()) + } + } + + binding.btnAddListCyrc.setOnClickListener { + if (visibleListCyrs == false){ + binding.cardViewLIstSportCurs.visibility = View.VISIBLE + visibleListCyrs = true + } + else{ + binding.cardViewLIstSportCurs.visibility = View.GONE + visibleListCyrs = false + } + } + + //Очистка курса + binding.cvClearDayUser.setOnClickListener { + if(FIO !=""){ + if (SportUserTrue == 1) { + val db = MainDB.getDB(requireContext()) + Thread { + db.getDaoDaySport().deleteItemDaySport() + db.getDao().deleteItem() + db.getDaoQB().deleteBQ() + db.getDaoQA().deleteAQ() + }.start() + clearDate() + clearSportCursDay() + clearSportCursDayDangerBefore() + clearSportCursDayDangerAfter() + clearPauseDay() + clearBlock() + clearDayBefore() + clearDayAfter() + clearSportPlusCount() + clearSportMaxCount() + clearSportDateStart() + clearCursDayNumber() + Log.i("SportUserTrue","${SportUserTrue}") + Log.i("SportCursDay","${SportCursDay}") + Log.i("SportCursDayDangerBefore","${SportCursDayDangerBefore}") + Log.i("SportCursDayDangerAfter","${SportCursDayDangerAfter}") + Log.i("Block", Block.toString()) + Log.i("Pause","${PauseDay}") + Log.i("DayAfter", DayAfter.toString()) + Log.i("DayBefore","${DayBefore}") + Log.i("SportMaxCount", SportMaxCount.toString()) + + + Toast(requireContext()).showCustomInfoToast( + "Курс пациента был очишен", + requireActivity() + ) + + //Очишаем хранилища +// clearNameSport() +// clearCountSport() +// clearQA_QB() + } else { + Toast(requireContext()).showCustomInfoToast( + "У пациента нету курса", + requireActivity() + ) + } + } + else{ + Toast(requireContext()).showCustomInfoToast("Создайте аккаунт пациенту", requireActivity()) + } + + } + + } + + fun saveCursDayNumber(scdn: Int) { + val edit = prefSportCursDayNumber?.edit() + edit?.putInt("scdn", scdn) + edit?.apply() + SportCursDayNumber = scdn + } + fun clearCursDayNumber() { + val edit = prefSportCursDayNumber?.edit() + edit?.clear() + edit?.apply() + SportCursDayNumber = 0 + } + + fun saveSportDateStart(sportdatestart: String) { + val edit = prefSportDateStart?.edit() + edit?.putString("sportdatestart", sportdatestart) + edit?.apply() + SportDateStart = sportdatestart + } + fun clearSportDateStart() { + val edit = prefSportDateStart?.edit() + edit?.clear() + edit?.apply() + SportDateStart = "0" + } + + fun saveSportPlusCount(spc: Int) { + val edit = prefSportPlusCount?.edit() + edit?.putInt("spc", spc) + edit?.apply() + SportPlusCount = spc + } + fun clearSportPlusCount() { + val edit = prefSportPlusCount?.edit() + edit?.clear() + edit?.apply() + SportPlusCount = 0 + } + + + fun saveSportMaxCount(smc: Int) { + val edit = prefSportMaxCount?.edit() + edit?.putInt("smc", smc) + edit?.apply() + SportPlusCount = smc + } + + fun clearSportMaxCount() { + val edit = prefSportMaxCount?.edit() + edit?.clear() + edit?.apply() + SportMaxCount = 0 + } + + fun clearDayBefore() { + val edit = prefDayBefore?.edit() + edit?.clear() + edit?.apply() + DayBefore = "" + } + fun clearDayAfter() { + val edit = prefDayAfter?.edit() + edit?.clear() + edit?.apply() + DayAfter = "" + } + fun saveBlock(b: String) { + val edit = prefBlock?.edit() + edit?.putString("b", b) + edit?.apply() + Block = b + } + + fun clearBlock() { + val edit = prefBlock?.edit() + edit?.clear() + edit?.apply() + SportPlusCount = 0 + } + fun savePauseDay(pd: String) { + val edit = prefPauseDay?.edit() + edit?.putString("pd", pd) + edit?.apply() + PauseDay = pd + } + fun clearPauseDay() { + val edit = prefPauseDay?.edit() + edit?.clear() + edit?.apply() + PauseDay = "" + } + + //Ести ли курс + fun saveDate(spt: Int) { + val edit = prefSport?.edit() + edit?.putInt("spt", spt) + edit?.apply() + SportUserTrue = spt + } + fun clearDate() { + val edit = prefSport?.edit() + edit?.clear() + edit?.apply() + SportUserTrue = 0 + } + + //Какой день + fun saveSportCursDay(scd: Int) { + val edit = prefCursDay?.edit() + edit?.putInt("scd", scd) + edit?.apply() + SportCursDay = scd + } + fun clearSportCursDay() { + val edit = prefCursDay?.edit() + edit?.clear() + edit?.apply() + SportCursDay = 0 + } + fun saveSportCursDayDangerBefore(cddb: Int) { + val edit = prefCursDangerDayBefore?.edit() + edit?.putInt("cddb", cddb) + edit?.apply() + SportCursDayDangerBefore = cddb + } + + fun clearSportCursDayDangerBefore() { + val edit = prefCursDangerDayBefore?.edit() + edit?.clear() + edit?.apply() + SportCursDayDangerBefore = 0 + } + fun saveSportCursDayDangerAfter(cdda: Int) { + val edit = prefCursDangerDayAfter?.edit() + edit?.putInt("cdda", cdda) + edit?.apply() + SportCursDayDangerAfter = cdda + } + + fun clearSportCursDayDangerAfter() { + val edit = prefCursDangerDayAfter?.edit() + edit?.clear() + edit?.apply() + SportCursDayDangerAfter = 0 + } + + + fun getDaySport( + i: Int, + description: String, + categoryImage: String, + categorySport: String, + visible: Int, + article: String, + check: Int, + ): String { + val db = MainDB.getDB(requireContext()) + val tomorrow = LocalDate.now().plusDays(i.toLong()) + val item = ItemSportCategory(null, i.toString(), description, "3", categoryImage, categorySport, article,check) + Thread { + db.getDaoSportCategory().insertItemSportCategory(item) + }.start() + + return tomorrow.toString() + } + + + //Экран создания пациенат + fun visible8() { + binding.CLPatientSport.visibility = View.GONE + binding.CLLoad.visibility = View.GONE + binding.CLEditSportPatient.visibility = View.VISIBLE + //addSportListView() + } + + //Функция для вывода списка + private fun addSportListView() { + + } + + //Функция создания тренеровок и фотографий + private fun createCyrs() { + binding.btnImage.setOnClickListener { + createImageBD() + } + + binding.btnCategorySport.setOnClickListener { + createSportCategory() + } + } + + //Экран о пациенте + fun visible3() { + activity?.supportFragmentManager?.beginTransaction() + ?.replace(R.id.CLMainSettinDoctor, MainPatientFragment.newInstance())?.addToBackStack(null)?.commit() + } + + private fun liveCountNameCategoryCurrent() = with(binding) { + model.liveCountNameCategoryCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + countCategory = it.count + //getDateTomorrow(countCategory.toInt(), it.name) + getDateTomorrow() + + } + } + + //ЗАполняем списки о дням и на месяц + fun getDateTomorrow() { + val db = MainDB.getDB(requireContext()) + var day = 1 + var tomorrow = LocalDate.now() + + + val arr1 = arrayOf("c1","c2","c3","c4","c8","c10","c14","c16","c15","c7","b1","b2","b3","j1","j2","j4","j3","j5","j6","j8") + for (j in 0..19) { + val item = ItemDaySport( + null, + tomorrow.toString(), + arr1[j], + 0, + 1 + ) + Thread { + db.getDaoDaySport().insertItemDaySport(item) + }.start() + } + + val arr2 = arrayOf("c1","c2","c3","c4","c8","c9","c5","c10","c14","c16","c15","c12","c7","b1","b2","b3","j1","j2","j4","j3","j5","j6","j8") + + day++ + tomorrow = LocalDate.now().plusDays(day.toLong()) + for (j in 0..22) { + val item = ItemDaySport( + null, + tomorrow.toString(), + arr2[j], + 0, + 1 + ) + Thread { + db.getDaoDaySport().insertItemDaySport(item) + }.start() + } + + val arr3 = arrayOf("c1","c2","c3","c4","c8","c9","c5","c6","c14","c16","c15","c12","c13","c10","c7","b1","b2","b3","j1","j2","j4","j3","j5","j6","j8") + day++ + tomorrow = LocalDate.now().plusDays(day.toLong()) + for (j in 0..24) { + val item = ItemDaySport( + null, + tomorrow.toString(), + arr3[j], + 0, + 1 + ) + Thread { + db.getDaoDaySport().insertItemDaySport(item) + }.start() + } + + + val arr4 = arrayOf("c1","c2","c3","c4","c8","c9","c5","c6","c14","c16","с17","c18","с15","с12","c13","c10","c7","b1","b2","b3","j1","j2","j4","j3","j5","j6","j8") + day++ + tomorrow = LocalDate.now().plusDays(day.toLong()) + for (j in 0..26) { + val item = ItemDaySport( + null, + tomorrow.toString(), + arr4[j], + 0, + 1 + ) + Thread { + db.getDaoDaySport().insertItemDaySport(item) + }.start() + } + + val arr5 = arrayOf("c1","c2","c3","c4","c8","c9","c5","c6","c14","c16","с17","c18","с15","с12","c13","c10","c7","b1","b2","b3","b4","j1","j2","j4","j3","j5","j6","j8","j9") + day++ + tomorrow = LocalDate.now().plusDays(day.toLong()) + for (j in 0..28) { + val item = ItemDaySport( + null, + tomorrow.toString(), + arr5[j], + 0, + 1 + ) + Thread { + db.getDaoDaySport().insertItemDaySport(item) + }.start() + } + + val arr6 = arrayOf("c1","c2","c3","c4","c8","c9","c5","c6","c14","c16","с17","c18","с15","с12","c13","c10","c7","b1","b2","b3","b4","j1","j2","j4","j3","j5","j6","j8","j10","j9") + day++ + tomorrow = LocalDate.now().plusDays(day.toLong()) + for (j in 0..29) { + val item = ItemDaySport( + null, + tomorrow.toString(), + arr6[j], + 0, + 1 + ) + Thread { + db.getDaoDaySport().insertItemDaySport(item) + }.start() + } + + + val arr7 = arrayOf("c1","c2","c3","c4","c8","c9","c5","c6","c7","c10","c14","c16","с17","c18","с15","с12","c13","c11","c7","b1","b2","b3","b4","j1","j2","j4","j3","j5","j6","j8","j10","j9") + day++ + tomorrow = LocalDate.now().plusDays(day.toLong()) + for (i in 1..7) { + for (j in 0..31) { + val item = ItemDaySport( + null, + tomorrow.toString(), + arr7[j], + 0, + 1 + ) + Thread { + db.getDaoDaySport().insertItemDaySport(item) + }.start() + + } + day++ + tomorrow = LocalDate.now().plusDays(day.toLong()) + } + + + //saveCountSport(countCategory.toString()) + saveDate(0) + Log.i("SportUserTrue", SportUserTrue.toString()) + Toast(requireContext()).showCustomNiceToast("Курс был добавлен", requireActivity()) + + } + + //Экран тренировок пациента + fun visible4() { + binding.CLPatientSport.visibility = View.VISIBLE + binding.CLLoad.visibility = View.GONE + binding.CLEditSportPatient.visibility = View.GONE + } + + + fun addSportCategoryDay() { + + if (SportUserTrue == 0) { + visibleLoad() + val db = MainDB.getDB(requireContext()) + Thread { + //Создаем карточки на 30 дней + for (i in 1..15) { + val item = Item( + null, + "", + //LocalDate.now().plusDays(i.toLong()).toString(), + //getDateTomorrow(i, "c"),//"11/11/2023", + i.toString(), + 0 + ) + db.getDao().insertItem(item) + } + }.start() + + saveSportDateStart(LocalDate.now().toString()) + saveDate(1) + saveSportCursDay(0) + Log.i("SportUserTrue","${SportUserTrue}") + Log.i("SportCursDay","${SportCursDay}") + Log.i("SportCursDayDangerBefore","${SportCursDayDangerBefore}") + Log.i("SportCursDayDangerAfter","${SportCursDayDangerAfter}") + //addSportCategoryCyrs("1cbjSport07082003") + visible4() + Toast(requireContext()).showCustomNiceToast("Курс был добавлен", requireActivity()) + } else { + Toast(requireContext()).showCustomInfoToast( + "Удалите предыдуший курс", + requireActivity() + ) + } + + } + + fun addSportCategoryCyrs(article: String) { + val articleArr = arrayOf( + "1cbjSport07082003", + "2cbjSport07082003", + "3cbjSport07082003", + "4cbjSport07082003", + "5cbjSport07082003", + "6cbjSport07082003", + "7cbjSport07082003" + ) + if (SportUserTrue == 0) { + visibleLoad() +// for (i in 0..6) { +// val db = MainDB.getDB(requireContext()) +// db.getDaoSportCategory().getSportArticle(articleArr[i]).asLiveData() +// .observe(requireActivity()) { itCount -> +// itCount.forEach() { +// val item = CountNameCategoryModel( +// it.count.toString(), +// it.category.toString(), +// ) +// model.liveCountNameCategoryCurrent.value = item +// } +// } +// } + getDateTomorrow() + } else { + Toast(requireContext()).showCustomInfoToast( + "Удалите предыдуший курс", + requireActivity() + ) + } + + } + + private fun addSportCategory(category: String) { + + if (SportUserTrue == 0) { + visibleLoad() + val db = MainDB.getDB(requireContext()) + db.getDaoSportCategory().getAllItemsSportCategoryCountSport(category).asLiveData() + .observe(requireActivity()) { itCount -> + itCount.forEach() { + val item = CountNameCategoryModel( + it.count.toString(), + it.image.toString() + ) + model.liveCountNameCategoryCurrent.value = item + } + } + Thread { + //Создаем карточки на 30 дней + for (i in 1..30) { + val item = Item( + null, + LocalDate.now().plusDays(i.toLong()).toString(), + //getDateTomorrow(i, "c"),//"11/11/2023", + i.toString(), + 0 + ) + db.getDao().insertItem(item) + } + }.start() + + } else { + Toast(requireContext()).showCustomInfoToast( + "Удалите предыдуший курс", + requireActivity() + ) + } + + } + + private fun liveEditSportCurrent() = with(binding) { + model.liveEditSportCurrent.observe(requireActivity()) {//viewLifecycleOwner - следит за циклом жизни fragment + + } + } + + + override fun onClickExceptionOrder(item: EditSportModel) { + + } + + override fun onClickEditCard(item: EditSportModel) { + visibleLoad() + val date = LocalDate.now().toString() + val db = MainDB.getDB(requireContext()) + if (item.visible == 0) { + GlobalScope.launch(Dispatchers.IO) { + db.getDaoDaySport().updateVisibleDaySportTrue(item.category, date) + } + //visible8() + itemDAySportOne() + Toast(requireContext()).showCustomInfoToast( + "Упражнение включено", + requireActivity() + ) + + } else if (item.visible == 1) { + GlobalScope.launch(Dispatchers.IO) { + db.getDaoDaySport().updateVisibleDaySportFalse(item.category, date) + } + //visible8() + itemDAySportOne() + Toast(requireContext()).showCustomInfoToast( + "Упражнение отключено", + requireActivity() + ) + } + } + +// private fun addListModelCardsDay(day: String) { +// +// val db = MainDB.getDB(requireContext()) +// val list = ArrayList() +// db.getDaoDaySport().getAllItemDaySport(day).asLiveData() +// .observe(requireActivity()) { itList -> +// var number = 1; +// +// itList.forEach { +// Log.d("123", it.category) +// //db.getDaoSportCategory().getAllItemsSportCategory(it.category).asLiveData().observe(requireActivity()){itSport-> +// val itemDay = EditSportModel( +// it.id.toString(), +// it, +// +// day, +// it.category.toString(), +// it.check.toString(), +// ) +// list.add(itemDay)//Передали заполненый список +// model.liveEditSportList.value = list +// //} +// } +// +// Log.d("sadas", list.toString()) +// } +// visible8() +// } + + //Функция для вывода списка + private fun addSportList(date: String) { + val db = MainDB.getDB(requireContext()) + val list = ArrayList() + var number = 1 + + db.getDaoDaySport().getListJoinDaySportAndSportCategory(date).asLiveData() + .observe(requireActivity()) { itList -> + + itList.forEach { + Log.d("123", it.category) + val itemDay = EditSportModel( + number++, + it.day, + it.category, + it.check, + it.visible, + it.desc, + it.categoryImage, + false + ) + list.add(itemDay)//Передали заполненый список + model.liveEditSportList.value = list + //} + } + } + visible8() + } + + private fun initRcViewDay() = with(binding) { + rcViewSportEdit.layoutManager = + GridLayoutManager(requireContext(), 1)//По вертикали будет выводить по умолчанию + editAdapter = EditSportAdapter(this@PatientSportFragment, this@PatientSportFragment) + rcViewSportEdit.adapter = editAdapter + } + + //Экран создания пациенат + fun visibleLoad() { + binding.CLLoad.visibility = View.VISIBLE + binding.CLPatientSport.visibility = View.GONE + binding.CLEditSportPatient.visibility = View.GONE + } + + //Спина + val c1 = arrayOf("c1_1", "c1_2") + val c2 = arrayOf("c2_1", "c2_2") + val c3 = arrayOf("c3_1", "c3_2") + val c4 = arrayOf("c4_1", "c4_2") + val c5 = arrayOf("c5_1", "c5_2") + val c6 = arrayOf("c6_1", "c6_2", "c6_3") + val c7 = arrayOf("c7_1") + val c8 = arrayOf("c8_1", "c8_2") + val c9 = arrayOf("c9_1", "c9_2", "c9_3") + val c10 = arrayOf("c10_1", "c10_2", "c10_3") + val c11 = arrayOf("c11_1") + val c12 = arrayOf("c12_1", "c12_2") + val c13 = arrayOf("c13_1", "c13_2") + val c14 = arrayOf("c14_1", "c14_2") + val c15 = arrayOf("c15_1", "c15_2") + val c16 = arrayOf("c16_1", "c16_2") + val c17 = arrayOf("c17_1", "c17_2") + val c18 = arrayOf("c18_1", "c18_2", "c18_3") + + //Бок + val b1 = arrayOf("b1_1", "b1_2") + val b2 = arrayOf("b2_1", "b2_2") + val b3 = arrayOf("b3_1", "b3_2", "b3_3") + val b4 = arrayOf("b4_1", "b4_2") + + //Живот + val j1 = arrayOf("j1_1", "j1_2") + val j2 = arrayOf("j2_1", "j2_2") + val j3 = arrayOf("j3_1", "j3_2") + val j4 = arrayOf("j4_1", "j4_2", "j4_3") + val j5 = arrayOf("j5_1") + val j6 = arrayOf("j6_1", "j6_2", "j6_3", "j6_4") + val j7 = arrayOf("j7_1", "j7_2", "j7_3", "j7_4", "j7_5", "j7_6", "j7_7") + val j8 = arrayOf("j8_1", "j8_2", "j8_3") + val j9 = arrayOf("j9_1") + val j10 = arrayOf("j10_1", "j10_2", "j10_3") + val j11 = arrayOf("j11_1", "j11_2", "j11_3", "j11_4") + val j12 = arrayOf("j12_1", "j12_2") + + val C1 = "Исходное положение, положить руки вверх.\n" + + "Счет \n" + + "1-2-3 - потянуться руками вверх, а пятками — в противоположную сторону;\n" + + "4 – Расслабиться\n" + + "Повторить 5—6 раз. Дыхание свободное.\n" + val C2 = + "Исходное положение, руки лежат под головой или направлены вниз, вдоль туловища.\n" + + "Счет\n" + + "1 - поднять одну прямую ногу на 45°;\n" + + "2-3 - удерживать ее;\n" + + "4 - опустить в исходное положение.\n" + + "То же повторить с другой ноги. С каждой ноги повторить по 4—б раз. Дыхание свободное.\n" + val C3 = "Исходное положение, руки лежат вверху.\n" + + "Счет\n" + + "1 - поднять вперед прямые правую руку и левую ногу; \n" + + "2- опустить их в исходное положение;\n" + + "3 - поднять вперед левую руку и правую ногу;\n" + + "4 - вернуться в исходное положение.\n" + + "Повторить 4-6 раз с каждой стороны, опустить их в исходное положение;\n" + val C4 = + "Исходное положение, руки лежат под головой или направлены вниз, вдоль туловища.\n" + + "Счет\n" + + "1 – напрячь оба бедра, как при выпрямлении колена;\n" + + "2-3 – удерживать в напряжении;\n" + + "4 - расслабиться.\n" + + "Повторить 6-10 раз. Дыхание произвольное. При ампутации на уровне голени можно подложить под нижнюю треть бедра валик, если есть сгибательная контрактура колена, или если пациент так лучше ощущает работу мышц.\n" + val C5 = + "Исходное положение, руки лежат вниз вдоль туловища, под культю и под аналогичный сегмент сохранной конечности подложить мячи. \n" + + "Счет\n" + + "1 — опереться на ноги, поднять таз вверх;\n" + + "2-3 — удерживать это положение;\n" + + "4 — опуститься в исходное положение. \n" + + "Повторить 4-8 раз. Дыхание произвольное, или подъем таза осуществлять на выдохе через рот, губы сложены «трубочкой».\n" + val C6 = + "Исходное положение, руки лежат вниз вдоль туловища, под культю и под аналогичный сегмент сохранной конечности подложить мячи. \n" + + "Счет\n" + + "1 — опереться на ноги и поднять таз вверх;\n" + + " 2 — поднять одну прямую ногу вверх на 30°—45% \n" + + "3 — опустить ногу на мяч;\n" + + " 4 — опустить таз и вернуться в исходное положение. Повторить упражнение по 4-8 раз с каждой ноги. Дыхание произвольное. При значительных трудностях с удержанием баланса на мячах данное упражнение можно выполнять на валике или любых стабильных опорах.\n" + val C7 = "Дыхательное упражнение — диафрагмальное дыхание. \n" + + "Сохранную ногу поставить согнутую, вторая нога или свободно лежит на полу, или бедро закинуто на другое бедро (фото), одна ладонь лежит на животе, а другая — на груди. На вдох носом надуть животом «шарик», на выдох через рот опустить переднюю стенку живота (и втянуть ее) и расслабиться. \n" + + "Повторить дыхательный цикл не более 4-6 раз. Дышать глубоко, в комфортном темпе.\n" + val C8 = + "Исходное положение, руки лежат вниз вдоль туловища, под ноги подложен большой гимнастический мяч.\n" + + "Счет\n" + + "1 – упереться ногами в мяч, поднять таз вверх;\n" + + "2-3 — удерживать это положение;\n" + + "4 - опустить таз и вернуться B исходное положение.\n" + + "Дыхание произвольное. Повторить упражнение 6-8 раз.\n" + val C9 = + "Исходное положение, руки лежат вниз вдоль туловища, под ноги подложен большой гимнастический мяч. \n" + + "Счет\n" + + "1 - поднять таз с опорой на обе ноги;\n" + + "2 - поднять сохранную ногу вверх от опоры и остаться стоять на одной культе;\n" + + "3 - опустить на опору сохранную ногу;\n" + + "4 - опустить таз и вернуться в исходное положение. Повторить упражнение для каждой ноги по 4—6 раз. Дыхание произвольное.\n" + val C10 = + "Исходное положение, руки лежат вниз вдоль туловища или под головой (усложненный вариант). \n" + + "Имитация велосипедных движений. По 6-10 движений сначала одной ногой, затем второй. Усложненный вариант упражнения (фото) — выполнение упражнения одновременно двумя ногами.\n" + + "Сначала движение ногами выполняется в направлении движения вперед, а затем — назад. \n" + + "Следить за дыханием и за тем, чтобы поясница была прижата к полу.\n" + val C11 = "Дыхательное упражнение — диафрагмальное дыхание.\n" + + "Повторить дыхательный цикл не более 4-6 раз. В необходимости повторения дыхательного упражнения — ориентироваться на самочувствие пациента.\n" + val C12 = + "Исходное положение, руки вытянуты перед собой, B руках — резиновая лента-амортизатор.\n" + + "Счет\n" + + "1 - развести в стороны прямые руки и коснуться кулачками пола, свести лопатки;\n" + + "2-3 — удерживать это положение;\n" + + "4 — свести руки перед собой и вернуться в исходное положение.\n" + + "При выполнении упражнения акцент делать на сведение лопаток в момент растяжения резинового амортизатора.\n" + val C13 = + "Исходное положение, в руках — резиновый амортизатор; одна рука лежит вниз вдоль туловища, вторая согнута в локте на 90° и отведена от туловища (локоть на уровне плеча), ее плечо лежит на полу. \n" + + "Счет\n" + + "1 - не разгибая локтя, разворачивая лопатку, положить кисть согнутой руки на пол;\n" + + "2-3 — удерживать это положение;\n" + + "4 - вернуться в исходное положение. Повторить 10—15-20 раз. Не меняя длины хвата амортизатора, повторить с другой руки. Дыхание произвольное.\n" + val C14 = + "Исходное положение, поставить руки B упоре на локти, немного отведя их от туловища.\n" + + "1 - надавить локтями на пол, свести лопатки прогнуть грудную клетку;\n" + + "2-3 — удерживать это напряжение;\n" + + "4 - расслабиться и вернуться в исходное положение \n" + + "Повторить 4-8 раз. Дыхание ровное, без задержек.\n" + val C15 = + "Исходное положение, на бедра надета резиновая петля, ногу со стороны ампутации ротировать внутрь (cкосолапить). \n" + + "Счет\n" + + "1 - скользя по поверхности, отвести ногу со стороны ампутации в сторону; \n" + + "2-3 - удерживать ногу в этом положении;\n" + + "4 - вернуть ногу в исходное положение.\n" + + "Повторить упражнение 10-15-20 раз.\n" + + "Повторить 10-15-20 раз. После короткого отдыха сделать второй подход. Дыхание произвольное. Следить, чтобы мышцы плечевого пояса не вовлекались в напряжение, а таз оставался неподвижным. Для улучшения самоконтроля можно руки ставить на пояс и таким 0бразом следить за неподвижностью таза.\n" + val C16 = "Исходное положение, бедрами удерживать мяч.\n" + + "Счет\n" + + "1 - сжать мяч между бедрами; \n" + + "2-3 - удерживать это положение; \n" + + "4 - расслабиться.\n" + + "Повторить упражнение 10-15-20 раз. \n" + + "Со временем возможно усложнение упражнения: удерживать сжатие не на счет 2-3, а на 2-3-4-5-6-7, и только на счет 8 — расслабиться. Дыхание произвольное. Следить, чтобы мышцы плечевого пояса не вовлекались B напряжение, и пациент не затаивал дыхание.\n" + val C17 = + "Исходное положение, руки лежат под головой, на ногу со стороны ампутации надета манжета-утяжелитель.\n" + + "Счет\n" + + "1 - поднять прямую ногу на 45°; \n" + + "2-3 - удерживать ногу в этом положении; \n" + + "4 - опустить ногу и вернуться в исходное положение. \n" + + "Повторить 10—15—20 раз.\n" + + "Усложнение упражнения:\n" + + "1 - поднять ногу; \n" + + "2-3-4-5-6-7 - держать ногу; \n" + + "8 - опустить ногу и вернуться в исходное положение.\n" + + "Со временем можно выполнять два подхода к упражнению.\n" + val C18 = + "Исходное положение, руки лежат под головой, на ногу со стороны ампутации надета манжета-утяжелитель. \n" + + "Счет\n" + + "1 - поднять прямую ногу на 45°;\n" + + "2 - согнуть ногу в бедре и колене до 90°; \n" + + "3 - выпрямить ногу обратно; \n" + + "4 - опустить ногу и вернуться в исходное положение. \n" + + "Повторить упражнение 10—15 раз. \n" + + "Усложнение упражнения: \n" + + "сгибание и разгибание колена и бедра можно осуществлять не один, а несколько раз подряд, и только потом. опускать ногу. Также можно делать имитацию велосипедных движений вперед, а потом B обратную сторону. \n" + + "Со временем весь комплекс упражнений можно выполнять с утяжелителем в постоянном режиме. Со стороны ампутации делать больше подходов и количество повторений предлагаемых упражнений.\n" + + val B1 = "Исходное положение. \n" + + "Счет\n" + + "1 - поднять верхнюю ногу на 10—35° точно в сторону;\n" + + "2-3 - удерживать это положение; \n" + + "4 - опустить ногу в исходное положение. \n" + + "Повторить упражнение 10—15-20 раз и положить согнутую ногу вперед — для растяжки и отдыха мышц. Во время выполнения упражнения следить за точностью направления движения — отведения.\n" + val B2 = "Исходное положение, верхняя нога согнута в колене и лежит впереди. \n" + + "Счет \n" + + "1 - поднять прямую нижнюю ногу точно вверх (приведение), стопу тянуть на себя;\n" + + "2-3 - удерживать ногу в верхней точке.\n" + + "4 - опустить ногу в исходное положение \n" + + "Повторить 10—15-20 раз. Следить за тем, чтобы нога не уходила вперед или назад, колено было всегда выпрямлено. Дыхание произвольное.\n" + val B3 = "Исходное положение. \n" + + "Счет\n" + + "1 — поднять верхнюю ногу на 10—35° точно в сторону; \n" + + "2 — согнуть в колене, не смещая бедро; \n" + + "3 — выпрямить колено, не смещая бедро; \n" + + "4 — опустить ногу в исходное положение. \n" + + "Повторить 10—15—20 раз. Дыхание произвольное. \n" + + "Повторяйте те же упражнения, лежа на другом боку.\n" + val B4 = "Исходное положение, на уровне бедра надета манжета с утяжелителем. \n" + + "Счет \n" + + "1 - поднять верхнюю ногу на 10—35° точно в сторону; \n" + + "2-3 — удерживать это положение \n" + + "4 - опустить ногу в исходное положение.\n" + + "Повторить 10—15-20 раз и положить согнутую ногу вперед для отдыха. Следить за точностью направления движения (отведение). \n" + + "Подобным образом — с утяжелителем — можно выполнять все упражнения в исходном положении лежа на боку.\n" + + + val J1 = "Исходное положение, руки лежат под головой, опираясь на лоб. \n" + + "1 - поднять плечевой пояс, руки и голову; \n" + + "2-3 - удерживать это положение;\n" + + "4 — опуститься в исходное положение и расслабиться. Повторить упражнение 6-10 раз. Следить за дыханием. \n" + + "Можно при подъеме туловища сводить лопатки, приводя локти к туловищу на все время удержания корпуса.\n" + val J2 = "Исходное положение, руки лежат под головой, голова опирается на лоб. \n" + + "1 - поднять правую прямую ногу вверх;\n" + + "2-3 - удерживать ногу; 4 - опустить ногу в исходное положение. \n" + + "С каждой стороны повторить упражнение по 6-10 раз. Следить за дыханием.\n" + val J3 = "Исходное положение, ноги лежат чуть шире плеч, руки под головой. \n" + + "1 — поднять плечевой пояс, руки и голову, и развести руки в стороны (ладонями вперед); \n" + + "2-3 — удерживать это положение;\n" + + "4 - опуститься в исходное положение. \n" + + "Повторить упражнение 6-10 раз. \n" + + "Усложнение: \n" + + "можно одновременно с подъемом корпуса поднимать поочередно то одну HOTY, то другую, или две ноги одновременно (фото). Следить за дыханием.\n" + val J4 = "Исходное положение, руки лежат наверху, голова опирается на лоб. \n" + + "Счет\n" + + "1 — поднять вверх одновременно прямые правую руку и левую ногу; \n" + + "2-3 - удерживать это положение; \n" + + "4 — опуститься в исходное положение. \n" + + "С каждой стороны повторить упражнение по 4-8 раз. Следить за дыханием.\n" + val J5 = + "Дыхательное упражнение. Исходное положение, голова опирается на лоб, руки под толовой. Глубокий вдох HOCOM, долгий выдох через рот, губы сложены «трубочкой». Повторить 4-6 раз.\n" + val J6 = "Исходное положение, голова опирается на лоб. Рисуем ногой медленно букву «П».\n" + + "Счет\n" + + "1 – поднять прямую правую ногу вверх;\n" + + "2 – отвести eё B сторону на 30°;\n" + + "3 – опустить ногу в стороне на пол;\n" + + "4 – поднять правую ногу;\n" + + "5 – привести ноту к центру;\n" + + "6 – опустить ногу в исходное положение;\n" + + "7-12 – повторить то же с левой ноги.\n" + + "Упражнение сделать по 4-8 раз на каждую ногу. Следить за дыханием." + val J7 = "Предыдущее упражнение можно немного усложнить. \n" + + "Счет\n" + + "1 — поднять одну ногу; \n" + + "2 — отвести ногу в сторону; \n" + + "3 — опустить ногу в стороне; \n" + + "4 — поднять вверх другую ногу;\n" + + "5 - отвести и ее в сторону; \n" + + "6 - опустить на пол в стороне; \n" + + "7-8 -скользя по опоре, соединить на полу ноги. \n" + + "Повторить упражнение с каждой ноги по 4-6 раз. Следить за дыханием.\n" + val J8 = "Исходное положение, две ноги поднять поочередно вверх. \n" + + "1 - развести ноги в стороны; \n" + + "2 - свести ноги вместе, и повторять 10—15-20 раз. \n" + + "Следить за дыханием. После небольшой паузы, со временем, можно выполнять второй подход. \n" + + "Также возможны следующие варианты:\n" + + "1 - развести ноги в стороны;\n" + + "2 - свести ноги вместе с перекрестом (одна нога выше, и нижнюю ноги. другая ниже);\n" + + "3 - развести ноги в стороны;\n" + + "4 - свести ноги и перекрестить их, поменяв верхнюю и нижнюю ноги.\n" + + "Упражнение сделать по 4-8 раз на каждую ногу. Следить за дыханием.\n" + val J9 = + "Дыхательное упражнение. Исходное положение, голова опирается на лоб, руки под головой. Глубокий вдох носом, долгий выдох через POT, губы сложены «трубочкой». Повторить 4-6 раз.\n" + val J10 = + "Исходное положение, голова опирается на лоб, руки лежат наверху на ширине, в руках — резиновый амортизатор. \n" + + "1 — поднять туловище, руки и голову вверх; \n" + + "2 — развести руки в стороны так, чтобы амортизатор лег на лопатки; \n" + + "3 — свести руки наверху до ширины плеч; \n" + + "4 — опуститься в исходное положение. \n" + + "Повторить упражнение 6-10 раз. Дыхание произвольное.\n" + + " Со временем можно усложнить упражнение: разводить руки в стороны не один раз, а несколько раз подряд; также можно сделать паузу в момент, когда руки разведены в стороны. Дыхание произвольное. Можно одновременно с подъемом туловища поднимать поочередно то одну, то вторую ногу.\n" + val J11 = + "Исходное положение, руки под головой. Поднять плечевой пояс и согнутые к плечам руки. Имитация плавания брассом. Дыхание ровное. \n" + + "Два подхода по 10-15-20 движений. Следить за полным выпрямлением рук наверх, разведением прямых рук B стороны, сведением лопаток B момент приведения плеч, а также за тем, чтобы корпус при выпрямлении рук наверх не опускался. Дыхание произвольное.\n" + val J12 = + "Исходное положение, руки лежат под головой, голова опирается на лоб. На ноге со стороны ампутации надета манжета с утяжелителем.\n" + + "Счет\n" + + "1 - поднять ногу с утяжелителем;\n" + + "2-3 — удерживать ногу; \n" + + "4 — опустить ногу в исходное положение. \n" + + "Повторить 10-15-20 раз.\n" + + "Усложнение: можно на счет 2 - отвести ногу в сторону, на счет 3 - вернуть ногу к центру, счет 4 — опуститься в исходное положение. Также можно отводить в сторону не один раз, а несколько раз подряд. Дыхание свободное. \n" + + "Со временем все упражнения можно выполнять с утяжелителем." + + private fun createImageBD() { + val db = MainDB.getDB(requireContext()) + + val itemС1_1 = ItemImage(null, "c1_1", "c1", "c") + val itemС1_2 = ItemImage(null, "c1_2", "c1", "c") + val itemС2_1 = ItemImage(null, "c2_1", "c2", "c") + val itemС2_2 = ItemImage(null, "c2_2", "c2", "c") + val itemС3_1 = ItemImage(null, "c3_1", "c3", "c") + val itemС3_2 = ItemImage(null, "c3_2", "c3", "c") + val itemС4_1 = ItemImage(null, "c4_1", "c4", "c") + val itemС4_2 = ItemImage(null, "c4_1", "c4", "c") + val itemС5_1 = ItemImage(null, "c5_1", "c5", "c") + val itemС5_2 = ItemImage(null, "c5_2", "c5", "c") + val itemС6_1 = ItemImage(null, "c6_1", "c6", "c") + val itemС6_2 = ItemImage(null, "c6_2", "c6", "c") + val itemС6_3 = ItemImage(null, "c6_3", "c6", "c") + val itemС7_1 = ItemImage(null, "c7_1", "c7", "c") + val itemС8_1 = ItemImage(null, "c8_1", "c8", "c") + val itemС8_2 = ItemImage(null, "c8_2", "c8", "c") + val itemС9_1 = ItemImage(null, "c9_1", "c9", "c") + val itemС9_2 = ItemImage(null, "c9_2", "c9", "c") + val itemС9_3 = ItemImage(null, "c9_3", "c9", "c") + val itemС10_1 = ItemImage(null, "c10_1", "c10", "c") + val itemС10_2 = ItemImage(null, "c10_2", "c10", "c") + val itemС10_3 = ItemImage(null, "c10_3", "c10", "c") + val itemС11_1 = ItemImage(null, "c11_1", "c11", "c") + val itemС12_1 = ItemImage(null, "c12_1", "c12", "c") + val itemС12_2 = ItemImage(null, "c12_2", "c12", "c") + val itemС13_1 = ItemImage(null, "c13_1", "c13", "c") + val itemС13_2 = ItemImage(null, "c13_2", "c13", "c") + val itemС14_1 = ItemImage(null, "c14_1", "c14", "c") + val itemС14_2 = ItemImage(null, "c14_2", "c14", "c") + val itemС15_1 = ItemImage(null, "c15_1", "c15", "c") + val itemС15_2 = ItemImage(null, "c15_2", "c15", "c") + val itemС16_1 = ItemImage(null, "c16_1", "c16", "c") + val itemС16_2 = ItemImage(null, "c16_2", "c16", "c") + val itemС17_1 = ItemImage(null, "c17_1", "c17", "c") + val itemС17_2 = ItemImage(null, "c17_2", "c17", "c") + val itemС18_1 = ItemImage(null, "c18_1", "c18", "c") + val itemС18_2 = ItemImage(null, "c18_2", "c18", "c") + val itemС18_3 = ItemImage(null, "c18_3", "c18", "c") + + val itemB1_1 = ItemImage(null, "b1_1", "b1", "b") + val itemB1_2 = ItemImage(null, "b1_2", "b1", "b") + val itemB2_1 = ItemImage(null, "b2_1", "b2", "b") + val itemB2_2 = ItemImage(null, "b2_2", "b2", "b") + val itemB3_1 = ItemImage(null, "b3_1", "b3", "b") + val itemB3_2 = ItemImage(null, "b3_2", "b3", "b") + val itemB3_3 = ItemImage(null, "b3_3", "b3", "b") + val itemB4_1 = ItemImage(null, "b4_1", "b4", "b") + val itemB4_2 = ItemImage(null, "b4_2", "b4", "b") + + val itemJ1_1 = ItemImage(null, "j1_1", "j1", "j") + val itemJ1_2 = ItemImage(null, "j1_2", "j1", "j") + val itemJ2_1 = ItemImage(null, "j2_1", "j2", "j") + val itemJ2_2 = ItemImage(null, "j2_2", "j2", "j") + val itemJ3_1 = ItemImage(null, "j3_1", "j3", "j") + val itemJ3_2 = ItemImage(null, "j3_2", "j3", "j") + val itemJ4_1 = ItemImage(null, "j4_1", "j4", "j") + val itemJ4_2 = ItemImage(null, "j4_2", "j4", "j") + val itemJ4_3 = ItemImage(null, "j4_3", "j4", "j") + val itemJ5_1 = ItemImage(null, "j5_1", "j5", "j") + val itemJ6_1 = ItemImage(null, "j6_1", "j6", "j") + val itemJ6_2 = ItemImage(null, "j6_2", "j6", "j") + val itemJ6_3 = ItemImage(null, "j6_3", "j6", "j") + val itemJ6_4 = ItemImage(null, "j6_4", "j6", "j") + val itemJ7_1 = ItemImage(null, "j7_1", "j7", "j") + val itemJ7_2 = ItemImage(null, "j7_2", "j7", "j") + val itemJ7_3 = ItemImage(null, "j7_3", "j7", "j") + val itemJ7_4 = ItemImage(null, "j7_4", "j7", "j") + val itemJ7_5 = ItemImage(null, "j7_5", "j7", "j") + val itemJ7_6 = ItemImage(null, "j7_6", "j7", "j") + val itemJ7_7 = ItemImage(null, "j7_7", "j7", "j") + val itemJ8_1 = ItemImage(null, "j8_1", "j8", "j") + val itemJ8_2 = ItemImage(null, "j8_2", "j8", "j") + val itemJ8_3 = ItemImage(null, "j8_3", "j8", "j") + val itemJ9_1 = ItemImage(null, "j9_1", "j9", "j") + val itemJ10_1 = ItemImage(null, "j10_1", "j10", "j") + val itemJ10_2 = ItemImage(null, "j10_2", "j10", "j") + val itemJ10_3 = ItemImage(null, "j10_2", "j10", "j") + val itemJ11_1 = ItemImage(null, "j11_1", "j11", "j") + val itemJ11_2 = ItemImage(null, "j11_2", "j11", "j") + val itemJ11_3 = ItemImage(null, "j11_3", "j11", "j") + val itemJ11_4 = ItemImage(null, "j11_4", "j11", "j") + val itemJ12_1 = ItemImage(null, "j12_1", "j12", "j") + val itemJ12_2 = ItemImage(null, "j12_2", "j12", "j") + + Thread { + db.getDaoImage().insertItemImage(itemС1_1) + db.getDaoImage().insertItemImage(itemС1_2) + db.getDaoImage().insertItemImage(itemС2_1) + db.getDaoImage().insertItemImage(itemС2_2) + db.getDaoImage().insertItemImage(itemС3_1) + db.getDaoImage().insertItemImage(itemС3_2) + db.getDaoImage().insertItemImage(itemС4_1) + db.getDaoImage().insertItemImage(itemС4_2) + db.getDaoImage().insertItemImage(itemС5_1) + db.getDaoImage().insertItemImage(itemС5_2) + db.getDaoImage().insertItemImage(itemС6_1) + db.getDaoImage().insertItemImage(itemС6_2) + db.getDaoImage().insertItemImage(itemС6_3) + db.getDaoImage().insertItemImage(itemС7_1) + db.getDaoImage().insertItemImage(itemС8_1) + db.getDaoImage().insertItemImage(itemС8_2) + db.getDaoImage().insertItemImage(itemС9_1) + db.getDaoImage().insertItemImage(itemС9_2) + db.getDaoImage().insertItemImage(itemС9_3) + db.getDaoImage().insertItemImage(itemС10_1) + db.getDaoImage().insertItemImage(itemС10_2) + db.getDaoImage().insertItemImage(itemС10_3) + db.getDaoImage().insertItemImage(itemС11_1) + db.getDaoImage().insertItemImage(itemС12_1) + db.getDaoImage().insertItemImage(itemС12_2) + db.getDaoImage().insertItemImage(itemС13_1) + db.getDaoImage().insertItemImage(itemС13_2) + db.getDaoImage().insertItemImage(itemС14_1) + db.getDaoImage().insertItemImage(itemС14_2) + db.getDaoImage().insertItemImage(itemС15_1) + db.getDaoImage().insertItemImage(itemС15_2) + db.getDaoImage().insertItemImage(itemС16_1) + db.getDaoImage().insertItemImage(itemС16_2) + db.getDaoImage().insertItemImage(itemС17_1) + db.getDaoImage().insertItemImage(itemС17_2) + db.getDaoImage().insertItemImage(itemС18_1) + db.getDaoImage().insertItemImage(itemС18_2) + db.getDaoImage().insertItemImage(itemС18_3) + + db.getDaoImage().insertItemImage(itemB1_1) + db.getDaoImage().insertItemImage(itemB1_2) + db.getDaoImage().insertItemImage(itemB2_1) + db.getDaoImage().insertItemImage(itemB2_2) + db.getDaoImage().insertItemImage(itemB3_1) + db.getDaoImage().insertItemImage(itemB3_2) + db.getDaoImage().insertItemImage(itemB3_3) + db.getDaoImage().insertItemImage(itemB4_1) + db.getDaoImage().insertItemImage(itemB4_2) + + db.getDaoImage().insertItemImage(itemJ1_1) + db.getDaoImage().insertItemImage(itemJ1_2) + db.getDaoImage().insertItemImage(itemJ2_1) + db.getDaoImage().insertItemImage(itemJ2_2) + db.getDaoImage().insertItemImage(itemJ3_1) + db.getDaoImage().insertItemImage(itemJ3_2) + db.getDaoImage().insertItemImage(itemJ4_1) + db.getDaoImage().insertItemImage(itemJ4_2) + db.getDaoImage().insertItemImage(itemJ4_3) + db.getDaoImage().insertItemImage(itemJ5_1) + db.getDaoImage().insertItemImage(itemJ6_1) + db.getDaoImage().insertItemImage(itemJ6_2) + db.getDaoImage().insertItemImage(itemJ6_3) + db.getDaoImage().insertItemImage(itemJ6_4) + db.getDaoImage().insertItemImage(itemJ7_1) + db.getDaoImage().insertItemImage(itemJ7_2) + db.getDaoImage().insertItemImage(itemJ7_3) + db.getDaoImage().insertItemImage(itemJ7_4) + db.getDaoImage().insertItemImage(itemJ7_5) + db.getDaoImage().insertItemImage(itemJ7_6) + db.getDaoImage().insertItemImage(itemJ7_7) + db.getDaoImage().insertItemImage(itemJ8_1) + db.getDaoImage().insertItemImage(itemJ8_2) + db.getDaoImage().insertItemImage(itemJ8_3) + db.getDaoImage().insertItemImage(itemJ9_1) + db.getDaoImage().insertItemImage(itemJ10_1) + db.getDaoImage().insertItemImage(itemJ10_2) + db.getDaoImage().insertItemImage(itemJ10_3) + db.getDaoImage().insertItemImage(itemJ11_1) + db.getDaoImage().insertItemImage(itemJ11_2) + db.getDaoImage().insertItemImage(itemJ11_3) + db.getDaoImage().insertItemImage(itemJ11_4) + db.getDaoImage().insertItemImage(itemJ12_1) + db.getDaoImage().insertItemImage(itemJ12_2) + + }.start() + + + } + + fun createSportCategory() { +// getDaySport(1, C1, "c", "c1", 0) +// getDaySport(2, C2, "c", "c2", 0) +// getDaySport(3, C3, "c", "c3", 0) +// getDaySport(4, C4, "c", "c4", 0) +// getDaySport(5, C5, "c", "c5", 0) +// getDaySport(6, C6, "c", "c6", 0) +// getDaySport(7, C7, "c", "c7", 0) +// getDaySport(8, C8, "c", "c8", 0) +// getDaySport(9, C9, "c", "c9", 0) +// getDaySport(10, C10, "c", "c10", 0) +// getDaySport(11, C11, "c", "c11", 0) +// getDaySport(12, C12, "c", "c12", 0) +// getDaySport(13, C13, "c", "c13", 0) +// getDaySport(14, C14, "c", "c14", 0) +// getDaySport(15, C15, "c", "c15", 0) +// getDaySport(16, C16, "c", "c16", 0) +// getDaySport(17, C17, "c", "c17", 0) +// getDaySport(18, C18, "c", "c18", 0) +// +// +// getDaySport(19, B1, "b", "b1", 0) +// getDaySport(20, B2, "b", "b2", 0) +// getDaySport(21, B3, "b", "b3", 0) +// getDaySport(22, B4, "b", "b4", 0) +// +// getDaySport(23, J1, "j", "j1", 0) +// getDaySport(24, J2, "j", "j2", 0) +// getDaySport(25, J3, "j", "j3", 0) +// getDaySport(26, C4, "j", "j4", 0) +// getDaySport(27, J5, "j", "j5", 0) +// getDaySport(28, J6, "j", "j6", 0) +// getDaySport(29, J7, "j", "j7", 0) +// getDaySport(30, J8, "j", "j8", 0) +// getDaySport(31, J9, "j", "j9", 0) +// getDaySport(32, J10, "j", "j10", 0) +// getDaySport(33, J11, "j", "j11", 0) +// getDaySport(34, J12, "j", "j12", 0,0) + + } + + companion object { + + fun newInstance() = PatientSportFragment() + } + + + } \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/StatisticsFragment.kt b/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/StatisticsFragment.kt deleted file mode 100644 index e529e6c..0000000 --- a/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/StatisticsFragment.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.example.rehabilitation.Admin.fragmrntAdmin - -import android.os.Bundle -import androidx.fragment.app.Fragment -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import com.example.rehabilitation.R -import com.example.rehabilitation.databinding.FragmentStatisticsBinding - -class StatisticsFragment : Fragment() { - private lateinit var binding: FragmentStatisticsBinding - - override fun onCreateView( - inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle? - ): View? { - binding = FragmentStatisticsBinding.inflate(layoutInflater, container,false) - return binding.root - //ТУТ БОЛЬШЕ НИЧЕГО НЕ ТРОГАЙ - } - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - //ВОТ ТУТ ТЫ ВСТАВЛЯЕШЬ КОД - } - - companion object { - - fun newInstance() = StatisticsFragment() - } -} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/UserSettingFragment.kt b/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/UserSettingFragment.kt deleted file mode 100644 index 8b967c5..0000000 --- a/app/src/main/java/com/example/rehabilitation/Admin/fragmrntAdmin/UserSettingFragment.kt +++ /dev/null @@ -1,26 +0,0 @@ -package com.example.rehabilitation.Admin.fragmrntAdmin - -import android.os.Bundle -import androidx.fragment.app.Fragment -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import com.example.rehabilitation.R -import com.example.rehabilitation.databinding.FragmentUserSettingBinding - -class UserSettingFragment : Fragment() { - private lateinit var binding: FragmentUserSettingBinding - - override fun onCreateView( - inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle? - ): View? { - binding = FragmentUserSettingBinding.inflate(layoutInflater,container,false) - return binding.root - } - - companion object { - - fun newInstance() = UserSettingFragment() - } -} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Auth/AuthDoctorActivity.kt b/app/src/main/java/com/example/rehabilitation/Auth/AuthDoctorActivity.kt new file mode 100644 index 0000000..5af2f9e --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Auth/AuthDoctorActivity.kt @@ -0,0 +1,29 @@ +package com.example.rehabilitation.Auth + +import androidx.appcompat.app.AppCompatActivity +import android.os.Bundle +import com.example.rehabilitation.R +import com.example.rehabilitation.User.fragmentUser.HomeFragment +import com.example.rehabilitation.databinding.ActivityAuthDoctorBinding + +class AuthDoctorActivity : AppCompatActivity() { + lateinit var binding: ActivityAuthDoctorBinding + + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityAuthDoctorBinding.inflate(layoutInflater) + setContentView(binding.root) + + //Вывод фрагмента на активити при первоначальной загрузке + supportFragmentManager.beginTransaction() + .replace(R.id.CLAutDoctor, AuthDoctorFragment.newInstance()) + .commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем + + } + + override fun onDestroy() { + super.onDestroy() + finish() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Auth/AuthDoctorFragment.kt b/app/src/main/java/com/example/rehabilitation/Auth/AuthDoctorFragment.kt new file mode 100644 index 0000000..7e304c2 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Auth/AuthDoctorFragment.kt @@ -0,0 +1,157 @@ +package com.example.rehabilitation.Auth + +import android.content.Context +import android.content.Intent +import android.os.Bundle +import android.util.Log +import androidx.fragment.app.Fragment +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.fragment.app.activityViewModels +import androidx.lifecycle.asLiveData +import com.example.admin.Toast.showCustomDangerToast +import com.example.admin.Toast.showCustomInfoToast +import com.example.rehabilitation.Admin.activityAdmin.UserSettingActivity +import com.example.rehabilitation.MainActivity +import com.example.rehabilitation.R +import com.example.rehabilitation.Room.MainDB +import com.example.rehabilitation.UserDoctorToken +import com.example.rehabilitation.databinding.ActivityAuthDoctorBinding +import com.example.rehabilitation.databinding.FragmentAuthDoctorBinding +import com.example.rehabilitation.model_adapter.Doctor.DoctorModel +import com.example.rehabilitation.prefUserDoctorToken +import com.example.sqlitework.dip.MainViewModel + +class AuthDoctorFragment : Fragment() { + lateinit var binding: FragmentAuthDoctorBinding + private val model: MainViewModel by activityViewModels()//Инициализировали класс + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + binding = FragmentAuthDoctorBinding.inflate(layoutInflater,container,false) + return binding.root + } + + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + data_prefDoctorPatientToken() + liveDoctorAuthCurrent() + + //Авторизация врача + //Нажатие на кнопку авторизации + binding.buttonAuthorizationDoctor.setOnClickListener{ + var email = binding.editTextEmailDoctor.text.toString() + var password = binding.editTextPasswordDoctor.text.toString() + if(email !="" || password !=""){ + AuthorizationDoctor(email,password) + Log.d("Result","email email - $email") + Log.d("Result","password password - $password") + } + else{ + Toast(requireContext()).showCustomInfoToast("Не все поля заполнены", requireActivity()) + } + } + + //Переход от авторизации врача к пациенту + binding.btnAutPatient.setOnClickListener{ + val intent = Intent(requireContext(), AuthorizationActivity::class.java) + activity?.finish()//Закрываем старый экран, для того чтобы очитсить оперативную память от лишнего хранения экрана + startActivity(intent) + } + + + + + } + + private fun liveDoctorAuthCurrent() = with(binding) { + model.liveAuthDoctorCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + if(it.id == "0"){ + Toast(requireContext()).showCustomDangerToast("Такого аккаунта нету", requireActivity()) + } + else{ + saveUserDoctorToken(it.login) + + if(UserDoctorToken !=""){ + val intent = Intent(requireContext(), UserSettingActivity::class.java) + activity?.finish()//Закрываем старый экран, для того чтобы очитсить оперативную память от лишнего хранения экрана + startActivity(intent) + } + } + + } + + } + + //Фиксируем токен врача + private fun data_prefDoctorPatientToken() { + prefUserDoctorToken = activity?.getSharedPreferences("UserDoctorToken", Context.MODE_PRIVATE) + UserDoctorToken = prefUserDoctorToken?.getString("userdoctortoken", "")!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0 + } + + //Записываем число + fun saveUserDoctorToken(userdoctortoken: String) { + val editer = prefUserDoctorToken?.edit() + editer?.putString("userdoctortoken", userdoctortoken) + editer?.apply() + UserDoctorToken = userdoctortoken + } + //Функция очистки данных + fun clearUserDoctorToken() { + val edit = prefUserDoctorToken?.edit() + edit?.clear() + edit?.apply() + UserDoctorToken = "" + } + + + + private fun AuthorizationDoctor(login:String,password:String){ + val db = MainDB.getDB(requireContext()) + + db.getDaoDoctor().getAuthItemDoctor(login,password).asLiveData().observe(requireActivity()) {itPatient-> + if (itPatient.isNullOrEmpty()) { + val item = DoctorModel( + "0", + "", + "", + "", + // it.email, + login, + "" + ) + + model.liveAuthDoctorCurrent.value = item + + } + else{ + val item = DoctorModel( + itPatient[0].id.toString(), + "", + "", + "", + // it.email, + login, + "" + ) + + model.liveAuthDoctorCurrent.value = item + } + } + } + + + override fun onDestroy() { + super.onDestroy() + activity?.finish() + } + + companion object { + fun newInstance() = AuthDoctorFragment() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Auth/AuthFragment.kt b/app/src/main/java/com/example/rehabilitation/Auth/AuthFragment.kt new file mode 100644 index 0000000..92a37fc --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Auth/AuthFragment.kt @@ -0,0 +1,198 @@ +package com.example.rehabilitation.Auth + +import android.content.Context +import android.content.Intent +import android.os.Bundle +import android.util.Log +import androidx.fragment.app.Fragment +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.fragment.app.activityViewModels +import androidx.lifecycle.asLiveData +import com.example.admin.Toast.showCustomDangerToast +import com.example.admin.Toast.showCustomInfoToast +import com.example.rehabilitation.Admin.activityAdmin.UserSettingActivity +import com.example.rehabilitation.MainActivity +import com.example.rehabilitation.counter1 +import com.example.rehabilitation.counter2 +import com.example.rehabilitation.databinding.FragmentAuthBinding +import com.example.rehabilitation.Room.MainDB +import com.example.rehabilitation.UserDoctorToken +import com.example.rehabilitation.UserPatientToken +import com.example.rehabilitation.model_adapter.Doctor.DoctorModel +import com.example.rehabilitation.model_adapter.Patient.PatientModel +import com.example.rehabilitation.pref +import com.example.rehabilitation.prefDoctor +import com.example.rehabilitation.prefUserDoctorToken +import com.example.rehabilitation.prefUserPatientToken +import com.example.rehabilitation.tokenClass +import com.example.rehabilitation.tokenClassDoctor +import com.example.sqlitework.dip.MainViewModel + + +class AuthFragment : Fragment() { + private lateinit var binding: FragmentAuthBinding + private val model: MainViewModel by activityViewModels()//Инициализировали класс + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + // Inflate the layout for this fragment + binding = FragmentAuthBinding.inflate(inflater, container, false) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + data_prefUserPatientToken() + + + livePatientAuthCurrent() + + + //Авиризация пациента + binding.buttonAuthorizationPatient.setOnClickListener { + var email = binding.editTextEmailPatient.text.toString() + var password = binding.editTextPasswordPatient.text.toString() + if (email != "" || password != "") { + AuthorizationPatient(email, password) + Log.d("Result", "email email - $email") + Log.d("Result", "password password - $password") + + } else { + Toast(requireContext()).showCustomInfoToast( + "Не все поля заполнены", + requireActivity() + ) + } + } + + //Если пользователь решил зайти в аккаунт врача и не подумал о том что не сможет вернуться со страницы авторизации, то он может нажать данную кнопку, и в случае если он был авторизован, то его вернет в приложение + binding.btnBack.setOnClickListener { + if (UserPatientToken != "") { + val intent = Intent(requireContext(), MainActivity::class.java) + startActivity(intent) + activity?.finish()//Закрываем старый экран, для того чтобы очитсить оперативную память от лишнего хранения экрана + + } else { + Toast(requireContext()).showCustomInfoToast("Авторизуйтесь", requireActivity()) + } + } + + + //Переход вход для врача + binding.txtDoctor.setOnClickListener { + val intent = Intent(requireContext(), AuthDoctorActivity::class.java) + startActivity(intent) + activity?.finish()//Закрываем старый экран, для того чтобы очитсить оперативную память от лишнего хранения экрана + + } + + + } + + + //Инициализация хранилища(для токена) и проверяем есть ли аккаунт и или перекидываем в авторизацую или остаемся на данном экране + fun data_prefUserPatientToken() { + prefUserPatientToken = + activity?.getSharedPreferences("UserPatientToken", Context.MODE_PRIVATE) + UserPatientToken = prefUserPatientToken?.getString( + "userpatienttoken", + "" + )!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0 + } + + //Записываем число + fun saveUserPatientToken(userpatienttoken: String) { + val editer = prefUserPatientToken?.edit() + editer?.putString("userpatienttoken", userpatienttoken) + editer?.apply() + UserPatientToken = userpatienttoken + } + + //Функция очистки данных + fun clearUserPatientToken() { + val edit = prefUserPatientToken?.edit() + edit?.clear() + edit?.apply() + UserPatientToken = "" + } + + + private fun AuthorizationPatient(login: String, password: String) { + val db = MainDB.getDB(requireContext()) + Log.d("Ressadsdasdasda3", "sadsdasdasda") + db.getDaoPatient().getAuthItemPatient(login, password).asLiveData() + .observe(requireActivity()) { itPatient -> + + if (itPatient.isNullOrEmpty()) { + val item = PatientModel( + "0", + "", + "", + "", + "", + "", + //it.email, + login, + "", + ) + model.liveAuthPatientCurrent.value = item + + } else { + val item = PatientModel( + itPatient[0].id.toString(), + "", + "", + "", + "", + "", + //it.email, + login, + "", + ) + model.liveAuthPatientCurrent.value = item + + } + } + } + + + private fun livePatientAuthCurrent() = with(binding) { + model.liveAuthPatientCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + Log.i("12312", "sadas") + if (it.id == "0") { + Log.i("4444", "4444") + Toast(requireContext()).showCustomDangerToast( + "Такого аккаунта нету", + requireActivity() + ) + } else { + Log.i("5555", "5555") + UserPatientToken = it.login + saveUserPatientToken(it.login) + + if (UserPatientToken != "") { + val intent = Intent(requireContext(), MainActivity::class.java) + activity?.finish()//Закрываем старый экран, для того чтобы очитсить оперативную память от лишнего хранения экрана + startActivity(intent) + } + } + + + } + + } + + override fun onDestroy() { + super.onDestroy() + activity?.finish() + } + companion object { + + fun newInstance() = AuthFragment() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Auth/AuthorizationActivity.kt b/app/src/main/java/com/example/rehabilitation/Auth/AuthorizationActivity.kt new file mode 100644 index 0000000..e9cfa63 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Auth/AuthorizationActivity.kt @@ -0,0 +1,32 @@ +package com.example.rehabilitation.Auth + +import android.os.Bundle +import androidx.appcompat.app.AppCompatActivity +import com.example.rehabilitation.R +import com.example.rehabilitation.databinding.ActivityAuthorizationBinding + + +class AuthorizationActivity : AppCompatActivity() { + private lateinit var binding: ActivityAuthorizationBinding + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + + binding = ActivityAuthorizationBinding.inflate(layoutInflater) + setContentView(binding.root) + supportFragmentManager.beginTransaction().replace(R.id.constraintLayoutAuth, AuthFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем + + + + + } + + + override fun onDestroy() { + super.onDestroy() + finish() + } + + +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Calendare/MonthCalendarViewHolder.kt b/app/src/main/java/com/example/rehabilitation/Calendare/MonthCalendarViewHolder.kt new file mode 100644 index 0000000..18bef86 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Calendare/MonthCalendarViewHolder.kt @@ -0,0 +1,5 @@ +package com.example.rehabilitation.Calendare + +class MonthCalendarViewHolder { + +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Hranilihe.kt b/app/src/main/java/com/example/rehabilitation/Hranilihe.kt new file mode 100644 index 0000000..16a3c66 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Hranilihe.kt @@ -0,0 +1,137 @@ +package com.example.rehabilitation + +import android.content.SharedPreferences +import com.example.rehabilitation.model_adapter.Month.MonthModel +import com.example.rehabilitation.model_adapter.Progress.AfterListModel +import com.example.rehabilitation.model_adapter.Progress.BeforeListModel +import com.example.rehabilitation.model_adapter.Progress.ProgressModel +import java.io.File +import java.io.FileOutputStream + +//Постоянное хранилище + +var prefUserPatientToken: SharedPreferences? = null +var UserPatientToken:String = "" +var prefUserDoctorToken: SharedPreferences? = null +var UserDoctorToken:String = "" +var prefPatientDoctorNew: SharedPreferences? = null +var PatientDoctorNew:Int = 0 + +var pref: SharedPreferences? = null +var prefDoctor: SharedPreferences? = null + +var prefSportCursNumber: SharedPreferences? = null +var prefCursDay: SharedPreferences? = null +var SportCursDay :Int = 0 + +//7 дней пройдено +var prefSport7Day: SharedPreferences? = null +var Sport7Day :Int = 0 + +//15 дней пройдено +var prefSport15Day: SharedPreferences? = null +var Sport15Day :Int = 0 + +//15 дней пройдено и отправлен отчет +var prefSport15DayAll: SharedPreferences? = null +var Sport15DayAll :Int = 0 + + +var prefSportCursDayNumber: SharedPreferences? = null +var SportCursDayNumber :Int = 0 + +var prefSport: SharedPreferences? = null +var SportUserTrue = 0 + +var prefCursDangerDayBefore: SharedPreferences? = null +var SportCursDayDangerBefore:Int = 0 +var prefCursDangerDayAfter: SharedPreferences? = null +var SportCursDayDangerAfter:Int = 0 +var prefCursDayNull: SharedPreferences? = null +var CursDayNull:String = "" + +var prefSportPlusCount: SharedPreferences? = null +var SportPlusCount:Int = 0 +var prefSportMaxCount: SharedPreferences? = null +var SportMaxCount:Int = 0 + +var prefDayBefore: SharedPreferences? = null +var DayBefore:String = "" +var prefDayAfter: SharedPreferences? = null +var DayAfter:String = "" + +var prefPauseDay: SharedPreferences? = null +var PauseDay:String = "" +var prefBlock: SharedPreferences? = null +var Block:String = "" + +var prefFIO: SharedPreferences? = null +var FIO:String = "" + +var prefEmailPatient: SharedPreferences? = null +var EmailPatient:String = "" + +//Дата начала тренировки +var prefSportDateStart: SharedPreferences? = null +var SportDateStart:String = "" + + + +var prefUser: SharedPreferences? = null +//Хранилище для анкеты +//var questionnaire: SharedPreferences? = null +var questionnaire_before :String = "" +var questionnaire_after:String = "" + +var nameSport :String = "" +var countSport:Int? = null +var countSportPlus:String = "" +//Ключи для хранилишь + + + +//Для пациента +var tokenClass:String = "" +var counter1:String = "" + +//Для врача +var counter2:String = "" +var tokenClassDoctor:String = "" + +var countCategory:String = "" + + +//Отчет по ребилитации +var listCheckSportDay:String = "" + +//Доктор +var loginDoctor:String = "maxi05092003" +//Пациент +var loginPatient:String = "t.t.maxi05092003@gmail.com" + +//Хранения отчета на время +var checkDaySportString:String = "" + +//Хранения для перехода на страницу +var daySpoartOpen:Int = 0 +var daySpoartOpenDate:String = "" +val daySpoartOpenKey:Int = 12321313 + //var itemDayOpenDate:MonthModel + + +//Анкетирование +var listBefore:List = listOf() +var listAfter:List = listOf() + + +//Прогрес +var listProgressAll:List = listOf() +var listProgressCheck:List = listOf() + + +var uriFileEF: File? =null +var fileUri2: FileOutputStream? =null +//Переменная для хранения дня, чтобы при нажатие на главной тсранице или в календаре +var dateHomeCalendare:String = "" +class Hranilihe { +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/InformationActivity.kt b/app/src/main/java/com/example/rehabilitation/InformationActivity.kt new file mode 100644 index 0000000..24cc224 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/InformationActivity.kt @@ -0,0 +1,31 @@ +package com.example.rehabilitation + +import android.content.Intent +import androidx.appcompat.app.AppCompatActivity +import android.os.Bundle +import androidx.appcompat.app.AlertDialog +import com.example.rehabilitation.User.fragmentUser.InformationFragment +import com.example.rehabilitation.User.fragmentUser.SceduleFragment +import com.example.rehabilitation.databinding.ActivityInformationBinding + +class InformationActivity : AppCompatActivity() { + var backPressedTime: Long = 0 + private lateinit var binding: ActivityInformationBinding + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityInformationBinding.inflate(layoutInflater) + setContentView(binding.root) + + supportFragmentManager.beginTransaction() + .replace(R.id.CLInformation, InformationFragment.newInstance()) + .commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем + } + + override fun onBackPressed() { + val intetn = Intent(this, MainActivity::class.java) + startActivity(intetn) + finish() + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/MainActivity.kt b/app/src/main/java/com/example/rehabilitation/MainActivity.kt index bed5581..c40cc58 100644 --- a/app/src/main/java/com/example/rehabilitation/MainActivity.kt +++ b/app/src/main/java/com/example/rehabilitation/MainActivity.kt @@ -1,18 +1,45 @@ package com.example.rehabilitation import android.annotation.SuppressLint +import android.content.Context import android.content.Intent +import android.icu.text.SimpleDateFormat +import android.icu.util.Calendar import android.os.Bundle +import android.util.Log +import android.widget.Toast +import androidx.activity.viewModels +import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity +import androidx.core.app.ActivityCompat +import androidx.core.view.GravityCompat +import androidx.lifecycle.LifecycleOwner +import com.example.rehabilitation.Auth.AuthDoctorActivity +import com.example.rehabilitation.Auth.AuthorizationActivity import com.example.rehabilitation.User.fragmentUser.CalendarFragment import com.example.rehabilitation.User.fragmentUser.HomeFragment import com.example.rehabilitation.User.fragmentUser.InformationFragment import com.example.rehabilitation.User.fragmentUser.ProgresFragment import com.example.rehabilitation.User.fragmentUser.SceduleFragment import com.example.rehabilitation.databinding.ActivityMainBinding +import com.example.rehabilitation.model_adapter.DataModel +import com.google.firebase.database.ktx.database +import com.google.firebase.ktx.Firebase +import java.time.LocalDate +import java.util.Date + class MainActivity : AppCompatActivity() { + + var backPressedTime: Long = 0 + private lateinit var binding: ActivityMainBinding + //Для постоянного охаранения данных(для токена) + //var pref: SharedPreferences? = null + private val dataModel: DataModel by viewModels()//Для передачи данных + var sdf: SimpleDateFormat = SimpleDateFormat("EEEE") + var d: Date = Date() + var dayOfTheWeek: String = sdf.format(d) @SuppressLint("DiscouragedApi") @@ -21,6 +48,15 @@ class MainActivity : AppCompatActivity() { binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) + //Функция инициализации хранилиша для токена + data_prefUserPatientToken() + + + dataModel.fragmentMenu.observe(this as LifecycleOwner, { + binding.buttonNavigation.selectedItemId = it + }) + + //Функция инициализации фрагметов fragment_inicializ() @@ -32,17 +68,171 @@ class MainActivity : AppCompatActivity() { binding.btnSetting.setOnClickListener { val intent = Intent(this, SettingActivity::class.java) startActivity(intent) + finish() + } + + binding.btnInformation.setOnClickListener { + val intent = Intent(this, InformationActivity::class.java) + startActivity(intent) + finish() + } + + + val database = Firebase.database + val myRef = database.getReference("message1235322") + + myRef.setValue("Hello, World!") + //binding.imageView3.resources.getIdentifier("b3_1","drawable",this.packageName); + + + //Выводим сегоднящнюю дату + addDate() + + + + } + + override fun onBackPressed() { + if (backPressedTime + 3000 > System.currentTimeMillis()) { + super.onBackPressed() + finish() + } else { + AlertDialog.Builder(this@MainActivity) + .setTitle("Выйти") + .setMessage("Вы точно хотите выйти из приложения?") + .setPositiveButton("Да") { dialog, whichButton -> + super.onBackPressed() + } + .setNegativeButton("Нет") { dialog, whichButton -> + + } + .show() + } + backPressedTime = System.currentTimeMillis() + } + + private fun addDate() { + val calendar: Calendar = Calendar.getInstance() + val sdf: SimpleDateFormat = SimpleDateFormat("EEEE") + val d: Date = Date() + val DayOfTheWeek: String = sdf.format(d) + val Day = calendar.get(Calendar.DATE) + val Month = calendar.get(Calendar.MONTH).plus(1) + var day = Day.toString() + var month = "" + var date_of_the_week = "" + + when (Month) { + 1 -> month="Январь" + 2 -> month="Февраль" + 3 -> month="Март" + 4 -> month="Апрель" + 5 -> month="Май" + 6 -> month="Июнь" + 7 -> month="Июль" + 8 -> month="Август" + 9 -> month="Сентябрь" + 10 -> month="Октябрь" + 11 -> month="Ноябрь" + 12 -> month="Декабрь" + else -> { // обратите внимание на блок + month="" + } + } + + when (dayOfTheWeek) { + "Monday" -> date_of_the_week="Пн" + "Tuesday" -> date_of_the_week="Вт" + "Wednesday" -> date_of_the_week="Ср" + "Thursday" -> date_of_the_week="Чт" + "Friday" -> date_of_the_week="Пт" + "Saturday" -> date_of_the_week="Сб" + "Sunday" -> date_of_the_week="Вс" + "Понедельник" -> date_of_the_week="Пн" + "Вторник" -> date_of_the_week="Вт" + "Стреда" -> date_of_the_week="Ср" + "Четверг" -> date_of_the_week="Чт" + "Пятница" -> date_of_the_week="Пт" + "Суббота" -> date_of_the_week="Сб" + "Воскресенье" -> date_of_the_week="Вс" + else -> { + date_of_the_week="" + } } - //binding.imageView3.resources.getIdentifier("b3_1","drawable",this.packageName); + System.out.println(calendar.get(Calendar.DATE)) + + //binding.txtDate.setText("${day}" +" "+ "${month}" +" "+ "(${date_of_the_week})") + binding.txtDate.setText("${day}" +" "+ "${month}") } +// interface IOnBackPressed { +// fun onBackPressed(): Boolean +// } +// +// override fun onBackPressed() { +// val fragment = +// this.supportFragmentManager.findFragmentById(R.id.placeHolderFragment) +// (fragment as? IOnBackPressed)?.onBackPressed()?.not()?.let { +// super.onBackPressed() +// } +// } +// override fun onBackPressed() { +// AlertDialog.Builder(this).apply { +// setTitle("Подтверждение") +// setMessage("Вы уверены, что хотите выйти из программы?") +// +// setPositiveButton("Таки да") { _, _ -> +// super.onBackPressed() +// } +// +// setNegativeButton("Нет"){_, _ -> +// // if user press no, then return the activity +// Toast.makeText(this@MainActivity, "Thank you", +// Toast.LENGTH_LONG).show() +// } +// setCancelable(true) +// }.create().show() +// } + + + //Инициализация хранилища(для токена) и проверяем есть ли аккаунт и или перекидываем в авторизацую или остаемся на данном экране + fun data_prefUserPatientToken() { + prefUserPatientToken = getSharedPreferences("UserPatientToken", Context.MODE_PRIVATE) + UserPatientToken = prefUserPatientToken?.getString("userpatienttoken", "")!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0 + + prefPatientDoctorNew = getSharedPreferences("PatientDoctorNew", Context.MODE_PRIVATE) + PatientDoctorNew = prefPatientDoctorNew?.getInt("patientdoctornew", 0)!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0 + + if (UserPatientToken == ""){ + if(PatientDoctorNew == 1){ + val intetn = Intent(this, AuthorizationActivity::class.java) + startActivity(intetn) + } + else{ + val intetn = Intent(this, AuthDoctorActivity::class.java) + startActivity(intetn) + } + + } + else{ + //Toast.makeText(this, "Добро пожаловать", Toast.LENGTH_SHORT).show() + } + } + //Записываем число + fun saveUserPatientToken(userpatienttoken: String) { + val editer = prefUserPatientToken?.edit() + editer?.putString("userpatienttoken", userpatienttoken) + editer?.apply() + UserPatientToken = userpatienttoken + } override fun onDestroy() { super.onDestroy() + finish() } override fun onResume() { @@ -54,12 +244,12 @@ class MainActivity : AppCompatActivity() { fun fragment_inicializ() { //Вывод фрагмента на активити при первоначальной загрузке supportFragmentManager.beginTransaction() - .replace(R.id.placeHolderFragment, HomeFragment.newInstance()) + .replace(R.id.placeHolderFragment, SceduleFragment.newInstance()) .commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем //Эран который будет выбран по умолчанию(кнопка которая будет прожата по умолчанию) - binding.buttonNavigation.selectedItemId = R.id.home//По умолчанию и так первая, но на всякий случай выберу еще програмным путем первую ячейку + binding.buttonNavigation.selectedItemId = R.id.schedule//По умолчанию и так первая, но на всякий случай выберу еще програмным путем первую ячейку //Нажатие на bottom navigation binding.buttonNavigation.setOnItemSelectedListener { @@ -71,17 +261,19 @@ class MainActivity : AppCompatActivity() { R.id.calendar -> { supportFragmentManager.beginTransaction().replace(R.id.placeHolderFragment, CalendarFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем } - R.id.home -> {//Если вы не авторизованный пользваотель то вам не будет доступен доступ к данном фрагменту - supportFragmentManager.beginTransaction().replace(R.id.placeHolderFragment, HomeFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем - } +// R.id.home -> {//Если вы не авторизованный пользваотель то вам не будет доступен доступ к данном фрагменту +// supportFragmentManager.beginTransaction().replace(R.id.placeHolderFragment, HomeFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем +// } R.id.progress -> {//Если вы не авторизованный пользваотель то вам не будет доступен доступ к данном фрагменту supportFragmentManager.beginTransaction().replace(R.id.placeHolderFragment, ProgresFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем } - R.id.information -> {//Если вы не авторизованный пользваотель то вам не будет доступен доступ к данном фрагменту - supportFragmentManager.beginTransaction().replace(R.id.placeHolderFragment, InformationFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем - } +// R.id.information -> {//Если вы не авторизованный пользваотель то вам не будет доступен доступ к данном фрагменту +// supportFragmentManager.beginTransaction().replace(R.id.placeHolderFragment, InformationFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем +// } } true } } + + } \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/db/Dao.kt b/app/src/main/java/com/example/rehabilitation/Room/Dao.kt similarity index 78% rename from app/src/main/java/com/example/rehabilitation/db/Dao.kt rename to app/src/main/java/com/example/rehabilitation/Room/Dao.kt index 63053bf..0c0ac5a 100644 --- a/app/src/main/java/com/example/rehabilitation/db/Dao.kt +++ b/app/src/main/java/com/example/rehabilitation/Room/Dao.kt @@ -1,9 +1,7 @@ -package com.example.rehabilitation.db +package com.example.rehabilitation.Room import androidx.room.Dao -import androidx.room.Delete import androidx.room.Insert -import androidx.room.OnConflictStrategy import androidx.room.Query import kotlinx.coroutines.flow.Flow @@ -16,7 +14,7 @@ interface Dao { //Список по дням - @Query("SELECT * FROM items ORDER BY day ASC") + @Query("SELECT * FROM items ORDER BY id ASC") fun getAllItems(): Flow> //Список определенного дня @@ -27,6 +25,9 @@ interface Dao { @Query("UPDATE items SET `check` = 1 WHERE id = :id") fun updateItems(id : String) + @Query("UPDATE items SET `day` = :day WHERE date = :date") + fun updateDay(day:String,date : String) + //Очистка таблицы @Query("DELETE FROM items") fun deleteItem() diff --git a/app/src/main/java/com/example/rehabilitation/Room/DaoDaySport.kt b/app/src/main/java/com/example/rehabilitation/Room/DaoDaySport.kt new file mode 100644 index 0000000..f5d8834 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/DaoDaySport.kt @@ -0,0 +1,60 @@ +package com.example.rehabilitation.Room + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import androidx.room.Update +import kotlinx.coroutines.flow.Flow + + +@Dao +interface DaoDaySport { + //Таблица определенного дня + @Insert + fun insertItemDaySport(itemDaySport:ItemDaySport) + + //Список определенного дня + @Query("SELECT * FROM DaySport ORDER BY day ASC") + fun getAllItemDaySportDay(): Flow> + + //Список определенного дня + @Query("SELECT * FROM DaySport WHERE day = :day AND visible = 1") + fun getAllItemDaySport(day:String): Flow> + + + //Список определенного дня + @Query("SELECT id,day,category, `check`,COUNT(*) as visible FROM DaySport WHERE visible='1' GROUP BY day ORDER BY day ASC") + fun getAllProgres(): Flow> + + //Список определенного дня + @Query("SELECT id,day,category, COUNT(*) as `check`, visible FROM DaySport WHERE `check`='1' and visible='1' GROUP BY day ORDER BY day ASC") + fun getcheckProgress(): Flow> + //Получаем любую рандомну строку для того чтобы использовать его дату в редактирование списка + @Query("SELECT * FROM DaySport ORDER BY day DESC LIMIT 1") + fun getItemDaySportRandomOne(): Flow> + + @Update + fun updateCheckDaySport(itemDaySport: ItemDaySport) + + @Query("SELECT DaySport.id as id ,DaySport.day as day,DaySport.category as category, DaySport.`check` as `check`,DaySport.visible as visible, SportCategory.`desc` as `desc`, SportCategory.image as categoryImage FROM DaySport JOIN SportCategory ON DaySport.category = SportCategory.category WHERE DaySport.day == :date ORDER BY day ASC") + fun getListJoinDaySportAndSportCategory(date:String): Flow> + + //Обновляем видимость у записей с данным + @Query("UPDATE DaySport SET visible = 1 WHERE category = :category AND day>=:date") + fun updateVisibleDaySportTrue(category:String,date :String) + @Query("UPDATE DaySport SET visible = 0 WHERE category = :category AND day>=:date") + fun updateVisibleDaySportFalse(category:String,date :String) + + + //Обновление что выполнил упражнение + @Query("UPDATE DaySport SET `check` = 1 WHERE id = :id") + fun updateCheckDaySport(id:Int) + + @Query("UPDATE DaySport SET `check` = 2 WHERE id = :id") + fun updateNoCheckDaySport(id:Int) + + //Очистка таблицы + @Query("DELETE FROM DaySport") + fun deleteItemDaySport() + +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/db/DaoImage.kt b/app/src/main/java/com/example/rehabilitation/Room/DaoImage.kt similarity index 73% rename from app/src/main/java/com/example/rehabilitation/db/DaoImage.kt rename to app/src/main/java/com/example/rehabilitation/Room/DaoImage.kt index 0f1603f..6c58912 100644 --- a/app/src/main/java/com/example/rehabilitation/db/DaoImage.kt +++ b/app/src/main/java/com/example/rehabilitation/Room/DaoImage.kt @@ -1,4 +1,4 @@ -package com.example.rehabilitation.db +package com.example.rehabilitation.Room import androidx.room.Dao import androidx.room.Insert @@ -12,15 +12,15 @@ interface DaoImage { fun insertItemImage(itemImage:ItemImage) //Список определенного дня - @Query("SELECT * FROM itemImage ") + @Query("SELECT * FROM Image") fun getAllItemImage(): Flow> //Список определенного дня - @Query("SELECT * FROM itemImage WHERE article = :article ORDER BY id ASC") + @Query("SELECT * FROM Image WHERE article = :article ORDER BY id ASC") fun getAllItemImage(article:String): Flow> //Очистка таблицы - @Query("DELETE FROM itemImage") + @Query("DELETE FROM Image") fun deleteItemImage() } \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Room/DaoSportCategory.kt b/app/src/main/java/com/example/rehabilitation/Room/DaoSportCategory.kt new file mode 100644 index 0000000..d335f36 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/DaoSportCategory.kt @@ -0,0 +1,53 @@ +package com.example.rehabilitation.Room + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import kotlinx.coroutines.flow.Flow + +@Dao +interface DaoSportCategory { + //Таблица по по дням + @Insert + fun insertItemSportCategory(item:ItemSportCategory) + //Таблица определенного дня + + + //Список по дням + @Query("SELECT * FROM SportCategory WHERE category = :category") + fun getAllItemsSportCategory(category:String): Flow> + + + +// @Query("SELECT * FROM SportCategory WHERE image = :category") +// fun getAllItemsSportCategoryEdit(category:String): Flow> +// + + @Query("SELECT id, name, `desc`, count,COUNT(*) as image,category,article,`check` FROM SportCategory WHERE image = :category and `check`=0") + fun getAllItemsSportCategoryCount(category:String): Flow> + + @Query("SELECT id, name, `desc`,COUNT(*) as count,image,category,article,`check` FROM SportCategory WHERE image = :category and `check`=0") + fun getAllItemsSportCategoryCountSport(category:String): Flow> + + //По артикулу + @Query("SELECT id, name, `desc`,COUNT(*) as count,image,category,article,`check` FROM SportCategory WHERE article = :article") + fun getSportArticle(article:String): Flow> + + //Rjkbxtcndj eghf;ytybq + @Query("SELECT id, COUNT(*) as name, `desc`, count, image,category,article,`check` FROM SportCategory WHERE article = :article and `check` = 0") + fun getCountSportCategory(article:String): Flow> + + + //Список определенного дня +// @Query("SELECT * FROM itemDay") +// fun getAllItemDay(): Flow> + + //Обновление по переднному параметру +// @Query("UPDATE itemSportCategory SET `check` = 1 WHERE id = :id") +// fun updateItemsSportCategory(id : String) + + //Очистка таблицы +// @Query("DELETE FROM SportCategory") +// fun deleteItemSportCategory() + +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/db/DaoSportCategory.kt b/app/src/main/java/com/example/rehabilitation/Room/DaoSportPatient.kt similarity index 60% rename from app/src/main/java/com/example/rehabilitation/db/DaoSportCategory.kt rename to app/src/main/java/com/example/rehabilitation/Room/DaoSportPatient.kt index 4fb85cb..dfe8a4c 100644 --- a/app/src/main/java/com/example/rehabilitation/db/DaoSportCategory.kt +++ b/app/src/main/java/com/example/rehabilitation/Room/DaoSportPatient.kt @@ -1,23 +1,21 @@ -package com.example.rehabilitation.db +package com.example.rehabilitation.Room import androidx.room.Dao -import androidx.room.Delete import androidx.room.Insert -import androidx.room.OnConflictStrategy import androidx.room.Query import kotlinx.coroutines.flow.Flow @Dao -interface DaoSportCategory { +interface DaoSportPatient { //Таблица по по дням @Insert - fun insertItemSportCategory(item:ItemSportCategory) + fun insertItemSportPatient(item:ItemSportPatient) //Таблица определенного дня //Список по дням - @Query("SELECT * FROM itemSportCategory WHERE image = :category") - fun getAllItemsSportCategory(category:String): Flow> + @Query("SELECT * FROM SportPatient WHERE image = :category") + fun getAllItemsSportPatient(category:String): Flow> //Список определенного дня // @Query("SELECT * FROM itemDay") @@ -28,7 +26,7 @@ interface DaoSportCategory { // fun updateItemsSportCategory(id : String) //Очистка таблицы - @Query("DELETE FROM itemSportCategory") - fun deleteItemSportCategory() +// @Query("DELETE FROM SportPatient") +// fun deleteItemSportPatient() } \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/db/Item.kt b/app/src/main/java/com/example/rehabilitation/Room/Item.kt similarity index 78% rename from app/src/main/java/com/example/rehabilitation/db/Item.kt rename to app/src/main/java/com/example/rehabilitation/Room/Item.kt index 6dcdacb..c3a7b82 100644 --- a/app/src/main/java/com/example/rehabilitation/db/Item.kt +++ b/app/src/main/java/com/example/rehabilitation/Room/Item.kt @@ -1,11 +1,10 @@ -package com.example.rehabilitation.db +package com.example.rehabilitation.Room import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey -import java.util.Date -@Entity(tableName = "items") +@Entity(tableName = "Items") data class Item( @PrimaryKey(autoGenerate = true) var id:Int? = null, diff --git a/app/src/main/java/com/example/rehabilitation/db/ItemDaySport.kt b/app/src/main/java/com/example/rehabilitation/Room/ItemDaySport.kt similarity index 73% rename from app/src/main/java/com/example/rehabilitation/db/ItemDaySport.kt rename to app/src/main/java/com/example/rehabilitation/Room/ItemDaySport.kt index 67018bf..4ad6d72 100644 --- a/app/src/main/java/com/example/rehabilitation/db/ItemDaySport.kt +++ b/app/src/main/java/com/example/rehabilitation/Room/ItemDaySport.kt @@ -1,10 +1,10 @@ -package com.example.rehabilitation.db +package com.example.rehabilitation.Room import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey -@Entity(tableName = "itemDaySport") +@Entity(tableName = "DaySport") data class ItemDaySport( @PrimaryKey(autoGenerate = true) var id:Int? = null, @@ -14,5 +14,7 @@ data class ItemDaySport( var category:String, @ColumnInfo(name = "check") var check:Int, + @ColumnInfo(name = "visible") + var visible:Int, ) diff --git a/app/src/main/java/com/example/rehabilitation/Room/ItemDaySportAndSportCategory.kt b/app/src/main/java/com/example/rehabilitation/Room/ItemDaySportAndSportCategory.kt new file mode 100644 index 0000000..0bc434e --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/ItemDaySportAndSportCategory.kt @@ -0,0 +1,24 @@ +package com.example.rehabilitation.Room + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "ItemDaySportAndSportCategory") +data class ItemDaySportAndSportCategory( + @ColumnInfo(name = "id") + var id:Int, + @ColumnInfo(name = "day") + var day:String, + @ColumnInfo(name = "category") + var category:String, + @ColumnInfo(name = "check") + var check:Int, + @ColumnInfo(name = "visible") + var visible:Int, + @ColumnInfo(name = "desc") + var desc:String, + @ColumnInfo(name = "categoryImage") + var categoryImage:String, +) + diff --git a/app/src/main/java/com/example/rehabilitation/db/ItemImage.kt b/app/src/main/java/com/example/rehabilitation/Room/ItemImage.kt similarity index 83% rename from app/src/main/java/com/example/rehabilitation/db/ItemImage.kt rename to app/src/main/java/com/example/rehabilitation/Room/ItemImage.kt index 2693b22..98dbadf 100644 --- a/app/src/main/java/com/example/rehabilitation/db/ItemImage.kt +++ b/app/src/main/java/com/example/rehabilitation/Room/ItemImage.kt @@ -1,10 +1,10 @@ -package com.example.rehabilitation.db +package com.example.rehabilitation.Room import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey -@Entity(tableName = "itemImage") +@Entity(tableName = "Image") data class ItemImage( @PrimaryKey(autoGenerate = true) var id:Int? = null, diff --git a/app/src/main/java/com/example/rehabilitation/Room/ItemProgressAll.kt b/app/src/main/java/com/example/rehabilitation/Room/ItemProgressAll.kt new file mode 100644 index 0000000..419dff9 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/ItemProgressAll.kt @@ -0,0 +1,16 @@ +package com.example.rehabilitation.Room + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "ItemProgressAll") +data class ItemProgressAll( + @ColumnInfo(name = "date") + var date:String, + @ColumnInfo(name = "countAll") + var countAll:Int, + @ColumnInfo(name = "category") + var category:String, + +) diff --git a/app/src/main/java/com/example/rehabilitation/Room/ItemProgressCheck.kt b/app/src/main/java/com/example/rehabilitation/Room/ItemProgressCheck.kt new file mode 100644 index 0000000..438fe0f --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/ItemProgressCheck.kt @@ -0,0 +1,16 @@ +package com.example.rehabilitation.Room + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "ItemProgressCheck") +data class ItemProgressCheck( + @ColumnInfo(name = "date") + var date:String, + @ColumnInfo(name = "countCheck") + var countCheck:Int, + @ColumnInfo(name = "category") + var category:String, + +) diff --git a/app/src/main/java/com/example/rehabilitation/Room/ItemProgressDay.kt b/app/src/main/java/com/example/rehabilitation/Room/ItemProgressDay.kt new file mode 100644 index 0000000..0ab75ad --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/ItemProgressDay.kt @@ -0,0 +1,20 @@ +package com.example.rehabilitation.Room + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "ItemProgressDay") +data class ItemProgressDay( + @PrimaryKey(autoGenerate = true) + var id:Int? = null, + @ColumnInfo(name = "countAll") + var countAll:Int, + @ColumnInfo(name = "CountCheckTrue") + var CountCheckTrue:Int, + @ColumnInfo(name = "category") + var category:String, + @ColumnInfo(name = "date") + var date:Int, + +) diff --git a/app/src/main/java/com/example/rehabilitation/Room/ItemSportCategory.kt b/app/src/main/java/com/example/rehabilitation/Room/ItemSportCategory.kt new file mode 100644 index 0000000..37a14a2 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/ItemSportCategory.kt @@ -0,0 +1,26 @@ +package com.example.rehabilitation.Room + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "SportCategory") +data class ItemSportCategory( + @PrimaryKey(autoGenerate = true) + var id: Int? = null, + @ColumnInfo(name = "name") + var name: String, + @ColumnInfo(name = "desc") + var desc: String, + @ColumnInfo(name = "count") + var count: String, + @ColumnInfo(name = "image") + var image: String, + @ColumnInfo(name = "category") + var category: String, + @ColumnInfo(name = "article") + var article: String, + @ColumnInfo(name = "check") + var check: Int +) + diff --git a/app/src/main/java/com/example/rehabilitation/Room/ItemSportCategoryCount.kt b/app/src/main/java/com/example/rehabilitation/Room/ItemSportCategoryCount.kt new file mode 100644 index 0000000..da4ef55 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/ItemSportCategoryCount.kt @@ -0,0 +1,9 @@ +package com.example.rehabilitation.Room + +import androidx.room.ColumnInfo + +data class ItemSportCategoryCount( + @ColumnInfo(name = "count") + var count:String, +) + diff --git a/app/src/main/java/com/example/rehabilitation/db/ItemSportCategory.kt b/app/src/main/java/com/example/rehabilitation/Room/ItemSportPatient.kt similarity index 66% rename from app/src/main/java/com/example/rehabilitation/db/ItemSportCategory.kt rename to app/src/main/java/com/example/rehabilitation/Room/ItemSportPatient.kt index 7a15ad4..be32033 100644 --- a/app/src/main/java/com/example/rehabilitation/db/ItemSportCategory.kt +++ b/app/src/main/java/com/example/rehabilitation/Room/ItemSportPatient.kt @@ -1,12 +1,11 @@ -package com.example.rehabilitation.db +package com.example.rehabilitation.Room import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey -import java.util.Date -@Entity(tableName = "itemSportCategory") -data class ItemSportCategory( +@Entity(tableName = "SportPatient") +data class ItemSportPatient( @PrimaryKey(autoGenerate = true) var id:Int? = null, @ColumnInfo(name = "name") @@ -17,7 +16,7 @@ data class ItemSportCategory( var count:String, @ColumnInfo(name = "image") var image:String, - @ColumnInfo(name = "category") - var category:String + @ColumnInfo(name = "day") + var day:String ) diff --git a/app/src/main/java/com/example/rehabilitation/Room/MainDB.kt b/app/src/main/java/com/example/rehabilitation/Room/MainDB.kt new file mode 100644 index 0000000..6e8d922 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/MainDB.kt @@ -0,0 +1,162 @@ +package com.example.rehabilitation.Room + +import android.content.Context +import androidx.room.Database +import androidx.room.Room.databaseBuilder +import androidx.room.RoomDatabase +import com.example.rehabilitation.Room.Questionnaire.After.DaoAfterQuestionnaire +import com.example.rehabilitation.Room.Questionnaire.After.ItemAfterQuestionnaire +import com.example.rehabilitation.Room.Questionnaire.Before.DaoBeforeQuestionnaire +import com.example.rehabilitation.Room.Questionnaire.Before.ItemBeforeQuestionnaire +import com.example.rehabilitation.Room.dbUser.dbDoctor.DaoDoctor +import com.example.rehabilitation.Room.dbUser.dbDoctor.ItemDoctor +import com.example.rehabilitation.Room.dbUser.dbPatient.DaoPatient +import com.example.rehabilitation.Room.dbUser.dbPatient.ItemPatient + + +@Database(entities = [ + Item::class, + ItemDaySport::class, + ItemImage::class, + ItemSportCategory::class, + ItemSportPatient::class, + ItemDoctor::class, + ItemPatient::class, + ItemBeforeQuestionnaire::class, + ItemAfterQuestionnaire::class, +], version = 12) +abstract class MainDB: RoomDatabase() { + + abstract fun getDao(): Dao + abstract fun getDaoDaySport(): DaoDaySport + abstract fun getDaoImage(): DaoImage + abstract fun getDaoSportCategory(): DaoSportCategory + abstract fun getDaoSportPatient(): DaoSportPatient + abstract fun getDaoDoctor(): DaoDoctor + abstract fun getDaoPatient(): DaoPatient + abstract fun getDaoQB(): DaoBeforeQuestionnaire + abstract fun getDaoQA(): DaoAfterQuestionnaire + // + + companion object{ +// fun getDB(context: Context):MainDB{ +// return Room.databaseBuilder( +// context.applicationContext, +// MainDB::class.java, +// "ClogonV22.db" +// ).build() +// +// } +//private val DB_NAME: String? = "ReabilitationV2.db" +// +// fun buildDatabase(context: Context): MainDB? { +// val dbFile = context.getDatabasePath(DB_NAME) +// if (!dbFile.exists()) { +// copyDatabaseFile(dbFile.absolutePath) +// } +// return databaseBuilder( +// context.applicationContext, +// MainDB::class.java, DB_NAME +// ) +// .build() +// } +// +// private fun copyDatabaseFile(destinationPath: String) { +// // code to copy the file from assets/database directory to destinationPath +// } + fun getDB(context: Context):MainDB{ + return databaseBuilder(context, MainDB::class.java,"ReabilitationV4.db") + .createFromAsset("ReabilitationV4.db") + .fallbackToDestructiveMigration() + .build() + } + + } +} + +/*abstract class MainDB: RoomDatabase(){ + abstract fun getDao(): Dao + abstract fun getDaoDaySport(): DaoDaySport + abstract fun getDaoImage(): DaoImage + abstract fun getDaoSportCategory(): DaoSportCategory + abstract fun getDaoSportPatient(): DaoSportPatient + override fun init(configuration: DatabaseConfiguration) { + importExistingDatabase( + configuration.context, + true + ) //<<<<<<<<<< Invokes the Import of the Exisiting Database. + super.init(configuration) + } + + private fun importExistingDatabase(context: Context, throw_exception: Boolean) { + val buffer_size = 32768 + val dbpath = context.getDatabasePath(DBNAME) + if (dbpath.exists()) { + return // Database already exists + } + // Just in case make the directories + val dirs = File(dbpath.parent) + dirs.mkdirs() + var stage = 0 + val buffer = ByteArray(buffer_size) + var total_bytes_read: Long = 0 + var total_bytes_written: Long = 0 + var bytes_read = 0 + try { + val assetdb = context.assets.open(DBNAME) + stage++ + dbpath.createNewFile() + stage++ + val realdb: OutputStream = FileOutputStream(dbpath) + stage++ + while (assetdb.read(buffer).also { bytes_read = it } > 0) { + total_bytes_read = total_bytes_read + bytes_read + realdb.write(buffer, 0, bytes_read) + total_bytes_written = total_bytes_written + bytes_read + } + stage++ + realdb.flush() + stage++ + assetdb.close() + stage++ + realdb.close() + stage++ + } catch (e: IOException) { + var failed_at = "" + when (stage) { + 0 -> failed_at = "Opening Asset " + DBNAME + 1 -> failed_at = "Creating Output Database " + dbpath.absolutePath + 2 -> failed_at = "Genreating Database OutputStream " + dbpath.absolutePath + 3 -> failed_at = "Copying Data from Asset Database to Output Database. " + + " Bytes read=" + total_bytes_read.toString() + + " Bytes written=" + total_bytes_written.toString() + + 4 -> failed_at = "Flushing Written Data ($total_bytes_written bytes written)" + 5 -> failed_at = "Closing Asset Database File." + 6 -> failed_at = "Closing Created Database File." + } + val msg = + """An error was encountered copying the Database from the asset file to New Database. The error was encountered whilst :- + $failed_at""" + Log.e("IMPORTDATABASE", msg) + e.printStackTrace() + if (throw_exception) { + throw RuntimeException(msg) + } + } + } + + companion object { + const val DBNAME = "ClogonV3.db" + const val TB_MYTABLE = "mytable" + const val TB_MYOTHERTABLE = "myothertable" + const val TB_MYMAPPINGTABLE = "mymappingtable" + const val COL_MYTABLE_ID = BaseColumns._ID + const val COL_MYTABLE_NAME = "_name" + const val COL_MYTABLE_DESCRIPTION = "_description" + const val COL_MYOTHERTABLE_ID = BaseColumns._ID + const val COL_MYOTHERTABLE_OTHERDETAILS = "_otherdetails" + const val COL_MYMAPPINGTABLE_MYTABLEREFERENCE = "_mytable_reference" + const val COL_MYMAPPINGTABLE_MYOTEHERTABLEREFERENCE = "_myothertable_reference" + } +}*/ diff --git a/app/src/main/java/com/example/rehabilitation/Room/Questionnaire/After/DaoAfterQuestionnaire.kt b/app/src/main/java/com/example/rehabilitation/Room/Questionnaire/After/DaoAfterQuestionnaire.kt new file mode 100644 index 0000000..090bf99 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/Questionnaire/After/DaoAfterQuestionnaire.kt @@ -0,0 +1,44 @@ +package com.example.rehabilitation.Room.Questionnaire.After + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import com.example.rehabilitation.Room.Item +import com.example.rehabilitation.Room.Questionnaire.Before.ItemBeforeQuestionnaire +import kotlinx.coroutines.flow.Flow + +@Dao +interface DaoAfterQuestionnaire { + //Таблица по по дням + @Insert + fun insertAQ(itemAfterQuestionnaire: ItemAfterQuestionnaire) + //Таблица определенного дня + + +//// //Список по дням +// @Query("SELECT * FROM AfterQuestionnaire ORDER BY date ASC") +// fun getAllAQ(): Flow> + + + //Весь список + @Query("SELECT * FROM AfterQuestionnaire ORDER BY date ASC") + fun getAllAQProgress(): Flow> + + + //Список определенного дня + @Query("SELECT * FROM AfterQuestionnaire WHERE date = :date") + fun getAllAQDay(date:String): Flow> + + //Список определенного дня + @Query("SELECT * FROM AfterQuestionnaire WHERE date = :date") + fun getAllProgress(date:String): Flow> + + //Обновление по переднному параметру + //@Query("UPDATE AfterQuestionnaire SET `check` = 1 WHERE id = :id") + //fun updateAQ(id : String) + + //Очистка таблицы + @Query("DELETE FROM AfterQuestionnaire") + fun deleteAQ() + +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Room/Questionnaire/After/ItemAfterQuestionnaire.kt b/app/src/main/java/com/example/rehabilitation/Room/Questionnaire/After/ItemAfterQuestionnaire.kt new file mode 100644 index 0000000..54740d9 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/Questionnaire/After/ItemAfterQuestionnaire.kt @@ -0,0 +1,38 @@ +package com.example.rehabilitation.Room.Questionnaire.After + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "AfterQuestionnaire") +data class ItemAfterQuestionnaire( + @PrimaryKey(autoGenerate = true) + var id:Int? = null, + @ColumnInfo(name = "one") + var one: String, + @ColumnInfo(name = "two") + var two: String, + @ColumnInfo(name = "three") + var three: String, + @ColumnInfo(name = "four") + var four:String, + @ColumnInfo(name = "five") + var five:String, + @ColumnInfo(name = "six") + var six:String, + @ColumnInfo(name = "seven") + var seven:String, + @ColumnInfo(name = "eight") + var eight:String, + @ColumnInfo(name = "nine") + var nine:String, + @ColumnInfo(name = "ten") + var ten:String, + @ColumnInfo(name = "eleven") + var elevenInt:String, + @ColumnInfo(name = "twelve") + var twelve:String, + @ColumnInfo(name = "date") + var date:String, + ) + diff --git a/app/src/main/java/com/example/rehabilitation/Room/Questionnaire/Before/DaoBeforeQuestionnaire.kt b/app/src/main/java/com/example/rehabilitation/Room/Questionnaire/Before/DaoBeforeQuestionnaire.kt new file mode 100644 index 0000000..cfaa9c3 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/Questionnaire/Before/DaoBeforeQuestionnaire.kt @@ -0,0 +1,38 @@ +package com.example.rehabilitation.Room.Questionnaire.Before + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import com.example.rehabilitation.Room.Item +import com.example.rehabilitation.Room.Questionnaire.After.ItemAfterQuestionnaire +import kotlinx.coroutines.flow.Flow + +@Dao +interface DaoBeforeQuestionnaire { + //Таблица по по дням + @Insert + fun insertBQ(item: ItemBeforeQuestionnaire) + //Таблица определенного дня + + +// // //Список по дням +// @Query("SELECT * FROM BeforeQuestionnaire ORDER BY date ASC") +// fun getAllBQ(): Flow> + + //Весь список + @Query("SELECT * FROM BeforeQuestionnaire ORDER BY date ASC") + fun getAllBQProgress(): Flow> + + //Список определенного дня + @Query("SELECT * FROM BeforeQuestionnaire WHERE date = :date") + fun getAllBQDay(date:String): Flow> + + //Обновление по переднному параметру + //@Query("UPDATE BeforeQuestionnaire SET `check` = 1 WHERE id = :id") + //fun updateBQ(id : String) + + //Очистка таблицы + @Query("DELETE FROM BeforeQuestionnaire") + fun deleteBQ() + +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Room/Questionnaire/Before/ItemBeforeQuestionnaire.kt b/app/src/main/java/com/example/rehabilitation/Room/Questionnaire/Before/ItemBeforeQuestionnaire.kt new file mode 100644 index 0000000..36c9bb0 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/Questionnaire/Before/ItemBeforeQuestionnaire.kt @@ -0,0 +1,33 @@ +package com.example.rehabilitation.Room.Questionnaire.Before + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "BeforeQuestionnaire") +data class ItemBeforeQuestionnaire( + @PrimaryKey(autoGenerate = true) + var id:Int? = null, + @ColumnInfo(name = "one") + var one: String, + @ColumnInfo(name = "two") + var two: String, + @ColumnInfo(name = "three") + var three: String, + @ColumnInfo(name = "four") + var four:String, + @ColumnInfo(name = "five") + var five:String, + @ColumnInfo(name = "six") + var six:String, + @ColumnInfo(name = "seven") + var seven:String, + @ColumnInfo(name = "eight") + var eight:String, + @ColumnInfo(name = "nine") + var nine:String, + + @ColumnInfo(name = "date") + var date:String, + ) + diff --git a/app/src/main/java/com/example/rehabilitation/Room/dbUser/dbDoctor/DaoDoctor.kt b/app/src/main/java/com/example/rehabilitation/Room/dbUser/dbDoctor/DaoDoctor.kt new file mode 100644 index 0000000..7619fa6 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/dbUser/dbDoctor/DaoDoctor.kt @@ -0,0 +1,51 @@ +package com.example.rehabilitation.Room.dbUser.dbDoctor + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import androidx.room.Update +import com.example.rehabilitation.Room.dbUser.dbPatient.ItemPatient +import kotlinx.coroutines.flow.Flow + + +@Dao +interface DaoDoctor { + //Таблица определенного дня + @Insert + fun insertItemDoctor(itemDoctor:ItemDoctor) + + //Список врачей + @Query("SELECT * FROM Doctor ORDER BY id ASC") + fun getAllItemDoctor(): Flow> + + //Список врачей + @Query("SELECT * FROM Doctor WHERE login") + fun getItemDoctor(): Flow> + + //Опредеоение авторизованного врача + @Query("SELECT * FROM Doctor WHERE login = :login AND password = :password") + fun getAuthItemDoctor(login:String, password:String): Flow> + + //Опредеоение авторизованного пациента + @Query("SELECT * FROM Doctor WHERE login = :login") + fun getAuthItemDoctorOutput(login:String): Flow> + + //Список определенного дня +// @Query("SELECT * FROM Doctor WHERE day = :day") +// fun getAllItemDaySport(day:String): Flow> + + + //Обновление что выполнил упражнение + @Query("UPDATE Doctor SET name = :name, surname = :surname, patronymic= :patronymic,login=:login,password=:password WHERE login =:loginOld") + fun updateDoctor(loginOld:String, name:String,surname:String,patronymic:String,login:String,password: String) + + + //Обновление что выполнил упражнение +// @Query("UPDATE Doctor SET `check` = 1 WHERE id = :id") +// fun updateDoctor(id:Int) + + //Очистка таблицы +// @Query("DELETE FROM Doctor") +// fun deleteItemDaySport() + +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Room/dbUser/dbDoctor/ItemDoctor.kt b/app/src/main/java/com/example/rehabilitation/Room/dbUser/dbDoctor/ItemDoctor.kt new file mode 100644 index 0000000..0a4005b --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/dbUser/dbDoctor/ItemDoctor.kt @@ -0,0 +1,23 @@ +package com.example.rehabilitation.Room.dbUser.dbDoctor + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "Doctor") +data class ItemDoctor( + @PrimaryKey(autoGenerate = true) + var id:Int? = null, + @ColumnInfo(name = "name")//Имя + var name:String, + @ColumnInfo(name = "surname")//Фамилия + var surname:String, + @ColumnInfo(name = "patronymic")//Отчество + var patronymic:String, +// @ColumnInfo(name = "email")//Логин +// var email:String, + @ColumnInfo(name = "login")//Логин + var login:String, + @ColumnInfo(name = "password")//Пароль + var password:String, +) diff --git a/app/src/main/java/com/example/rehabilitation/Room/dbUser/dbPatient/DaoPatient.kt b/app/src/main/java/com/example/rehabilitation/Room/dbUser/dbPatient/DaoPatient.kt new file mode 100644 index 0000000..f434217 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/dbUser/dbPatient/DaoPatient.kt @@ -0,0 +1,47 @@ +package com.example.rehabilitation.Room.dbUser.dbPatient + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import kotlinx.coroutines.flow.Flow + + +@Dao +interface DaoPatient { + //Таблица определенного дня + @Insert + fun insertItemPatient(itemPatient:ItemPatient) + + //Список пациентов + @Query("SELECT * FROM Patient ORDER BY id ASC") + fun getAllItemPatient(): Flow> + + //Опредеоение авторизованного пациента + @Query("SELECT * FROM Patient WHERE login = :login AND password = :password") + fun getAuthItemPatient(login:String, password:String): Flow> + + //Опредеоение авторизованного пациента + @Query("SELECT count(*)as id,name,surname,patronymic,diagnosis,number_of_courses,login,password FROM Patient WHERE login = :login AND password = :password") + fun getAuthItemPatient2(login:String, password:String): Flow> + //Опредеоение авторизованного пациента + @Query("SELECT * FROM Patient WHERE login = :login") + fun getAuthItemPatientOutput(login:String): Flow> + + //Опредеоение авторизованного пациента + @Query("DELETE FROM Patient WHERE login = :login") + fun deletePatient(login:String) +// @Update +// fun updateCheckDaySport(itemPatient: ItemPatient) + + //Обновление что выполнил упражнение + @Query("UPDATE Patient SET name = :name, surname = :surname, patronymic= :patronymic,diagnosis=:diagnosis,login=:login,password=:password WHERE login =:loginOld") + fun updatePatient(loginOld:String, name:String,surname:String,patronymic:String,diagnosis:String,login:String,password: String) + + @Query("SELECT (SELECT COUNT(*) FROM Patient) == 0") + fun isPatientNull(): Boolean + + //Очистка таблицы +// @Query("DELETE FROM Patient") +// fun deleteItemPatient() + +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Room/dbUser/dbPatient/ItemPatient.kt b/app/src/main/java/com/example/rehabilitation/Room/dbUser/dbPatient/ItemPatient.kt new file mode 100644 index 0000000..4b096b6 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Room/dbUser/dbPatient/ItemPatient.kt @@ -0,0 +1,28 @@ +package com.example.rehabilitation.Room.dbUser.dbPatient + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "Patient") +data class ItemPatient( + @PrimaryKey(autoGenerate = true) + var id:Int? = null, + @ColumnInfo(name = "name")//Имя + var name:String, + @ColumnInfo(name = "surname")//Фамилия + var surname:String, + @ColumnInfo(name = "patronymic")//Отчество + var patronymic:String, + @ColumnInfo(name = "diagnosis")//Диагноз + var diagnosis:String, + @ColumnInfo(name = "number_of_courses")//Дата рождения + var number_of_courses:Int, +// @ColumnInfo(name = "email")//Логин +// var email:String, + @ColumnInfo(name = "login")//Логин + var login:String, + @ColumnInfo(name = "password")//Пароль + var password:String, + +) diff --git a/app/src/main/java/com/example/rehabilitation/SettingActivity.kt b/app/src/main/java/com/example/rehabilitation/SettingActivity.kt index 4ee6f56..0f65ade 100644 --- a/app/src/main/java/com/example/rehabilitation/SettingActivity.kt +++ b/app/src/main/java/com/example/rehabilitation/SettingActivity.kt @@ -1,24 +1,25 @@ package com.example.rehabilitation +import android.content.Context import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle +import androidx.appcompat.app.AlertDialog import com.example.rehabilitation.Admin.activityAdmin.FeedbackActivity -import com.example.rehabilitation.Admin.activityAdmin.StatisticsActivity import com.example.rehabilitation.Admin.activityAdmin.UserSettingActivity import com.example.rehabilitation.databinding.ActivitySettingBinding -import com.example.rehabilitation.Admin.fragmrntAdmin.FeedbackFragment -import com.example.rehabilitation.Admin.fragmrntAdmin.MainSettingFragment -import com.example.rehabilitation.Admin.fragmrntAdmin.StatisticsFragment -import com.example.rehabilitation.Admin.fragmrntAdmin.UserSettingFragment +import com.example.rehabilitation.Auth.AuthorizationActivity class SettingActivity : AppCompatActivity() { + var backPressedTime: Long = 0 private lateinit var binding: ActivitySettingBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySettingBinding.inflate(layoutInflater) setContentView(binding.root) + data_prefUserPatientToken() + // //Выводим фрагмент как экран // supportFragmentManager.beginTransaction() // .replace(R.id.CLMainSetting, MainSettingFragment.newInstance()) @@ -26,7 +27,9 @@ class SettingActivity : AppCompatActivity() { binding.btnExitSetting.setOnClickListener { + val intetn = Intent(this, MainActivity::class.java) finish() + startActivity(intetn) } binding.cvSettingUser.setOnClickListener{ @@ -37,15 +40,65 @@ class SettingActivity : AppCompatActivity() { binding.cvFeedback.setOnClickListener{ val intent = Intent(this, FeedbackActivity::class.java) startActivity(intent) + } - binding.cvStatistics.setOnClickListener{ - val intent = Intent(this, StatisticsActivity::class.java) - startActivity(intent) - } + + + //Выход из аккаунта + binding.cvExitPatient.setOnClickListener{ + createAlеrtDialogExitAuth() + } } + override fun onDestroy() { + super.onDestroy() + finish() + } + //Диалоговое окно + private fun createAlеrtDialogExitAuth() { + val builder = AlertDialog.Builder(this) + builder.setTitle("Выход") + builder.setMessage("Вы уверены что хотите выйти из аккаунта") + builder.setNegativeButton("Назад") { dialogInterface, i -> + + } + builder.setPositiveButton("Подтвердить") { dialogInterface, i -> + clearUserPatientToken() + val intetn = Intent(this, AuthorizationActivity::class.java) + finish() + startActivity(intetn) + } + builder.show() + } + + //Инициализация хранилища(для токена) и проверяем есть ли аккаунт и или перекидываем в авторизацую или остаемся на данном экране + fun data_prefUserPatientToken() { + prefUserPatientToken = getSharedPreferences("UserPatientToken", Context.MODE_PRIVATE) + UserPatientToken = prefUserPatientToken?.getString("userpatienttoken", "")!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0 + } + //Записываем число + fun saveUserPatientToken(userpatienttoken: String) { + val editer = prefUserPatientToken?.edit() + editer?.putString("userpatienttoken", userpatienttoken) + editer?.apply() + UserPatientToken = userpatienttoken + } + //Функция очистки данных + fun clearUserPatientToken() { + val edit = prefUserPatientToken?.edit() + edit?.clear() + edit?.apply() + UserPatientToken = "" + } + + + override fun onBackPressed() { + val intetn = Intent(this, MainActivity::class.java) + startActivity(intetn) + finish() + } } \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/Toast/Notification.kt b/app/src/main/java/com/example/rehabilitation/Toast/Notification.kt new file mode 100644 index 0000000..1d6ad55 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Toast/Notification.kt @@ -0,0 +1,67 @@ +package com.example.rehabilitation.Toast + +import android.app.NotificationChannel +import android.app.NotificationManager +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import androidx.core.app.NotificationCompat +import com.example.rehabilitation.R + +const val notificationID = 1 +const val channelID= "channel1" +const val titleExtra = "titleExtra" +const val messageExtra = "messageExtra" + +open class Notification:BroadcastReceiver() { + + + var manager_: NotificationManager? = null + + override fun onReceive(context: Context?, intent: Intent?) { + + val notification = context?.let { + NotificationCompat.Builder(it,channelID) + .setSmallIcon(R.drawable.basket_24) + .setContentTitle(intent?.getStringExtra(titleExtra)) + .setContentText(intent?.getStringExtra(messageExtra)) + .build() + } + val manager = context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + manager.notify(notificationID,notification) + manager_ = manager + + } + + //Удаление + fun cancel_notification(notificationID:Int){ + manager_?.cancel(notificationID) + } + + + +} + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/com/example/rehabilitation/Toast/WrapToast.kt b/app/src/main/java/com/example/rehabilitation/Toast/WrapToast.kt new file mode 100644 index 0000000..f18055d --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/Toast/WrapToast.kt @@ -0,0 +1,103 @@ +package com.example.admin.Toast + +import android.app.Activity +import android.view.Gravity +import android.widget.TextView +import android.widget.Toast +import com.example.rehabilitation.R + + +fun Toast.showCustomToast(message: String, activity: Activity) +{ + + val layout = activity.layoutInflater.inflate ( + R.layout.custom_toast_layout, + activity.findViewById(R.id.toast_container) + ) + + + // set the text of the TextView of the message + val textView = layout.findViewById(R.id.toast_text) + //Передача текста который мы введем + textView.text = message + + //Если добавить кнопку то можно сделать некую функцию, к примеру при добавление товара в корзину, можно сверху выводить перейти в корзину и по нажатию мы переходим в корзину + /* textView.setOnClickListener{ + setToolbarTitle.perehods() + Log.d("dsfsd","111111111111111111111111111") + }*/ + // use the application extension function + this.apply { + //setGravity(Gravity.BOTTOM, 0, 40) + duration = Toast.LENGTH_SHORT + view = layout.rootView + show() + } + + +} fun Toast.showCustomDangerToast(message: String, activity: Activity) +{ + val layout = activity.layoutInflater.inflate ( + R.layout.custom_toast_layout_danger, + activity.findViewById(R.id.toast_container) + ) + + // set the text of the TextView of the message + val textView = layout.findViewById(R.id.toast_text) + //Передача текста который мы введем + textView.text = message + + //Если добавить кнопку то можно сделать некую функцию, к примеру при добавление товара в корзину, можно сверху выводить перейти в корзину и по нажатию мы переходим в корзину + + // use the application extension function + this.apply { + setGravity(Gravity.BOTTOM, 0, 40) + duration = Toast.LENGTH_SHORT + view = layout.rootView + show() + } +} + +fun Toast.showCustomInfoToast(message: String, activity: Activity) { + val layout = activity.layoutInflater.inflate( + R.layout.custom_toast_layout_info, + activity.findViewById(R.id.toast_container) + ) + + // set the text of the TextView of the message + val textView = layout.findViewById(R.id.toast_text) + //Передача текста который мы введем + textView.text = message + + //Если добавить кнопку то можно сделать некую функцию, к примеру при добавление товара в корзину, можно сверху выводить перейти в корзину и по нажатию мы переходим в корзину + + // use the application extension function + this.apply { + setGravity(Gravity.BOTTOM, 0, 40) + duration = Toast.LENGTH_SHORT + view = layout.rootView + show() + } +} + +fun Toast.showCustomNiceToast(message: String, activity: Activity) { + val layout = activity.layoutInflater.inflate( + R.layout.custom_toast_layout_nice, + activity.findViewById(R.id.toast_container) + ) + + // set the text of the TextView of the message + val textView = layout.findViewById(R.id.toast_text) + //Передача текста который мы введем + textView.text = message + + //Если добавить кнопку то можно сделать некую функцию, к примеру при добавление товара в корзину, можно сверху выводить перейти в корзину и по нажатию мы переходим в корзину + + // use the application extension function + this.apply { + setGravity(Gravity.BOTTOM, 0, 40) + duration = Toast.LENGTH_SHORT + view = layout.rootView + show() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/User/fragmentUser/CalendarFragment.kt b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/CalendarFragment.kt index 1e8d158..9b64def 100644 --- a/app/src/main/java/com/example/rehabilitation/User/fragmentUser/CalendarFragment.kt +++ b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/CalendarFragment.kt @@ -1,46 +1,50 @@ package com.example.rehabilitation.User.fragmentUser -import android.content.ContentResolver -import android.net.Uri +//import ru.cleverpumpkin.calendar.CalendarDate import android.os.Bundle import android.util.Log -import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CalendarView import android.widget.Toast +import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.asLiveData import androidx.recyclerview.widget.GridLayoutManager -import com.example.rehabilitation.BuildConfig +import androidx.recyclerview.widget.RecyclerView import com.example.rehabilitation.R +import com.example.rehabilitation.Room.MainDB import com.example.rehabilitation.databinding.FragmentCalendarBinding -import com.example.rehabilitation.db.MainDB -import com.example.rehabilitation.dip.Day.DayAdapter -import com.example.rehabilitation.dip.Day.DayModel +import com.example.rehabilitation.dateHomeCalendare +import com.example.rehabilitation.model_adapter.DataModel +import com.example.rehabilitation.model_adapter.Day.DayAdapter +import com.example.rehabilitation.model_adapter.Day.DayListModel import com.example.sqlitework.dip.MainViewModel import java.time.LocalDate import java.util.Calendar -class CalendarFragment : Fragment(),DayAdapter.Listener { +class CalendarFragment : Fragment(), DayAdapter.Listener { private lateinit var binding: FragmentCalendarBinding lateinit var adapterDay: DayAdapter private val model: MainViewModel by activityViewModels()//Инициализировали класс + private val dataModel: DataModel by activityViewModels()//Для передачи данных + + var visibleCalendar = true override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { - binding = FragmentCalendarBinding.inflate(layoutInflater,container,false) + binding = FragmentCalendarBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initRcViewDay() - liveReadOrderDayCurrent() + //liveReadOrderDayCurrent() model.liveDayList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment adapterDay.submitList(it)//Напрямую переадем созданный список в adapter(ProductAdapter) } @@ -56,29 +60,103 @@ class CalendarFragment : Fragment(),DayAdapter.Listener { // Now set calenderView with this calender object to highlight selected date on UI. calView.setDate(calender.timeInMillis, true, true) - Log.d("SelectedDate", "${LocalDate.of(year, month+1, dayOfMonth)}") - if(LocalDate.of(year, month+1, dayOfMonth).toString() == LocalDate.now().toString()){ - addListModelCardsDay("${LocalDate.of(year, month+1, dayOfMonth)}") - } - else{ + Log.d("SelectedDate", "${LocalDate.of(year, month + 1, dayOfMonth)}") + if (LocalDate.of(year, month + 1, dayOfMonth).toString() > LocalDate.now().toString()) { Toast.makeText(requireContext(), "Ошибка", Toast.LENGTH_SHORT).show() + } else { + addListModelCardsDay("${LocalDate.of(year, month + 1, dayOfMonth)}") } } - //addListModelCardsDay("2023-7-13") - val fileName = "b3_1.png" - val fileUri = Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://"+ BuildConfig.APPLICATION_ID+"/drawable/${fileName}") - val filePath = fileUri.path + binding.btnVisible.setOnClickListener { + if (visibleCalendar == true) { + binding.CLCalendar.visibility = View.GONE + visibleCalendar = false + binding.btnVisible.setBackgroundResource(R.drawable.visible_eas_false) + } else if (visibleCalendar == false){ + binding.CLCalendar.visibility = View.VISIBLE + visibleCalendar = true + binding.btnVisible.setBackgroundResource(R.drawable.visible_eas_true) + } + } -// val fileName1 = "my_image.png" -// val inputStream1 = assets.open("drawable/${fileName}") -// val filePath1 = inputStream.toString() + // calendarV2() + calendarV3() -// val resourceId12 = R.drawable.b3_1 -// val fileUri12 = Uri.parse("android.resource://"+ BuildConfig.APPLICATION_ID+"/${resourceId12}") -// val filePath12 = fileUri12.path + } + + private fun calendarV3() { +// +// binding.fabButton.setOnClickListener { openDatePicker() } +// binding.calendarViewV3.setOnDayClickListener(requireContext()) +// val view: View = LayoutInflater.from(parent.context).inflate(R.layout.item_calendar_horizontal, parent, false) +// return MonthCalendarViewHolder(view) + } + + private fun calendarV2() { +// val calendarView = binding.calendarViewV2 +// val calendar = Calendar.getInstance() +//// var dates = ArrayList() +//// dates.add(LocalDate.now().dayOfMonth) +//// Initial date +// calendar.set(2023, Calendar.JUNE, 1 ) +// val initialDate = CalendarDate(calendar.time) +// +//// Minimum available date +// calendar.set(2023, Calendar.MAY, 1) +// val minDate = CalendarDate(calendar.time) +// +//// Maximum available date +// calendar.set(2023, Calendar.JULY, 15) +// val maxDate = CalendarDate(calendar.time) +// +//// List of preselected dates that will be initially selected +// //val preselectedDates: List = ru.cleverpumpkin.calendar.getPreselectedDates() +// +//// The first day of week +// val firstDayOfWeek = java.util.Calendar.MONDAY +// +//// Set up calendar with all available parameters +// calendarView.setupCalendar( +// initialDate = initialDate, +// minDate = minDate, +// maxDate = maxDate, +// selectionMode = ru.cleverpumpkin.calendar.CalendarView.SelectionMode.NONE, +// //selectedDates = preselectedDates, +// firstDayOfWeek = firstDayOfWeek, +// showYearSelectionView = true +// ) +// // Set up calendar +// calendarView.setupCalendar() +//// Set up calendar +// calendarView.setupCalendar() +// +// +// val additionalTexts: List = generateAdditionalTexts() +// +//// Set List of additional texts that will be displayed on the calendar +// calendarView.datesAdditionalTexts = additionalTexts +// +// +//// Set List of indicators that will be displayed on the calendar +// //calendarView.datesIndicators = indicators + } + + fun ClearRCView(){ + adapterDay.notifyDataSetChanged(); // let your adapter know about the changes and reload view. + initRcViewDay() + } + override fun onResume() { + super.onResume() + //ClearRCView() + //addListModelCardsDay("${LocalDate.now()}") + } + + override fun onDestroy() { + super.onDestroy() + adapterDay.notifyDataSetChanged() + ClearRCView() - // binding.imageView4.setImageResource(filePath12!!.toInt()) } //Функция запускающая отслеживания за списком, чтобы вовремя обновлять основную карточку продукта @@ -87,46 +165,52 @@ class CalendarFragment : Fragment(),DayAdapter.Listener { } } + //Инициализация списка private fun initRcViewDay() = with(binding) { - rcViewDayCalendar.layoutManager = GridLayoutManager(requireContext(),1)//По вертикали будет выводить по умолчанию + rcViewDayCalendar.layoutManager = GridLayoutManager(requireContext(), 1)//По вертикали будет выводить по умолчанию adapterDay = DayAdapter(this@CalendarFragment) rcViewDayCalendar.adapter = adapterDay + + + } - //Заполнения модели и списка - private fun addListModelCardsDay(day:String){ + + private fun addListModelCardsDay(day: String) { + val db = MainDB.getDB(requireContext()) - val list = ArrayList() - db.getDaoDaySport().getAllItemDaySport(day).asLiveData().observe(requireActivity()){itList-> - var number = 0; - itList.forEach{ - //val text = "Id: ${it.id} Name: ${it.name} Proce: ${it.price}" - //binding.txtList.append(text) - val itemDay = DayModel( - it.id.toString(), - //it.name.toString(), - //it.desc.toString(), - "123", - "321", - it.day.toString(), - (number++).toString(), - it.category.toString(), - //it.count.toString(), - //it.image.toString(), - it.check.toString(), - ) - //model.liveZakazCurrent.value = item//Передаем в liveDataCurrent один из продуктов, чтобы дальше эти данные использовать и передавать их в пробную ячейку - list.add(itemDay)//Передали заполненый список + val list = ArrayList() + db.getDaoDaySport().getAllItemDaySport(day).asLiveData() + .observe(requireActivity()) { itList -> + var number = 1; + + itList.forEach { + Log.d("123", it.category) + //db.getDaoSportCategory().getAllItemsSportCategory(it.category).asLiveData().observe(requireActivity()){itSport-> + val itemDay = DayListModel( + it.id.toString(), + number++.toString(), + day, + it.category.toString(), + it.check.toString(), + ) + list.add(itemDay)//Передали заполненый список + model.liveDayList.value = list + //} + } + + Log.d("sadas", list.toString()) } - model.liveDayList.value = list - } } + companion object { fun newInstance() = CalendarFragment() } - override fun onClickDay(item: DayModel) { + override fun onClickDay(item: DayListModel) { + dataModel.fragmentMenu.value = R.id.schedule + dateHomeCalendare = item.day } } \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/User/fragmentUser/HomeFragment.kt b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/HomeFragment.kt index deecba4..58d11a1 100644 --- a/app/src/main/java/com/example/rehabilitation/User/fragmentUser/HomeFragment.kt +++ b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/HomeFragment.kt @@ -1,14 +1,38 @@ package com.example.rehabilitation.User.fragmentUser import android.os.Bundle +import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup +import androidx.activity.viewModels +import androidx.fragment.app.activityViewModels +import androidx.lifecycle.asLiveData +import androidx.recyclerview.widget.GridLayoutManager +import com.example.rehabilitation.model_adapter.Edit.adapterFirebase.ReportPatient +import com.example.rehabilitation.R +import com.example.rehabilitation.Room.MainDB +import com.example.rehabilitation.checkDaySportString +import com.example.rehabilitation.countCategory import com.example.rehabilitation.databinding.FragmentHomeBinding +import com.example.rehabilitation.dateHomeCalendare +import com.example.rehabilitation.loginDoctor +import com.example.rehabilitation.loginPatient +import com.example.rehabilitation.model_adapter.DataModel +import com.example.rehabilitation.model_adapter.Day.DayAdapter +import com.example.rehabilitation.model_adapter.Day.DayListModel +import com.example.rehabilitation.model_adapter.modelCount.CountDayModel +import com.example.rehabilitation.model_adapter.modelCount.CountMonthModel +import com.example.sqlitework.dip.MainViewModel +import java.time.LocalDate -class HomeFragment : Fragment() { +class HomeFragment : Fragment(),DayAdapter.Listener { private lateinit var binding: FragmentHomeBinding + private val model: MainViewModel by activityViewModels()//Инициализировали класс + lateinit var adapterDay: DayAdapter + //private val dataModel: DataModel by activityViewModels()//Для передачи данных + private val dataModel: DataModel by activityViewModels()//Для передачи данных override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? @@ -17,8 +41,106 @@ class HomeFragment : Fragment() { return binding.root } + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + initRcViewDay() + + model.liveDayList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + adapterDay.submitList(it)//Напрямую переадем созданный список в adapter(ProductAdapter) + } + + progresMonthAndDay() + liveCountDayCurrent() + addListModelCardsDay(LocalDate.now().toString()) + + + +// dataModel.fragmentMenu.observe(this as LifecycleOwner, { +// binding.buttonNavigation.selectedItemId = it +// }) + + } + //Заполнения модели и списка + private fun addListModelCardsDay(day:String){ + + val db = MainDB.getDB(requireContext()) + val list = ArrayList() + db.getDaoDaySport().getAllItemDaySport(day).asLiveData().observe(requireActivity()){itList-> + var number = 1; + + itList.forEach{ + Log.d("123",it.category) + //db.getDaoSportCategory().getAllItemsSportCategory(it.category).asLiveData().observe(requireActivity()){itSport-> + val itemDay = DayListModel( + it.id.toString(), + number++.toString(), + day, + it.category.toString(), + it.check.toString(), + ) + list.add(itemDay)//Передали заполненый список + model.liveDayList.value = list + //} + } + + Log.d("sadas",list.toString()) + } + } + private fun progresMonthAndDay() { + val db = MainDB.getDB(requireContext()) + val data= LocalDate.now().toString() + + var listDayDown =0 + var listDayAll =0 + var name = "" + //Прогрес за в течение данного дня + db.getDaoDaySport().getAllItemDaySport(LocalDate.now().toString()).asLiveData().observe(requireActivity()){itList-> + var number = 1; + + itList.forEach{ + + if(it.check ==1){ + listDayDown=listDayDown+1 + listDayAll=listDayAll+1 + } + else{ + listDayAll=listDayAll+1 + } + } + val item = CountDayModel( + listDayDown, + listDayAll + ) + model.liveCountDayCurrent.value = item + + } + } + + //Вывод прогресса на один день + private fun liveCountDayCurrent() = with(binding) { + model.liveCountDayCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + binding.txtSportToday.setText(it.countDown.toString()) + binding.txtSportTodayAll.setText(it.countAll.toString()) + } + + } + + + //Инициализация списка + private fun initRcViewDay() = with(binding) { + rcVIewDayList.layoutManager = GridLayoutManager(requireContext(),1)//По вертикали будет выводить по умолчанию + adapterDay = DayAdapter(this@HomeFragment) + rcVIewDayList.adapter = adapterDay + } companion object { fun newInstance() = HomeFragment() } + + override fun onClickDay(item: DayListModel) { + //Передаем фрагмент на вывод(это фрагмент страницы с продукцией) + //parentFragmentManager.beginTransaction() .replace(R.id.placeHolderFragment, SceduleFragment()).commit() + dataModel.fragmentMenu.value = R.id.schedule + dateHomeCalendare = item.day + } } \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/User/fragmentUser/InfoFragment/CommonInfoFragment.kt b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/InfoFragment/CommonInfoFragment.kt new file mode 100644 index 0000000..3ae4b1e --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/InfoFragment/CommonInfoFragment.kt @@ -0,0 +1,37 @@ +package com.example.rehabilitation.fragment.InfoFragment + +import android.os.Bundle +import androidx.fragment.app.Fragment +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import com.example.rehabilitation.R +import com.example.rehabilitation.databinding.FragmentCommonInfoBinding + +class CommonInfoFragment : Fragment() { + private lateinit var binding: FragmentCommonInfoBinding + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + binding = FragmentCommonInfoBinding.inflate(inflater, container, false) + return binding.root + } + +// override fun onResume() { +// super.onResume() +// binding.CLCommonInfo.visibility = View.VISIBLE +// } +// +// override fun onDestroy() { +// super.onDestroy() +// binding.CLCommonInfo.visibility = View.GONE +// +// } + + companion object { + @JvmStatic + fun newInstance() = CommonInfoFragment() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/User/fragmentUser/InfoFragment/MedicalReabilitationFragment.kt b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/InfoFragment/MedicalReabilitationFragment.kt new file mode 100644 index 0000000..281d789 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/InfoFragment/MedicalReabilitationFragment.kt @@ -0,0 +1,38 @@ +package com.example.rehabilitation.fragment.InfoFragment + +import android.os.Bundle +import androidx.fragment.app.Fragment +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import com.example.rehabilitation.R +import com.example.rehabilitation.databinding.FragmentMedicalReabilitationBinding + +class MedicalReabilitationFragment : Fragment() { + private lateinit var binding: FragmentMedicalReabilitationBinding + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + binding = FragmentMedicalReabilitationBinding.inflate(inflater, container, false) + return inflater.inflate(R.layout.fragment_medical_reabilitation, container, false) + } + +// override fun onResume() { +// super.onResume() +// binding.CLMadicalReabilitation.visibility = View.VISIBLE +// } +// +// override fun onDestroy() { +// super.onDestroy() +// binding.CLMadicalReabilitation.visibility = View.GONE +// +// } + + companion object { + + @JvmStatic + fun newInstance() = MedicalReabilitationFragment() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/User/fragmentUser/InfoFragment/faqFragment.kt b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/InfoFragment/faqFragment.kt new file mode 100644 index 0000000..52f1c02 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/InfoFragment/faqFragment.kt @@ -0,0 +1,40 @@ +package com.example.rehabilitation.fragment.InfoFragment + +import android.os.Bundle +import androidx.fragment.app.Fragment +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import com.example.rehabilitation.R +import com.example.rehabilitation.databinding.FragmentFaqBinding + +class faqFragment : Fragment() { + private lateinit var binding: FragmentFaqBinding + + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + // Inflate the layout for this fragment + + binding = FragmentFaqBinding.inflate(inflater, container, false) + return binding.root + } + +// override fun onResume() { +// super.onResume() +// binding.CLFaq.visibility = View.VISIBLE +// } +// +// override fun onDestroy() { +// super.onDestroy() +// binding.CLFaq.visibility = View.GONE +// +// } + + companion object { + @JvmStatic + fun newInstance() = faqFragment() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/User/fragmentUser/InformationFragment.kt b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/InformationFragment.kt index 36b6f2d..325cba3 100644 --- a/app/src/main/java/com/example/rehabilitation/User/fragmentUser/InformationFragment.kt +++ b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/InformationFragment.kt @@ -1,11 +1,19 @@ package com.example.rehabilitation.User.fragmentUser +import android.content.Intent +import android.net.Uri import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup +import com.example.rehabilitation.Auth.AuthDoctorActivity +import com.example.rehabilitation.MainActivity +import com.example.rehabilitation.R import com.example.rehabilitation.databinding.FragmentInformationBinding +import com.example.rehabilitation.fragment.InfoFragment.CommonInfoFragment +import com.example.rehabilitation.fragment.InfoFragment.MedicalReabilitationFragment +import com.example.rehabilitation.fragment.InfoFragment.faqFragment class InformationFragment : Fragment() { @@ -18,6 +26,60 @@ class InformationFragment : Fragment() { return binding.root } + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + binding.commonInformationButton.setOnClickListener { + val infoFrag = activity?.supportFragmentManager?.beginTransaction() + infoFrag?.replace(R.id.CLInformation, CommonInfoFragment.newInstance()) + infoFrag?.addToBackStack(null) + infoFrag?.commit() + + } + + binding.frequentlyAskedQuestionsButton.setOnClickListener { + val infoFrag = activity?.supportFragmentManager?.beginTransaction() + infoFrag?.replace(R.id.CLInformation, faqFragment.newInstance()) + infoFrag?.addToBackStack(null) + infoFrag?.commit() + + } + + binding.medicalReabilitationButton.setOnClickListener { + val infoFrag = activity?.supportFragmentManager?.beginTransaction() + infoFrag?.replace(R.id.CLInformation, MedicalReabilitationFragment.newInstance()) + infoFrag?.addToBackStack(null) + infoFrag?.commit() + + } + + binding.fondButton.setOnClickListener{ + val i = Intent(Intent.ACTION_VIEW, Uri.parse("https://фонд-защитники-отечества.рф/filials")) + startActivity(i) + } + + //Выход со страницы + binding.btnExitInformation.setOnClickListener { + val intetn = Intent(requireContext(), MainActivity::class.java) + startActivity(intetn) + activity?.finish() + } + } + +// override fun onDestroy() { +// super.onDestroy() +// activity?.finish() +// +// binding.CLFragmentInformation.visibility = View.GONE +// } +// +// override fun onResume() { +// super.onResume() +// binding.CLFragmentInformation.visibility = View.VISIBLE +// +// } + + + companion object { fun newInstance() = InformationFragment() diff --git a/app/src/main/java/com/example/rehabilitation/User/fragmentUser/ProgresFragment.kt b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/ProgresFragment.kt index 75ab5aa..d98c21d 100644 --- a/app/src/main/java/com/example/rehabilitation/User/fragmentUser/ProgresFragment.kt +++ b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/ProgresFragment.kt @@ -1,15 +1,126 @@ package com.example.rehabilitation.User.fragmentUser +import android.Manifest +import android.annotation.SuppressLint +import android.app.AlertDialog +import android.content.ContentValues +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Build import android.os.Bundle -import androidx.fragment.app.Fragment +import android.os.Environment +import android.os.Handler +import android.provider.MediaStore +import android.provider.Settings +import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup +import android.widget.Button +import android.widget.Toast +import androidx.activity.result.ActivityResultLauncher +import androidx.activity.result.contract.ActivityResultContracts +import androidx.core.app.ActivityCompat +import androidx.core.content.ContextCompat +import androidx.core.content.FileProvider +import androidx.core.net.toFile +import androidx.core.net.toUri +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.lifecycle.asLiveData +import androidx.recyclerview.widget.LinearLayoutManager +import com.example.admin.Toast.showCustomInfoToast +import com.example.rehabilitation.BuildConfig +import com.example.rehabilitation.EmailPatient +import com.example.rehabilitation.FIO +import com.example.rehabilitation.model_adapter.Edit.adapterFirebase.ExcelFile +import com.example.rehabilitation.model_adapter.Edit.adapterFirebase.ReportPatient +import com.example.rehabilitation.Room.MainDB +import com.example.rehabilitation.Sport15Day +import com.example.rehabilitation.Sport15DayAll +import com.example.rehabilitation.Sport7Day +import com.example.rehabilitation.SportCursDay +import com.example.rehabilitation.SportCursDayNumber +import com.example.rehabilitation.checkDaySportString +import com.example.rehabilitation.countCategory import com.example.rehabilitation.databinding.FragmentProgresBinding +import com.example.rehabilitation.listAfter +import com.example.rehabilitation.listBefore +import com.example.rehabilitation.listProgressAll +import com.example.rehabilitation.listProgressCheck +import com.example.rehabilitation.loginDoctor +import com.example.rehabilitation.loginPatient +import com.example.rehabilitation.model_adapter.Day.DayListModel +import com.example.rehabilitation.model_adapter.Image.Category.CountCategoryModel +import com.example.rehabilitation.model_adapter.Progress.AfterListModel +import com.example.rehabilitation.model_adapter.Progress.BeforeListModel +import com.example.rehabilitation.model_adapter.Progress.ProgressAdapter +import com.example.rehabilitation.model_adapter.Progress.ProgressModel +import com.example.rehabilitation.model_adapter.modelCount.CountDayModel +import com.example.rehabilitation.model_adapter.modelCount.CountMonthModel +import com.example.rehabilitation.prefEmailPatient +import com.example.rehabilitation.prefFIO +import com.example.rehabilitation.prefSport15Day +import com.example.rehabilitation.prefSport15DayAll +import com.example.rehabilitation.prefSport7Day +import com.example.rehabilitation.uriFileEF +import com.example.sqlitework.dip.MainViewModel +import com.google.firebase.database.DatabaseReference +import com.google.firebase.database.ktx.database +import com.google.firebase.ktx.Firebase +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.io.OutputStream +import java.time.LocalDate +import java.time.LocalDateTime +import kotlin.io.path.Path +import kotlin.io.path.absolutePathString +import kotlin.io.path.listDirectoryEntries -class ProgresFragment : Fragment() { +//import java.util.Properties +//import javax.mail.Authenticator +//import javax.mail.Message +//import javax.mail.MessagingException +//import javax.mail.PasswordAuthentication +//import javax.mail.Session +//import javax.mail.Transport +//import javax.mail.internet.InternetAddress +//import javax.mail.internet.MimeMessage + +class ProgresFragment : Fragment(), ProgressAdapter.Listener { private lateinit var binding: FragmentProgresBinding + + private lateinit var pLauncher: ActivityResultLauncher + lateinit var adapterProgress: ProgressAdapter + + + private val model: MainViewModel by activityViewModels()//Инициализировали класс + lateinit var uri: Uri + private val pickFromGallery: Int = 101 + + var uri2: String? = null + + //FireBase + //Подключение к FireBase + val database = + Firebase.database("https://rehabilitationtest-default-rtdb.europe-west1.firebasedatabase.app/") + var idChat = "azazaza08" + val myRef: DatabaseReference? = database.getReference(idChat.toString()) + + //Для анкеты + var txt = "" + + //Кастыль для разрешения отправки сообщений, так как иначе оно отправляет их само и это мешает + var TrueAddEmail = false + + + private val filePath = + File(Environment.getExternalStorageDirectory().toString() + "/Demow.xlsx") + override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? @@ -18,8 +129,953 @@ class ProgresFragment : Fragment() { return binding.root } + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + //Пройдено ли 15 дне и отправен отчет + prefSport15DayAll = activity?.getSharedPreferences("Sport15DayAll", Context.MODE_PRIVATE) + Sport15DayAll = prefSport15DayAll?.getInt("s15da", 0)!! + + //Отчет на 15 день + prefSport15Day = activity?.getSharedPreferences("Sport15Day", Context.MODE_PRIVATE) + Sport15Day = prefSport15Day?.getInt("s15d", 0)!! + + //Отчет на 7 день + prefSport7Day = activity?.getSharedPreferences("Sport7Day", Context.MODE_PRIVATE) + Sport7Day = prefSport7Day?.getInt("s7d", 0)!! + + + ActivityCompat.requestPermissions( + requireActivity(), arrayOf( + Manifest.permission.WRITE_EXTERNAL_STORAGE, + Manifest.permission.READ_EXTERNAL_STORAGE + ), PackageManager.PERMISSION_GRANTED + ) + + + liveDayListProgres() + liveDayListProgres2() + liveCountMonthCurrent() + liveCountDayCurrent() + progresMonthAndDay() + initRcViewProgress() + //registerPrmissionListener() + progressList() + model.liveListProgresBeforeList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + Log.i("TrueAddEmailB", "${TrueAddEmail}") + if (TrueAddEmail == true) { + listBefore = it + Log.i("listBefore", listBefore.toString()) + progressListAddEmailAfter() + } + } + model.liveListProgresAfterList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + Log.i("TrueAddEmailA", "${TrueAddEmail}") + if (TrueAddEmail == true) { + listAfter = it + if (listAfter.count() >= 2) { + ActivityCompat.requestPermissions( + requireActivity(), arrayOf( + Manifest.permission.WRITE_EXTERNAL_STORAGE, + Manifest.permission.READ_EXTERNAL_STORAGE + ), PackageManager.PERMISSION_GRANTED + ) + if (ContextCompat.checkSelfPermission( + requireContext(), + Manifest.permission.READ_EXTERNAL_STORAGE + ) == PackageManager.PERMISSION_GRANTED + ) { + Log.i("listAfter", listAfter.toString()) + formationOfReportsOnQuestionnaires() + } + else if (ContextCompat.checkSelfPermission( + requireContext(), + Manifest.permission.READ_EXTERNAL_STORAGE + ) == PackageManager.PERMISSION_DENIED + ){ + AlertDialog.Builder(requireContext()) + .setTitle("Разрешение") + .setMessage("Вам необходимо разрешить приложению доступ к файлам, чтобы вам был сохранен отчет по реабилитации") + .setNeutralButton("Добавить разрешение") { dialog, whichButton -> + // startActivity(Intent(Settings.ACTION_SETTINGS)) + //Переход в настройки данного приложения + val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) + intent.data = Uri.parse("package:" + context?.packageName) + startActivity(intent) + } + .setNegativeButton("Отмена") { dialog, whichButton -> + + } + .show() + Toast(requireContext()).showCustomInfoToast( + "Вам необходимо разрешить приложению доступ к файлам", + requireActivity() + ) + } + + } else { + Toast(requireContext()).showCustomInfoToast( + "Отчет можно отправлять при наличие 2 выполненных дней", + requireActivity() + ) + + } + + } + + } + + model.liveProgressAllList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + listProgressAll = it + progressCheckAdd() + } + + model.liveProgressCheckList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + adapterProgress.submitList(it)//Напрямую переадем созданный список в adapter(ProductAdapter) + listProgressCheck = it + } + + + //Отправка отчета на почту + binding.btnPushEmailReport.setOnClickListener { + progresListAddEmail() + } + + binding.btnPushProgress.setOnClickListener { + + + Log.i("TrueAddEmailfalse", "${TrueAddEmail}") + TrueAddEmail = true + Log.i("TrueAddEmailtrue", "${TrueAddEmail}") + progressListAddEmailBefore() + + prefFIO = activity?.getSharedPreferences("FIO", Context.MODE_PRIVATE) + FIO = prefFIO?.getString("fio", "")!! + + prefEmailPatient = activity?.getSharedPreferences("EmailPatient", Context.MODE_PRIVATE) + EmailPatient = prefEmailPatient?.getString("emailPatient", "")!! + + + } + fun saveFIO(fio: String) { + val edit = prefFIO?.edit() + edit?.putString("fio", fio) + edit?.apply() + FIO = fio + } + + fun clearFIO() { + val edit = prefFIO?.edit() + edit?.clear() + edit?.apply() + FIO = "" + } + + +// binding.btnPushApi.setOnClickListener { +// sendEmail() +// } + + + binding.btnExit.setOnClickListener { + visible1() + } + binding.btnReport.setOnClickListener { + visible2() + } + + binding.btnAttach.setOnClickListener { + openFolder() + } + binding.btnCreateText.setOnClickListener { + + } + + } + + private fun progressCheckAdd() { + val db = MainDB.getDB(requireContext()) + val list = ArrayList() + db.getDaoDaySport().getcheckProgress().asLiveData().observe(requireActivity()) { itList -> + var number = 1; + var i = 0 + itList.forEach { + listProgressAll[i].CountCheckTrue = it.check + i++ + } + model.liveProgressCheckList.value = listProgressAll + Log.d("sadas", list.toString()) + } + binding.txtLoadProgres.visibility = View.GONE + } + + fun progressList() { + ClearRCView() + binding.txtLoadProgres.visibility = View.VISIBLE + val db = MainDB.getDB(requireContext()) + val list = ArrayList() + db.getDaoDaySport().getAllProgres().asLiveData().observe(requireActivity()) { itList -> + var number = 1; + + itList.forEach { + val itemDay = ProgressModel( + number++.toString(), + it.visible, + it.check, + it.category, + it.day + + ) + list.add(itemDay)//Передали заполненый список + model.liveProgressAllList.value = list + + } + + Log.d("sadas", list.toString()) + } + } + + //Инициализация списка для фотографий + private fun initRcViewProgress() = with(binding) { + rcViewProgress.layoutManager = LinearLayoutManager( + requireContext(), + LinearLayoutManager.VERTICAL, + false + )//По вертикали будет выводить по умолчанию + adapterProgress = ProgressAdapter(this@ProgresFragment) + rcViewProgress.adapter = adapterProgress + } + + private fun formationOfReportsOnQuestionnaires() { + Log.i("111111123333", "111111123333") + Log.i("Questionnaires", listBefore[0].date) + Log.i("Questionnaires", listBefore.count().toString()) + try { + Log.i("222222222223333", "222222222223333") + val excel = ExcelFile( + FIO, + listBefore.count(), + listAfter.count(), + LocalDate.now().toString(), + listBefore, + listAfter + ) + val fullPath = Path("source.txt") + Log.i("fullPath", "${fullPath}") + Log.i("111111123333", "5234234243") + txt = "" + Log.i("Questionnaires", listBefore[0].date) + for (i in 1..listBefore.count()) { + Log.i("listBefore1", "1") + excel.addBeforeDay( + i, 1, if (listBefore[i - 1].one.toInt() == 0) { + 0 + } else { + 1 + } + ) + excel.addBeforeDay(i, 2, listBefore[i - 1].one.toInt()) + excel.addBeforeDay(i, 3, listBefore[i - 1].two.toInt()) + excel.addBeforeDay(i, 4, listBefore[i - 1].thee.toInt()) + excel.addBeforeDay(i, 5, listBefore[i - 1].four.toInt()) + excel.addBeforeDay(i, 6, listBefore[i - 1].five.toInt()) + excel.addBeforeDay(i, 7, listBefore[i - 1].six.toInt()) + excel.addBeforeDay(i, 8, listBefore[i - 1].seven.toInt()) + excel.addBeforeDay(i, 9, listBefore[i - 1].eight.toInt()) + excel.addBeforeDay(i, 10, listBefore[i - 1].nine.toInt()) + } + + for (i in 1..listAfter.count()) { + Log.i("listAfter2", "2") + excel.addAfterDay(i, 1, listAfter[i - 1].one.toInt()) + excel.addAfterDay(i, 2, listAfter[i - 1].two.toInt()) + excel.addAfterDay(i, 3, listAfter[i - 1].thee.toInt()) + excel.addAfterDay(i, 4, listAfter[i - 1].four.toInt()) + excel.addAfterDay(i, 5, listAfter[i - 1].five.toInt()) + excel.addAfterDay(i, 6, listAfter[i - 1].six.toInt()) + excel.addAfterDay(i, 7, listAfter[i - 1].seven.toInt()) + excel.addAfterDay(i, 8, listAfter[i - 1].eight.toInt()) + excel.addAfterDay(i, 9, listAfter[i - 1].nine.toInt()) + excel.addAfterDay(i, 10, listAfter[i - 1].ten.toInt()) + excel.addAfterDay(i, 11, listAfter[i - 1].eleven.toInt()) + excel.addAfterDay(i, 12, listAfter[i - 1].twelve.toInt()) + } + Log.i("27654756231231231", "27654756231231231") + chekStoragePermissio() + excel.saveTable() + Log.i("23231231231", "23231231231") + sendEmailQ() + } catch (e: Exception) { + e.printStackTrace() + } + + } + + private fun formationOfReportsOnQuestionnaires2() { + try { + txt = "" + var dayPlus = 1 + var afterPlus = 0 + Log.i("Questionnaires", listBefore[0].date) + for (i in 0..listBefore.count() - 1) { + if (listBefore[i].date == listAfter[afterPlus].date) { + txt += + "День ${dayPlus++}: ${listBefore[i].date} \n" + + "Анкета до выполненния: \n" + + "|1. ${listBefore[i].one}||2. ${listBefore[i].two}||3. ${listBefore[i].thee}||4. ${listBefore[i].four}||5. ${listBefore[i].five}||6. ${listBefore[i].six}||7. ${listBefore[i].seven}||8. ${listBefore[i].eight}||9. ${listBefore[i].nine}|\n" + + " \n" + + "Анкета после выполненния: \n" + + "|1. ${listAfter[afterPlus].one}||2. ${listAfter[afterPlus].two}||3. ${listAfter[afterPlus].thee}||4. ${listAfter[afterPlus].four}||5. ${listAfter[afterPlus].five}||6. ${listAfter[afterPlus].six}||7. ${listAfter[afterPlus].seven}||8. ${listAfter[afterPlus].eight}||9. ${listAfter[afterPlus].nine}||10. ${listAfter[afterPlus].ten}||11. ${listAfter[afterPlus].eleven}||12. ${listAfter[afterPlus].twelve}|\n" + + + " \n" + + "______________\n" + + " \n" + afterPlus++ + } else { + txt += + "День ${dayPlus++}: ${listBefore[i].date} \n" + + "Анкета до выполненния: \n" + + "|1. ${listBefore[i].one}||2. ${listBefore[i].two}||3. ${listBefore[i].thee}||4. ${listBefore[i].four}||5. ${listBefore[i].five}||6. ${listBefore[i].six}||7. ${listBefore[i].seven}||8. ${listBefore[i].eight}||9. ${listBefore[i].nine}|\n" + + " \n" + + "Анкета после выполненния: \n" + + "ЗАБЫЛ ЗАПОЛНИТЬ" + + " \n" + + "____________________________\n" + + " \n" + } + + } + + chekStoragePermissio() + + txtFileExport(txt) + + } catch (e: Exception) { + e.printStackTrace() + } + + } + + + fun chekStoragePermissio() { + //Разрешние + when { + ContextCompat.checkSelfPermission( + requireContext(), + Manifest.permission.WRITE_EXTERNAL_STORAGE + ) + == PackageManager.PERMISSION_GRANTED -> { + //Toast.makeText(requireContext(), "STORAGE run", Toast.LENGTH_LONG).show() + } + + shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE) -> { + //Toast.makeText(requireContext(), "We need your permission", Toast.LENGTH_LONG) .show() + + } + + else -> { + pLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE) + } + } + } + + private fun registerPrmissionListener() { + pLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { + if (it) { + //Toast.makeText(requireContext(), "STORAGE run", Toast.LENGTH_LONG).show() + } else { + //Toast.makeText(requireContext(), "Permission denid", Toast.LENGTH_LONG).show() + + } + } + + } + + + @Throws(IOException::class) + private fun saveFile(context: Context, fileName: String, text: String, extension: String) { + val outputStream: OutputStream? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + val values = ContentValues() + values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName) + values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain") + values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS) + val extVolumeUri: Uri = MediaStore.Files.getContentUri("external") + val fileUri: Uri? = context.contentResolver.insert(extVolumeUri, values) + context.contentResolver.openOutputStream(fileUri!!) + } else { + val path = + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + .toString() + val file = File(path, "$fileName.$extension") + FileOutputStream(file) + } + + val bytes = text.toByteArray() + outputStream?.write(bytes) + outputStream?.close() + } + + + // логика проверки разрешения + private fun hasWriteStoragePermission(): Boolean { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + // API version >= 29 (Android 10, 11, ...) + return true + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + // API version >= 23 (Android 6, 7, ...) + if (ActivityCompat.checkSelfPermission( + requireContext(), + Manifest.permission.WRITE_EXTERNAL_STORAGE + ) != PackageManager.PERMISSION_GRANTED + ) { + requestPermissions( + arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), + TXTWRITEFILE + ) + return false + } + } + // для более древних API не требуется проверки + return true + } + + //var uri:Uri + val TXTWRITEFILE: Int = 2000 + + @SuppressLint("SuspiciousIndentation") + fun txtFileExport(txt: String) { + val fileName = LocalDateTime.now().toString() + + val fileContent = txt + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + // API version >= 29 (Android 10, 11, ...) + + val contentValues = ContentValues().apply { + put(MediaStore.Downloads.DISPLAY_NAME, fileName) + put(MediaStore.Downloads.MIME_TYPE, "text/plain") + put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS) + } + val resolver = requireActivity().contentResolver + + // регистрация файла + uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues)!! + //Toast.makeText(requireContext(), uri.toString(), Toast.LENGTH_LONG).show() + Log.i("132", uri.toString()) + + if (uri != null) { + val fileOutputStream = resolver.openOutputStream(uri) + fileOutputStream?.write(fileContent.toByteArray()) + fileOutputStream?.close() +// sendEmail() + } else { + //Toast.makeText(requireContext(), "Can\'t resolve media path", Toast.LENGTH_LONG).show() + } + } else { + // API version < 29 (Android ..., 7,8,9) + val outputFile = File( + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), + fileName + ) + outputFile.writeText(fileContent) + //uri = outputFile + } + } + fun ClearRCView(){ + adapterProgress.notifyDataSetChanged(); // let your adapter know about the changes and reload view. + initRcViewProgress() + //progresMonthAndDay() + } + override fun onResume() { + super.onResume() + //ClearRCView() + progresMonthAndDay() + } + + override fun onDestroy() { + super.onDestroy() + ClearRCView() + } + override fun onRequestPermissionsResult( + requestCode: Int, + permissions: Array, + grantResults: IntArray + ) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + when (requestCode) { + TXTWRITEFILE -> { + if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + //txtFileExport(txt) + } else { + // Toast.makeText(requireContext(), "Feature is not available, because you didn't permit to crate an export file.", Toast.LENGTH_LONG) + } + } + } + } + + fun saveTextFile() { + + } + + private fun txtEmail() { + saveTextFile() + } + + private fun openFolder() { + val intent = Intent() + intent.type = "image/*" + intent.action = Intent.ACTION_GET_CONTENT + intent.putExtra("return-data", true) + startActivityForResult( + Intent.createChooser(intent, "Complete action using"), + pickFromGallery + ) + } + + private fun sendEmailQ() { + + Log.i("123111123123123", "123111123123123") + try { + TrueAddEmail = false + Log.i("TrueAddEmailfalse", "${TrueAddEmail}") + Log.i("123123123123", "123123123123") + if (SportCursDay == 7 && Sport7Day == 1) { + clearSport7Day() + } else if (SportCursDay == 15 && Sport15Day == 1) { + clearSport15Day() + saveSport15DayAll(1) + } + val filesDir = + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + val uri3 = FileProvider.getUriForFile( + requireContext(), + BuildConfig.APPLICATION_ID + ".provider", + "file://${filesDir}/${LocalDate.now()}.xlsx".toUri().toFile() + ) + + //val email = EmailPatient// the id of textview where email is stored + val email = "Mnv.vmeda@ya.ru"// the id of textview where email is stored + val subject = "Отчет по тренировкам ${FIO}"// the id of textview where subject is stored + val message = checkDaySportString // the id of textview where body is stored + val emailIntent = Intent(Intent.ACTION_SEND) + emailIntent.type = "application/excel" + emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(email)) + emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject) + emailIntent.putExtra(Intent.EXTRA_STREAM, uri3) + emailIntent.putExtra(Intent.EXTRA_TEXT, message) + this.startActivity(Intent.createChooser(emailIntent, "Sending email...")) + //addDownload(uri) + Log.i("uri", uri.toString()) + + } catch (t: Throwable) { + //Toast.makeText(requireContext(), "Request failed try again: $t", Toast.LENGTH_LONG) .show() + } + } + + fun saveSport15DayAll(s15da: Int) { + val edit = prefSport15DayAll?.edit() + edit?.putInt("s15da", s15da) + edit?.apply() + Sport15DayAll = s15da + } + + fun saveSport15Day(s15d: Int) { + val edit = prefSport15Day?.edit() + edit?.putInt("s15d", s15d) + edit?.apply() + Sport15Day = s15d + } + + fun clearSport15Day() { + val edit = prefSport15Day?.edit() + edit?.clear() + edit?.apply() + Sport15Day = 0 + } + + fun saveSport7Day(s7d: Int) { + val edit = prefSport7Day?.edit() + edit?.putInt("s7d", s7d) + edit?.apply() + Sport7Day = s7d + } + + fun clearSport7Day() { + val edit = prefSport7Day?.edit() + edit?.clear() + edit?.apply() + Sport7Day = 0 + } + + + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) +// if (requestCode == pickFromGallery && resultCode == RESULT_OK) { +// if (data != null) { +// uri = data.data!! +// } +// binding.tvAttachment.text = uri.lastPathSegment +// binding.tvAttachment.visibility = View.VISIBLE +// } + } + + private fun progresListAdd() { + val db = MainDB.getDB(requireContext()) + val list = ArrayList() + liveCountCategoryCurrent() + + //Количество тренировок в день + db.getDaoSportCategory().getAllItemsSportCategoryCount("c").asLiveData() + .observe(requireActivity()) { itCount -> + itCount.forEach() { + val item = CountCategoryModel( + it.image.toString(), + ) + model.liveCountCategoryCurrent.value = item + } + } + + //Список тренировок по дня + db.getDaoDaySport().getAllItemDaySportDay().asLiveData() + .observe(requireActivity()) { itList -> + itList.forEach { + Log.d("123", it.category) + //db.getDaoSportCategory().getAllItemsSportCategory(it.category).asLiveData().observe(requireActivity()){itSport-> + val itemDayList = DayListModel( + it.id.toString(), + it.id.toString(), + it.day, + it.category, + it.check.toString(), + ) + list.add(itemDayList) + } + Log.d("sada", list.toString()) + model.liveDayListProgres.value = list + } + } + + private fun progresListAddEmail() { + val db = MainDB.getDB(requireContext()) + val list = ArrayList() + liveCountCategoryCurrent() + + //Количество тренировок в день + db.getDaoSportCategory().getAllItemsSportCategoryCount("c").asLiveData() + .observe(requireActivity()) { itCount -> + itCount.forEach() { + val item = CountCategoryModel( + it.image.toString(), + ) + model.liveCountCategoryCurrent.value = item + } + } + + //Список тренировок по дня + db.getDaoDaySport().getAllItemDaySportDay().asLiveData() + .observe(requireActivity()) { itList -> + itList.forEach { + Log.d("123", it.category) + //db.getDaoSportCategory().getAllItemsSportCategory(it.category).asLiveData().observe(requireActivity()){itSport-> + val itemDayList = DayListModel( + it.id.toString(), + it.id.toString(), + it.day, + it.category, + it.check.toString(), + ) + list.add(itemDayList) + } + Log.d("sada", list.toString()) + model.liveDayListProgres2.value = list + } + } + + fun progressListAddEmailBefore() { + val db = MainDB.getDB(requireContext()) + val list = ArrayList() + //Количество тренировок в день + db.getDaoQB().getAllBQProgress().asLiveData().observe(requireActivity()) { itCount -> + itCount.forEach() { + //val text = "Id: ${it.id} Name: ${it.name} Proce: ${it.price}" + //binding.txtList.append(text) + val item = BeforeListModel( + it.id!!.toInt(), + it.one, + it.two, + it.three, + it.four, + it.five, + it.six, + it.seven, + it.eight, + it.nine, + it.date + ) + //model.liveZakazCurrent.value = item//Передаем в liveDataCurrent один из продуктов, чтобы дальше эти данные использовать и передавать их в пробную ячейку + list.add(item)//Передали заполненый список + } + model.liveListProgresBeforeList.value = list + } + + } + + fun progressListAddEmailAfter() { + val db = MainDB.getDB(requireContext()) + val list = ArrayList() + db.getDaoQA().getAllAQProgress().asLiveData().observe(requireActivity()) { itCount -> + itCount.forEach() { + //val text = "Id: ${it.id} Name: ${it.name} Proce: ${it.price}" + //binding.txtList.append(text) + val item = AfterListModel( + it.id!!.toInt(), + it.one, + it.two, + it.three, + it.four, + it.five, + it.six, + it.seven, + it.eight, + it.nine, + it.ten, + it.elevenInt, + it.twelve, + it.date, + ) + //model.liveZakazCurrent.value = item//Передаем в liveDataCurrent один из продуктов, чтобы дальше эти данные использовать и передавать их в пробную ячейку + list.add(item)//Передали заполненый список + } + model.liveListProgresAfterList.value = list + } + } + + + private fun progresMonthAndDay() { + //initRcViewProgress() + val db = MainDB.getDB(requireContext()) + var listMouthDown = 0 + var listMouthAll = 0 + val data = LocalDate.now().toString() + //Прогрес в течение месяца + db.getDao().getAllItems().asLiveData().observe(requireActivity()) { itList -> + itList.forEach { + + if (it.day < data) { + listMouthDown = listMouthDown + 1 + listMouthAll = listMouthAll + 1 + } else { + listMouthAll = listMouthAll + 1 + } + } + val item = CountMonthModel( + listMouthDown, + listMouthAll + ) + model.liveCountMonthCurrent.value = item + } + + var listDayDown = 0 + var listDayAll = 0 + var name = "" + //Прогрес за в течение данного дня + db.getDaoDaySport().getAllItemDaySport(data).asLiveData() + .observe(requireActivity()) { itList -> + + itList.forEach { + if (it.check == 1) { + listDayDown = listDayDown + 1 + listDayAll = listDayAll + 1 + } else { + listDayAll = listDayAll + 1 + } + + } + val item = CountDayModel( + listDayDown, + listDayAll + ) + model.liveCountDayCurrent.value = item + + } + + + } + + + //Вывод прогресса по дням + private fun liveCountMonthCurrent() = with(binding) { + model.liveCountMonthCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + binding.txtProgresMonth.setText("Пройдено дней: ${it.countDown}/${it.countAll}") + } + + } + + //Вывод прогресса на один день + private fun liveCountDayCurrent() = with(binding) { + model.liveCountDayCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + binding.txtProgresDay.setText("Выполнено сегодня: ${it.countDown}/${it.countAll}") + } + + } + + //Получение количества записей + private fun liveCountCategoryCurrent() = with(binding) { + model.liveCountCategoryCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + countCategory = it.count + Log.d("countCategory", countCategory) + } + } + + //Функция запускающая отслеживания за списком, чтобы вовремя обновлять основную карточку продукта + private fun liveDayListProgres() = with(binding) { + val myRef = database.getReference(loginDoctor) + + model.liveDayListProgres.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + checkDaySportString = "" + var idCheck = 0 + for (i in 0..29) { + var checkDaySportInt = 0 + checkDaySportString += it[idCheck].day + ": " + for (j in 0..(countCategory.toInt()) - 1) { + if (it[idCheck].check == "0") { + checkDaySportString += it[idCheck].category + ", " + } else { + checkDaySportInt++ + } + idCheck++ + } + Log.d("checkDaySportInt", checkDaySportInt.toString()) + Log.d("countCategory.toInt())-1", ((countCategory.toInt()) - 1).toString()) + //Если пройдены все тренировки + if (checkDaySportInt == (countCategory.toInt())) { + checkDaySportString += "пройден.\n\n" + } + //Если пройдены не все тренировки + else { + checkDaySportString += ".\n\n" + } + } + + // binding.txtView.setText(checkDaySportString) + //Отправляем отчет в на сервер, где его получит врач + myRef.child(myRef.push().key ?: "blabla") + .setValue(ReportPatient(loginPatient, checkDaySportString)) + + } + } + + //Функция запускающая отслеживания за списком, чтобы вовремя обновлять основную карточку продукта + private fun liveDayListProgres2() = with(binding) { + val myRef = database.getReference(loginDoctor) + + model.liveDayListProgres2.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + checkDaySportString = "" + var idCheck = 0 + for (i in 0..29) { + var checkDaySportInt = 0 + checkDaySportString += it[idCheck].day + ": " + for (j in 0..(countCategory.toInt()) - 1) { + if (it[idCheck].check == "0") { + checkDaySportString += it[idCheck].category + ", " + } else { + checkDaySportInt++ + } + idCheck++ + } + Log.d("checkDaySportInt", checkDaySportInt.toString()) + Log.d("countCategory.toInt())-1", ((countCategory.toInt()) - 1).toString()) + //Если пройдены все тренировки + if (checkDaySportInt == (countCategory.toInt())) { + checkDaySportString += "пройден.\n\n" + } + //Если пройдены не все тренировки + else { + checkDaySportString += ".\n\n" + } + } + + // binding.txtView.setText(checkDaySportString) + //Отправляем отчет в на сервер, где его получит врач + myRef.child(myRef.push().key ?: "blabla") + .setValue(ReportPatient(loginPatient, checkDaySportString)) + sendEmail(checkDaySportString) + } + } + + fun txtProgresEmailCreate() { + + } + + fun visible1() { + binding.CLMainProgres.visibility = View.VISIBLE + binding.CLReportProgres.visibility = View.GONE + } + + fun visible2() { + binding.CLMainProgres.visibility = View.GONE + binding.CLReportProgres.visibility = View.VISIBLE + } + + //Открытие приложения Gmail и отправка через него + @SuppressLint("IntentReset") + fun sendEmail(checkDaySportString: String) { + val email = "azazaza08@yandex.ru" // the id of textview where email is stored + val subject = + "Отчет по тренировка Олега Игоревича Васильевочвича"// the id of textview where subject is stored + val message = checkDaySportString // the id of textview where body is stored + //val addresses = "t.t.maxi05092003@gmail.com" //incase if you are wishing to send it to multiple people + + + val intent = Intent(Intent.ACTION_SEND) + intent.data = Uri.parse("mailto:") + intent.type = "text/plain" + intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(email))// herer adresses is already string + intent.putExtra(Intent.EXTRA_SUBJECT, subject) // send the values as string + intent.putExtra(Intent.EXTRA_TEXT, message)// send the values as string + + + try { + startActivity(Intent.createChooser(intent, "Choose Email Client...")) + } catch (e: Exception) { + //Toast.makeText(requireContext(), e.message, Toast.LENGTH_LONG).show() + } + } + + private fun chatView(idUserChat: String) { + val database = Firebase.database + val myRef = database.getReference("message123w52") + + myRef.setValue("Hello, World!") + } + + private fun chatView1(idUserChat: String) { + binding.btnPushProgress.setOnClickListener() { + //if(binding.editMessage.text != null){ + //myRef.setValue(binding.editMessage.text.toString()) + // } + } + + } + + //ЗАдержка нажатия на кнопку + private fun timerButtonDoubleButton(btn: Button) { + val updateHandler = Handler() + + val runnable = Runnable { + btn.setEnabled(true) + } + + updateHandler.postDelayed(runnable, 5000) + } + + companion object { fun newInstance() = ProgresFragment() } + + override fun onClickDay(item: ProgressModel) { + + } } \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/User/fragmentUser/QuestionnaireFragment/QAfterFragment.kt b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/QuestionnaireFragment/QAfterFragment.kt new file mode 100644 index 0000000..f655572 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/QuestionnaireFragment/QAfterFragment.kt @@ -0,0 +1,681 @@ +package com.example.rehabilitation.User.fragmentUser.QuestionnaireFragment + +import android.app.AlertDialog +import android.content.Context +import android.content.Intent +import android.graphics.Color +import android.net.Uri +import android.os.Bundle +import android.provider.Settings +import android.util.Log +import androidx.fragment.app.Fragment +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import com.example.admin.Toast.showCustomInfoToast +import com.example.admin.Toast.showCustomNiceToast +import com.example.rehabilitation.Block +import com.example.rehabilitation.DayAfter +import com.example.rehabilitation.DayBefore +import com.example.rehabilitation.PauseDay +import com.example.rehabilitation.R +import com.example.rehabilitation.Room.MainDB +import com.example.rehabilitation.Room.Questionnaire.After.ItemAfterQuestionnaire +import com.example.rehabilitation.Room.Questionnaire.Before.ItemBeforeQuestionnaire +import com.example.rehabilitation.Sport15Day +import com.example.rehabilitation.Sport15DayAll +import com.example.rehabilitation.Sport7Day +import com.example.rehabilitation.SportCursDay +import com.example.rehabilitation.SportCursDayDangerAfter +import com.example.rehabilitation.SportCursDayDangerBefore +import com.example.rehabilitation.SportCursDayNumber +import com.example.rehabilitation.SportPlusCount +import com.example.rehabilitation.User.fragmentUser.SceduleFragment +import com.example.rehabilitation.countSport +import com.example.rehabilitation.databinding.FragmentQAfterBinding +import com.example.rehabilitation.prefBlock +import com.example.rehabilitation.prefCursDangerDayAfter +import com.example.rehabilitation.prefCursDangerDayBefore +import com.example.rehabilitation.prefCursDay +import com.example.rehabilitation.prefDayAfter +import com.example.rehabilitation.prefDayBefore +import com.example.rehabilitation.prefPauseDay +import com.example.rehabilitation.prefSport15Day +import com.example.rehabilitation.prefSport15DayAll +import com.example.rehabilitation.prefSport7Day +import com.example.rehabilitation.prefSportCursDayNumber +import com.example.rehabilitation.questionnaire_after +import com.example.rehabilitation.questionnaire_before + +import java.time.LocalDate + + +class QAfterFragment : Fragment() { + private lateinit var binding: FragmentQAfterBinding + + var one = "" + var two = "" + var thee = "" + var four = "" + var five = "" + var six = "" + var seven = "" + var eight = "" + var nine = "" + var ten = "" + var eleven = "" + var twelve = "" + + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + binding = FragmentQAfterBinding.inflate(layoutInflater, container, false) + return binding.root + } + + companion object { + fun newInstance() = QAfterFragment() + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + Log.d("lookDanger", "lookDanger") + Log.d("SportCursDayDangerAfter", "${SportCursDayDangerAfter}") + Log.d("SportCursDay", "${SportCursDay}") + Log.d("SportCursDayDangerBefore", "${SportCursDayDangerBefore}") + + + prefCursDay = activity?.getSharedPreferences("SportCursDay", Context.MODE_PRIVATE) + SportCursDay = prefCursDay?.getInt("scd", 0)!! + prefCursDangerDayAfter = + activity?.getSharedPreferences("CursDangerDayAfter", Context.MODE_PRIVATE) + SportCursDayDangerAfter = prefCursDangerDayAfter?.getInt("cdda", 0)!! + + prefCursDangerDayBefore = + activity?.getSharedPreferences("CursDangerDayBefore", Context.MODE_PRIVATE) + SportCursDayDangerBefore = prefCursDangerDayBefore?.getInt("cddb", 0)!! + + //Какой сегодня курс + prefSportCursDayNumber = + activity?.getSharedPreferences("SportCursDayNumber", Context.MODE_PRIVATE) + SportCursDayNumber = prefSportCursDayNumber?.getInt("scdn", 0)!! + + + //Для анкет, какие выполнены + prefPauseDay = activity?.getSharedPreferences("PauseDay", Context.MODE_PRIVATE) + PauseDay = prefPauseDay?.getString("pd", "")!! + prefBlock = activity?.getSharedPreferences("Block", Context.MODE_PRIVATE) + Block = prefBlock?.getString("b", "")!! + + //Для анкет, какие выполнены + prefDayBefore = activity?.getSharedPreferences("DayBefore", Context.MODE_PRIVATE) + DayBefore = prefDayBefore?.getString("db", "")!! + prefDayAfter = activity?.getSharedPreferences("DayAfter", Context.MODE_PRIVATE) + DayAfter = prefDayAfter?.getString("da", "")!! + + //Пройдено ли 15 дне и отправен отчет + prefSport15DayAll = activity?.getSharedPreferences("Sport15DayAll", Context.MODE_PRIVATE) + Sport15DayAll = prefSport15DayAll?.getInt("s15da", 0)!! + + //Отчет на 15 день + prefSport15Day = activity?.getSharedPreferences("Sport15Day", Context.MODE_PRIVATE) + Sport15Day = prefSport15Day?.getInt("s15d", 0)!! + + //Отчет на 7 день + prefSport7Day = activity?.getSharedPreferences("Sport7Day", Context.MODE_PRIVATE) + Sport7Day = prefSport7Day?.getInt("s7d", 0)!! + + buttenAdd() + + //Выход + binding.btnBack.setOnClickListener { + activity?.supportFragmentManager?.beginTransaction() + ?.replace(R.id.placeHolderFragment, SceduleFragment.newInstance())?.commit() + } + + //Сохраняем результат + binding.btnSaveQuestionnaire.setOnClickListener { + if (one != "" && two != "" && thee != "" && four != "" && five != "" && six != "" && seven != "" && eight != "" && nine != "" && ten != "" && eleven != "" && twelve != "") { + + if(ten == "1"){ + AlertDialog.Builder(requireContext()) + .setTitle("Анкета") + .setMessage("Вы уверенны в выбронных пунктах анкеты? Если вы нажмете 'Подтвердить' ваш курс временно заблакируется, чтобы вы не нанесли вред своему здоровью") + .setNeutralButton("Подтвердить") { dialog, whichButton -> + addQuestionnaire() + } + .setNegativeButton("Отмена") { dialog, whichButton -> + + } + .show() + } + else{ + addQuestionnaire() + } + + + } else { + Toast(requireContext()).showCustomInfoToast( + "Не все пункты выбраны", + requireActivity() + ) + } + } + + } + + //Функция + fun addQuestionnaire(){ + clearSportCursDayDangerBefore() + if(ten == "1"){ + saveBlock(LocalDate.now().plusDays(3).toString()) + saveSportCursDayDangerAfter(2) + Log.d("saveSportCursDayDangerAfter","${2}") + addQuestionAfter() + } + else if (one >= "6" || thee == "0"||six == "1"||eight == "1"||eleven == "1") { + savePauseDay(LocalDate.now().plusDays(1).toString()) + saveSportCursDayDangerAfter(1) + addQuestionAfter() + } + else{ + clearSportCursDayDangerBefore() + clearSportCursDayDangerAfter() + addQuestionAfter() + + } + + } + + fun addQuestionAfter() { + val db = MainDB.getDB(requireContext()) + + val item = ItemAfterQuestionnaire( + null, + one, + two, + thee, + four, + five, + six, + seven, + eight, + nine, + ten, + eleven, + twelve, + LocalDate.now().toString() + ) + Thread { + db.getDaoQA().insertAQ(item) + db.getDao().updateDay(LocalDate.now().toString(), (SportCursDay - 1).toString()) + }.start() + + saveDayAfter(LocalDate.now().toString()) + + if (SportCursDay == 7 && Sport7Day == 0) { + saveSport7Day(1) + } else if (SportCursDay == 15 && Sport15Day == 0) { + saveSport15Day(1) + } + +// questionnaire_after = LocalDate.now().toString() +// questionnaire_before = LocalDate.now().toString() +// //QBSaveDataB(LocalDate.now().toString()) +// //Log.d("aaaaaa",questionnaire?.getString("QB", "")!!.toString()) + activity?.supportFragmentManager?.beginTransaction() + ?.replace(R.id.placeHolderFragment, SceduleFragment.newInstance())?.commit() + } + + + fun saveSport15Day(s15d: Int) { + val edit = prefSport15Day?.edit() + edit?.putInt("s15d", s15d) + edit?.apply() + Sport15Day = s15d + } + + fun clearSport15Day() { + val edit = prefSport15Day?.edit() + edit?.clear() + edit?.apply() + Sport15Day = 0 + } + + fun saveSport7Day(s7d: Int) { + val edit = prefSport7Day?.edit() + edit?.putInt("s7d", s7d) + edit?.apply() + Sport7Day = s7d + } + + fun clearSport7Day() { + val edit = prefSport7Day?.edit() + edit?.clear() + edit?.apply() + Sport7Day = 0 + } + + fun savePauseDay(pd: String) { + val edit = prefPauseDay?.edit() + edit?.putString("pd", pd) + edit?.apply() + PauseDay = pd + } + + fun clearPauseDay() { + val edit = prefPauseDay?.edit() + edit?.clear() + edit?.apply() + PauseDay = "" + } + + fun saveBlock(b: String) { + val edit = prefBlock?.edit() + edit?.putString("b", b) + edit?.apply() + Block = b + } + + fun clearBlock() { + val edit = prefBlock?.edit() + edit?.clear() + edit?.apply() + Block = "" + } + + + fun saveDayBefore(db: String) { + val edit = prefDayBefore?.edit() + edit?.putString("db", db) + edit?.apply() + DayBefore = db + } + + fun clearDayBefore() { + val edit = prefDayBefore?.edit() + edit?.clear() + edit?.apply() + DayBefore = "" + } + + fun saveDayAfter(da: String) { + val edit = prefDayAfter?.edit() + edit?.putString("da", da) + edit?.apply() + DayAfter = da + } + + fun clearDayAfter() { + val edit = prefDayAfter?.edit() + edit?.clear() + edit?.apply() + DayAfter = "" + } + + + fun saveSportCursDay(scd: Int) { + val edit = prefCursDay?.edit() + edit?.putInt("scd", scd) + edit?.apply() + SportCursDay = scd + } + + fun clearSportCursDay() { + val edit = prefCursDay?.edit() + edit?.clear() + edit?.apply() + SportCursDay = 0 + } + + fun saveSportCursDayDangerBefore(cddb: Int) { + val edit = prefCursDangerDayBefore?.edit() + edit?.putInt("cddb", cddb) + edit?.apply() + SportCursDayDangerBefore = cddb + } + + fun clearSportCursDayDangerBefore() { + val edit = prefCursDangerDayBefore?.edit() + edit?.clear() + edit?.apply() + SportCursDayDangerBefore = 0 + } + + fun saveSportCursDayDangerAfter(cdda: Int) { + val edit = prefCursDangerDayAfter?.edit() + edit?.putInt("cdda", cdda) + edit?.apply() + SportCursDayDangerAfter = cdda + } + + fun clearSportCursDayDangerAfter() { + val edit = prefCursDangerDayAfter?.edit() + edit?.clear() + edit?.apply() + SportCursDayDangerAfter = 0 + } + + private fun buttenAdd() { + buttenAdd1() + buttenAdd2() + buttenAdd3() + buttenAdd4() + buttenAdd5() + buttenAdd6() + buttenAdd7() + buttenAdd8() + buttenAdd9() + buttenAdd10() + buttenAdd11() + buttenAdd12() + } + + private fun buttenAdd1() { + binding.CVQ10.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "0" + } + binding.CVQ11.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "1" + } + binding.CVQ12.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "2" + } + binding.CVQ13.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "3" + } + binding.CVQ14.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "4" + + } + binding.CVQ15.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "5" + } + binding.CVQ16.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "6" + } + binding.CVQ17.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "7" + } + binding.CVQ18.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "8" + } + binding.CVQ19.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "9" + } + binding.CVQ110.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ110.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + one = "10" + } + } + + private fun buttenAdd2() { + binding.CVQyes2.setOnClickListener { + binding.CVQyes2.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno2.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + two = "1" + } + binding.CVQno2.setOnClickListener { + binding.CVQyes2.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno2.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + two = "0" + } + } + + private fun buttenAdd3() { + binding.CVQyes3.setOnClickListener { + Log.d("CVQyes3", "CVQyes3") + binding.CVQyes3.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno3.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + thee = "1" + } + binding.CVQno3.setOnClickListener { + binding.CVQyes3.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno3.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + thee = "0" + } + } + + private fun buttenAdd4() { + binding.CVQyes4.setOnClickListener { + binding.CVQyes4.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno4.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + four = "1" + } + binding.CVQno4.setOnClickListener { + binding.CVQyes4.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno4.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + four = "0" + } + } + + private fun buttenAdd5() { + binding.CVQyes5.setOnClickListener { + binding.CVQyes5.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno5.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + five = "1" + } + binding.CVQno5.setOnClickListener { + binding.CVQyes5.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno5.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + five = "0" + } + } + + private fun buttenAdd6() { + binding.CVQyes6.setOnClickListener { + binding.CVQyes6.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno6.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + six = "1" + } + binding.CVQno6.setOnClickListener { + binding.CVQyes6.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno6.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + six = "0" + } + } + + private fun buttenAdd7() { + binding.CVQyes7.setOnClickListener { + binding.CVQyes7.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno7.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + seven = "1" + } + binding.CVQno7.setOnClickListener { + binding.CVQyes7.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno7.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + seven = "0" + } + } + + private fun buttenAdd8() { + binding.CVQyes8.setOnClickListener { + binding.CVQyes8.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno8.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + eight = "1" + } + binding.CVQno8.setOnClickListener { + binding.CVQyes8.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno8.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + eight = "0" + } + } + + private fun buttenAdd9() { + binding.CVQyes9.setOnClickListener { + binding.CVQyes9.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno9.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + nine = "1" + } + binding.CVQno9.setOnClickListener { + binding.CVQyes9.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno9.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + nine = "0" + } + } + + private fun buttenAdd10() { + binding.CVQyes10.setOnClickListener { + binding.CVQyes10.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + ten = "1" + } + binding.CVQno10.setOnClickListener { + binding.CVQyes10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno10.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + ten = "0" + } + } + + private fun buttenAdd11() { + binding.CVQyes11.setOnClickListener { + binding.CVQyes11.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + eleven = "1" + } + binding.CVQno11.setOnClickListener { + binding.CVQyes11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno11.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + eleven = "0" + } + } + + private fun buttenAdd12() { + binding.CVQyes12.setOnClickListener { + binding.CVQyes12.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + twelve = "1" + } + binding.CVQno12.setOnClickListener { + binding.CVQyes12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno12.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + twelve = "0" + } + } + + +// fun QBSaveDataA(date: String) { +// val QB = questionnaire?.edit() +// QB?.putString("QA", date) +// QB?.apply() +// } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/User/fragmentUser/QuestionnaireFragment/QBeforeFragment.kt b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/QuestionnaireFragment/QBeforeFragment.kt new file mode 100644 index 0000000..53bcf93 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/QuestionnaireFragment/QBeforeFragment.kt @@ -0,0 +1,1446 @@ +package com.example.rehabilitation.User.fragmentUser.QuestionnaireFragment + +import android.app.AlertDialog +import android.content.Context +import android.graphics.Color +import android.os.Bundle +import android.util.Log +import androidx.fragment.app.Fragment +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.fragment.app.activityViewModels +import androidx.lifecycle.asLiveData +import com.example.admin.Toast.showCustomInfoToast +import com.example.admin.Toast.showCustomNiceToast +import com.example.rehabilitation.Block +import com.example.rehabilitation.CursDayNull +import com.example.rehabilitation.DayAfter +import com.example.rehabilitation.DayBefore +import com.example.rehabilitation.PauseDay +import com.example.rehabilitation.R +import com.example.rehabilitation.Room.ItemDaySport +import com.example.rehabilitation.Room.MainDB +import com.example.rehabilitation.Room.Questionnaire.Before.ItemBeforeQuestionnaire +import com.example.rehabilitation.SportCursDay +import com.example.rehabilitation.SportCursDayDangerAfter +import com.example.rehabilitation.SportCursDayDangerBefore +import com.example.rehabilitation.SportCursDayNumber +import com.example.rehabilitation.SportMaxCount +import com.example.rehabilitation.SportPlusCount +import com.example.rehabilitation.User.fragmentUser.SceduleFragment +import com.example.rehabilitation.databinding.FragmentQBeforeBinding +import com.example.rehabilitation.daySpoartOpen +import com.example.rehabilitation.daySpoartOpenKey +import com.example.rehabilitation.model_adapter.Day.DayListModel +import com.example.rehabilitation.model_adapter.Questionnair.BeforeModel +import com.example.rehabilitation.model_adapter.SportCategory.SportCategoryModel +import com.example.rehabilitation.prefBlock +import com.example.rehabilitation.prefCursDangerDayAfter +import com.example.rehabilitation.prefCursDangerDayBefore +import com.example.rehabilitation.prefCursDay +import com.example.rehabilitation.prefCursDayNull +import com.example.rehabilitation.prefDayAfter +import com.example.rehabilitation.prefDayBefore +import com.example.rehabilitation.prefPauseDay +import com.example.rehabilitation.prefSportCursDayNumber +import com.example.rehabilitation.prefSportMaxCount +import com.example.rehabilitation.prefSportPlusCount +import com.example.rehabilitation.questionnaire_after +//import com.example.rehabilitation.questionnaire +import com.example.rehabilitation.questionnaire_before +import com.example.sqlitework.dip.MainViewModel +import java.time.LocalDate + + +class QBeforeFragment : Fragment() { + private lateinit var binding: FragmentQBeforeBinding + private val model: MainViewModel by activityViewModels()//Инициализировали класс + + + var one = "" + var two = "" + var thee = "" + var four = "" + var five = "" + var six = "" + var seven = "" + var eight = "" + var nine = "" + + var eleven = "" + var twelve = "" + + //Check для запуска считывания базы + var CheckSportCategory = false + + //Количество упражнений + var maxCountSC = 0 + + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + // Inflate the layout for this fragment + binding = FragmentQBeforeBinding.inflate(layoutInflater, container, false) + return binding.root + } + + companion object { + fun newInstance() = QBeforeFragment() + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + // data_prefB() + // onInkrementB() + saveSportPlusCount(0) + saveSportMaxCount(0) + //Количество пройденых дней + prefCursDay = activity?.getSharedPreferences("SportCursDay", Context.MODE_PRIVATE) + SportCursDay = prefCursDay?.getInt("scd", 0)!! + + //Какой сегодня курс + prefSportCursDayNumber = + activity?.getSharedPreferences("SportCursDayNumber", Context.MODE_PRIVATE) + SportCursDayNumber = prefSportCursDayNumber?.getInt("scdn", 0)!! + + prefCursDangerDayBefore = + activity?.getSharedPreferences("CursDangerDayBefore", Context.MODE_PRIVATE) + SportCursDayDangerBefore = prefCursDangerDayBefore?.getInt("cddb", 0)!! + + + prefCursDayNull = activity?.getSharedPreferences("CursDayNull", Context.MODE_PRIVATE) + CursDayNull = prefCursDayNull?.getString("cdn", "")!! + + prefCursDangerDayAfter = + activity?.getSharedPreferences("CursDangerDayAfter", Context.MODE_PRIVATE) + SportCursDayDangerAfter = prefCursDangerDayAfter?.getInt("cdda", 0)!! + + //Для количества тренирвоок + prefSportPlusCount = activity?.getSharedPreferences("SportPlusCount", Context.MODE_PRIVATE) + SportPlusCount = prefSportPlusCount?.getInt("spc", 0)!! + prefSportMaxCount = activity?.getSharedPreferences("SportMaxCount", Context.MODE_PRIVATE) + SportMaxCount = prefSportMaxCount?.getInt("smc", 0)!! + + + //Для пауз и блоков + prefPauseDay = activity?.getSharedPreferences("PauseDay", Context.MODE_PRIVATE) + PauseDay = prefPauseDay?.getString("pd", "")!! + prefBlock = activity?.getSharedPreferences("Block", Context.MODE_PRIVATE) + Block = prefBlock?.getString("b", "")!! + + //Для анкет, какие выполнены + prefDayBefore = activity?.getSharedPreferences("DayBefore", Context.MODE_PRIVATE) + DayBefore = prefDayBefore?.getString("db", "")!! + prefDayAfter = activity?.getSharedPreferences("DayAfter", Context.MODE_PRIVATE) + DayAfter = prefDayAfter?.getString("da", "")!! + + buttenAdd() + + //Выход + binding.btnExitQB.setOnClickListener { + activity?.supportFragmentManager?.beginTransaction() + ?.replace(R.id.placeHolderFragment, SceduleFragment.newInstance())?.commit() + } + + //Сохраняем результат + binding.btnSaveQuestionnaire.setOnClickListener { + Log.d("lookDanger", "lookDanger") + Log.d("SportCursDayDangerAfter", "${SportCursDayDangerAfter}") + Log.d("SportCursDay", "${SportCursDay}") + Log.d("SportCursDayDangerBefore", "${SportCursDayDangerBefore}") + Log.d("btnSaveQuestionnaire", "btnSaveQuestionnaire") + if (one != "" && two != "" && thee != "" && four != "" && five != "" && six != "" && seven != "" && eight != "" && nine != "") { + if (one >= "6") { + AlertDialog.Builder(requireContext()) + .setTitle("Анкета") + .setMessage("Вы уверенны в выбронных пунктах анкеты? Если вы нажмете 'Подтвердить' ваш курс временно заблакируется, чтобы вы не нанесли вред своему здоровью") + .setNeutralButton("Подтвердить") { dialog, whichButton -> + addQuestionnaire() + } + .setNegativeButton("Отмена") { dialog, whichButton -> + + } + .show() + } else { + addQuestionnaire() + } + + } else { + Toast(requireContext()).showCustomInfoToast( + "Не все пункты выбраны", + requireActivity() + ) + } + + + } + + //Получение данных по курсу + liveCountSportCategoryCurrent() + liveSportCategoryAllArticleList() + } + + //Функция + fun addQuestionnaire() { + visibleLoad() + + clearSportPlusCount() + clearSportMaxCount() + if (one >= "6") { + saveBlock(LocalDate.now().plusDays(3).toString()) + saveSportCursDayDangerBefore(2) + addQuestianBefore() + activity?.supportFragmentManager?.beginTransaction() + ?.replace(R.id.placeHolderFragment, SceduleFragment.newInstance())?.commit() + } else if (four == "1" || five == "1" || six == "1" || seven == "1" || nine == "1") { + savePauseDay(LocalDate.now().plusDays(1).toString()) + saveSportCursDayDangerBefore(1) + addQuestianBefore() + activity?.supportFragmentManager?.beginTransaction() + ?.replace(R.id.placeHolderFragment, SceduleFragment.newInstance())?.commit() + } else {//Если все хорошо + if (SportCursDayDangerBefore == 0 && SportCursDayDangerAfter == 0) { + Log.i("SportCursDay", "${SportCursDay}") + Log.i("SportCursDayNumber", "${SportCursDayNumber}") + + saveCursDayNumber(SportCursDayNumber + 1) + saveSportCursDay(SportCursDay + 1) + addDaySport(SportCursDayNumber) + + } else if (SportCursDayDangerBefore == 2 || SportCursDayDangerAfter == 2) { + saveSportCursDay(SportCursDay + 1) + Log.i("SportCursDay", "${SportCursDay}") + Log.i("SportCursDayNumber", "${SportCursDayNumber}") + if (SportCursDayNumber == 0) { + addDaySport(1) + saveCursDayNumber(SportCursDayNumber + 1) + } else if (SportCursDayNumber == 1) { + addDaySport(SportCursDayNumber) + } else if (SportCursDayNumber == 2) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(SportCursDayNumber) + } else if (SportCursDayNumber == 3) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(SportCursDayNumber) + } else if (SportCursDayNumber == 4) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(SportCursDayNumber) + } else if (SportCursDayNumber == 5) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(SportCursDayNumber) + } else if (SportCursDayNumber == 6) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(SportCursDayNumber) + } else if (SportCursDayNumber == 7) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } else if (SportCursDayNumber == 8) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } else if (SportCursDayNumber == 9) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } else if (SportCursDayNumber == 10) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } else if (SportCursDayNumber == 11) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } else if (SportCursDayNumber == 12) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } else if (SportCursDayNumber == 13) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } else if (SportCursDayNumber == 14) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } + } else if (SportCursDayDangerBefore == 1 || SportCursDayDangerAfter == 1) { + Log.i("SportCursDayDangerBefore1", "${SportCursDayDangerBefore}") + Log.i("SportCursDayDangerAfter1", "${SportCursDayDangerAfter}") + + saveSportCursDay(SportCursDay + 1) + Log.i("SportCursDay", "${SportCursDay}") + Log.i("SportCursDayNumber", "${SportCursDayNumber}") + if (SportCursDayNumber == 0) { + addDaySport(1) + saveCursDayNumber(SportCursDayNumber + 1) + } else if (SportCursDayNumber == 1) { + addDaySport(SportCursDayNumber) + } else if (SportCursDayNumber == 2) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(SportCursDayNumber) + } else if (SportCursDayNumber == 3) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(SportCursDayNumber) + } else if (SportCursDayNumber == 4) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(SportCursDayNumber) + } else if (SportCursDayNumber == 5) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(SportCursDayNumber) + } else if (SportCursDayNumber == 6) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(SportCursDayNumber) + } else if (SportCursDayNumber == 7) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } else if (SportCursDayNumber == 8) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } else if (SportCursDayNumber == 9) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } else if (SportCursDayNumber == 10) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } else if (SportCursDayNumber == 11) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } else if (SportCursDayNumber == 12) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } else if (SportCursDayNumber == 13) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } else if (SportCursDayNumber == 14) { + saveCursDayNumber(SportCursDayNumber - 1) + addDaySport(6) + } + + } + + } + + } + + + fun visibleLoad() { + binding.CLMainBefore.visibility = View.GONE + binding.CLLoad.visibility = View.VISIBLE + } + + fun visibleBefore() { + binding.CLMainBefore.visibility = View.VISIBLE + binding.CLLoad.visibility = View.GONE + } + + fun lookDanger() { + + + if (SportCursDayDangerBefore == 1) { + if (SportCursDay == 1) { + addDaySport(SportCursDay) + } else if (SportCursDay <= 7) { + addDaySport(SportCursDay - 1) + } else if (SportCursDay in 8..15) { + addDaySport(6) + } + } else if (SportCursDayDangerAfter == 0 && SportCursDayDangerBefore == 0) { + addDaySport(SportCursDay) + } else if (SportCursDayDangerAfter == 2) { + Toast(requireContext()).showCustomInfoToast("Обратитесь к врачу", requireActivity()) + addQuestianBefore() + } + + } + + + //Вызываем нужное заполнение данных + fun addDaySport(DaySport: Int) { + Log.d("addDaySport", "${DaySport}") + when (DaySport) { + 1 -> addSportCyrs1() + 2 -> addSportCyrs2() + 3 -> addSportCyrs3() + 4 -> addSportCyrs4() + 5 -> addSportCyrs5() + 6 -> addSportCyrs6() + 7 -> addSportCyrs7() + 8 -> addSportCyrs7() + 9 -> addSportCyrs7() + 10 -> addSportCyrs7() + 11 -> addSportCyrs7() + 12 -> addSportCyrs7() + 13 -> addSportCyrs7() + 14 -> addSportCyrs7() + 15 -> addSportCyrs7() + } + } + + //Вывод прогресса на один день + private fun liveCountSportCategoryCurrent() = with(binding) { + if (CheckSportCategory == true) { + model.liveCountSportCategoryCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + maxCountSC = it.name.toInt()//КОличество активированных упражнений + + val db = MainDB.getDB(requireContext()) + val list = ArrayList() + db.getDaoSportCategory().getCountSportCategory(it.article).asLiveData() + .observe(requireActivity()) { itList -> + var number = 1; + itList.forEach { + Log.d("123", it.category) + val itemSportCategory = SportCategoryModel( + it.id.toString(), + it.name, + it.desc, + it.count, + it.image, + it.category, + it.article, + it.check + ) + list.add(itemSportCategory)//Передали заполненый список + + } + model.liveSportCategoryAllArticleList.value = list + Log.d("sadas", list.toString()) + } + + } + } + } + + //Вывод прогресса на один день + private fun liveSportCategoryAllArticleList() = with(binding) { + val db = MainDB.getDB(requireContext()) + if (CheckSportCategory == true) { + model.liveSportCategoryAllArticleList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment + for (j in 0..maxCountSC-1) { + val item = ItemDaySport( + null, + LocalDate.now().toString(), + it[j].category, + 0, + 1 + ) + Thread { + db.getDaoDaySport().insertItemDaySport(item) + }.start() + } + saveCursDayNull(LocalDate.now().toString()) + saveSportPlusCount(0) + saveSportMaxCount(maxCountSC) + clearDayAfter() + clearSportCursDayDangerBefore() + clearSportCursDayDangerAfter() + addQuestianBefore() + CheckSportCategory = false + } + } + } + + private fun addSportCyrs1() { + CheckSportCategory = true //Активируем получение данных + Log.d("addSportCyrs1", "addSportCyrs1") + val db = MainDB.getDB(requireContext()) + db.getDaoSportCategory().getCountSportCategory("1cbjSport07082003").asLiveData() + .observe(requireActivity()) { itList -> + var number = 1; + itList.forEach { + Log.d("123", it.category) + val itemSportCategory = SportCategoryModel( + it.id.toString(), + it.name, + it.desc, + it.count, + it.image, + it.category, + it.article, + it.check + ) + model.liveCountSportCategoryCurrent.value = itemSportCategory + } + + } + +// val arr1 = arrayOf("c1","c2","c3","c4","c8","c10","c14","c16","c15","c7","b1","b2","b3","j1","j2","j4","j3","j5","j6","j8") +// val max = 19 +// for (j in 0..max) { +// val item = ItemDaySport( +// null, +// LocalDate.now().toString(), +// arr1[j], +// 0, +// 1 +// ) +// Thread { +// db.getDaoDaySport().insertItemDaySport(item) +// }.start() +// } +// saveCursDayNull(LocalDate.now().toString()) +// saveSportPlusCount(0) +// saveSportMaxCount(max+1) +// clearDayAfter() +// clearSportCursDayDangerBefore() +// clearSportCursDayDangerAfter() +// addQuestianBefore() + } + + private fun addSportCyrs2() { + CheckSportCategory = true //Активируем получение данных + Log.d("addSportCyrs2", "addSportCyrs2") + val db = MainDB.getDB(requireContext()) + db.getDaoSportCategory().getCountSportCategory("2cbjSport07082003").asLiveData() + .observe(requireActivity()) { itList -> + var number = 1; + itList.forEach { + Log.d("123", it.category) + val itemSportCategory = SportCategoryModel( + it.id.toString(), + it.name, + it.desc, + it.count, + it.image, + it.category, + it.article, + it.check + ) + model.liveCountSportCategoryCurrent.value = itemSportCategory + } + + } +// val db = MainDB.getDB(requireContext()) +// +// val arr2 = arrayOf( +// "c1", +// "c2", +// "c3", +// "c4", +// "c8", +// "c9", +// "c5", +// "c10", +// "c14", +// "c16", +// "c15", +// "c12", +// "c7", +// "b1", +// "b2", +// "b3", +// "j1", +// "j2", +// "j4", +// "j3", +// "j5", +// "j6", +// "j8" +// ) +// val max = 22 +// for (j in 0..max) { +// val item = ItemDaySport( +// null, +// LocalDate.now().toString(), +// arr2[j], +// 0, +// 1 +// ) +// Thread { +// db.getDaoDaySport().insertItemDaySport(item) +// }.start() +// } +// saveCursDayNull(LocalDate.now().toString()) +// saveSportPlusCount(0) +// saveSportMaxCount(max + 1) +// clearDayAfter() +// clearSportCursDayDangerBefore() +// clearSportCursDayDangerAfter() +// addQuestianBefore() + } + + private fun addSportCyrs3() { + CheckSportCategory = true //Активируем получение данных + Log.d("addSportCyrs3", "addSportCyrs3") + val db = MainDB.getDB(requireContext()) + db.getDaoSportCategory().getCountSportCategory("3cbjSport07082003").asLiveData() + .observe(requireActivity()) { itList -> + var number = 1; + itList.forEach { + Log.d("123", it.category) + val itemSportCategory = SportCategoryModel( + it.id.toString(), + it.name, + it.desc, + it.count, + it.image, + it.category, + it.article, + it.check + ) + model.liveCountSportCategoryCurrent.value = itemSportCategory + } + + } +// val db = MainDB.getDB(requireContext()) +// val arr3 = arrayOf( +// "c1", +// "c2", +// "c3", +// "c4", +// "c8", +// "c9", +// "c5", +// "c6", +// "c14", +// "c16", +// "c15", +// "c12", +// "c13", +// "c10", +// "c7", +// "b1", +// "b2", +// "b3", +// "j1", +// "j2", +// "j4", +// "j3", +// "j5", +// "j6", +// "j8" +// ) +// val max = 24 +// for (j in 0..max) { +// val item = ItemDaySport( +// null, +// LocalDate.now().toString(), +// arr3[j], +// 0, +// 1 +// ) +// Thread { +// db.getDaoDaySport().insertItemDaySport(item) +// }.start() +// } +// saveCursDayNull(LocalDate.now().toString()) +// saveSportPlusCount(0) +// saveSportMaxCount(max + 1) +// clearDayAfter() +// clearSportCursDayDangerBefore() +// clearSportCursDayDangerAfter() +// addQuestianBefore() + } + + private fun addSportCyrs4() { + CheckSportCategory = true //Активируем получение данных + Log.d("addSportCyrs4", "addSportCyrs4") + val db = MainDB.getDB(requireContext()) + db.getDaoSportCategory().getCountSportCategory("4cbjSport07082003").asLiveData() + .observe(requireActivity()) { itList -> + var number = 1; + itList.forEach { + Log.d("123", it.category) + val itemSportCategory = SportCategoryModel( + it.id.toString(), + it.name, + it.desc, + it.count, + it.image, + it.category, + it.article, + it.check + ) + model.liveCountSportCategoryCurrent.value = itemSportCategory + } + + } +// val db = MainDB.getDB(requireContext()) +// val arr4 = arrayOf( +// "c1", +// "c2", +// "c3", +// "c4", +// "c8", +// "c9", +// "c5", +// "c6", +// "c14", +// "c16", +// "c17", +// "c18", +// "c15", +// "c12", +// "c13", +// "c10", +// "c7", +// "b1", +// "b2", +// "b3", +// "j1", +// "j2", +// "j4", +// "j3", +// "j5", +// "j6", +// "j8" +// ) +// val max = 26 +// for (j in 0..max) { +// val item = ItemDaySport( +// null, +// LocalDate.now().toString(), +// arr4[j], +// 0, +// 1 +// ) +// Thread { +// db.getDaoDaySport().insertItemDaySport(item) +// }.start() +// } +// saveCursDayNull(LocalDate.now().toString()) +// saveSportPlusCount(0) +// saveSportMaxCount(max + 1) +// clearDayAfter() +// clearSportCursDayDangerBefore() +// clearSportCursDayDangerAfter() +// addQuestianBefore() + } + + private fun addSportCyrs5() { + CheckSportCategory = true //Активируем получение данных + Log.d("addSportCyrs5", "addSportCyrs5") + val db = MainDB.getDB(requireContext()) + db.getDaoSportCategory().getCountSportCategory("5cbjSport07082003").asLiveData() + .observe(requireActivity()) { itList -> + var number = 1; + itList.forEach { + Log.d("123", it.category) + val itemSportCategory = SportCategoryModel( + it.id.toString(), + it.name, + it.desc, + it.count, + it.image, + it.category, + it.article, + it.check + ) + model.liveCountSportCategoryCurrent.value = itemSportCategory + } + + } +// val db = MainDB.getDB(requireContext()) +// val arr5 = arrayOf( +// "c1", +// "c2", +// "c3", +// "c4", +// "c8", +// "c9", +// "c5", +// "c6", +// "c14", +// "c16", +// "c17", +// "c18", +// "c15", +// "c12", +// "c13", +// "c10", +// "c7", +// "b1", +// "b2", +// "b3", +// "b4", +// "j1", +// "j2", +// "j4", +// "j3", +// "j5", +// "j6", +// "j8", +// "j9" +// ) +// val max = 28 +// for (j in 0..max) { +// val item = ItemDaySport( +// null, +// LocalDate.now().toString(), +// arr5[j], +// 0, +// 1 +// ) +// Thread { +// db.getDaoDaySport().insertItemDaySport(item) +// }.start() +// } +// saveCursDayNull(LocalDate.now().toString()) +// saveSportPlusCount(0) +// saveSportMaxCount(max + 1) +// clearDayAfter() +// clearSportCursDayDangerBefore() +// clearSportCursDayDangerAfter() +// addQuestianBefore() + } + + private fun addSportCyrs6() { + CheckSportCategory = true //Активируем получение данных + Log.d("addSportCyrs6", "addSportCyrs6") + val db = MainDB.getDB(requireContext()) + db.getDaoSportCategory().getCountSportCategory("6cbjSport07082003").asLiveData() + .observe(requireActivity()) { itList -> + var number = 1; + itList.forEach { + Log.d("123", it.category) + val itemSportCategory = SportCategoryModel( + it.id.toString(), + it.name, + it.desc, + it.count, + it.image, + it.category, + it.article, + it.check + ) + model.liveCountSportCategoryCurrent.value = itemSportCategory + } + + } +// val db = MainDB.getDB(requireContext()) +// val arr6 = arrayOf( +// "c1", +// "c2", +// "c3", +// "c4", +// "c8", +// "c9", +// "c5", +// "c6", +// "c14", +// "c16", +// "c17", +// "c18", +// "c15", +// "c12", +// "c13", +// "c10", +// "c7", +// "b1", +// "b2", +// "b3", +// "b4", +// "j1", +// "j2", +// "j4", +// "j3", +// "j5", +// "j6", +// "j8", +// "j10", +// "j9" +// ) +// val max = 29 +// for (j in 0..max) { +// val item = ItemDaySport( +// null, +// LocalDate.now().toString(), +// arr6[j], +// 0, +// 1 +// ) +// Thread { +// db.getDaoDaySport().insertItemDaySport(item) +// }.start() +// } +// saveCursDayNull(LocalDate.now().toString()) +// saveSportPlusCount(0) +// saveSportMaxCount(max + 1) +// clearDayAfter() +// clearSportCursDayDangerBefore() +// clearSportCursDayDangerAfter() +// addQuestianBefore() + } + + private fun addSportCyrs7() { + CheckSportCategory = true //Активируем получение данных + Log.d("addSportCyrs7", "addSportCyrs7") + val db = MainDB.getDB(requireContext()) + db.getDaoSportCategory().getCountSportCategory("7cbjSport07082003").asLiveData() + .observe(requireActivity()) { itList -> + var number = 1; + itList.forEach { + Log.d("123", it.category) + val itemSportCategory = SportCategoryModel( + it.id.toString(), + it.name, + it.desc, + it.count, + it.image, + it.category, + it.article, + it.check + ) + model.liveCountSportCategoryCurrent.value = itemSportCategory + } + + } +// val db = MainDB.getDB(requireContext()) +// +// +// val arr7 = arrayOf( +// "c1", +// "c2", +// "c3", +// "c4", +// "c8", +// "c9", +// "c5", +// "c6", +// "c7", +// "c10", +// "c14", +// "c16", +// "c17", +// "c18", +// "c15", +// "c12", +// "c13", +// "c11", +// "b1", +// "b2", +// "b3", +// "b4", +// "j1", +// "j2", +// "j4", +// "j3", +// "j5", +// "j6", +// "j7", +// "j8", +// "j10", +// "j9" +// ) +// val max = 31 +// for (j in 0..max) { +// val item = ItemDaySport( +// null, +// LocalDate.now().toString(), +// arr7[j], +// 0, +// 1 +// ) +// Thread { +// db.getDaoDaySport().insertItemDaySport(item) +// }.start() +// } +// saveCursDayNull(LocalDate.now().toString()) +// saveSportPlusCount(0) +// saveSportMaxCount(max + 1) +// clearDayAfter() +// clearSportCursDayDangerBefore() +// clearSportCursDayDangerAfter() +// addQuestianBefore() + } + + fun saveCursDayNull(cdn: String) { + val edit = prefCursDayNull?.edit() + edit?.putString("cdn", cdn) + edit?.apply() + CursDayNull = cdn + } + + fun clearCursDayNull() { + val edit = prefCursDayNull?.edit() + edit?.clear() + edit?.apply() + CursDayNull = "" + } + + fun addQuestianBefore() { + val db = MainDB.getDB(requireContext()) + + val item = ItemBeforeQuestionnaire( + null, + one, + two, + thee, + four, + five, + six, + seven, + eight, + nine, + LocalDate.now().toString() + ) + Thread { + db.getDaoQB().insertBQ(item) + }.start() + questionnaire_before = LocalDate.now().toString() + saveDayBefore(LocalDate.now().toString()) + //QBSaveDataB(LocalDate.now().toString()) + activity?.supportFragmentManager?.beginTransaction() + ?.replace(R.id.placeHolderFragment, SceduleFragment.newInstance())?.commit() + //Log.d("aaaaaa",questionnaire?.getString("QB", "")!!.toString()) + daySpoartOpen = daySpoartOpenKey + } + + fun saveCursDayNumber(scdn: Int) { + val edit = prefSportCursDayNumber?.edit() + edit?.putInt("scdn", scdn) + edit?.apply() + SportCursDayNumber = scdn + } + + fun clearCursDayNumber() { + val edit = prefSportCursDayNumber?.edit() + edit?.clear() + edit?.apply() + SportCursDayNumber = 0 + } + + fun saveDayBefore(db: String) { + val edit = prefDayBefore?.edit() + edit?.putString("db", db) + edit?.apply() + DayBefore = db + } + + fun clearDayBefore() { + val edit = prefDayBefore?.edit() + edit?.clear() + edit?.apply() + DayBefore = "" + } + + fun saveDayAfter(da: String) { + val edit = prefDayAfter?.edit() + edit?.putString("da", da) + edit?.apply() + DayAfter = da + } + + fun clearDayAfter() { + val edit = prefDayAfter?.edit() + edit?.clear() + edit?.apply() + DayAfter = "" + } + + fun savePauseDay(pd: String) { + val edit = prefPauseDay?.edit() + edit?.putString("pd", pd) + edit?.apply() + PauseDay = pd + } + + fun clearPauseDay() { + val edit = prefPauseDay?.edit() + edit?.clear() + edit?.apply() + PauseDay = "" + } + + fun saveBlock(b: String) { + val edit = prefBlock?.edit() + edit?.putString("b", b) + edit?.apply() + Block = b + } + + fun clearBlock() { + val edit = prefBlock?.edit() + edit?.clear() + edit?.apply() + Block = "" + } + + + fun saveSportPlusCount(spc: Int) { + val edit = prefSportPlusCount?.edit() + edit?.putInt("spc", spc) + edit?.apply() + SportPlusCount = spc + } + + fun clearSportPlusCount() { + val edit = prefSportPlusCount?.edit() + edit?.clear() + edit?.apply() + SportPlusCount = 0 + } + + + fun saveSportMaxCount(smc: Int) { + val edit = prefSportMaxCount?.edit() + edit?.putInt("smc", smc) + edit?.apply() + SportPlusCount = smc + } + + fun clearSportMaxCount() { + val edit = prefSportMaxCount?.edit() + edit?.clear() + edit?.apply() + SportMaxCount = 0 + } + + + fun saveSportCursDay(scd: Int) { + val edit = prefCursDay?.edit() + edit?.putInt("scd", scd) + edit?.apply() + SportCursDay = scd + } + + fun clearSportCursDay() { + val edit = prefCursDay?.edit() + edit?.clear() + edit?.apply() + SportCursDay = 0 + } + + fun saveSportCursDayDangerBefore(cddb: Int) { + val edit = prefCursDangerDayBefore?.edit() + edit?.putInt("cddb", cddb) + edit?.apply() + SportCursDayDangerBefore = cddb + } + + fun clearSportCursDayDangerBefore() { + val edit = prefCursDangerDayBefore?.edit() + edit?.clear() + edit?.apply() + SportCursDayDangerBefore = 0 + } + + fun saveSportCursDayDangerAfter(cdda: Int) { + val edit = prefCursDangerDayAfter?.edit() + edit?.putInt("cdda", cdda) + edit?.apply() + SportCursDayDangerAfter = cdda + } + + fun clearSportCursDayDangerAfter() { + val edit = prefCursDangerDayAfter?.edit() + edit?.clear() + edit?.apply() + SportCursDayDangerAfter = 0 + } + + private fun buttenAdd() { + buttenAdd1() + buttenAdd1_2() + buttenAdd2() + buttenAdd3() + buttenAdd4() + buttenAdd5() + buttenAdd6() + buttenAdd7() + buttenAdd8() + buttenAdd9() + + } + + + private fun buttenAdd1() { + binding.CVQyes1.setOnClickListener { + binding.CLQ112.visibility = View.VISIBLE + binding.CVQyes1.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno1.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + + } + binding.CVQno1.setOnClickListener { + binding.CLQ112.visibility = View.GONE + binding.CVQyes1.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno1.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + one = "0" + } + } + + + private fun buttenAdd1_2() { + binding.CVQ10.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "0" + } + binding.CVQ11.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "1" + } + binding.CVQ12.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "2" + } + binding.CVQ13.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "3" + } + binding.CVQ14.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "4" + + } + binding.CVQ15.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "5" + } + binding.CVQ16.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "6" + } + binding.CVQ17.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "7" + } + binding.CVQ18.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "8" + } + binding.CVQ19.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + one = "9" + } + binding.CVQ110.setOnClickListener { + binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQ110.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + one = "10" + } + } + + private fun buttenAdd2() { + binding.CVQyes2.setOnClickListener { + binding.CVQyes2.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno2.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + two = "1" + } + binding.CVQno2.setOnClickListener { + binding.CVQyes2.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno2.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + two = "0" + } + } + + private fun buttenAdd3() { + binding.CVQyes3.setOnClickListener { + binding.CVQyes3.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno3.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + thee = "1" + } + binding.CVQno3.setOnClickListener { + binding.CVQyes3.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno3.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + thee = "0" + } + } + + private fun buttenAdd4() { + binding.CVQyes4.setOnClickListener { + binding.CVQyes4.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno4.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + four = "1" + } + binding.CVQno4.setOnClickListener { + binding.CVQyes4.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno4.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + four = "0" + } + } + + private fun buttenAdd5() { + binding.CVQyes5.setOnClickListener { + binding.CVQyes5.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno5.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + five = "1" + } + binding.CVQno5.setOnClickListener { + binding.CVQyes5.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno5.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + five = "0" + } + } + + private fun buttenAdd6() { + binding.CVQyes6.setOnClickListener { + binding.CVQyes6.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno6.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + six = "1" + } + binding.CVQno6.setOnClickListener { + binding.CVQyes6.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno6.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + six = "0" + } + } + + private fun buttenAdd7() { + binding.CVQyes7.setOnClickListener { + binding.CVQyes7.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno7.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + seven = "1" + } + binding.CVQno7.setOnClickListener { + binding.CVQyes7.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno7.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + seven = "0" + } + } + + private fun buttenAdd8() { + binding.CVQyes8.setOnClickListener { + binding.CVQyes8.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno8.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + eight = "1" + } + binding.CVQno8.setOnClickListener { + binding.CVQyes8.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno8.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + eight = "0" + } + } + + private fun buttenAdd9() { + binding.CVQyes9.setOnClickListener { + binding.CVQyes9.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + binding.CVQno9.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + nine = "1" + } + binding.CVQno9.setOnClickListener { + binding.CVQyes9.setCardBackgroundColor(Color.parseColor("#A8A8A8")) + binding.CVQno9.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + nine = "0" + } + } + + +// fun QBSaveDataB(date: String) { +// val QB = questionnaire?.edit() +// QB?.putString("QB", date) +// QB?.apply() +// } +// +// //Инициализация хранилища(для токена) +// fun data_prefB() { +// questionnaire = activity?.getSharedPreferences("QB", Context.MODE_PRIVATE) +// QBC = questionnaire?.getString("QB", "")!! +// QBSaveDataB(QBC) +// } +// +// fun onInkrementB() { +// Log.d("fsd", "QBC - $QBC") +// Log.d("fsd", "questionnaire_before - $questionnaire_before") +// //Не сохранять пустоту если токен уже лежит, так как tokenClass при перезаходе в приложение очишается и нужно проверять если counter равен пустоте, то сохранять токен, иначе не сохранять +// if (questionnaire_before != "" && QBC == "") { +// QBC = questionnaire_before +// +// //Сохранение результата +// QBSaveDataB(QBC) +// +// } else {//Иначе передаем в общую переменную tokenClass данные храняшиеся в counter +// questionnaire_before = QBC +// } +// } + +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/User/fragmentUser/SceduleFragment.kt b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/SceduleFragment.kt index f30f79f..dae294f 100644 --- a/app/src/main/java/com/example/rehabilitation/User/fragmentUser/SceduleFragment.kt +++ b/app/src/main/java/com/example/rehabilitation/User/fragmentUser/SceduleFragment.kt @@ -1,44 +1,113 @@ package com.example.rehabilitation.User.fragmentUser import android.annotation.SuppressLint -import android.content.ContentResolver -import android.net.Uri +import android.content.Context +import android.graphics.Color +import android.media.MediaPlayer import android.os.Bundle -import android.os.Environment +import android.os.CountDownTimer import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import android.widget.HorizontalScrollView import android.widget.Toast +import androidx.core.view.size import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.asLiveData import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager -import com.example.rehabilitation.BuildConfig +import androidx.recyclerview.widget.RecyclerView +import com.example.admin.Toast.showCustomInfoToast +import com.example.admin.Toast.showCustomNiceToast +import com.example.rehabilitation.Block +import com.example.rehabilitation.CursDayNull +import com.example.rehabilitation.DayAfter +import com.example.rehabilitation.DayBefore +import com.example.rehabilitation.PauseDay import com.example.rehabilitation.R +import com.example.rehabilitation.Room.MainDB +import com.example.rehabilitation.Sport15Day +import com.example.rehabilitation.Sport15DayAll +import com.example.rehabilitation.Sport7Day +import com.example.rehabilitation.SportCursDay +import com.example.rehabilitation.SportCursDayDangerAfter +import com.example.rehabilitation.SportCursDayDangerBefore +import com.example.rehabilitation.SportCursDayNumber +import com.example.rehabilitation.SportMaxCount +import com.example.rehabilitation.SportPlusCount +import com.example.rehabilitation.SportUserTrue +import com.example.rehabilitation.User.fragmentUser.QuestionnaireFragment.QAfterFragment +import com.example.rehabilitation.User.fragmentUser.QuestionnaireFragment.QBeforeFragment import com.example.rehabilitation.databinding.FragmentSceduleBinding -import com.example.rehabilitation.db.MainDB -import com.example.rehabilitation.dip.Day.DayAdapter -import com.example.rehabilitation.dip.Day.DayModel -import com.example.rehabilitation.dip.Image.ImageSportAdapter -import com.example.rehabilitation.dip.Image.ImageSportModel -import com.example.rehabilitation.dip.Month.MonthAdapter -import com.example.rehabilitation.dip.Month.MonthModel +import com.example.rehabilitation.model_adapter.DataModel +import com.example.rehabilitation.model_adapter.Day.DayAdapter +import com.example.rehabilitation.model_adapter.Day.DayListModel +import com.example.rehabilitation.model_adapter.Day.DayModel +import com.example.rehabilitation.model_adapter.Image.ImageSportAdapter +import com.example.rehabilitation.model_adapter.Image.ImageSportModel +import com.example.rehabilitation.model_adapter.Month.MonthModel +import com.example.rehabilitation.prefBlock +import com.example.rehabilitation.prefCursDangerDayAfter +import com.example.rehabilitation.prefCursDangerDayBefore +import com.example.rehabilitation.prefCursDay +import com.example.rehabilitation.prefCursDayNull +import com.example.rehabilitation.prefDayAfter +import com.example.rehabilitation.prefDayBefore +import com.example.rehabilitation.prefPauseDay +import com.example.rehabilitation.prefSport +import com.example.rehabilitation.prefSport15Day +import com.example.rehabilitation.prefSport15DayAll +import com.example.rehabilitation.prefSport7Day +import com.example.rehabilitation.prefSportCursDayNumber +import com.example.rehabilitation.prefSportMaxCount +import com.example.rehabilitation.prefSportPlusCount import com.example.sqlitework.dip.MainViewModel -import java.io.File +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.launch import java.time.LocalDate -class SceduleFragment(/*var taskItem: TaskItem?*/) : Fragment(), MonthAdapter.Listener,DayAdapter.Listener{ +class SceduleFragment(/*var taskItem: TaskItem?*/) : Fragment()/*, MonthAdapter.Listener*/, + DayAdapter.Listener { private lateinit var binding: FragmentSceduleBinding - // private lateinit var taskViewModel: TaskViewModel - private val model: MainViewModel by activityViewModels()//Инициализировали класс - lateinit var adapterMonth: MonthAdapter + + // private lateinit var taskViewModel: TaskViewModel + private val model: MainViewModel by activityViewModels()//Инициализировали класс + + private val dataModel: DataModel by activityViewModels()//Для передачи данных + + // lateinit var adapterMonth: MonthAdapter lateinit var adapterDay: DayAdapter lateinit var adapterImage: ImageSportAdapter + private lateinit var scrollListener: RecyclerView.OnScrollListener + + //Количество выполненных тренировок + + //Хранение id для подтверждения упражнения + var idDaySport = 0 + + //Выбранный день + var dayCard = "" + + //Переключения вида или список или календарь + var calendar_list = 0 + + //Сегодняшний день + var date = LocalDate.now().toString() + + //Для хранения при нажатие на один из дней + var mothModel: MonthModel? = null + + //Метроном + var mMediaPlayer: MediaPlayer? = null + var metronom = false + + //Таймер для открытия упражнения + var time: Long = 0 + var times = 0 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? @@ -47,17 +116,83 @@ class SceduleFragment(/*var taskItem: TaskItem?*/) : Fragment(), MonthAdapter.Li return binding.root } +// var adsad = 0 override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - initRcView() + Log.d("111111111", "11111111111111111111111111111") + + prefCursDay = activity?.getSharedPreferences("SportCursDay", Context.MODE_PRIVATE) + SportCursDay = prefCursDay?.getInt("scd", 0)!! + + prefCursDangerDayBefore = activity?.getSharedPreferences("CursDangerDayBefore", Context.MODE_PRIVATE) + SportCursDayDangerBefore = prefCursDangerDayBefore?.getInt("cddb", 0)!! + prefCursDangerDayAfter = activity?.getSharedPreferences("CursDangerDayAfter", Context.MODE_PRIVATE) + SportCursDayDangerAfter = prefCursDangerDayAfter?.getInt("cdda", 0)!! + + //Какой сегодня курс + prefSportCursDayNumber = activity?.getSharedPreferences("SportCursDayNumber", Context.MODE_PRIVATE) + SportCursDayNumber = prefSportCursDayNumber?.getInt("scdn", 0)!! + + //Пройдено ли 15 дне и отправен отчет + prefSport15DayAll = activity?.getSharedPreferences("Sport15DayAll", Context.MODE_PRIVATE) + Sport15DayAll = prefSport15DayAll?.getInt("s15da", 0)!! + + //Отчет на 15 день + prefSport15Day = activity?.getSharedPreferences("Sport15Day", Context.MODE_PRIVATE) + Sport15Day = prefSport15Day?.getInt("s15d", 0)!! + + //Отчет на 7 день + prefSport7Day = activity?.getSharedPreferences("Sport7Day", Context.MODE_PRIVATE) + Sport7Day = prefSport7Day?.getInt("s7d", 0)!! + + + prefCursDayNull = activity?.getSharedPreferences("CursDayNull", Context.MODE_PRIVATE) + CursDayNull = prefCursDayNull?.getString("cdn", "")!! + + //Для количества тренирвоок + prefSportPlusCount = activity?.getSharedPreferences("SportPlusCount", Context.MODE_PRIVATE) + SportPlusCount = prefSportPlusCount?.getInt("spc", 0)!! + prefSportMaxCount = activity?.getSharedPreferences("SportMaxCount", Context.MODE_PRIVATE) + SportMaxCount = prefSportMaxCount?.getInt("smc", 0)!! + + + //Для пауз и блоков + prefPauseDay = activity?.getSharedPreferences("PauseDay", Context.MODE_PRIVATE) + PauseDay = prefPauseDay?.getString("pd", "")!! + prefBlock = activity?.getSharedPreferences("Block", Context.MODE_PRIVATE) + Block = prefBlock?.getString("b", "")!! + + //Для анкет, какие выполнены + prefDayBefore = activity?.getSharedPreferences("DayBefore", Context.MODE_PRIVATE) + DayBefore = prefDayBefore?.getString("db", "")!! + prefDayAfter = activity?.getSharedPreferences("DayAfter", Context.MODE_PRIVATE) + DayAfter = prefDayAfter?.getString("da", "")!! + + //Разрешение на начинание курса, в случае если создан список на n дней + prefSport = activity?.getSharedPreferences("SportUserTrue", Context.MODE_PRIVATE) + SportUserTrue = prefSport?.getInt("spt", 0)!! + Log.i("SportUserTrue",SportUserTrue.toString()) + Log.d("lookDanger","lookDanger") + Log.d("SportCursDayDangerAfter","${SportCursDayDangerAfter}") + Log.d("SportCursDay","${SportCursDay}") + Log.d("SportCursDayDangerBefore","${SportCursDayDangerBefore}") + Log.d("btnSaveQuestionnaire","btnSaveQuestionnaire") + binding.button2.setOnClickListener { + activity?.supportFragmentManager?.beginTransaction() + ?.replace(R.id.placeHolderFragment, QBeforeFragment.newInstance())?.commit() + + } + + binding.button3.setOnClickListener { + activity?.supportFragmentManager?.beginTransaction() + ?.replace(R.id.placeHolderFragment, QAfterFragment.newInstance())?.commit() + + } + initRcViewDay() initRcViewImage() liveReadOrderCurrent() - liveReadOrderDayCurrent() - model.liveListList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment - adapterMonth.submitList(it)//Напрямую переадем созданный список в adapter(ProductAdapter) - binding.txtNullList.visibility = View.GONE - } + model.liveDayList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment adapterDay.submitList(it)//Напрямую переадем созданный список в adapter(ProductAdapter) @@ -65,202 +200,716 @@ class SceduleFragment(/*var taskItem: TaskItem?*/) : Fragment(), MonthAdapter.Li model.liveImageList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment adapterImage.submitList(it)//Напрямую переадем созданный список в adapter(ProductAdapter) + binding.LoadImage.visibility = View.GONE } + //Drk.xtybt vtnhjyjvf + binding.btnMp3.setOnClickListener { + if(metronom == true){ + metronom = false + stopSound() + binding.btnMp3.setBackgroundResource(android.R.drawable.ic_media_play) - //Закрытие карточки определенного дня - binding.btnExitCardSport.setOnClickListener { - visible2() - binding.txtNameCard.setText("") - binding.txtDescCard.setText("") + } + else{ + metronom = true + playSound() + binding.btnMp3.setBackgroundResource(android.R.drawable.ic_media_pause) + } + + } + //Переход для отправки отчетности за 7 дней + binding.btnProgres7.setOnClickListener { + dataModel.fragmentMenu.value = R.id.progress + } + //Переход для отправки отчетности за 15 дней + binding.btnProgres15.setOnClickListener { + dataModel.fragmentMenu.value = R.id.progress } - binding.btnExitCLDayList.setOnClickListener{ - visible1() + addButton() + outputSportUnder_the_conditions() + + binding.button5.setOnClickListener { + ClearRCView() } - //Заполнение списка - addListModelCards() + Log.i("111111212222","111112211111") + Log.i("DayBefore","${DayBefore}") + Log.i("DayAfter","${DayAfter}") + Log.i("SportPlusCount","${SportPlusCount}") + Log.i("SportMaxCount","${SportMaxCount}") + Log.i("SportCursDay","${SportCursDay}") + Log.i("DayBefore","${DayBefore}") + Log.i("DayAfter","${DayAfter}") + Log.i("Sport7Day","${Sport7Day}") + Log.i("Sport15Day","${Sport15Day}") + Log.i("Sport15DayAll","${Sport15DayAll}") + Log.i("SportCursDayNumber","${SportCursDayNumber}") + + + } + + + //Функция для вывода тренировок при определенных условиях + fun outputSportUnder_the_conditions() { + Log.i("PauseDay","${PauseDay}"+" "+"${LocalDate.now().toString()}") + + if(SportCursDay ==15 && Sport15DayAll == 1 && Sport7Day == 0 && Sport15Day == 0){ + visible15dayall() + } + else if(SportCursDay ==7 && Sport7Day == 1){ + visible7day() + } + else if(SportCursDay ==15 && Sport15Day == 1){ + visible15day() + } + else if(Block > LocalDate.now().toString() && Block != ""){ + visibleBlock() + } + else if(PauseDay > LocalDate.now().toString() && PauseDay != ""){ + visiblePause() + } + else if((PauseDay <= LocalDate.now().toString() || PauseDay == "")&&(Block <= LocalDate.now().toString() || Block == "")){ + ClearRCView() + //Если это первая тренировка + if (SportCursDay == 0) { + //Очишаем возможные созданенные старе данные + visibleLoad() + clearBlock() + clearPauseDay() + clearCursDayNull() + visibleYesNoSport() + } + else if(SportCursDay in 1..15 && CursDayNull != LocalDate.now().toString()){ + visibleYesNoSport() + } + else if(SportCursDay in 1..15 && CursDayNull == LocalDate.now().toString() && DayBefore==LocalDate.now().toString()&&DayAfter!=LocalDate.now().toString() && SportPlusCount != SportMaxCount){ + visibleLoad() + addListModelCardsDay(LocalDate.now().toString()) + visibleDayList() + } + else if(DayBefore==LocalDate.now().toString() && DayAfter==LocalDate.now().toString() && SportPlusCount == SportMaxCount){ + visibleLoad() + addListModelCardsDay(LocalDate.now().toString()) + visibleDayList() + } + else if(DayBefore==LocalDate.now().toString() && DayAfter!=LocalDate.now().toString() && SportPlusCount == SportMaxCount){ + activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.placeHolderFragment, QAfterFragment.newInstance())?.commit() + } + + + } } + + //Выводим экран с фразой готовы ли вы начать тренировку + private fun visibleYesNoSport() { + binding.CLListSport.visibility = View.GONE + binding.CLDayList.visibility = View.GONE + binding.CLCardSport.visibility = View.GONE + binding.CLLoad.visibility = View.GONE + binding.CLYesNoSport.visibility = View.VISIBLE + binding.CLPaus.visibility = View.GONE + binding.CLBlock.visibility = View.GONE + binding.CL7day.visibility = View.GONE + binding.CL15day.visibility = View.GONE + binding.CLFinal.visibility = View.GONE + binding.btnYesStartSport.setOnClickListener { + if(SportUserTrue == 0){ + Toast(requireContext()).showCustomInfoToast("Попросите врача создать вам курс", requireActivity()) + } + else { + activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.placeHolderFragment, QBeforeFragment.newInstance())?.commit() + } + } + } + + //Выводим списка тренировок + private fun visibleDayList() { + binding.CLListSport.visibility = View.GONE + binding.CLDayList.visibility = View.VISIBLE + binding.CLCardSport.visibility = View.GONE + binding.CLLoad.visibility = View.GONE + binding.CLYesNoSport.visibility = View.GONE + binding.CLPaus.visibility = View.GONE + binding.CLBlock.visibility = View.GONE + binding.CL7day.visibility = View.GONE + binding.CL15day.visibility = View.GONE + binding.CLFinal.visibility = View.GONE + } + + + //Выводим карточку тренировок + private fun visibleDayCard() { + binding.CLListSport.visibility = View.GONE + binding.CLDayList.visibility = View.GONE + binding.CLCardSport.visibility = View.VISIBLE + binding.CLLoad.visibility = View.GONE + binding.CLYesNoSport.visibility = View.GONE + binding.CLPaus.visibility = View.GONE + binding.CLBlock.visibility = View.GONE + Log.i("visibleDayCard","visibleDayCard") + binding.CL7day.visibility = View.GONE + binding.CL15day.visibility = View.GONE + binding.CLFinal.visibility = View.GONE + } + + private fun visibleLoad() { + binding.CLListSport.visibility = View.GONE + binding.CLDayList.visibility = View.GONE + binding.CLCardSport.visibility = View.GONE + binding.CLLoad.visibility = View.VISIBLE + binding.CLYesNoSport.visibility = View.GONE + binding.CLPaus.visibility = View.GONE + binding.CLBlock.visibility = View.GONE + binding.CL7day.visibility = View.GONE + binding.CL15day.visibility = View.GONE + binding.CLFinal.visibility = View.GONE + } + + + //Выводим экран паузы + private fun visiblePause() { + binding.CLListSport.visibility = View.GONE + binding.CLDayList.visibility = View.GONE + binding.CLCardSport.visibility = View.GONE + binding.CLLoad.visibility = View.GONE + binding.CLYesNoSport.visibility = View.GONE + binding.CLPaus.visibility = View.VISIBLE + binding.CLBlock.visibility = View.GONE + binding.txtDatePause.setText("${PauseDay}") + binding.CL7day.visibility = View.GONE + binding.CL15day.visibility = View.GONE + binding.CLFinal.visibility = View.GONE + } + + + //Выводим экран блока + private fun visibleBlock() { + binding.CLListSport.visibility = View.GONE + binding.CLDayList.visibility = View.GONE + binding.CLCardSport.visibility = View.GONE + binding.CLLoad.visibility = View.GONE + binding.CLYesNoSport.visibility = View.GONE + binding.CLPaus.visibility = View.GONE + binding.txtDateBlock.setText("${Block}") + binding.CLBlock.visibility = View.VISIBLE + binding.CL7day.visibility = View.GONE + binding.CL15day.visibility = View.GONE + binding.CLFinal.visibility = View.GONE + } + + //Выводим сообщенеи от отправке отчета на 7 день + private fun visible7day() { + binding.CLListSport.visibility = View.GONE + binding.CLDayList.visibility = View.GONE + binding.CLCardSport.visibility = View.GONE + binding.CLLoad.visibility = View.GONE + binding.CLYesNoSport.visibility = View.GONE + binding.CLPaus.visibility = View.GONE + binding.CLBlock.visibility = View.GONE + binding.CL7day.visibility = View.VISIBLE + binding.CL15day.visibility = View.GONE + binding.CLFinal.visibility = View.GONE + } + + //Выводим сообщенеи от отправке отчета на 15 день + private fun visible15day() { + binding.CLListSport.visibility = View.GONE + binding.CLDayList.visibility = View.GONE + binding.CLCardSport.visibility = View.GONE + binding.CLLoad.visibility = View.GONE + binding.CLYesNoSport.visibility = View.GONE + binding.CLPaus.visibility = View.GONE + binding.CLBlock.visibility = View.GONE + binding.CL7day.visibility = View.GONE + binding.CL15day.visibility = View.VISIBLE + binding.CLFinal.visibility = View.GONE + } + + //Выводим экрана окончания курса + private fun visible15dayall() { + binding.CLListSport.visibility = View.GONE + binding.CLDayList.visibility = View.GONE + binding.CLCardSport.visibility = View.GONE + binding.CLLoad.visibility = View.GONE + binding.CLYesNoSport.visibility = View.GONE + binding.CLPaus.visibility = View.GONE + binding.CLBlock.visibility = View.GONE + binding.CL7day.visibility = View.GONE + binding.CL15day.visibility = View.GONE + binding.CLFinal.visibility = View.VISIBLE + } + + + + //Открытие карточки дня + override fun onClickDay(item: DayListModel) { + Log.i("times","${times}") + Log.i("time","${time}") + //Если это сегодняшнее упражнение + if((item.number.toInt() == (SportPlusCount+1))|| (item.number.toInt() < (SportPlusCount+1))) { + times = time.toInt() + if(times ==0 || times == 1000){ + + binding.LoadImage.visibility = View.VISIBLE + liveReadOrderDayCurrent() + visibleLoad()//Загрузочный экран + val db = MainDB.getDB(requireContext()) + db.getDaoSportCategory().getAllItemsSportCategory(item.category).asLiveData() + .observe(requireActivity()) { itList -> + var number = 1; + val itemDay = DayModel( + item.id, + itList[0].name, + itList[0].desc, + item.day, + item.number, + itList[0].category, + item.check + ) + model.liveDayCurrent.value = itemDay + //} + + + } + } + else{ + Toast(requireContext()).showCustomInfoToast("Пауза в 1 минуту", requireActivity()) + + } + } + else{ + Toast(requireContext()).showCustomInfoToast("Сначало выполните ${SportPlusCount+1} упражнение", requireActivity()) + } + + } + + //Функция активации кнпок + fun addButton(){ + val db = MainDB.getDB(requireContext()) + //Закрытие карточки определенного дня + binding.btnExitCardSport.setOnClickListener { + visibleLoad() + stopSound() + binding.btnMp3.setBackgroundResource(android.R.drawable.ic_media_play) + //binding.txtNameCard.setText("") + binding.txtDescCard.setText("") + addListModelCardsDay(LocalDate.now().toString()) + } + + binding.btnAddDayCategoryCheck.setOnClickListener { + + stopSound() + binding.btnMp3.setBackgroundResource(android.R.drawable.ic_media_play) + + visibleLoad() + GlobalScope.launch(Dispatchers.IO) { + db.getDaoDaySport().updateCheckDaySport(idDaySport) + } + saveSportPlusCount((SportPlusCount+1)) + binding.btnAddDayCategoryCheck.isEnabled = false + binding.btnAddDayCategoryCheck.isClickable = false + binding.btnAddDayCategoryCheck.setCardBackgroundColor(Color.parseColor("#A68C78")) + Toast(requireContext()).showCustomNiceToast( + "Упражнение выполнено", + requireActivity() + ) + + addListModelCardsDay(LocalDate.now().toString()) + + if (SportPlusCount == SportMaxCount && DayBefore==LocalDate.now().toString()&& DayAfter =="" ) { + activity?.supportFragmentManager?.beginTransaction() + ?.replace(R.id.placeHolderFragment, QAfterFragment.newInstance())?.commit() + } + + binding.txtDescCard.setText("") + Log.i("DayBefore","${DayBefore}") + Log.i("DayAfter","${DayAfter}") + Log.i("SportPlusCount","${SportPlusCount}") + Log.i("SportMaxCount","${SportMaxCount}") + Log.i("SportCursDay","${SportCursDay}") + val timer = object: CountDownTimer(60000, 1000) { + override fun onTick(millisUntilFinished: Long) { + time = millisUntilFinished + Log.i("asad3444a","${time}") + } + + override fun onFinish() { + time = 0 + } + } + timer.start() + + } + + + + binding.btnNoAddDayCategoryCheck.setOnClickListener { + stopSound() + binding.btnMp3.setBackgroundResource(android.R.drawable.ic_media_play) + + visibleLoad() + GlobalScope.launch(Dispatchers.IO) { + db.getDaoDaySport().updateNoCheckDaySport(idDaySport) + } + saveSportPlusCount((SportPlusCount+1)) + binding.btnNoAddDayCategoryCheck.isEnabled = false + binding.btnNoAddDayCategoryCheck.isClickable = false + binding.btnNoAddDayCategoryCheck.setCardBackgroundColor(Color.parseColor("#A3B8A1")) + Toast(requireContext()).showCustomInfoToast( + "Упражнение было пропушено", + requireActivity() + ) + + addListModelCardsDay(LocalDate.now().toString()) + + if (SportPlusCount == SportMaxCount && DayBefore==LocalDate.now().toString()&& DayAfter =="" ) { + activity?.supportFragmentManager?.beginTransaction() + ?.replace(R.id.placeHolderFragment, QAfterFragment.newInstance())?.commit() + } + + binding.txtDescCard.setText("") + Log.i("DayBefore","${DayBefore}") + Log.i("DayAfter","${DayAfter}") + Log.i("SportPlusCount","${SportPlusCount}") + Log.i("SportMaxCount","${SportMaxCount}") + Log.i("SportCursDay","${SportCursDay}") + + val timer = object: CountDownTimer(60000, 1000) { + override fun onTick(millisUntilFinished: Long) { + time = millisUntilFinished + Log.i("asad3444a","${time}") + } + + override fun onFinish() { + time = 0 + } + } + timer.start() + } + + + } + + //Заполнения модели и списка + private fun addListModelCardsDay(day: String) { + + val db = MainDB.getDB(requireContext()) + val list = ArrayList() + db.getDaoDaySport().getAllItemDaySport(day).asLiveData() + .observe(requireActivity()) { itList -> + var number = 1; + + itList.forEach { + Log.d("123", it.category) + //db.getDaoSportCategory().getAllItemsSportCategory(it.category).asLiveData().observe(requireActivity()){itSport-> + val itemDay = DayListModel( + it.id.toString(), + number++.toString(), + day, + it.category.toString(), + it.check.toString(), + ) + list.add(itemDay)//Передали заполненый список + } + model.liveDayList.value = list + Log.d("sadas", list.toString()) + } + visibleDayList() + } + companion object { fun newInstance() = SceduleFragment(/*null*/) } + //Функция запускающая отслеживания за списком, чтобы вовремя обновлять основную карточку продукта private fun liveReadOrderCurrent() = with(binding) { model.liveListCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment - visible2() - //addListModelCardsDay(it.day) + visibleDayList() } - } + //Функция запускающая отслеживания за списком, чтобы вовремя обновлять основную карточку продукта @SuppressLint("DiscouragedApi") private fun liveReadOrderDayCurrent() = with(binding) { model.liveDayCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment - visible3() - //val db = MainDB.getDB(requireContext()) - //db.getDaoDaySport().getAllItemDaySport(day).asLiveData().observe(requireActivity()){itList-> + visibleLoad() + + //Фиксируем id + idDaySport = it.id.toInt() + + //Отключаем нажатие на кнопку подтверждения, если упражнени уже выполнено, для того чтобы не тыкали + if (it.check.toInt() == 1 || it.check.toInt() == 2) { + binding.btnAddDayCategoryCheck.isEnabled = false + binding.btnAddDayCategoryCheck.isClickable = false + binding.btnAddDayCategoryCheck.setCardBackgroundColor(Color.parseColor("#A3B8A1")) + + binding.btnNoAddDayCategoryCheck.isEnabled = false + binding.btnNoAddDayCategoryCheck.isClickable = false + binding.btnNoAddDayCategoryCheck.setCardBackgroundColor(Color.parseColor("#A68C78")) + + } else { + + binding.btnAddDayCategoryCheck.isEnabled = true + binding.btnAddDayCategoryCheck.isClickable = true + binding.btnAddDayCategoryCheck.setCardBackgroundColor(Color.parseColor("#53D54A")) + + binding.btnNoAddDayCategoryCheck.isEnabled = true + binding.btnNoAddDayCategoryCheck.isClickable = true + binding.btnNoAddDayCategoryCheck.setCardBackgroundColor(Color.parseColor("#EDAA76")) + } -// var gpath:String = Environment.getExternalStorageDirectory().absolutePath -// var spath = R.drawable.b3_1 -// var fullpath = File(gpath + File.separator + spath) - //var image = R.drawable. - - //val mFile1 = Environment.getExternalStorageDirectory() - //val fileName = "b3_1.png" - //val mFile2 = File(mFile1, fileName) - //val sdPath = mFile1.absolutePath.toString() + "/" + fileName - // val temp = File(sdPath) val db = MainDB.getDB(requireContext()) val listImage = ArrayList() - db.getDaoImage().getAllItemImage(it.category).asLiveData().observe(requireActivity()) { itList1 -> - itList1.forEach { - val item = ImageSportModel( - it.id.toString(), - it.image, - it.name.toString(), - ) - Log.d("sdaasd","${item.article}") - listImage.add(item)//Передали заполненый список + db.getDaoImage().getAllItemImage(it.category).asLiveData() + .observe(requireActivity()) { itList1 -> + itList1.forEach { + val item = ImageSportModel( + it.id.toString(), + it.image, + it.name.toString(), + ) + Log.d("sdaasd", "${item.article}") + listImage.add(item)//Передали заполненый список + } + + model.liveImageList.value = listImage + } - model.liveImageList.value = listImage - - } - //Log.i("5555", "Your IMAGE ABSOLUTE PATH:-$sdPath") - //val otherPath = Uri.parse("android.resource://"+ BuildConfig.APPLICATION_ID+"/drawable/b3_1.png") - //val path = Uri.parse("android.resource://com.nikhil.material/" + R.drawable.ima) - //val fileUri = Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://"+ BuildConfig.APPLICATION_ID+"/drawable/${fileName}") - binding.txtNameCard.setText("") + //binding.txtNameCard.setText("") binding.txtDescCard.setText("") binding.txtTitle.setText("") - binding.txtTitle.setText("Упражнение "+it.number) - binding.txtNameCard.setText(it.name) - binding.txtDescCard.setText(binding.txtDescCard.text.toString()+it.desc) - // binding.txtTitle.setText(it.name) - //binding.imageView2.setImageResource(R.drawable.b3_1) - //val resourceId = resources.getIdentifier("b3_1", "drawable", activity?.packageName) -// val sads = "2131231027" -// binding.imageView2.setImageResource(sads.toInt()); -// Log.d("otherPath", sads.toString()) + binding.txtTitle.setText("Упражнение " + it.number) + //binding.txtNameCard.setText(it.name) + binding.txtDescCard.setText(binding.txtDescCard.text.toString() + it.desc) - } - } - - //Заполнения модели и списка - private fun addListModelCards(){ - val db = MainDB.getDB(requireContext()) - val list = ArrayList() - db.getDao().getAllItems().asLiveData().observe(requireActivity()){itList-> - binding.txtList.text = "" - itList.forEach{ - //val text = "Id: ${it.id} Name: ${it.name} Proce: ${it.price}" - //binding.txtList.append(text) - val item = MonthModel( - it.id.toString(), - it.day.toString(), - it.date.toString(), - it.check.toString() - ) - //model.liveZakazCurrent.value = item//Передаем в liveDataCurrent один из продуктов, чтобы дальше эти данные использовать и передавать их в пробную ячейку - list.add(item)//Передали заполненый список - } - model.liveListList.value = list - } - - - - } - - //Заполнения модели и списка - private fun addListModelCardsDay(day:String){ - - val db = MainDB.getDB(requireContext()) - val list = ArrayList() - db.getDaoDaySport().getAllItemDaySport(day).asLiveData().observe(requireActivity()){itList-> - var number = 1; - itList.forEach{ - db.getDaoSportCategory().getAllItemsSportCategory("c").asLiveData().observe(requireActivity()){itSport-> - itSport.forEach { - val itemDay = DayModel( - it.id.toString(), - it.name, - it.desc, - day, - (number++).toString(), - it.category.toString(), - "0", - ) - list.add(itemDay)//Передали заполненый список - } - } - } - model.liveDayList.value = list - Log.d("sadas",list.toString()) + //Выводим экран + visibleDayCard() } } - //Инициализация списка - private fun initRcView() = with(binding) { - todoListRecycleView.layoutManager = GridLayoutManager(requireContext(),1)//По вертикали будет выводить по умолчанию - adapterMonth = MonthAdapter(this@SceduleFragment) - todoListRecycleView.adapter = adapterMonth + + //Сохранение и удаление хранилиш + fun savePauseDay(pd: String) { + val edit = prefPauseDay?.edit() + edit?.putString("pd", pd) + edit?.apply() + PauseDay = pd } + fun clearPauseDay() { + val edit = prefPauseDay?.edit() + edit?.clear() + edit?.apply() + PauseDay = "" + } + + fun saveBlock(b: String) { + val edit = prefBlock?.edit() + edit?.putString("b", b) + edit?.apply() + Block = b + } + fun clearBlock() { + val edit = prefBlock?.edit() + edit?.clear() + edit?.apply() + Block = "" + } + + fun saveSportPlusCount(spc: Int) { + val edit = prefSportPlusCount?.edit() + edit?.putInt("spc", spc) + edit?.apply() + SportPlusCount = spc + } + + fun clearSportPlusCount() { + val edit = prefSportPlusCount?.edit() + edit?.clear() + edit?.apply() + SportPlusCount = 0 + } + + + + fun saveSportCursDay(scd: Int) { + val edit = prefCursDay?.edit() + edit?.putInt("scd", scd) + edit?.apply() + SportCursDay = scd + } + + fun clearSportCursDay() { + val edit = prefCursDay?.edit() + edit?.clear() + edit?.apply() + SportCursDay = 0 + } + + fun saveSportCursDayDangerBefore(cddb: Int) { + val edit = prefCursDangerDayBefore?.edit() + edit?.putInt("cddb", cddb) + edit?.apply() + SportCursDayDangerBefore = cddb + } + + fun clearSportCursDayDangerBefore() { + val edit = prefCursDangerDayBefore?.edit() + edit?.clear() + edit?.apply() + SportCursDayDangerBefore = 0 + } + + fun saveSportCursDayDangerAfter(cdda: Int) { + val edit = prefCursDangerDayAfter?.edit() + edit?.putInt("cdda", cdda) + edit?.apply() + SportCursDayDangerAfter = cdda + } + + fun clearSportCursDayDangerAfter() { + val edit = prefCursDangerDayAfter?.edit() + edit?.clear() + edit?.apply() + SportCursDayDangerAfter = 0 + } + + fun saveCursDayNull(cdn: String) { + val edit = prefCursDayNull?.edit() + edit?.putString("cdn", cdn) + edit?.apply() + CursDayNull = cdn + } + + fun clearCursDayNull() { + val edit = prefCursDayNull?.edit() + edit?.clear() + edit?.apply() + CursDayNull = "" + } + //Инициализация списка private fun initRcViewDay() = with(binding) { - rcVIewDayList.layoutManager = GridLayoutManager(requireContext(),1)//По вертикали будет выводить по умолчанию + rcVIewDayList.layoutManager = + GridLayoutManager(requireContext(), 1)//По вертикали будет выводить по умолчанию adapterDay = DayAdapter(this@SceduleFragment) rcVIewDayList.adapter = adapterDay + } + //Инициализация списка для фотографий private fun initRcViewImage() = with(binding) { - rcViewImage.layoutManager = LinearLayoutManager(requireContext(),LinearLayoutManager.HORIZONTAL,false)//По вертикали будет выводить по умолчанию - adapterImage = ImageSportAdapter() + rcViewImage.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)//По вертикали будет выводить по умолчанию + adapterImage = ImageSportAdapter(requireContext()) rcViewImage.adapter = adapterImage - } - - - //Вывод первого экрана - private fun visible1(){ - binding.CLListSport.visibility = View.VISIBLE - binding.CLCardSport.visibility = View.GONE - binding.CLDayList.visibility = View.GONE - } - //Вывод второго экрана - private fun visible2(){ - binding.CLListSport.visibility = View.GONE - binding.CLDayList.visibility = View.VISIBLE - binding.CLCardSport.visibility = View.GONE +// +// +// Log.i("123112213","${binding.rcViewImage.size.toInt()}") +// +// var loading = true +// var pastVisiblesItems: Int +// var visibleItemCount: Int +// var totalItemCount: Int +// +// mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { +// override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { +// if (dy > 0) { //check for scroll down +// visibleItemCount = mLayoutManager.getChildCount() +// totalItemCount = mLayoutManager.getItemCount() +// pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition() +// if (loading) { +// if (visibleItemCount + pastVisiblesItems >= totalItemCount) { +// loading = false +// Log.v("...", "Last Item Wow !") +// // Do pagination.. i.e. fetch new data +// loading = true +// } +// } +// } +// } +// }) } - //Вывод второго экрана - private fun visible3(){ - binding.CLListSport.visibility = View.GONE - binding.CLDayList.visibility = View.GONE - binding.CLCardSport.visibility = View.VISIBLE + + fun ClearRCView(){ + adapterImage.notifyDataSetChanged(); // let your adapter know about the changes and reload view. + adapterDay.notifyDataSetChanged(); // let your adapter know about the changes and reload view. + initRcViewImage() + initRcViewDay() + } - override fun onClickExceptionOrder(item: MonthModel) { - //Если открываешь тренировку не сегодняшнего дня то тебя ругает - // if(item.day.toString() == LocalDate.now().toString()){ - model.liveListCurrent.value = item - addListModelCardsDay(item.day) -// } -// else{ -// Toast.makeText(requireContext(), "Ошибка", Toast.LENGTH_SHORT).show() +// private val lastVisibleItemPosition: Int +// get() = linearLayoutManager.findLastVisibleItemPosition() +// private fun setRecyclerViewScrollListener() { +// var scrollListener = object : RecyclerView.OnScrollListener() { +// override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) { +// super.onScrollStateChanged(recyclerView!!, newState) +// val totalItemCount = recyclerView!!.layoutManager.itemCount +// if (totalItemCount == lastVisibleItemPosition + 1) { +// Log.d("MyTAG", "Load new list") +// binding.rcViewImage.removeOnScrollListener(scrollListener) +// } +// } // } +// binding.rcViewImage.addOnScrollListener(scrollListener) +// } + + override fun onResume() { + super.onResume() + Log.d("11112222222111111111111", "11111111111111111") + //ClearRCView() + //outputSportUnder_the_conditions() } - override fun onClickDay(item: DayModel) { - model.liveDayCurrent.value = item + override fun onDestroy() { + super.onDestroy() + ClearRCView() } + //Звуковая часть + // 1. Plays the water sound + fun playSound() { + if (mMediaPlayer == null) { + mMediaPlayer = MediaPlayer.create(requireContext(), R.raw.sec1_metronom) + mMediaPlayer!!.isLooping = true + mMediaPlayer!!.start() + } else mMediaPlayer!!.start() + } + + // 2. Pause playback + fun pauseSound() { + if (mMediaPlayer?.isPlaying == true) mMediaPlayer?.pause() + } + + // 3. Stops playback + fun stopSound() { + if (mMediaPlayer != null) { + mMediaPlayer!!.stop() + mMediaPlayer!!.release() + mMediaPlayer = null + } + } + + // 4. Destroys the MediaPlayer instance when the app is closed + override fun onStop() { + super.onStop() + if (mMediaPlayer != null) { + mMediaPlayer!!.release() + mMediaPlayer = null + } + } + + + } \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/db/DaoDaySport.kt b/app/src/main/java/com/example/rehabilitation/db/DaoDaySport.kt deleted file mode 100644 index d89683e..0000000 --- a/app/src/main/java/com/example/rehabilitation/db/DaoDaySport.kt +++ /dev/null @@ -1,26 +0,0 @@ -package com.example.rehabilitation.db - -import androidx.room.Dao -import androidx.room.Insert -import androidx.room.Query -import kotlinx.coroutines.flow.Flow - -@Dao -interface DaoDaySport { - //Таблица определенного дня - @Insert - fun insertItemDaySport(itemDaySport:ItemDaySport) - - //Список определенного дня - @Query("SELECT * FROM itemDaySport ORDER BY id ASC") - fun getAllItemDaySport(): Flow> - - //Список определенного дня - @Query("SELECT * FROM itemDaySport WHERE day = :day ORDER BY id ASC") - fun getAllItemDaySport(day:String): Flow> - - //Очистка таблицы - @Query("DELETE FROM itemDaySport") - fun deleteItemDaySport() - -} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/db/MainDB.kt b/app/src/main/java/com/example/rehabilitation/db/MainDB.kt deleted file mode 100644 index 5bdc6ca..0000000 --- a/app/src/main/java/com/example/rehabilitation/db/MainDB.kt +++ /dev/null @@ -1,23 +0,0 @@ -package com.example.rehabilitation.db - -import androidx.room.Room -import androidx.room.RoomDatabase -import android.content.Context -import androidx.room.Database - -@Database(entities = [Item::class, ItemDaySport::class, ItemImage::class, ItemSportCategory::class], version = 1) -abstract class MainDB: RoomDatabase() { - abstract fun getDao(): Dao - abstract fun getDaoDaySport(): DaoDaySport - abstract fun getDaoImage(): DaoImage - abstract fun getDaoSportCategory(): DaoSportCategory - companion object{ - fun getDB(context: Context):MainDB{ - return Room.databaseBuilder( - context.applicationContext, - MainDB::class.java, - "tttttttttttttt1.db" - ).build() - } - } -} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/dip/MainViewModel.kt b/app/src/main/java/com/example/rehabilitation/dip/MainViewModel.kt deleted file mode 100644 index b0d001e..0000000 --- a/app/src/main/java/com/example/rehabilitation/dip/MainViewModel.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.example.sqlitework.dip - -import android.app.Application -import androidx.lifecycle.* -import com.example.rehabilitation.dip.Day.DayModel -import com.example.rehabilitation.dip.Image.ImageSportModel -import com.example.rehabilitation.dip.Month.MonthModel - - -//Тут будут обновлятся данные, следим за списками если что-то обновилось, то уведомлякм и потом ProductAdapter обновит -class MainViewModel(application: Application) :AndroidViewModel(application){ - - - //Объявления - val liveListCurrent = MutableLiveData()//Сюда передается новая информация на один день(для слайдера) - val liveListList= MutableLiveData>()//Сюда передается новая информация на один день(для все продукции - всего списка) - - val liveDayCurrent = MutableLiveData()//Сюда передается новая информация на один день(для слайдера) - val liveDayList= MutableLiveData>()//Сюда передается новая информация на один день(для все продукции - всего списка) - - - val liveImageCurrent = MutableLiveData()//Сюда передается новая информация на один день(для слайдера) - val liveImageList= MutableLiveData>()//Сюда передается новая информация на один день(для все продукции - всего списка) - -} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/DataModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/DataModel.kt new file mode 100644 index 0000000..8aef7db --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/DataModel.kt @@ -0,0 +1,28 @@ +package com.example.rehabilitation.model_adapter + +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.ViewModel + +//Ослеживание за обновлением подробной продуктовой карточкой +open class DataModel: ViewModel() { + /*//Для отлеживания обновлений активити + val messageForActivity: MutableLiveData by lazy{//by lazy - чтобы каждый раз не создавался MutableLiveData(MutableLiveData()), а он один раз при загрузке создаться и дальше будет пользоваться уже созданным + MutableLiveData()//LiveData - означает что будет обновляться в нужынй момент, не постоянна, а в зависимоти от жизни активити + }*/ + //Для отлеживания обновлений фрагммента 1 + val messageForFrag1: MutableLiveData by lazy{//by lazy - чтобы каждый раз не создавался MutableLiveData(MutableLiveData()), а он один раз при загрузке создаться и дальше будет пользоваться уже созданным + MutableLiveData()//LiveData - означает что будет обновляться в нужынй момент, не постоянна, а в зависимоти от жизни активити + } + + val fragmentMenu: MutableLiveData by lazy{//by lazy - чтобы каждый раз не создавался MutableLiveData(MutableLiveData()), а он один раз при загрузке создаться и дальше будет пользоваться уже созданным + MutableLiveData()//LiveData - означает что будет обновляться в нужынй момент, не постоянна, а в зависимоти от жизни активити + } + val addZakaz: MutableLiveData by lazy{//by lazy - чтобы каждый раз не создавался MutableLiveData(MutableLiveData()), а он один раз при загрузке создаться и дальше будет пользоваться уже созданным + MutableLiveData()//LiveData - означает что будет обновляться в нужынй момент, не постоянна, а в зависимоти от жизни активити + } + + /*//Для отлеживания обновлений фрагммента 2 + val messageForFrag2: MutableLiveData by lazy{//by lazy - чтобы каждый раз не создавался MutableLiveData(MutableLiveData()), а он один раз при загрузке создаться и дальше будет пользоваться уже созданным + MutableLiveData()//LiveData - означает что будет обновляться в нужынй момент, не постоянна, а в зависимоти от жизни активити + }*/ +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/dip/Day/DayAdapter.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Day/DayAdapter.kt similarity index 61% rename from app/src/main/java/com/example/rehabilitation/dip/Day/DayAdapter.kt rename to app/src/main/java/com/example/rehabilitation/model_adapter/Day/DayAdapter.kt index efb6b11..54a23a0 100644 --- a/app/src/main/java/com/example/rehabilitation/dip/Day/DayAdapter.kt +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Day/DayAdapter.kt @@ -1,5 +1,8 @@ -package com.example.rehabilitation.dip.Day +package com.example.rehabilitation.model_adapter.Day +import android.annotation.SuppressLint +import android.graphics.Color +import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -7,11 +10,10 @@ import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.example.rehabilitation.R -import com.example.rehabilitation.databinding.RcItemBinding import com.example.rehabilitation.databinding.RcItemDayBinding -class DayAdapter(val listener_zakaz: Listener) : ListAdapter( +class DayAdapter(val listener_zakaz: Listener) : ListAdapter( Comparator() ) {//Productitem - по этой форме будем заполнять.//ProductAdapter.holder - это создаваемый holder который хранит логику как нужно заполнять карточку @@ -22,28 +24,66 @@ class DayAdapter(val listener_zakaz: Listener) : ListAdapter listener_zakaz.onClickDay(it1) } } } //Функция bind для заполнения - fun bind(item: DayModel) = with(binding) {//Productitem - перпедаем данные + + //ЗАдержка нажатия на кнопку + private fun timerButtonDoubleButton(btn: View){ + val updateHandler = Handler() + + val runnable = Runnable { + btn.setEnabled(true) + } + + updateHandler.postDelayed(runnable, 5000) + } + @SuppressLint("SuspiciousIndentation") + fun bind(item: DayListModel) = with(binding) {//Productitem - перпедаем данные itemTemp = item //txtName.text = item.name //txtCount.text = item.count //txtImage.text = item.image txtName.text = item.number txtDay.text = item.day + val category = item.category[0].toString() + if (category == "c"){ + binding.imageSport.setImageResource(R.drawable.c_sport) + } + else if (category == "b"){ + binding.imageSport.setImageResource(R.drawable.b_sport) + } + else if (category == "j"){ + binding.imageSport.setImageResource(R.drawable.j_sport) } + if(item.check.toInt() == 0){ + binding.CardViewDay.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + } + else if(item.check.toInt() == 1) { + binding.CardViewDay.setCardBackgroundColor(Color.parseColor("#98EA88")) + } + else if(item.check.toInt() == 2){ + binding.CardViewDay.setCardBackgroundColor(Color.parseColor("#A68C78")) + } + + } + + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { val view = LayoutInflater.from(parent.context).inflate(R.layout.rc_item_day, parent, false)//Создаем(надуваем) list_item return Holder(view, listener_zakaz)//Через Holder возврощаем view @@ -55,19 +95,19 @@ class DayAdapter(val listener_zakaz: Listener) : ListAdapter() { - override fun areItemsTheSame(oldItem: DayModel, newItem: DayModel): Boolean {//Тут лучше всего сравнивать по id//oldItem - элементы старого списка, newItem - элементы нового списка//Возврощает Boolean, тоесть есть изменения или нет + class Comparator : DiffUtil.ItemCallback() { + override fun areItemsTheSame(oldItem: DayListModel, newItem: DayListModel): Boolean {//Тут лучше всего сравнивать по id//oldItem - элементы старого списка, newItem - элементы нового списка//Возврощает Boolean, тоесть есть изменения или нет return oldItem.id == newItem.id//Сравниваем полностью весь список новы и старый, по очередно по одной карточке и по элементно, то есть нулевой элемент, первый, второй и т.д.. Но лучше сравнивать по id списки, а не просто весь список, так как это эфективнее, так как id уникальный(oldItem.id == newItem.id) } - override fun areContentsTheSame(oldItem: DayModel, newItem: DayModel): Boolean {//Утут нужно сравнивать весь спсок старых элементов и новых + override fun areContentsTheSame(oldItem: DayListModel, newItem: DayListModel): Boolean {//Утут нужно сравнивать весь спсок старых элементов и новых return oldItem == newItem//Сравниваем полностью весь список новы и старый } } //Интерфейс нажатия на кнопку удалить товар из корзины interface Listener { - fun onClickDay(item: DayModel) + fun onClickDay(item: DayListModel) } diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Day/DayListModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Day/DayListModel.kt new file mode 100644 index 0000000..2434d9f --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Day/DayListModel.kt @@ -0,0 +1,11 @@ +package com.example.rehabilitation.model_adapter.Day + +data class DayListModel( + val id: String, + val number: String, + val day: String, + val category: String, + val check:String, + //val categoryAlf: String, +) + diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Day/DayListOneModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Day/DayListOneModel.kt new file mode 100644 index 0000000..b97efb6 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Day/DayListOneModel.kt @@ -0,0 +1,6 @@ +package com.example.rehabilitation.model_adapter.Day + +data class DayListOneModel( + val day: String, +) + diff --git a/app/src/main/java/com/example/rehabilitation/dip/Day/DayModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Day/DayModel.kt similarity index 81% rename from app/src/main/java/com/example/rehabilitation/dip/Day/DayModel.kt rename to app/src/main/java/com/example/rehabilitation/model_adapter/Day/DayModel.kt index 6d194b2..32924d4 100644 --- a/app/src/main/java/com/example/rehabilitation/dip/Day/DayModel.kt +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Day/DayModel.kt @@ -1,4 +1,4 @@ -package com.example.rehabilitation.dip.Day +package com.example.rehabilitation.model_adapter.Day data class DayModel( val id: String, diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Doctor/DoctorModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Doctor/DoctorModel.kt new file mode 100644 index 0000000..a6675ff --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Doctor/DoctorModel.kt @@ -0,0 +1,12 @@ +package com.example.rehabilitation.model_adapter.Doctor + +data class DoctorModel( + val id: String, + val name:String, + val surname:String, + val patronymic:String, + //val email:String, + val login:String, + val password:String, +) + diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/EditSportAdapter.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/EditSportAdapter.kt new file mode 100644 index 0000000..58940de --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/EditSportAdapter.kt @@ -0,0 +1,119 @@ +package com.example.rehabilitation.model_adapter.Edit + +import android.annotation.SuppressLint +import android.graphics.Color +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.recyclerview.widget.DiffUtil +import androidx.recyclerview.widget.ListAdapter +import androidx.recyclerview.widget.RecyclerView +import com.example.rehabilitation.R +import com.example.rehabilitation.databinding.RcItemBinding +import com.example.rehabilitation.databinding.RcItemDayBinding +import com.example.rehabilitation.databinding.RcItemDayEditBinding +import java.time.LocalDate + + +class EditSportAdapter(val listener_zakaz: Listener,val visible_card: ListenerEdit) : ListAdapter( + Comparator() +) {//Productitem - по этой форме будем заполнять.//ProductAdapter.holder - это создаваемый holder который хранит логику как нужно заполнять карточку + + + //В holder создаетс код с помошью которого мы будем заполнять и сохронять разметку + class Holder(view: View, val listener_zakaz: Listener,val visible_card: ListenerEdit): RecyclerView.ViewHolder(view) {//Класс который будет хранить сссылки на элементы, и отвечает за один элемент за 1 раз, то есть сначсало нулевой элемент заполнит, потом первый, потом второй и т.д. + //Для передачи данных + + val binding = RcItemDayEditBinding.bind(view)//view - здесь храянтся элементы и мы их bind заполним в ListItemBinding//ListItemBinding - это клласс даннйо разметки(карточки) которую мы будем заполнять, а нужна дання переменная(binding), чтобы мжно было при заполнение обращатся к элементам карточки + + var itemTemp: EditSportModel? = null//Глобальная переменная для нашего item, чтобы можно было передать данные для нажатия + + //init - дает возможность внутри адаптера обращаться к элементам экрана + init { + itemView.setOnClickListener {//Нажатие на ячейку//itemView - это весь элемент карточки из списка + itemTemp?.let { it1 -> listener_zakaz.onClickExceptionOrder(it1) } + } + binding.btnVisibleCardEdit.setOnClickListener { + itemTemp?.let { it2 -> visible_card.onClickEditCard(it2) } + } + } + + //Функция bind для заполнения + @SuppressLint("SuspiciousIndentation") + fun bind(item: EditSportModel) = with(binding) {//Productitem - перпедаем данные + itemTemp = item + //txtName.text = item.name + //txtCount.text = item.count + //txtImage.text = item.image + txtName.text = item.id.toString() + txtDay.text = item.category + txtDescSport.text = item.desc + binding.CLMainPluss.visibility = if (item.expand) View.VISIBLE else View.GONE + binding.CLMainEdit.setOnClickListener{ + if(item.expand == false){ + binding.CLMainPluss.visibility = View.VISIBLE + item.expand = true + }else{ + + binding.CLMainPluss.visibility = View.GONE + item.expand = false + } + } + if(item.visible == 1){ + binding.CardViewDay.setCardBackgroundColor(Color.parseColor("#3AB0FF")) + } + else{ + binding.CardViewDay.setCardBackgroundColor(Color.parseColor("#99ADBA")) + + } + +// if(item.check.toInt() == 0){ +// binding.CardViewDay.setCardBackgroundColor(Color.parseColor("#3AB0FF")) +// } +// else{ +// binding.CardViewDay.setCardBackgroundColor(Color.parseColor("#33BC0E")) +// } + } + + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { + val view = LayoutInflater.from(parent.context).inflate(R.layout.rc_item_day_edit, parent, false)//Создаем(надуваем) list_item + return Holder(view, listener_zakaz,visible_card)//Через Holder возврощаем view + } + + override fun onBindViewHolder(holder: Holder, position: Int) { + val view = holder.bind(getItem(position))//Заполняем по позиции карточку + } + + + //Comparator - сравнивает старый список и новый и если что-то изменилось, то работает с конкретным изменением списке, а не весь список переписывает + class Comparator : DiffUtil.ItemCallback() { + override fun areItemsTheSame(oldItem: EditSportModel, newItem: EditSportModel): Boolean {//Тут лучше всего сравнивать по id//oldItem - элементы старого списка, newItem - элементы нового списка//Возврощает Boolean, тоесть есть изменения или нет + return oldItem.id == newItem.id//Сравниваем полностью весь список новы и старый, по очередно по одной карточке и по элементно, то есть нулевой элемент, первый, второй и т.д.. Но лучше сравнивать по id списки, а не просто весь список, так как это эфективнее, так как id уникальный(oldItem.id == newItem.id) + } + + override fun areContentsTheSame( + oldItem: EditSportModel, + newItem: EditSportModel + ): Boolean {//Утут нужно сравнивать весь спсок старых элементов и новых + return oldItem == newItem//Сравниваем полностью весь список новы и старый + } + } + + //Открытие подробного описания спортивного упражнения + interface Listener { + fun onClickExceptionOrder(item: EditSportModel) + } + //Интерфейс нажатия на кнопку отключить карточку + interface ListenerEdit { + fun onClickEditCard(item: EditSportModel) + } + + + +} + + + + diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/EditSportModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/EditSportModel.kt new file mode 100644 index 0000000..ade517c --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/EditSportModel.kt @@ -0,0 +1,13 @@ +package com.example.rehabilitation.model_adapter.Edit + +data class EditSportModel( + val id: Int, + val day: String, + val category: String, + val check:Int, + val visible:Int, + val desc:String, + val categoryImage:String, + var expand : Boolean = false +) + diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/adapterFirebase/Email.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/adapterFirebase/Email.kt new file mode 100644 index 0000000..d7a1666 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/adapterFirebase/Email.kt @@ -0,0 +1,33 @@ +package com.example.rehabilitation.model_adapter.Edit.adapterFirebase + +import android.annotation.SuppressLint +import android.content.Intent +import android.net.Uri +import android.os.Environment +import android.text.Html +import android.text.Spanned +import androidx.core.content.FileProvider +import androidx.core.net.toFile +import java.io.File + +class Email { + + fun getSendIntent(recipient: String, + subject: String, + text: String, + uri: Uri): Intent{ + + val emailIntent = Intent(Intent.ACTION_SEND) + + emailIntent.type = "application/excel" + emailIntent.putExtra(Intent.EXTRA_STREAM, uri) + emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject) + emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(recipient)) + emailIntent.putExtra(Intent.EXTRA_TEXT, text) + emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + emailIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION + emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK + + return emailIntent + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/adapterFirebase/ExcelFile.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/adapterFirebase/ExcelFile.kt new file mode 100644 index 0000000..6e986b5 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/adapterFirebase/ExcelFile.kt @@ -0,0 +1,341 @@ +package com.example.rehabilitation.model_adapter.Edit.adapterFirebase + +import android.os.Environment +import android.util.Log +import com.example.rehabilitation.fileUri2 +import com.example.rehabilitation.model_adapter.Progress.AfterListModel +import com.example.rehabilitation.model_adapter.Progress.BeforeListModel +import com.example.rehabilitation.uriFileEF +import org.apache.poi.ss.usermodel.BorderStyle +import org.apache.poi.ss.usermodel.CellStyle +import org.apache.poi.ss.usermodel.FillPatternType +import org.apache.poi.ss.usermodel.HorizontalAlignment +import org.apache.poi.ss.usermodel.IndexedColors +import org.apache.poi.ss.usermodel.Row +import org.apache.poi.ss.usermodel.Sheet +import org.apache.poi.ss.usermodel.VerticalAlignment +import org.apache.poi.ss.usermodel.Workbook +import org.apache.poi.ss.util.CellRangeAddress +import org.apache.poi.xssf.usermodel.XSSFWorkbook +import java.io.File +import java.io.FileNotFoundException +import java.io.FileOutputStream +import java.io.IOException + +class ExcelFile( private val FIO: String, private val numDaysB: Int, private val numDaysA: Int, private val nameFile:String, private val BQDate: List, private val AQDate: List) { + + private lateinit var sheetAfter: Sheet + private lateinit var sheetBefore: Sheet + private lateinit var ourWorkbook: Workbook + private lateinit var cs: CellStyle + private lateinit var csRed: CellStyle + private lateinit var csGreen: CellStyle + private val filesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + init { + //Check whether it exists or not, and create one if it does not exist. + if (filesDir != null && !filesDir.exists()) { + filesDir.mkdirs() + } + ourWorkbook = createWorkbook() + Log.i("1", "1") + } + + fun saveTable(){ + + val excelFile = File(filesDir, "/"+nameFile+".xlsx") + uriFileEF = excelFile + Log.i("excelFile","${excelFile}") + try { + val fileOut = FileOutputStream(excelFile) + fileUri2 = fileOut + Log.i("fileOut","${fileOut}") + ourWorkbook.write(fileOut) + fileOut.close() + Log.i("File", "Done") + } catch (e: FileNotFoundException) { + Log.e("File", e.message, e) + } catch (e: IOException) { + Log.e("File", e.message, e) + } + } + + private fun createWorkbook(): Workbook { + Log.i("2", "2") + // Creating a workbook object from the XSSFWorkbook() class + ourWorkbook = XSSFWorkbook() + + csRed = ourWorkbook.createCellStyle() + csRed.fillForegroundColor = IndexedColors.RED.index + csRed.fillPattern = FillPatternType.SOLID_FOREGROUND + csRed.verticalAlignment = VerticalAlignment.CENTER + csRed.alignment = HorizontalAlignment.CENTER + + csRed.borderTop = BorderStyle.THIN; + csRed.borderBottom = BorderStyle.THIN; + csRed.borderLeft = BorderStyle.THIN; + csRed.borderRight = BorderStyle.THIN; + + csRed.topBorderColor = IndexedColors.BLACK.index; + csRed.bottomBorderColor = IndexedColors.BLACK.index; + csRed.rightBorderColor = IndexedColors.BLACK.index; + csRed.leftBorderColor = IndexedColors.BLACK.index; + + csGreen = ourWorkbook.createCellStyle() + csGreen.fillForegroundColor = IndexedColors.GREEN.index + csGreen.fillPattern = FillPatternType.SOLID_FOREGROUND + csGreen.verticalAlignment = VerticalAlignment.CENTER + csGreen.alignment = HorizontalAlignment.CENTER + + csGreen.borderTop = BorderStyle.THIN; + csGreen.borderBottom = BorderStyle.THIN; + csGreen.borderLeft = BorderStyle.THIN; + csGreen.borderRight = BorderStyle.THIN; + + csGreen.topBorderColor = IndexedColors.BLACK.index; + csGreen.bottomBorderColor = IndexedColors.BLACK.index; + csGreen.rightBorderColor = IndexedColors.BLACK.index; + csGreen.leftBorderColor = IndexedColors.BLACK.index; + + cs = ourWorkbook.createCellStyle() + cs.verticalAlignment = VerticalAlignment.CENTER + cs.alignment = HorizontalAlignment.CENTER + cs.borderTop = BorderStyle.THIN; + cs.borderBottom = BorderStyle.THIN; + cs.borderLeft = BorderStyle.THIN; + cs.borderRight = BorderStyle.THIN; + cs.topBorderColor = IndexedColors.BLACK.index; + cs.bottomBorderColor = IndexedColors.BLACK.index; + cs.rightBorderColor = IndexedColors.BLACK.index; + cs.leftBorderColor = IndexedColors.BLACK.index; + + sheetBefore = ourWorkbook.createSheet("Перед занятием") + sheetAfter = ourWorkbook.createSheet("После занятия") + addBeforeData() + addAfterData() + + return ourWorkbook + } + + private fun createCell(sheetRow: Row, columnIndex: Int, cellValue: String?, cellStyle: CellStyle?) { + Log.i("4", "4") + //create a cell at a passed in index + val ourCell = sheetRow.createCell(columnIndex) + //add the value to it + //a cell can be empty. That's why its nullable + ourCell?.setCellValue(cellValue) + if (cellStyle != null){ + ourCell?.cellStyle = cellStyle + } + } + + + private fun addBeforeData() { + Log.i("31", "31") + Log.i("BQDate", "${BQDate[0].date.substring(5)}") + + val row1 = sheetBefore.createRow(0) + val row2 = sheetBefore.createRow(1) + val row3 = sheetBefore.createRow(2) + val row4 = sheetBefore.createRow(3) + val row5 = sheetBefore.createRow(4) + val row6 = sheetBefore.createRow(5) + val row7 = sheetBefore.createRow(6) + val row8 = sheetBefore.createRow(7) + val row9 = sheetBefore.createRow(8) + val row10 = sheetBefore.createRow(9) + val row11 = sheetBefore.createRow(10) + val row12 = sheetBefore.createRow(11) + val row13 = sheetBefore.createRow(12) + + sheetBefore.setColumnWidth(1, 25000) + sheetBefore.addMergedRegion(CellRangeAddress.valueOf("A1:${'B'+numDaysB}1")) + sheetBefore.addMergedRegion(CellRangeAddress.valueOf("B2:B3")) + sheetBefore.addMergedRegion(CellRangeAddress.valueOf("A2:A3")) + sheetBefore.addMergedRegion(CellRangeAddress.valueOf("C2:${'B'+numDaysB}2")) + + createCell(row1, 0, "Анкета для контроля состояния пациента $FIO перед занятием", cs) + createCell(row2, 0, "№ п/п", cs) + createCell(row2, 1, "Вопрос", cs) + createCell(row2, 2, "День", cs) + for (i in 1..BQDate.count()){ + Log.i("311", "311") + val date = BQDate[i-1].date.substring(5) + val day = "${date[3]}"+"${date[4]}"//День + val mount = "${date[0]}"+"${date[1]}"//Месяц + createCell(row3, 1+i, "${day}.${mount}", cs) + } + + createCell(row4, 0, "1", cs) + createCell(row4, 1, "Есть ли у Вас фантомные боли?", cs) + + createCell(row5, 0, "1.2", cs) + createCell(row5, 1, "Интенсивность фантомных болей?", cs) + + createCell(row6, 0, "3", cs) + createCell(row6, 1, "Есть отек в области культи?", cs) + + createCell(row7, 0, "4", cs) + createCell(row7, 1, "Есть ли покраснения в области культи?", cs) + + createCell(row8, 0, "5", cs) + row8.height = 1000 + createCell(row8, 1, "Есть ли покраснения в области культи?\n Есть ли локальное повышение температуры в области культи?", cs) + + + createCell(row9, 0, "6", cs) + createCell(row9, 1, "Есть ли выделения (кровь, сукровица) из области шва?", cs) + + + createCell(row10, 0, "7", cs) + createCell(row10, 1, "Есть ли повышение температуры (общее) выше 37,5?", cs) + + + createCell(row11, 0, "8", cs) + createCell(row11, 1, "Было ли ухудшение состояния после предыдущего занятия?", cs) + + + createCell(row12, 0, "9", cs) + createCell(row12, 1, "Удалось ли полностью восстановиться после предыдущего занятия?", cs) + + + createCell(row13, 0, "10", cs) + createCell(row13, 1, "Были ухудшения самочувствия?", cs) + + } + + private fun addAfterData() { + Log.i("32", "32") + val row1 = sheetAfter.createRow(0) + val row2 = sheetAfter.createRow(1) + val row3 = sheetAfter.createRow(2) + val row4 = sheetAfter.createRow(3) + val row5 = sheetAfter.createRow(4) + val row6 = sheetAfter.createRow(5) + val row7 = sheetAfter.createRow(6) + val row8 = sheetAfter.createRow(7) + val row9 = sheetAfter.createRow(8) + val row10 = sheetAfter.createRow(9) + val row11 = sheetAfter.createRow(10) + val row12 = sheetAfter.createRow(11) + val row13 = sheetAfter.createRow(12) + val row14 = sheetAfter.createRow(13) + val row15 = sheetAfter.createRow(14) + + sheetAfter.setColumnWidth(1, 25000) + sheetAfter.addMergedRegion(CellRangeAddress.valueOf("A1:${'B'+numDaysA}1")) + sheetAfter.addMergedRegion(CellRangeAddress.valueOf("B2:B3")) + sheetAfter.addMergedRegion(CellRangeAddress.valueOf("A2:A3")) + sheetAfter.addMergedRegion(CellRangeAddress.valueOf("C2:${'B'+numDaysA}2")) + + createCell(row1, 0, "Анкета для контроля состояния пациента $FIO после занятия", cs) + createCell(row2, 0, "№ п/п", cs) + createCell(row2, 1, "Вопрос", cs) + createCell(row2, 2, "День", cs) + + for (i in 1..AQDate.count()){ + val date = AQDate[i-1].date.substring(5) + val day = "${date[3]}"+"${date[4]}"//День + val mount = "${date[0]}"+"${date[1]}"//Месяц + + createCell(row3, 1+(i), "${day}.${mount}", cs) + + } + + createCell(row4, 0, "1", cs) + createCell(row4, 1, "Интенсивность фантомных болей?", cs) + + createCell(row5, 0, "2", cs) + createCell(row5, 1, "Было ли усиление болевого синдрома во время занятий? ", cs) + + createCell(row6, 0, "3", cs) + row6.height = 1000 + createCell(row6, 1, "При прекращении упражнения, которое вызвало усиление болевого синдрома,\n боль купируется (или возвращается к уровню до занятия) в течение 2 минут? ", cs) + + createCell(row7, 0, "4", cs) + createCell(row7, 1, "Интенсивность болевого синдрома до занятия и после одинаковая? ", cs) + + createCell(row8, 0, "5", cs) + createCell(row8, 1, "Есть отек в области культи? ", cs) + + createCell(row9, 0, "6", cs) + createCell(row9, 1, "По сравнению с состояние перед занятием увеличился ли отек культи?", cs) + + createCell(row10, 0, "7", cs) + createCell(row10, 1, "Есть ли покраснения в области культи? ", cs) + + createCell(row11, 0, "8", cs) + createCell(row11, 1, "Есть ли локальное повышение температуры в области культи?", cs) + + createCell(row12, 0, "9", cs) + createCell(row12, 1, "Есть ли выделения (кровь, сукровица) из области шва?", cs) + + createCell(row13, 0, "10", cs) + createCell(row13, 1, "Выделения из области шва усилились/изменили характер?", cs) + + createCell(row14, 0, "11", cs) + createCell(row14, 1, "Есть ли общее ощущение слабости, чрезмерной усталости, «разбитости»?", cs) + + createCell(row15, 0, "12", cs) + createCell(row15, 1, "Все ли упражнения удалось выполнить?", cs) + + } + + fun addBeforeDay(day: Int, question: Int, data: Int){ + if ((day > numDaysB) or (question > 10)){ + throw ArrayIndexOutOfBoundsException("Выход за пределы таблицы") + } + val row = sheetBefore.getRow(question+2) + if (question == 2){ + if (data > 5){ + createCell(row, day+1, data.toString(), csRed) + } + else { + createCell(row, day+1, data.toString(), csGreen) + } + } + else{ + if (question == 9){ + when(data){ + 0 -> createCell(row, day+1, "Нет", csRed) + else -> createCell(row, day+1, "Да", csGreen) + } + } + else { + when(data){ + 0 -> createCell(row, day+1, "Нет", csGreen) + else -> createCell(row, day+1, "Да", csRed) + } + } + } + } + + fun addAfterDay(day: Int, question: Int, data: Int){ + if ((day > numDaysA) or (question > 12)){ + throw ArrayIndexOutOfBoundsException("Выход за пределы таблицы") + } + val row = sheetAfter.getRow(question+2) + if (question == 1){ + if (data > 5){ + createCell(row, day+1, data.toString(), csRed) + } + else { + createCell(row, day+1, data.toString(), csGreen) + } + } + else{ + if (question in listOf(3, 4, 12)){ + when(data){ + 0 -> createCell(row, day+1, "Нет", csRed) + else -> createCell(row, day+1, "Да", csGreen) + } + } + else { + when(data){ + 0 -> createCell(row, day+1, "Нет", csGreen) + else -> createCell(row, day+1, "Да", csRed) + } + } + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/adapterFirebase/MyFirebaseMessagingService.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/adapterFirebase/MyFirebaseMessagingService.kt new file mode 100644 index 0000000..6982957 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/adapterFirebase/MyFirebaseMessagingService.kt @@ -0,0 +1,83 @@ +package com.example.rehabilitation.model_adapter.Edit.adapterFirebase + +import android.annotation.SuppressLint +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.os.Build +import android.widget.RemoteViews +import androidx.core.app.NotificationCompat +//import com.google.firebase.messaging.FirebaseMessagingService +//import com.google.firebase.messaging.RemoteMessage + +const val channel_id = "channel_id" +const val channel_name = "user" + +@SuppressLint("MissingFirebaseInstanceTokenRefresh") +//class MyFirebaseMessagingService:FirebaseMessagingService() { + class MyFirebaseMessagingService { +/* + //Вывод уведомления + override fun onMessageReceived(remoteMessage: RemoteMessage) { + if(remoteMessage.notification != null){ + + try { + generateNotification( + remoteMessage.notification!!.title!!, + remoteMessage.notification!!.body!! + ) + } + catch (e: Exception){ + + } + + } + } + + + fun generateNotification(title:String, message:String){ + + val intent = Intent(this, MainActivity::class.java) + //Вывод уведомления поверх всех экранов + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) + + //Удаляем уведомление по нажатию на него 1 раз + val pendingIntent = PendingIntent.getActivity(this, 0,intent,PendingIntent.FLAG_ONE_SHOT) + + // + var builder=NotificationCompat.Builder(applicationContext, channel_id) + .setSmallIcon(R.drawable.cart_24)//Изображение + .setAutoCancel(true) + .setVibrate(longArrayOf(1000,1000,1000,1000))//Вибрации 1 секунда вибрации 1 секунда бе и повтор + .setContentIntent(pendingIntent)//Создалии строитель + + builder = builder.setContent(getRemoteView(title, message)) + + val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + //Если версия выше или равна oreo + if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){ + val notificationChannel = NotificationChannel(channel_id, channel_name,NotificationManager.IMPORTANCE_HIGH) + notificationManager.createNotificationChannel(notificationChannel) + } + + //Отправляем уведомление + notificationManager.notify(0,builder.build()) + + } + + private fun getRemoteView(title: String, message: String): RemoteViews? { + //Разметка + val remoteView = RemoteViews("com.example.get_post_zaprose.Chat.firebase",R.layout.push_notification) + + //Присваиваем значения + remoteView.setTextViewText(R.id.txtTitle,title) + remoteView.setTextViewText(R.id.txtTitle2,message) + remoteView.setImageViewResource(R.id.imLogo,R.drawable.cart_24) + + return remoteView + + }*/ +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/adapterFirebase/User.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/adapterFirebase/User.kt new file mode 100644 index 0000000..d0ff9f7 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/adapterFirebase/User.kt @@ -0,0 +1,7 @@ +package com.example.rehabilitation.model_adapter.Edit.adapterFirebase + +//Класс с помошью которого мы будем хранить информацию на Firebase +data class ReportPatient( + val name:String? = null,//? - так как может быть равен null + val message:String? = null, +) diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/adapterFirebase/sample.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/adapterFirebase/sample.kt new file mode 100644 index 0000000..b13d685 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Edit/adapterFirebase/sample.kt @@ -0,0 +1,11 @@ +package com.example.rehabilitation.model_adapter.Edit.adapterFirebase + +import org.apache.poi.xssf.usermodel.XSSFWorkbook +import java.io.File +import java.io.FileOutputStream + +class sample { + + + +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Image/Category/CountCategoryModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Image/Category/CountCategoryModel.kt new file mode 100644 index 0000000..101b6f8 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Image/Category/CountCategoryModel.kt @@ -0,0 +1,6 @@ +package com.example.rehabilitation.model_adapter.Image.Category + +data class CountCategoryModel( + val count: String, +) + diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Image/Category/CountNameCategoryArticleModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Image/Category/CountNameCategoryArticleModel.kt new file mode 100644 index 0000000..c12b242 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Image/Category/CountNameCategoryArticleModel.kt @@ -0,0 +1,8 @@ +package com.example.rehabilitation.model_adapter.Image.Category + +data class CountNameCategoryArticleModel( + val count: String, + val name: String, + val article: String, +) + diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Image/Category/CountNameCategoryModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Image/Category/CountNameCategoryModel.kt new file mode 100644 index 0000000..887ece6 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Image/Category/CountNameCategoryModel.kt @@ -0,0 +1,7 @@ +package com.example.rehabilitation.model_adapter.Image.Category + +data class CountNameCategoryModel( + val count: String, + val name: String, +) + diff --git a/app/src/main/java/com/example/rehabilitation/dip/Image/ImageSportAdapter.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Image/ImageSportAdapter.kt similarity index 82% rename from app/src/main/java/com/example/rehabilitation/dip/Image/ImageSportAdapter.kt rename to app/src/main/java/com/example/rehabilitation/model_adapter/Image/ImageSportAdapter.kt index 38064ff..cdd72ab 100644 --- a/app/src/main/java/com/example/rehabilitation/dip/Image/ImageSportAdapter.kt +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Image/ImageSportAdapter.kt @@ -1,5 +1,7 @@ -package com.example.rehabilitation.dip.Image +package com.example.rehabilitation.model_adapter.Image +import android.annotation.SuppressLint +import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -8,17 +10,15 @@ import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.example.rehabilitation.R import com.example.rehabilitation.databinding.ImageSportCardsBinding -import com.example.rehabilitation.databinding.RcItemDayBinding -import java.time.LocalDate -class ImageSportAdapter() : ListAdapter( +class ImageSportAdapter(val contextF:Context) : ListAdapter( Comparator() ) {//Productitem - по этой форме будем заполнять.//ProductAdapter.holder - это создаваемый holder который хранит логику как нужно заполнять карточку //В holder создаетс код с помошью которого мы будем заполнять и сохронять разметку - class Holder(view: View): RecyclerView.ViewHolder(view) {//Класс который будет хранить сссылки на элементы, и отвечает за один элемент за 1 раз, то есть сначсало нулевой элемент заполнит, потом первый, потом второй и т.д. + class Holder(view: View,val contextF:Context): RecyclerView.ViewHolder(view) {//Класс который будет хранить сссылки на элементы, и отвечает за один элемент за 1 раз, то есть сначсало нулевой элемент заполнит, потом первый, потом второй и т.д. //Для передачи данных val binding = ImageSportCardsBinding.bind(view)//view - здесь храянтся элементы и мы их bind заполним в ListItemBinding//ListItemBinding - это клласс даннйо разметки(карточки) которую мы будем заполнять, а нужна дання переменная(binding), чтобы мжно было при заполнение обращатся к элементам карточки @@ -34,16 +34,18 @@ class ImageSportAdapter() : ListAdapter()//Сюда передается новая информация на один день(для слайдера) + val liveListList= MutableLiveData>()//Сюда передается новая информация на один день(для все продукции - всего списка) + + val liveDayCurrent = MutableLiveData()//Сюда передается новая информация на один день(для слайдера) + val liveDayList= MutableLiveData>()//Сюда передается новая информация на один день(для все продукции - всего списка) + val liveDayListProgres= MutableLiveData>()//Сюда передается новая информация на один день(для все продукции - всего списка) + val liveDayListProgres2= MutableLiveData>()//Сюда передается новая информация на один день(для все продукции - всего списка) + + + val liveImageCurrent = MutableLiveData()//Сюда передается новая информация на один день(для слайдера) + val liveImageList= MutableLiveData>()//Сюда передается новая информация на один день(для все продукции - всего списка) + + + val liveCountCategoryCurrent = MutableLiveData()//Сюда передается новая информация на один день(для слайдера) + val liveCountNameCategoryCurrent = MutableLiveData()//Сюда передается новая информация на один день(для слайдера) + + val liveAuthPatientCurrent = MutableLiveData()//Сюда передается новая информация на один день(для слайдера) + val liveAuthDoctorCurrent = MutableLiveData()//Сюда передается новая информация на один день(для слайдера) + + + //Количество дней прошедших + val liveCountMonthCurrent = MutableLiveData()//Сюда передается новая информация на один день(для слайдера) + //Количество пройденых тренировок + val liveCountDayCurrent = MutableLiveData()//Сюда передается новая информация на один день(для слайдера) + + val liveCountDaySceduleCurrent = MutableLiveData()//Сюда передается новая информация на один день(для слайдера) + + //Информация пациента + val liveSettingPatientCurrent = MutableLiveData() + val liveLookPatientCurrent = MutableLiveData() + val liveSettingDoctorCurrent = MutableLiveData() + + + //Информация для анкетирования + val liveAfterCurrent = MutableLiveData() + val liveBeforeCurrent = MutableLiveData() + val liveCountSportCurrent = MutableLiveData() + val liveCountSportPlusCurrent = MutableLiveData() + val liveNameSportCurrent = MutableLiveData() + val liveCountDaySportandPlusCurrent = MutableLiveData() + + + //Список для редактирвоания + val liveEditSportCurrent = MutableLiveData() + val liveEditSportList= MutableLiveData>() + + //Список для редактирвоания + val liveListDaySportOneCurrent = MutableLiveData() + + + //АНКЕТИРОВАНИЕ + //Список для редактирвоания + val liveListProgresBeforeList = MutableLiveData>() + val liveListProgresAfterList = MutableLiveData>() + + + //ПРОГРЕСС + val liveProgressAllList = MutableLiveData>() + val liveProgressCheckList = MutableLiveData>() + + //Количество упражнений + val liveCountSportCategoryCurrent = MutableLiveData() + val liveSportCategoryAllArticleList = MutableLiveData>() + +} \ No newline at end of file diff --git a/app/src/main/java/com/example/rehabilitation/dip/Month/MonthAdapter.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Month/MonthAdapter.kt similarity index 83% rename from app/src/main/java/com/example/rehabilitation/dip/Month/MonthAdapter.kt rename to app/src/main/java/com/example/rehabilitation/model_adapter/Month/MonthAdapter.kt index bafebb4..cceac25 100644 --- a/app/src/main/java/com/example/rehabilitation/dip/Month/MonthAdapter.kt +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Month/MonthAdapter.kt @@ -1,13 +1,18 @@ -package com.example.rehabilitation.dip.Month +package com.example.rehabilitation.model_adapter.Month +import android.annotation.SuppressLint +import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView +import com.example.rehabilitation.CursDayNull import com.example.rehabilitation.R +import com.example.rehabilitation.SportCursDay import com.example.rehabilitation.databinding.RcItemBinding +import java.time.LocalDate class MonthAdapter(val listener_zakaz: Listener) : ListAdapter( @@ -32,10 +37,23 @@ class MonthAdapter(val listener_zakaz: Listener) : ListAdapter( + Comparator() +) {//Productitem - по этой форме будем заполнять.//ProductAdapter.holder - это создаваемый holder который хранит логику как нужно заполнять карточку + + + //В holder создаетс код с помошью которого мы будем заполнять и сохронять разметку + class Holder(view: View, val listener_zakaz: Listener): RecyclerView.ViewHolder(view) {//Класс который будет хранить сссылки на элементы, и отвечает за один элемент за 1 раз, то есть сначсало нулевой элемент заполнит, потом первый, потом второй и т.д. + //Для передачи данных + + val binding = RcItemProgressBinding.bind(view)//view - здесь храянтся элементы и мы их bind заполним в ListItemBinding//ListItemBinding - это клласс даннйо разметки(карточки) которую мы будем заполнять, а нужна дання переменная(binding), чтобы мжно было при заполнение обращатся к элементам карточки + + var itemTemp: ProgressModel? = null//Глобальная переменная для нашего item, чтобы можно было передать данные для нажатия + + //init - дает возможность внутри адаптера обращаться к элементам экрана + init { + itemView.setOnClickListener {//Нажатие на ячейку//itemView - это весь элемент карточки из списка + itemView.setEnabled(false) + timerButtonDoubleButton(itemView) + itemTemp?.let { it1 -> listener_zakaz.onClickDay(it1) } + + } + } + + //Функция bind для заполнения + + //ЗАдержка нажатия на кнопку + private fun timerButtonDoubleButton(btn: View){ + val updateHandler = Handler() + + val runnable = Runnable { + btn.setEnabled(true) + } + + updateHandler.postDelayed(runnable, 5000) + } + @SuppressLint("SuspiciousIndentation") + fun bind(item: ProgressModel) = with(binding) {//Productitem - перпедаем данные + itemTemp = item + txtDate.text = item.id+". " + item.date + ": " + txtProgress.text = item.CountCheckTrue.toString()+"/"+item.countAll.toString() + if(item.CountCheckTrue == 0) { + CardViewDay.setCardBackgroundColor(Color.parseColor("#1993FF")) + } + else{ + CardViewDay.setCardBackgroundColor(Color.parseColor("#98EA88")) + + } + + } + + } + + + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { + val view = LayoutInflater.from(parent.context).inflate(R.layout.rc_item_progress, parent, false)//Создаем(надуваем) list_item + return Holder(view, listener_zakaz)//Через Holder возврощаем view + } + + override fun onBindViewHolder(holder: Holder, position: Int) { + val view = holder.bind(getItem(position))//Заполняем по позиции карточку + } + + + //Comparator - сравнивает старый список и новый и если что-то изменилось, то работает с конкретным изменением списке, а не весь список переписывает + class Comparator : DiffUtil.ItemCallback() { + override fun areItemsTheSame(oldItem: ProgressModel, newItem: ProgressModel): Boolean {//Тут лучше всего сравнивать по id//oldItem - элементы старого списка, newItem - элементы нового списка//Возврощает Boolean, тоесть есть изменения или нет + return oldItem.id == newItem.id//Сравниваем полностью весь список новы и старый, по очередно по одной карточке и по элементно, то есть нулевой элемент, первый, второй и т.д.. Но лучше сравнивать по id списки, а не просто весь список, так как это эфективнее, так как id уникальный(oldItem.id == newItem.id) + } + + override fun areContentsTheSame(oldItem: ProgressModel, newItem: ProgressModel): Boolean {//Утут нужно сравнивать весь спсок старых элементов и новых + return oldItem == newItem//Сравниваем полностью весь список новы и старый + } + } + + //Интерфейс нажатия на кнопку удалить товар из корзины + interface Listener { + fun onClickDay(item: ProgressModel) + } + + +} + + + + diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Progress/ProgressModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Progress/ProgressModel.kt new file mode 100644 index 0000000..c6bcae9 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Progress/ProgressModel.kt @@ -0,0 +1,11 @@ +package com.example.rehabilitation.model_adapter.Progress + +data class ProgressModel( + val id: String, + val countAll: Int, + var CountCheckTrue: Int, + val category: String, + val date:String, + + ) + diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Questionnair/AfterModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Questionnair/AfterModel.kt new file mode 100644 index 0000000..3986f13 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Questionnair/AfterModel.kt @@ -0,0 +1,6 @@ +package com.example.rehabilitation.model_adapter.Questionnair + +data class AfterModel( + val date: String, +) + diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Questionnair/BeforeModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Questionnair/BeforeModel.kt new file mode 100644 index 0000000..eadc09b --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Questionnair/BeforeModel.kt @@ -0,0 +1,6 @@ +package com.example.rehabilitation.model_adapter.Questionnair + +data class BeforeModel( + val date: String, +) + diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Questionnair/CountSportModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Questionnair/CountSportModel.kt new file mode 100644 index 0000000..34d7878 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Questionnair/CountSportModel.kt @@ -0,0 +1,6 @@ +package com.example.rehabilitation.model_adapter.Questionnair + +data class CountSportModel( + val count: Int, +) + diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Questionnair/CountSportPlusModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Questionnair/CountSportPlusModel.kt new file mode 100644 index 0000000..d0d8a1a --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Questionnair/CountSportPlusModel.kt @@ -0,0 +1,6 @@ +package com.example.rehabilitation.model_adapter.Questionnair + +data class CountSportPlusModel( + val count: Int, +) + diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/Questionnair/NameSportModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/Questionnair/NameSportModel.kt new file mode 100644 index 0000000..d3cc195 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/Questionnair/NameSportModel.kt @@ -0,0 +1,6 @@ +package com.example.rehabilitation.model_adapter.Questionnair + +data class NameSportModel( + val name: String, +) + diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/SportCategory/SportCategoryModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/SportCategory/SportCategoryModel.kt new file mode 100644 index 0000000..757cdc8 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/SportCategory/SportCategoryModel.kt @@ -0,0 +1,13 @@ +package com.example.rehabilitation.model_adapter.SportCategory + +data class SportCategoryModel( + val id: String, + val name: String, + val desc:String, + val count: String, + val image: String, + val category: String, + val article:String, + val check:Int, +) + diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/modelCount/CountDayModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/modelCount/CountDayModel.kt new file mode 100644 index 0000000..c9540bf --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/modelCount/CountDayModel.kt @@ -0,0 +1,7 @@ +package com.example.rehabilitation.model_adapter.modelCount + +data class CountDayModel( + val countDown: Int, + val countAll: Int, +) + diff --git a/app/src/main/java/com/example/rehabilitation/model_adapter/modelCount/CountMonthModel.kt b/app/src/main/java/com/example/rehabilitation/model_adapter/modelCount/CountMonthModel.kt new file mode 100644 index 0000000..203aeb7 --- /dev/null +++ b/app/src/main/java/com/example/rehabilitation/model_adapter/modelCount/CountMonthModel.kt @@ -0,0 +1,7 @@ +package com.example.rehabilitation.model_adapter.modelCount + +data class CountMonthModel( + val countDown: Int, + val countAll: Int, +) + diff --git a/app/src/main/res/color/bottom_menu.xml b/app/src/main/res/color/bottom_menu.xml new file mode 100644 index 0000000..3c6b0cf --- /dev/null +++ b/app/src/main/res/color/bottom_menu.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/amputation.png b/app/src/main/res/drawable/amputation.png new file mode 100644 index 0000000..369a3c1 Binary files /dev/null and b/app/src/main/res/drawable/amputation.png differ diff --git a/app/src/main/res/drawable/arrow.xml b/app/src/main/res/drawable/arrow.xml new file mode 100644 index 0000000..2e30840 --- /dev/null +++ b/app/src/main/res/drawable/arrow.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/b_sport.png b/app/src/main/res/drawable/b_sport.png new file mode 100644 index 0000000..f17315a Binary files /dev/null and b/app/src/main/res/drawable/b_sport.png differ diff --git a/app/src/main/res/drawable/c_sport.png b/app/src/main/res/drawable/c_sport.png new file mode 100644 index 0000000..95fdc17 Binary files /dev/null and b/app/src/main/res/drawable/c_sport.png differ diff --git a/app/src/main/res/drawable/gradientv1.xml b/app/src/main/res/drawable/gradientv1.xml new file mode 100644 index 0000000..2b00d72 --- /dev/null +++ b/app/src/main/res/drawable/gradientv1.xml @@ -0,0 +1,12 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml index 36707c2..ca3826a 100644 --- a/app/src/main/res/drawable/ic_launcher_background.xml +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -1,9 +1,10 @@ - + xmlns:android="http://schemas.android.com/apk/res/android"> + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/settings_24.xml b/app/src/main/res/drawable/settings_24.xml new file mode 100644 index 0000000..298a5a1 --- /dev/null +++ b/app/src/main/res/drawable/settings_24.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/sportshebuleicon.png b/app/src/main/res/drawable/sportshebuleicon.png new file mode 100644 index 0000000..56f4b86 Binary files /dev/null and b/app/src/main/res/drawable/sportshebuleicon.png differ diff --git a/app/src/main/res/drawable/visible_aes.png b/app/src/main/res/drawable/visible_aes.png new file mode 100644 index 0000000..62dc80a Binary files /dev/null and b/app/src/main/res/drawable/visible_aes.png differ diff --git a/app/src/main/res/drawable/visible_eas_false.png b/app/src/main/res/drawable/visible_eas_false.png new file mode 100644 index 0000000..62dc80a Binary files /dev/null and b/app/src/main/res/drawable/visible_eas_false.png differ diff --git a/app/src/main/res/drawable/visible_eas_true.png b/app/src/main/res/drawable/visible_eas_true.png new file mode 100644 index 0000000..59c30d9 Binary files /dev/null and b/app/src/main/res/drawable/visible_eas_true.png differ diff --git a/app/src/main/res/font/roboto_bold.ttf b/app/src/main/res/font/roboto_bold.ttf new file mode 100644 index 0000000..43da14d Binary files /dev/null and b/app/src/main/res/font/roboto_bold.ttf differ diff --git a/app/src/main/res/font/roboto_medium.ttf b/app/src/main/res/font/roboto_medium.ttf new file mode 100644 index 0000000..ac0f908 Binary files /dev/null and b/app/src/main/res/font/roboto_medium.ttf differ diff --git a/app/src/main/res/layout/activity_auth_doctor.xml b/app/src/main/res/layout/activity_auth_doctor.xml new file mode 100644 index 0000000..8e656e5 --- /dev/null +++ b/app/src/main/res/layout/activity_auth_doctor.xml @@ -0,0 +1,10 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_authorization.xml b/app/src/main/res/layout/activity_authorization.xml new file mode 100644 index 0000000..be77ee7 --- /dev/null +++ b/app/src/main/res/layout/activity_authorization.xml @@ -0,0 +1,79 @@ + + + + + + + +