<script>
  // @ts-nocheck

  import { getAuthInfo, makeAuthHeaderForAxios } from "$lib/auth/Auth";
  import { makePost } from "$lib/tools/requests/requests";
  import { toValidNumberFormat } from "$lib/tools/strings/Strings";
  import { sayError, sayInfo } from "$lib/tools/toaster/Toaster";

  import QRCode from "qrcode";
  import { onMount } from "svelte";

  const orderStatusMap = {
    "1": "Ожидает исполнения",
    "2": "Время заявки истекло",
    "3": "Исполнена",
    "4": "Спор на проверке у администрации",
    "5": "Спор на проверке у трейдера",
    "6": "Спор принят трейдером",
    "7": "Спор отклонён трейдером",
    "8": "Сумма проверяется администрацией",
  };

  export let data;
  let { userData } = data;
  let { token } = data;

  let showFoundedOrderWindow = false;
  let showLoadingFind = false;
  let foundedDisputes = [];
  let selectedDispute;

  let currentDepositSearchPage = 1;
  let maxDepositSearchPages = 1;

  let external_uuidValue = "";
  let uuidValue = "";
  let external_user_idValue = "";
  let searchValue = "";

  async function findDispute() {
    if (searchValue.length < 5 || showLoadingFind) return;

    showLoadingFind = true;
    let sData = {
      searchData: searchValue.trim(),
      page: currentDepositSearchPage,
    };

    const res = await makePost(
      "admin/deposit/search",
      sData,
      makeAuthHeaderForAxios(getAuthInfo()?.a)
    );

    if (res.error) {
      sayError("Заявка не найдена!");
      showLoadingFind = false;
      return;
    }
    console.log(res.data);

    foundedDisputes = res.data.data;
    maxDepositSearchPages = Number(res.data.pages);
    console.log(foundedDisputes);
    // showFoundedOrderWindow = true;
    showLoadingFind = false;
  }

  let showLoadingRollback = false;
  async function rollbackOrder(uuid) {
    showLoadingRollback = true;
    const res = await makePost(
      "admin/rollbackOrder",
      {
        id: uuid,
        summa: selectedDispute["summa"],
      },
      makeAuthHeaderForAxios(getAuthInfo()?.a)
    );
    if (res.error) {
      // console.log(res);
      if (res.status == 401) {
        sayError("Данные авторизации устарели!");
      }
      sayError("Не удалось закрыть заявку!");
      showLoadingRollback = false;
      return;
    }
    sayInfo("Заявка закрыта!");
    showLoadingRollback = false;
    showFoundedOrderWindow = false;
  }

  let showChangeSum = false;
  let newSum = 0;

  // $: if (foundedDispute !== 0) newSum = Number(foundedDispute?.summa);

  let showLoadingChangeSum = false;
  async function changeSum(uuid) {
    showLoadingChangeSum = true;
    const res = await makePost(
      "admin/rollbackOrder",
      {
        id: uuid,
        summa: newSum.toString(),
      },
      makeAuthHeaderForAxios(getAuthInfo()?.a)
    );
    if (res.error) {
      if (res.status == 401) {
        sayError("Данные авторизации устарели!");
      }
      sayError("Не удалось изменить сумму");
      showLoadingChangeSum = false;
      return;
    }
    sayInfo("Сумма успешно изменена!");
    showLoadingChangeSum = false;
    showChangeSum = false;
    showFoundedOrderWindow = false;
  }
  async function changeSumWithoutBalance(uuid) {
    showLoadingChangeSum = true;
    const res = await makePost(
      "admin/rollbackOrderWithoutBalance",
      {
        id: uuid,
        summa: newSum.toString(),
      },
      makeAuthHeaderForAxios(getAuthInfo()?.a)
    );
    if (res.error) {
      if (res.status == 401) {
        sayError("Данные авторизации устарели!");
      }
      sayError("Не удалось изменить сумму");
      showLoadingChangeSum = false;
      return;
    }
    sayInfo("Сумма успешно изменена!");
    showLoadingChangeSum = false;
    showChangeSum = false;
    showFoundedOrderWindow = false;
  }

  let showLoadingSendCallback = false;
  async function sendCallbackToServer(uuid) {
    if (showLoadingSendCallback) return;
    showLoadingSendCallback = true;
    const res = await makePost(
      "admin/deposit/sendCallback",
      {
        uuid,
      },
      makeAuthHeaderForAxios(getAuthInfo()?.a)
    );
    if (res.error) {
      if (res.status == 401) {
        sayError("Данные авторизации устарели!");
      }
      sayError("Не удалось отправить коллбэк");
      showLoadingSendCallback = false;
      return;
    }
    sayInfo("Коллбэк отправлен!");
    showLoadingSendCallback = false;
    // showFoundedOrderWindow = false;
  }

  let showChangeTeamWindow = false;
  let newTokenValue = "";
  let changingTeam = false;
  async function changeToken(uuid, newValue = "") {
    if (newValue.length < 5 || changingTeam) return;
    changingTeam = true;
    const res = await makePost(
      "admin/deposit/change/token",
      {
        deposit_id: uuid,
        token: newValue,
      },
      makeAuthHeaderForAxios(getAuthInfo()?.a)
    );
    if (res.error) {
      sayError("Не удалось сменить команду");
      changingTeam = false;
      return;
    }
    sayInfo("Команда изменена");
    changingTeam = false;
    showChangeTeamWindow = false;
  }

  let img64 = "";
  let qrCode = false;

  $: if (selectedDispute && selectedDispute["cardnumber"].length > 16) {
    qrCode = true;
    QRCode.toDataURL(selectedDispute["cardnumber"], {
      type: "image/jpeg",
    }).then((url) => {
      img64 = url;
    });
  } else {
    qrCode = false;
  }
