const managerScheduleTrip = {
  haveObservedScheduleTrip: false,
  haveObservedPreAcceptedTrip: false,
};

function initEventScheduleTrip() {
  const elementProperty = new ElementProperty();

  elementProperty.addEventInElement("#openScheduleTrip", "onclick", () => {
      Route.startClassesInComponent(
          [{component: "#containerListScheduleTrip", class: "active"}],
          () => {
              elementProperty.removeClass("#containerListScheduleTrip", "active");
          }
      );
  });

  viewController.elementProperty.addEventInElement(
      ".go-back-schedule-trip",
      "onclick",
      () => {
          Route.backPage();
      }
  );

  viewController.elementProperty.addEventInElement(
      ".go-back",
      "onclick",
      () => {
          Route.backPage();
      }
  );
}

function checkTripPreAcceptedByDriver() {
  if (managerScheduleTrip.haveObservedPreAcceptedTrip)
      return;

  managerScheduleTrip.haveObservedPreAcceptedTrip = true;

  const tripRepository = new TripRepository();
  tripRepository.checkTripPreAcceptedByDriver(
      Session.get("user").idDriver,
      (result) => {
          const resultData = result[0];

          if (resultData) {
              if (resultData.type === tripRepository.typeRemoved) {
                  Session.delete("preAvailableTripData");
              } else {
                  Session.set("preAvailableTripData", resultData.data);
                  checkPreAvailable();
              }
          }
      }
  );
}

