let options = {
    message: "",
    diapason_akk: [],
    posting_mode: 0,
    request_spambot: 0,
    request_leavechat: 0,
    sleep_send_sms: [2,8],
    answer_sleep: [2,8],
    answer_sleep_start: [4,8],
    posting_sleep_start: [30,60],
    file_list: [],
    messages_for_answer: "",
    answer_status: "0"
  };

  
  $('#start_posting_massages').on('click', async function () {
  
    // Получение сообщения
    options.message = $('#text_textarea').val();
  
    if ($('#posting_mode').is(':checked')){
        options.posting_mode = 1;
    } else {
        options.posting_mode = 0;
    }

    if ($('#request_spambot').is(':checked')){
      options.request_spambot = 1;
    } else {
      options.request_spambot = 0;
    }

    if ($('#request_leavechat').is(':checked')){
      options.request_leavechat = 1;
    } else {
      options.request_leavechat = 0;
    }

    options.sleep_send_sms[0] = Number($('#sleep_send_sms_from').val());
    options.sleep_send_sms[1] = Number($('#sleep_send_sms_before').val());
    options.posting_sleep_start[0] = Number($('#posting_sleep_start_from').val());
    options.posting_sleep_start[1] = Number($('#posting_sleep_start_before').val());

    // Получение данных из textarea - @ЮЗЕРНЕЙМЫ
    options.file_list = [];
    let lines2 = $('#add_file_textarea').val().split(/\n/);
    for (var i = 0; i < lines2.length; i++) {
      if (/\S/.test(lines2[i])) {
        options.file_list.push($.trim(lines2[i]));
      }
    }
  
    clear_log = 0
    let json = JSON.stringify(options);
    let this_class = $(this).hasClass("btn-success");
    if (this_class == true) {
      if(options.answer_status == '1'){
        let this_class = $('#start_answer').hasClass("d-none");
        if(this_class == false){
          error('Сначала завершите автоответчик!')
          return
        }
        $('#start_answer').removeClass('d-none');
      }
      $("#num_send_user").text(0);
      $(this).removeClass('btn-success');
      $(this).addClass('btn-danger');
      $(this).text("Остановить рассылку");
      $('#log li').remove();
      console.log(json);
      await eel.auto_posting_v524(json)();
    } else {
      $(this).removeClass('btn-danger');
      $(this).addClass('btn-success');
      $(this).text("Запустить рассылку");
      if(options.answer_status == '1'){
        eel.stopped('spam_answer_event')
      } else { eel.stopped('spam') } //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ТУТ КНОПКА ОТМЕНИТЬ
    }
  
  });
  
  eel.expose(set_finished_btn);
  function set_finished_btn(){
      $('#start_posting_massages').removeClass('btn-danger');
      $('#start_posting_massages').addClass('btn-success');
      $('#start_posting_massages').text("Запустить рассылку");
  }

  $('#start_answer').on('click', async function () {
    $('#start_answer').addClass('d-none');
    eel.stopped('answer_sent')
  })
  
  window.addEventListener("beforeunload", function (e) {        
    eel.stopped('posting_sent')
  });

  eel.expose(success_count);
  function success_count(num) {
    $("#num_send_user").text(num); 
  }
  
  $('#set_sleep_sending').on('click', async function () {
    $('#set_sleep_modal').modal('hide');
  });
  
  $('#select_accounts').on('click', async function () {
    options.diapason_akk = [];
    load_accounts();
  });

  $('#save_messages').on('click', async function () {
    $("#text_textarea").val('save_messages@1');
  });

  $('#save_messages_album').on('click', async function () {
    $("#text_textarea").val('save_messages@album');
  });
  
  $('#repost_channel').on('click', async function () {
    $("#text_textarea").val('repost@https://t.me/notcoin/733');
  });

  $('#repost_hidden_channel').on('click', async function () {
    $("#text_textarea").val('repost_hidden@https://t.me/notcoin/733');
  });

  $('#sendbot_channel').on('click', async function () {
    $("#text_textarea").val('sendbot@PostBot@63cdb7581c7ae');
  });

  $('#save_massage').on('click', async function () {
    options.sleep_send_sms[0] = Number($('#sleep_send_sms_from').val());
    options.sleep_send_sms[1] = Number($('#sleep_send_sms_before').val());
    options.posting_sleep_start[0] = Number($('#posting_sleep_start_from').val());
    options.posting_sleep_start[1] = Number($('#posting_sleep_start_before').val());
    options.answer_sleep_start[0] = Number($('#answer_sleep_start_from').val());
    options.answer_sleep_start[1] = Number($('#answer_sleep_start_before').val());
    options.answer_sleep[0] = Number($('#answer_sleep_from').val());
    options.answer_sleep[1] = Number($('#answer_sleep_before').val());
    options.message = $('#text_textarea').val();
    if ($('#posting_mode').is(':checked')){ options.posting_mode = 1;} else {options.posting_mode = 0;}
    if ($('#request_spambot').is(':checked')){ options.request_spambot = 1;} else {options.request_spambot = 0;}
    if ($('#request_leavechat').is(':checked')){ options.request_leavechat = 1;} else {options.request_leavechat = 0;}

    localStorage.setItem('text_send_autoposting_two', JSON.stringify(options));
  });
  
  $('#get_save_massage').on('click', async function () {
    let options = JSON.parse(localStorage.getItem('text_send_autoposting_two'));
    console.log(options)
    options.messages_for_answer = options.messages_for_answer;
    options.answer_status = options.answer_status;
    $('#text_textarea').val(options.message)
    $('#sleep_send_sms_from').val(options.sleep_send_sms[0])
    $('#sleep_send_sms_before').val(options.sleep_send_sms[1])
    $('#posting_sleep_start_from').val(options.posting_sleep_start[0])
    $('#posting_sleep_start_before').val(options.posting_sleep_start[1])
    $('#answer_sleep_start_from').val(options.answer_sleep_start[0])
    $('#answer_sleep_start_before').val(options.answer_sleep_start[1])
    $('#answer_sleep_from').val(options.answer_sleep[0])
    $('#answer_sleep_before').val(options.answer_sleep[1])
    // ==================
    if(options.answer_status == 1)
      $("#alerts_color").prop( 'checked', true )
      $('#alerts_color').removeClass('alert-primary');
      $('#alerts_color').addClass('alert-success');
      $('#answering_check_text').text("Автоответчик активирован!");
      $('#sms_answer_check').removeClass('d-none');
      $('#answering_log_block').removeClass('d-none');
      $('#log_div').css('height', '250px');
      $("#answering_check").prop( 'checked', true )
    // ==================
    if(options.posting_mode == 1){ $("#posting_mode").prop('checked', true);}  // checked
    else { $("#posting_mode").prop('checked', false);}  // unchecked
    if(options.request_spambot == 1){ $("#request_spambot").prop('checked', true);}  // checked
    else { $("#request_spambot").prop('checked', false);}  // unchecked
    if(options.request_leavechat == 1){ $("#request_leavechat").prop('checked', true);}  // checked
    else { $("#request_leavechat").prop('checked', false);}  // unchecked
  });

  // ОБРАБОТЧИК НАЖАТИЯ КАРТИНКА
  $('#add_img').on('click', async function () {
    let img_res = await eel.get_image_for_message()();//тут нужно вставить путь на картинку которую выбрал пользователь
    console.log(img_res)
    if (img_res !== "" && img_res !== 0 && img_res != false) {// Демонстрация изображения если есть
      $('#myimage').attr('src', img_res[0]);
      $.each(img_res, function(index, value){
        let text = $("#add_file_textarea").val();
        $('#add_file_textarea').val(text + 'web/' + value + '\n')
      })
      $("#add_file_form").removeClass('d-none');
      // $('#add_file_textarea').val(text + 'web/' + img_res + '\n')
    }
  });

  $('#select_accounts_apply').on('click', async function () {
    console.log("Нажали")
    $('#select_accounts_modal').modal('hide');
    let from = 1;
    let before = $('#table_users >tbody >tr').length;
    //Запускаем цикл по всей таблице
    for (let i = from; i <= before; i++) {
      let type_bg = $('#table_users tr').eq(i).attr("class");
      if (type_bg == "bg_selected") {
        //Получаем номер телефона
        phone_user = $('#table_users tr').eq(i).children('#phone').html();
        options.diapason_akk.push(phone_user);
      }
    }
    $("#account_num").removeClass('d-none');
    $("#account_num").text(options.diapason_akk.length);
  });
  
  eel.expose(counter_sess);
  function counter_sess(num) {
    $("#counter_sess").text(num);
  }
  
  let clear_log = 0
  eel.expose(log);
  function log(log_line) {
    if (clear_log == 250){
      $('#log li:first').remove();
    } else {clear_log = clear_log + 1}
    $('#log').append('<li>' + log_line + '</li>');
    $('#log_div').scrollTop($('#log_div')[0].scrollHeight);
  }

  eel.expose(reload_python);
  function reload_python() {
    window.location.reload();
  }

  
  let answer_num = 2;