</script>

<div class="w-full flex flex-col gap-8">
  <div class="flex gap-4">
    <div class="bg-accent rounded-[4px] w-[10px] h-full"></div>
    <h1 class="text-2xl font-semibold">Поиск по депозитам</h1>
  </div>
  <div class="w-full flex flex-col p-4 rounded-box bg-base-300">
    <input
      bind:value={searchValue}
      placeholder="UUID, External UUID или External User ID"
      type="text"
      class="input input-bordered"
    />

    <button
      on:click={() => {
        maxDepositSearchPages = 1;
        currentDepositSearchPage = 1;
        findDispute();
      }}
      class="btn btn-outline mt-2"
    >
      {#if showLoadingFind}
        <span class="loading loading-dots loading-xs"></span>
      {:else}
        {"Найти депозиты"}
      {/if}
    </button>
  </div>
  <div class="w-full flex flex-col p-4 rounded-box bg-base-300 overflow-x-auto">
    <div class="flex w-full justify-center items-center">
      <button
        class="btn"
        on:click={() => {
          if (currentDepositSearchPage <= 1) return;
          currentDepositSearchPage -= 1;
          findDispute();
        }}
      >
        &lt;
      </button>
      <div class="btn cursor-default hover:cursor-default">
        {"Страница"}
        {currentDepositSearchPage}
      </div>
      <button
        class="btn"
        on:click={() => {
          if (currentDepositSearchPage >= maxDepositSearchPages) return;
          currentDepositSearchPage += 1;
          findDispute();
        }}
      >
        &gt;
      </button>
    </div>
    <p class="opacity-50 text-sm self-center mt-1">
      {"Всего страниц:"}
      {maxDepositSearchPages}
    </p>
    {#if showLoadingFind}
      <span class="loading loading-lg self-center mt-4"></span>
    {:else}
      <table class="w-full mt-4">
        <thead>
          <th></th>
          <th class="text-left px-2">{"Статус"}</th>
          <th class="text-left px-2">{"Сумма"}</th>
          <th class="text-left px-2">{"Банк"}</th>
          <th class="text-left px-2">{"Время создания"}</th>
          <th class="text-left px-2">{"Трейдер"}</th>
        </thead>
        <tbody>
          {#each foundedDisputes as dep}
            <tr class="border-b-2 border-b-base-200">
              <td
                ><button
                  class="btn btn-info"
                  on:click={() => {
                    selectedDispute = dep;
                    console.log(selectedDispute, "11231");

                    showFoundedOrderWindow = true;
                  }}
                >
                  <div
                    class="bg-info border-2 outline-white rounded-full w-5 h-5 flex-shrink-0 flex justify-center items-center text-white"
                  >
                    i
                  </div>
                </button></td
              >
              <td class="px-4 py-2">{orderStatusMap[dep["status"]]}</td>
              <td class="px-4">{Number(dep["summa"])} {dep["currency_code"]}</td
              >
              <td class="px-4">{dep["bank_name"]}</td>
              <td class="px-4">{dep["creationtime"]}</td>
              <td class="px-4">{dep["trader_name"]} {dep["surname"]}</td>
            </tr>
          {/each}
        </tbody>
      </table>
    {/if}
  </div>
</div>

{#if showFoundedOrderWindow}
  <div
    class="fixed inset-0 z-[1000] bg-black bg-opacity-50 flex justify-center items-center"
  >
    <div
      class="flex flex-col p-4 bg-base-100 rounded-md overflow-y-auto max-h-[90%]"
    >
      <p class="text-sm">UUID</p>
      <p class="font-semibold">{selectedDispute["uuid"]}</p>
      <!-- <p class="text-sm mt-3">ID заявки</p>
      <p class="font-semibold">{foundedDispute["id"]}</p> -->
      <p class="text-sm mt-3">ID клиента</p>
      <p class="font-semibold">{selectedDispute["external_user_id"]}</p>
      <p class="text-sm mt-3">External ID</p>
      <p class="font-semibold">{selectedDispute["external_uuid"]}</p>
      <p class="text-sm mt-3">Статус</p>
      <p class="">{orderStatusMap[selectedDispute["status"]]}</p>
      {#if selectedDispute["token"] !== ""}
        <p class="text-sm mt-3">Токен трейдера</p>
        <p>{selectedDispute["token"]}</p>
      {/if}
      {#if selectedDispute["trader_name"] !== ""}
        <p class="text-sm mt-3">Трейдер</p>
        <p>{selectedDispute["trader_name"]} {selectedDispute["surname"]}</p>
      {/if}
      {#if selectedDispute["close_reason"] !== ""}
        <p class="text-sm mt-3">Причина отклонения</p>
        <p>{selectedDispute["close_reason"]}</p>
      {/if}
      <p class="text-sm mt-3">Сумма</p>
      <p>
        {toValidNumberFormat(selectedDispute["summa"])}
        {selectedDispute["currency_code"]}
        <!-- ({(
          Number(foundedDispute["summa"]) / Number(foundedDispute["rate"])
        ).toFixed(2)} USDT) -->
      </p>
      <!-- <p class="text-sm mt-3">Курс</p>
      <p>{foundedDispute["rate"]} {foundedDispute["currency_code"]}</p> -->
      {#if selectedDispute["bank_name"] !== ""}
        <p class="text-sm mt-3">Банк</p>
        <p>{selectedDispute["bank_name"]}</p>
      {/if}
      {#if selectedDispute["name"] !== ""}
        <p class="text-sm mt-3">Владелец</p>
        <p>{selectedDispute["name"]}</p>
      {/if}
      {#if selectedDispute["cardnumber"] !== ""}
        {#if selectedDispute["cardnumber"].length <= 16}
          <p class="text-sm mt-3">Карта</p>
          <p>{selectedDispute["cardnumber"]}</p>
        {:else}
          <p class="text-sm mt-3">QR</p>
          <img
            src={img64}
            alt="qr"
            download={`QR-${new Date().toLocaleString()}.jpeg`}
            style="width: 200px; height: 200px;"
          />
        {/if}
      {/if}
      {#if selectedDispute["phone"] !== ""}
        <p class="text-sm mt-3">Телефон</p>
        <p>{selectedDispute["phone"]}</p>
      {/if}
      <p class="text-sm mt-3">Время создания</p>
      <p>{selectedDispute["creationtime"]}</p>
      {#if selectedDispute["closetime"] && selectedDispute["closetime"] !== ""}
        <p class="text-sm mt-3">Время закрытия</p>
        <p>{selectedDispute["closetime"]}</p>
      {/if}
      <!-- <p>{foundedDispute["closetime"]}</p> -->
      <button
        on:click={() => {
          rollbackOrder(selectedDispute["uuid"]);
        }}
        class="btn btn-outline btn-info mt-4"
      >
        {#if showLoadingRollback}
          <span class="loading loading-dots loading-xs"></span>
        {:else}
          {"Закрыть заявку ручками"}
        {/if}</button
      >
      <button
        on:click={() => {
          showChangeSum = true;
        }}
        class="btn btn-info btn-outline mt-1">Изменить сумму</button
      >
      <button
        on:click={() => {
          sendCallbackToServer(selectedDispute["uuid"]);
        }}
        class="btn btn-warning btn-outline mt-1"
      >
        {#if showLoadingSendCallback}
          <span class="loading loading-xs"></span>
        {:else}
          {"Отправить коллбэк"}
        {/if}
      </button>
      <!-- <p class="mt-2">Новый токен</p>
      <input
        type="text"
        class="input input-sm w-full input-white input-bordered"
        bind:value={newTokenValue}
      /> -->
      <button
        class="btn btn-outline mt-1 btn-info"
        on:click={() => {
          showChangeTeamWindow = true;
        }}
      >
        {#if changingTeam}
          {"Ожидайте..."}
        {:else}
          {"Сменить команду"}
        {/if}
      </button>
      <button
        on:click={() => {
          showFoundedOrderWindow = false;
        }}
        class="btn btn-outline mt-4">Закрыть окно</button
      >
    </div>
  </div>
{/if}

{#if showChangeSum}
  <div
    class="fixed inset-0 z-[1001] bg-black bg-opacity-50 flex justify-center items-center"
  >
    <div class="flex flex-col p-4 bg-base-100 rounded-md gap-1">
      <p>Укажите новую сумму ({selectedDispute["currency_code"]})</p>
      <input
        bind:value={newSum}
        type="number"
        class="input input-bordered min-w-[320px]"
      />
      <button
        on:click={() => {
          changeSum(selectedDispute["uuid"]);
        }}
        class="btn btn-outline btn-info"
      >
        {#if showLoadingChangeSum}
          <span class="loading loading-dots loading-xs"></span>
        {:else}
          {"Изменить сумму ручками"}
        {/if}
      </button>
      <button
        on:click={() => {
          changeSumWithoutBalance(selectedDispute["uuid"]);
        }}
        class="btn btn-outline btn-info"
      >
        {#if showLoadingChangeSum}
          <span class="loading loading-dots loading-xs"></span>
        {:else}
          {"Изменить сумму ручками (без списания баланса)"}
        {/if}
      </button>
      <button
        on:click={() => {
          showChangeSum = false;
        }}
        class="btn btn-outline">Закрыть</button
      >
    </div>
  </div>
{/if}

{#if showChangeTeamWindow}
  <div
    class="fixed inset-0 z-[1001] bg-black bg-opacity-50 flex justify-center items-center"
  >
    <div class="flex flex-col p-4 bg-base-100 rounded-md gap-1">
      <p>Укажите новый токен</p>
      <input
        bind:value={newTokenValue}
        type="text"
        class="input input-bordered min-w-[320px]"
      />
      <button
        on:click={() => {
          changeToken(selectedDispute["uuid"], newTokenValue);
        }}
        class="btn btn-outline btn-info"
      >
        {#if changingTeam}
          <span class="loading loading-dots loading-xs"></span>
        {:else}
          {"Изменить"}
        {/if}
      </button>
      <button
        on:click={() => {
          showChangeTeamWindow = false;
        }}
        class="btn btn-outline">Закрыть</button
      >
    </div>
  </div>
{/if}
