Files
Parasha/SvetoforVKBot/Models/Commands/LK/SelectEditDataCommand.cs
2021-10-19 06:04:52 +03:00

453 lines
23 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using Newtonsoft.Json;
using VkNet.Enums.Filters;
using VkNet.Model.Attachments;
using System.Collections.Generic;
using System.Threading;
using SvetoforVKBot.Models.Dop;
using SvetoforVKBot.Models.Commands;
using System.Text.RegularExpressions;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.LK
{
public class SelectEditDataCommand : Command
{
public override string Name => "{\"button\":\"selectEditData-";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
var chatId = update.@object.message.from_id;
MessagesSendParams @params = new MessagesSendParams();
var keyboardBuilder = new KeyboardBuilder().Clear();
Regex regex = new Regex("[^0-9]");
string tag = "";
string msgSports = "";
string strSportKind = "";
string sportName = "";
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Личный кабинет - Данные";
db.SaveChanges();
Dictionary<int, string> colors = new Dictionary<int, string>(3);
colors.Add(1, "🟩"); //З
colors.Add(2, "🟦"); //C
colors.Add(3, "🟨"); //Ж
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
tracks.Add(1, "Оптимизация питания");
tracks.Add(2, "Снижение жировой массы");
tracks.Add(3, "Увеличение мышечной массы");
tracks.Add(4, "Персональный режим");
Dictionary<int, string> notifies = new Dictionary<int, string>(4);
notifies.Add(1, "1 раз в день");
notifies.Add(3, "3 раза в день");
notifies.Add(4, "Более 3х раз в день");
notifies.Add(0, "Никогда");
int weight = user.weight;
int height = user.height;
int gender = user.gender;
int notifyCount = user.notifyCount;
string fio = user.fio;
var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);
var birthday = user.birthday;
int track = user.track;
int waterNotify = user.waterNotify;
int activityKind = user.activityKind;
int sportId = user.sportId;
keyboardBuilder
.AddButton("⚖Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
.AddButton("📐Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("🔔Уведомления", "selectEditData-3", KeyboardButtonColor.Primary)
.AddButton("✏ФИО", "selectEditData-4", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("📅Дата рождения", "selectEditData-5", KeyboardButtonColor.Primary)
.AddButton("📞Телефон", "selectEditData-6", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Режим питания", "selectEditData-7", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Вид спорта/активности", "selectEditData-8", KeyboardButtonColor.Primary)
.AddLine();
if (activityKind == 0 || activityKind == 3)
msgSports = "Ничем не занимаюсь";
else
{
msgSports = "";
var sport = db.SportKinds.Single(s => s.id == sportId);
sportName = sport.name;
int sportKind = sport.kind;
if (sportKind == 1) strSportKind = sportName + " (Спорт)";
else strSportKind = sportName + " (Физ. активность)";
}
if (waterNotify == 1)
{
keyboardBuilder
.AddButton("✅Напоминания о воде", "selectOffWaterNotify", KeyboardButtonColor.Positive);
}
else
{
keyboardBuilder
.AddButton("⛔Напоминания о воде", "selectGoWaterNotify", KeyboardButtonColor.Negative);
}
keyboardBuilder
.AddLine()
.AddButton("Готово", "startPL", KeyboardButtonColor.Default);
@params.Message = "РЕДАКТИРОВАНИЕ ДАННЫХ" +
"\n\n" +
"ФИО: " + fio +
"\n" +
"Телефон: " + jsPhones[0] +
"\n" +
"Дата рождения: " + birthday.ToShortDateString() +
"\n" +
"Рост: " + height + " см" +
"\n" +
"Вес: " + weight + " кг" +
"\n" +
colors[track] + "Выбранный трек: " + tracks[track] +
"\n" +
"Уведомления: " + notifies[notifyCount] +
"\n" +
$"Вид спорта/активности: {msgSports}{strSportKind}" +
"\n\n" +
"Выберите на клавиатуре показатель, который хотите изменить или нажмите \"Готово\"👇🏻";
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectEditDataCommand.Execute: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
var chatId = update.@object.message.from_id;
MessagesSendParams @params = new MessagesSendParams();
var keyboardBuilder = new KeyboardBuilder().Clear();
Regex regex = new Regex("[^0-9]");
string tag = "";
int startYear = DateTime.Now.Year - 18;
int i = 0;
int btnCount = 0;
int btnLines = 0;
string msgSports = "";
string strSportKind = "";
string sportName = "";
try
{
string[] payload = update.@object.message.payload.Split('-');
int curOption = Convert.ToInt32(regex.Replace(payload[1], ""));
Dictionary<int, string> notifies = new Dictionary<int, string>(4);
notifies.Add(1, "1 раз в день");
notifies.Add(3, "3 раза в день");
notifies.Add(4, "Более 3х раз в день");
notifies.Add(0, "Никогда");
Dictionary<int, string> colors = new Dictionary<int, string>(3);
colors.Add(1, "🟩"); //З
colors.Add(2, "🟦"); //C
colors.Add(3, "🟨"); //Ж
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
tracks.Add(1, "Оптимизация питания");
tracks.Add(2, "Снижение жировой массы");
tracks.Add(3, "Увеличение мышечной массы");
tracks.Add(4, "Персональный режим");
var user = db.Users.Single(usr => usr.chatId == chatId);
int weight = user.weight;
int height = user.height;
int gender = user.gender;
int notifyCount = user.notifyCount;
string fio = user.fio;
var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);
var birthday = user.birthday;
int track = user.track;
int waterNotify = user.waterNotify;
int activityKind = user.activityKind;
int sportId = user.sportId;
switch (curOption)
{
case 0:
tag = "Личный кабинет - Данные";
keyboardBuilder
.AddButton("⚖Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
.AddButton("📐Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("🔔Уведомления", "selectEditData-3", KeyboardButtonColor.Primary)
.AddButton("✏ФИО", "selectEditData-4", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("📅Дата рождения", "selectEditData-5", KeyboardButtonColor.Primary)
.AddButton("📞Телефон", "selectEditData-6", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Режим питания", "selectEditData-7", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Вид спорта/активности", "selectEditData-8", KeyboardButtonColor.Primary)
.AddLine();
if (activityKind == 0)
msgSports = "Ничем не занимаюсь";
else
{
msgSports = "";
var sport = db.SportKinds.Single(s => s.id == sportId);
sportName = sport.name;
int sportKind = sport.kind;
if (sportKind == 1) strSportKind = sportName + " (Спорт)";
else strSportKind = sportName + " (Физ. активность)";
}
if (waterNotify >= 1 && waterNotify != 10)
{
keyboardBuilder
.AddButton("✅Напоминания о воде", "selectOffWaterNotify", KeyboardButtonColor.Positive);
}
else
{
keyboardBuilder
.AddButton("⛔Напоминания о воде", "selectGoWaterNotify", KeyboardButtonColor.Negative);
}
keyboardBuilder
.AddLine()
.AddButton("Готово", "startPL", KeyboardButtonColor.Default);
@params.Message = "РЕДАКТИРОВАНИЕ ДАННЫХ" +
"\n\n" +
"ФИО: " + fio +
"\n" +
"Телефон: " + jsPhones[0] +
"\n" +
"Дата рождения: " + birthday.ToShortDateString() +
"\n" +
"Рост: " + height + " см" +
"\n" +
"Вес: " + weight + " кг" +
"\n" +
colors[track] + "Выбранный трек: " + tracks[track] +
"\n" +
"Уведомления: " + notifies[notifyCount] +
"\n" +
$"Вид спорта/активности: {msgSports}{strSportKind}" +
"\n\n" +
"Выберите на клавиатуре показатель, который хотите изменить или нажмите \"Готово\"👇🏻";
break;
case 1:
tag = "Личный кабинет - Изменить вес";
keyboardBuilder
//.AddButton("Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
//.AddLine()
//.AddButton("Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
//.AddLine()
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
@params.Message = "Введите свой вес в кг. Например, 65.\n\n" +
"⚠ Лучшее время для измерения веса - утро. Взвешиваться следует после утренних процедур и до приёма пищи."; //❕
break;
case 2:
tag = "Личный кабинет - Изменить рост";
keyboardBuilder
//.AddButton("Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
//.AddLine()
//.AddButton("Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
//.AddLine()
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
@params.Message = "Введите свой рост в см. Например, 168.";
break;
case 3:
tag = "Личный кабинет - Уведомления";
keyboardBuilder
.AddButton("Раз в день", "selectEditNotifyCount-1", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Три раза в день", "selectEditNotifyCount-3", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Более 3х раз", "selectEditNotifyCount-4", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Никогда", "selectEditNotifyCount-0", KeyboardButtonColor.Default)
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
@params.Message = "Как часто Вы готовы получать напоминания от чат-бота?\n\n" +
"Вы будете получать уведомления о приёмах пищи и воды. Если Вы хотите сформировать привычку " +
"по режиму питания или употреблению достаточного количества воды, выберите вариант \"Более 3х раз\".\n" +
"Наш чат-бот не будет рассылать рекламу или спам. Только персональные уведомления и рекомендации по здоровому питанию.";
break;
case 4:
tag = "Личный кабинет - ФИО";
keyboardBuilder
//.AddButton("Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
//.AddLine()
//.AddButton("Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
//.AddLine()
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
@params.Message = "Введите фамилию, имя и отчество одним сообщением.\n\nНапример: Иванов Иван Иванович";
break;
case 5:
tag = "Личный кабинет - ДР - Год";
@params.Message = "Выберите на клавиатуре внизу или введите свой год рождения, например 1993. \n";
for (i = startYear; i > startYear - 20; i--)
{
keyboardBuilder
.AddButton(i.ToString(), i.ToString(), KeyboardButtonColor.Primary);
btnCount++;
if (btnCount % 4 == 0)
{
btnLines++;
keyboardBuilder.AddLine();
}
}
if (btnCount % 4 != 0)
{
keyboardBuilder.AddLine();
}
keyboardBuilder
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder
.Build();
break;
case 6:
tag = "Личный кабинет - Телефон";
keyboardBuilder
//.AddButton("Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
//.AddLine()
//.AddButton("Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
//.AddLine()
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
@params.Message = "Напишите номер телефона в формате 11 цифр через \"8\" или \"7\" \n";
break;
case 7:
tag = "Личный кабинет - Режим питания";
//SqlCommand editTrack = new SqlCommand("UPDATE Users SET track = @track WHERE chatId = @chatId;", Con);
//editTrack.Parameters.AddWithValue("@chatId", chatId);
//editTrack.Parameters.AddWithValue("@track", 0);
//editTrack.ExecuteNonQuery();
@params.Message = "Выберите желаемый трек оптимизации питания👇🏻";
keyboardBuilder
.AddButton("🟩Оптимизация питания", "selectTrack-1", KeyboardButtonColor.Primary) //З🟩
.AddLine()
.AddButton("🟦Снижение жировой массы", "selectTrack-2", KeyboardButtonColor.Primary) //С🟦
.AddLine()
.AddButton("🟨Увеличение мыш. массы", "selectTrack-3", KeyboardButtonColor.Primary) //Ж🟨
.AddLine()
.AddButton("Персональный режим", "selectTrack-4", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
//keyboardBuilder
// //.AddButton("Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
// //.AddLine()
// //.AddButton("Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
// //.AddLine()
// .AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
break;
case 8:
tag = "Личный кабинет - Вид спорта";
@params.Message = "Вы заниматесь спортом или физкультурой?\n" +
"Выберите на клавиатуре вариант, который наиболее точно описывает Ваш образ жизни.\n\n" +
"👉🏻 Если Вы профессионально занимаетесь спортом или Ваша работа связана с тяжёлым физическим трудом, выберите вариант \"Занимаюсь спортом\"\n" +
"👉🏻 Если Вы не занимаетесь спортом профессионально, но регулярно поддерживаете физическую активность (занятия физкультурой), выберите вариант \"Занимаюсь физкультурой\"\n" +
"👉🏻 Если у Вас сидячая работа или нерегулярная физическая активность (менее одного раза в неделю), выберите вариант \"Ничем не занимаюсь\".\n";
keyboardBuilder
.AddButton("Занимаюсь спортом", "selectActivityKind-1", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Занимаюсь физкультурой", "selectActivityKind-2", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Ничем не занимаюсь", "selectActivityKind-3", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
break;
}
user.tag = tag;
db.SaveChanges();
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectEditDataCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}