$('#answer_sms_add').on('click', async function () {
  multi_dialog = await eel.paid_func('multi_dialog')();
  if(multi_dialog == false){
    error('Модуль не активирован!')
    return
  }
  $('#answer_sms').append('<label class="mt-2 answer_sms_cl">Ответ №' + answer_num++ + '</label>');
  $('#answer_sms').append('<textarea class="form-control answer_sms_text" rows="7">' + '</textarea>');
  $('#answer_sms').append('<input class="input-sm form-control mt-1 answer_sms_key" type="text" placeholder="Ключевое слово для ответа">' + '</input>');
  // <input id="key_answering" type="text" class="input-sm form-control mt-1" placeholder="Ключевое слово"></input>

  $('#answer_sms_dell').removeClass('d-none');
});

function answer_text(){
  let from = 0
  let before  = $('.answer_sms_cl').length
  let mass_text = []
  mass_text.push([$('#text_textarea_answering').val(),$('#key_answering').val()]);
  for (let i = from; i < before; i++) {
    let text = $('.answer_sms_text').eq(i).val();
    let key = $('.answer_sms_key').eq(i).val();
    console.log(text, key)
    mass_text.push([text, key]);
  }
  console.log(before)
  return mass_text
}


$('#answer_sms_dell').on('click', async function () {
  let count = $("#answer_sms label").last().text().split('№')[1]
  answer_num = Number(count)
  $("#answer_sms label").last().remove();
  $("#answer_sms textarea").last().remove();
  $("#answer_sms input").last().remove();
  if(answer_num == 2){
    $('#answer_sms_dell').addClass('d-none');
  }
});