async function createListScheduleTrip() {
  if (managerScheduleTrip.haveObservedScheduleTrip) return;

  if (Session.get("user").tripTypes == null) return;

  managerScheduleTrip.haveObservedScheduleTrip = true;

  const refusedDriverCustomer = await new RefusedDriverController().driversBlockedByCustomer(Session.get("user").idDriver).then((result) => {
        return result.data;
    });

    const dataVerify = await verifyReceivedTripSchedule(); 
  
    Session.get("user").tripTypes.map((item) => {
        const tripRepository = new TripRepository();
        const config = Session.get('configGeneral')
  
        tripRepository.getTripScheduled(
            Session.getValueInSession("cityConfig", "cityId"),
            item.tripTypeId,
            (result) => {
              if (config?.find((el) => el.key === 'enable_sound_initial_app_driver').value === '1' || result.length > 0) {
                  viewController.elementProperty.getElement(
                      "#scheduledTrip",
                      (element) => {
                          element.play();
                      }
                  );
              }
                
                result
                    .map(({data: freight, type}) => {
                        if (type === tripRepository.typeAdded){
                            if (refusedDriverCustomer?.filter((item) => {
                                return item.customerId == freight.customer.idCustomer;
                            }).length > 0) return;
                              
                            viewController.elementProperty.getElement("#scheduledTrip",(element) => {
                                element.play();
                            });

                            const conditionOnReceivedTrip = dataVerify.selectedPaymentFormIds.length === 0 || dataVerify.selectedPaymentFormIds.includes(String(freight?.tripPaymentFormId)) || dataVerify.impositionPaymentFormIds.includes(String(freight?.tripPaymentFormId))
                            if (!conditionOnReceivedTrip) return;

                            addItemTrip(freight) 
                        }
  
                        if (type === tripRepository.typeRemoved) removeItemTrip(freight);
                    })
                    .join("");
  
                viewController.elementProperty.getElement(
                    "#countNewScheduleTrip",
                    (element) => {
                        element.innerHTML = document.querySelectorAll(
                            ".new-scheduled-trip"
                        ).length;
  
                        showScheduledBar();
                    }
                );
  
                initEventDetailFreight();
            }
        );
    });
  }
  
  function showScheduledBar() {
    const userLogged = Session.get("user");
  
    const count = document.querySelectorAll(".new-scheduled-trip").length;
    const countScheduledTripAccepted = document.querySelectorAll(".schedule-trip-accepted").length;
    const countTripBidOffer = document.querySelectorAll(".item-trip-bid-offer").length;
  
    if (((count <= 0 && countScheduledTripAccepted <= 0 && countTripBidOffer <= 0) &&
            ConfigGeneral().get("travel_only_by_offer") == false)
        || userLogged.status === "corrida") {
        viewController.elementProperty.removeClass(".footer-race", "active-schedule");
        viewController.elementProperty.removeClass(".container-qrcode-driver", "active-schedule");
        viewController.elementProperty.addClass(".schedule-bar", "hidden");
    } else {
        viewController.elementProperty.addClass(".footer-race", "active-schedule");
        viewController.elementProperty.addClass(".container-qrcode-driver", "active-schedule")
        viewController.elementProperty.removeClass(".schedule-bar", "hidden");
    }
  
    showModuleOnlyBid();
  }
  
  function removeItemTrip(freight) {
    const element = document.querySelector(
        `.item-schedule-trip[tripReference='${freight.tripReference}']`
    );
  
    if (element != null) element.remove();
  }
  
  async function verifyReceivedTripSchedule () {
    const dataValuesPaymentFormAll = await Promise.all([
        DriverFormOfPaymentController.getAll(),
        DriverFormOfPaymentController.getAllImposition()
    ])
    const {data: listPaymentFormAllChoosed} = dataValuesPaymentFormAll?.[0];
    const {data: listPaymentFormImposition} = dataValuesPaymentFormAll?.[1];

    const selectedPaymentFormIds = listPaymentFormAllChoosed.map(item => String(item?.tripPaymentFormId));
    const impositionPaymentFormIds = listPaymentFormImposition.map(item => String(item?.tripPaymentFormId));

    return {selectedPaymentFormIds, impositionPaymentFormIds}
    }
  
  function addItemTrip(trip) {
      const liquidPrice = Session.get("cityConfig").showNetValueForDriverOnCall
      if ((trip.disableOnPromotion == 0 && liquidPrice == 0) || liquidPrice == 0){
          totalValue = trip.price
      } else {
          if (trip.driverCommissionType === "%"){
              pricePercentage = (trip.price) * (trip.driverCommissionValue/100);
              totalValue = (trip.price) - pricePercentage;
          } else {
              totalValue = (trip.price) - (trip.driverCommissionValue);
          }
      }

    viewController.elementProperty.getElement("#listScheduledTrip", (element) => {
        element.innerHTML += `<li class="item-schedule-trip new-scheduled-trip" tripReference="${
            trip.tripReference
        }">
            ${verifyExistSchedule(trip)}
            <p>
                <span>Origem: </span>
                <span>${trip.origin.address}</span>
            </p>
            <p>
                <span>Destino: </span>
                <span>${trip.destination.name}</span>
            </p>

            <p>
                <span>Distância estimada: </span>
                <span id="estimatedDistanceScheduled-${trip.tripReference}"></span>
            </p>
            <p>
                <span>Valor: </span>
                <span class="value-freight-item">${CityConfig.getTypeCoin()}${Mask.maskMoney(
                    parseFloat(totalValue)
                )}</span>
            </p>
            <div>
                <div>
                    <span>Tipo: </span>
                    <span>${trip.tripType.toUpperCase()}</span>
                </div>
                <div class="content-option-trip">
                    ${checkTypeEventByTrip(trip)}
                    <button type="button" class="btn-schedule-trip-accept" tripReference="${
                        trip.tripReference
                    }">ACEITAR</button>
                </div>
            </div>
        </li>`;
    });

    DirectionController.search(
        `${trip.origin.latitude},${trip.origin.longitude}`,
        `${trip.destination.latitude},${trip.destination.longitude}`
    ).then((result) => {
        viewController.elementProperty.getElement(`#estimatedDistanceScheduled-${trip.tripReference}`, (element) => {
            element.innerHTML = `${(result.data.distance / 1000).toFixed(0)} km/${(result.data.duration / 60).toFixed(0)}min`
        })
    }).catch((error) => {
        return `nao disponivel`;
    })
  }
  
  function checkTypeEventByTrip(trip) {
    switch (trip.tripCallTypeId) {
        case TRIP_FREIGHT: {
            return `<button type="button" class="btn-schedule-freight-detail" trip='${JSON.stringify(
                trip
            )}'>Detalhes do frete</button>`;
        }
        case TRIP_CALL_RIDE: {
            return `<button type="button" class="btn-schedule-riders-chats" trip='${JSON.stringify(
                trip
            )}'>Mensagens</button>
                    <button type="button" class="btn-schedule-riders-detail" trip='${JSON.stringify(
                trip
            )}'>Passageiros</button>`;
        }
        default: {
            return "";
        }
    }
  }
  
  function verifyExistSchedule(freight) {
    if (freight.schedule == null) return ``;
  
    return `<p>
                <span>Data da viagem: </span>
                <span>${new Date(
        freight.schedule.scheduleUTC == null
            ? freight.schedule.schedule
            : freight.schedule.scheduleUTC
    ).toLocaleString()}</span>
            </p>`;
  }
  
  function initEventDetailFreight() {
    viewController.elementProperty.addEventInElement(
        ".btn-schedule-trip-accept",
        "onclick",
        function () {
            SwalCustom.dialogConfirm(
                "Deseja aceitar essa corrida ?",
                "",
                (status) => {
                    if (!status) return;
                    acceptScheduleTrip(this.getAttribute("tripReference"));
                }
            );
        }
    );
  
    viewController.elementProperty.addEventInElement(
        ".btn-schedule-riders-detail",
        "onclick",
        function () {
            const trip = JSON.parse(this.getAttribute("trip"));
            window.plugins.spinnerDialog.show();
            TripController.actionGet(trip.tripReference).then(({data}) => {
                window.plugins.spinnerDialog.hide();
                showListCustomerRide(data);
            });
        }
    );
  
    viewController.elementProperty.addEventInElement(
        ".btn-schedule-riders-chats",
        "onclick",
        function () {
            const trip = JSON.parse(this.getAttribute("trip"));
            viewController.addParams("multiple-chat", trip);
            Route.redirectDynamic("Driver", "MultipleChat");
        }
    );
  
    viewController.elementProperty.addEventInElement(
        ".btn-schedule-freight-detail",
        "onclick",
        function () {
            const data = JSON.parse(this.getAttribute("trip"));
            TripController.actionGet(data.tripReference).then((response) => {
                Route.startClassesInComponent(
                    [{component: ".container-detail-freight", class: "active"}],
                    () => {
                        viewController.elementProperty.removeClass(
                            ".container-detail-freight",
                            "active"
                        );
                    }
                );
                showDetailFreight(response.data);
            });
        }
    );
  
    viewController.elementProperty.addEventInElement(
        ".btn-schedule-trip-cancel",
        "onclick",
        function () {
            SwalCustom.dialogConfirm(
                "Deseja cancelar essa corrida ?",
                "",
                (status) => {
                    if (!status) return;
  
                    Route.backPage();
  
                    const userLogged = Session.get("user");
  
                    new DriverController()
                        .cancelTrip({
                            tripReference: this.getAttribute("tripReference"),
                            driverId: userLogged.idDriver,
                            cancellationReasonsId: 4,
                        })
                        .then(({status, message}) => {
                            if (!status)
                                return SwalCustom.messageDialog("", message, undefined, "info");
  
                            SwalCustom.messageDialog("", message, undefined, "success");
                        });
                }
            );
        }
    );
  }
  
  function acceptScheduleTrip(tripReference) {
    DriverController.acceptScheduled(
        tripReference,
        Session.getValueInSession("user", "idDriver")
    ).then(({status, data, message}) => {
        if (!status) return SwalCustom.messageDialog("", message);
  
        SwalCustom.messageDialog(
            "",
            message,
            () => {
                Route.backPage();
            },
            "success"
        );
    });
  }