// Автоответчик
$('#answering_check').on('click', function () {
  let this_class = $('#alerts_color').hasClass("alert-success");
  if (this_class == true) {
    $('#alerts_color').removeClass('alert-success');
    $('#alerts_color').addClass('alert-primary');
    $('#answering_check_text').text("Включить автоответчик во время рассылки?");
    $('#sms_answer_check').addClass('d-none');
    options.answer_status = '0';
    $('#answering_log_block').addClass('d-none');
    $('#log_div').css('height', '397px');
    $('#start_answer').addClass('d-none');
  } else {
    $('#alerts_color').removeClass('alert-primary');
    $('#alerts_color').addClass('alert-success');
    $('#answering_check_text').text("Автоответчик активирован!");
    $('#write_text_answering').modal('show');
    $('#sms_answer_check').removeClass('d-none');
    options.answer_status = '1';
    $('#answering_log_block').removeClass('d-none');
    $('#log_div').css('height', '250px');
  }
});
$('#sms_answer_check').on('click', function () {
  $('#write_text_answering').modal('show');
});
$('#get_text_answering').on('click', function () { 
  // options.messages_for_answer = $('#text_textarea_answering').val();
  options.messages_for_answer = answer_text()
  $('#write_text_answering').modal('hide');
  console.log(options.messages_for_answer);
});
eel.expose(log_answer);
function log_answer(log_line) {
  $('#answering_log').append('<li>' + log_line + '</li>');
  $('#answering_log_div').scrollTop($('#answering_log_div')[0].scrollHeight);
}


$('#download_leavechat').on('click', function () {
  var link = document.createElement('a');
  link.setAttribute('href', '/uploads/chat_write_forbidden.txt');
  link.setAttribute('download', 'chat_write_forbidden.txt');
  link.click();
  return false;
});