<template>
  <div class="header-menu-search" id="header-drawer">
    <t-input
      v-show="!chooseSearchTwo"
      class="header-search"
      v-model="inputPlaceholder"
      placeholder=""
      @focus="showSelect"
    >
      <template #prefix-icon>
        <div class="input2-icon">
          <SearchSvg></SearchSvg>
        </div>
        <div class="circular-box">{{ $t('Search.search') }}</div>
      </template>
    </t-input>
    <ClientOnly>
      <t-drawer
        :footer="false"
        :zIndex="2000"
        attach="#header-drawer"
        v-model:visible="selectDialogVisible"
        :on-click-overlay="() => (visible = false)"
        placement="top"
        @click-cancel="visible = false"
      >
        <template #header>
          <t-input
            class="header-search2"
            v-show="chooseSearchTwo"
            :autofocus="autofocus"
            v-model="keyword"
            @change="doSeach"
            placeholder="Search name or paste address"
          >
            <template #prefix-icon>
              <div class="input2-icon">
                <SearchSvg2></SearchSvg2>
              </div>
            </template>
          </t-input>
          <t-tabs :default-value="1">
            <t-tab-panel :value="1" :label="$t('tokenInfo.TopSearch')">
              <div class="table-box">
                <div
                  id="search-token-list"
                  class="total-token-info-fa narrow-scrollbar"
                >
                  <div v-if="resultList.length > 0">
                    <div
                      class="total-token-info"
                      v-for="item in resultList"
                      :key="item"
                      @click="goDetail(item)"
                    >
                      <div class="header-pro"></div>
                      <div class="token-information">
                        <div class="token-name">
                          <span>Name: </span>
                          <span>&nbsp;{{ item.name }}</span>
                          <span>/{{ item.pool }}</span>
                          <span>&nbsp;-&nbsp;{{ item.symbol }}</span>
                          <div
                            class="collection-box"
                            @click.stop="collectData(item)"
                          >
                            <star-filled-icon
                              size="22px"
                              v-if="item.isStar"
                              class="filled-star"
                            />
                            <star-icon v-else size="22px"></star-icon>
                          </div>
                        </div>
                        <div class="price-and-time">
                          <div class="token">
                            <span>Price: </span>
                            <span>&nbsp;{{ item.up }}</span>
                          </div>
                          <div class="token not_first">
                            <span>24H Price Change: </span>
                            <span :style="{ color: monitor(item.Newr24h) }">{{
                              item.Newr24h
                            }}</span>
                          </div>
                          <div class="token not_first">
                            <span>Holders: </span>
                            <span>&nbsp;{{ item.holders }}</span>
                          </div>
                        </div>
                        <div class="price-and-time">
                          <div class="token">
                            <span>Tx: </span>
                            <span>&nbsp;{{ item.tx }}</span>
                          </div>
                          <div class="token not_first">
                            <span>Pool: </span>
                            <span>&nbsp;{{ item.filterPool }}</span>
                          </div>
                          <div class="token not_first">
                            <span>Token: </span>
                            <span>&nbsp;{{ item.filterToken }}</span>
                          </div>
                        </div>
                      </div>
                      <div class="right-btns">
                        <JumpOther
                          :tb="item.tb_name"
                          type="detail"
                          content="K Line"
                        >
                          <template #svg>
                            <KLink class="k-link"></KLink> </template
                        ></JumpOther>
                        <JumpOther
                          :tb="item.tb_name"
                          type="analysis"
                          content="analysis"
                        >
                          <template #svg>
                            <analysisSvg class="to-analysis"></analysisSvg>
                          </template>
                        </JumpOther>
                      </div>
                    </div>
                  </div>
                  <div v-else-if="isLoading" class="loading-center2">
                    <t-loading
                      :text="$t('Search.Loading')"
                      size="small"
                    ></t-loading>
                  </div>
                  <TableEmpty v-else top="150px"></TableEmpty>
                </div>
                <div v-show="loadingMore" class="loading-center">
                  <t-loading
                    :text="$t('Search.Loading')"
                    size="small"
                  ></t-loading>
                </div>
              </div>
            </t-tab-panel>
          </t-tabs>
        </template>
      </t-drawer>
    </ClientOnly>
  </div>
</template>

<script setup lang="ts">
import request from '@/utils/request';
import {
  parseCoinAmount,
  parsePercent,
  RemoveSpaces,
  debounce,
} from '@/utils/tool';
import SearchSvg from '/public/images/svg/header/searchIcon.svg';
import SearchSvg2 from '/public/images/svg/header/searchIconTwo.svg';
import { StarIcon, StarFilledIcon } from 'tdesign-icons-vue-next';
import * as Cache from '@/utils/cache';
import { WebS } from '@/utils/TokenTrans';
import JumpOther from '/views/token/JumpOther.vue';
import KLink from '/public/images/svg/table/k_link.svg';
import analysisSvg from '/public/images/svg/table/media.svg';
import { chain_options } from '@/constants/UnifiedManagementChain';
const keyword = ref('');
const inputPlaceholder = ref('');
const visible = ref(false);
const selectDialogVisible = ref(false);
const autofocus = ref(false);
// 搜索结果是否还有其他页数
const hasMorePages = ref(true);
// 默认页数
const defalutPage = ref(1);
// 第二个输入框的显示隐藏
const chooseSearchTwo = ref(false);
// 加载更多样式显示隐藏
const loadingMore = ref(false);

//
watch(
  () => selectDialogVisible.value,
  (v) => {
    if (!v) {
      chooseSearchTwo.value = false;
    }
  }
);
// 输入框聚焦
watch(
  () => selectDialogVisible.value,
  (v) => {
    if (v) {
      setTimeout(() => {
        autofocus.value = true;
      }, 500);
    } else {
      autofocus.value = false;
    }
  }
);
// 监听正负改变颜色
const monitor = (item) => {
  if (item[0] === '-') {
    return '#f85260';
  } else {
    return '#23ab94';
  }
};

const showSelect = () => {
  selectDialogVisible.value = true;
  // 显示第二个搜索框
  chooseSearchTwo.value = true;
};
const current = ref('all');
const collectData = (item) => {
  if (item.isStar) {
    Cache.deleteCollection(item.tb_name);
    item.isStar = false;
  } else {
    Cache.setCollection({
      hash: item.tb_name,
      symbol: item.symbol,
    });
    item.isStar = true;
  }
};
const resultList = ref([]);
const isLoading = ref(false);
const darg = () => {
  let dom = document.getElementById('search-token-list');
  if (dom !== null) {
    dom.addEventListener('scroll', () => {
      let domHeight = dom.scrollHeight;
      let domTop = dom.scrollTop;
      let cliheight = dom.clientHeight;
      if (
        domHeight - cliheight - domTop <= 20 &&
        resultList.value.length > 19
      ) {
        // 滚动到底部
        if (hasMorePages.value) {
          // 如果当前加载更多已经执行，return
          if (loadingMore.value) {
            return;
          }
          loadingMore.value = true;
          getTokenList();
        }
      }
    });
  }
};

// 滚动加载
onMounted(() => {
  nextTick(() => {
    darg();
  });
});
const getTokenList = () => {
  if (keyword.value.trim() === '') {
    return;
  }
  if (!loadingMore.value) {
    resultList.value = [];
    isLoading.value = true;
    defalutPage.value = 1;
  }
  request
    .get(`/search`, {
      params: {
        q: WebS(RemoveSpaces(keyword.value)),
        page: defalutPage.value,
        lable: current.value,
      },
    })
    .then((res: any) => {
      if (!(res instanceof Array)) {
        if (!loadingMore.value) {
          if (res.list.length) {
            resultList.value = [];
            let list = resultFilter(res.list);
            resultList.value = list;
          } else {
            resultList.value = [];
          }
          // 否则push
        } else {
          // 遍历新得到的数据
          if (res.list.length) {
            let list = resultFilter(res.list);
            resultList.value = resultList.value.concat(list);
          }
        }
        // 是否还有数据
        if (parseInt(res.has_more_pages)) {
          hasMorePages.value = true;
        } else {
          hasMorePages.value = false;
        }
        if (hasMorePages.value === true) {
          defalutPage.value += 1;
        }
      }
      isLoading.value = false;
      // 隐藏加载更多
      loadingMore.value = false;
    })
    .catch((e) => {
      isLoading.value = false;
      console.log(e);
    });
};
// 搜索结果过滤
const resultFilter = (list) => {
  let newList = list;
  newList.forEach((item, index) => {
    if (item.name.length >= 20) {
      item.name = item.name.substring(0, 20) + '...';
    }
    item.up = '$' + parseCoinAmount(item.up);

    item.Newr24h = parsePercent(item.r24h);
    item.r24h = item.r24h.toFixed(3);
    // 将token转换为常用样式
    item.filterToken =
      item.token.substring(0, 6) +
      '...' +
      item.token.substring(item.token.length - 4);
    item.filterPool =
      item.tb_name.substring(0, 6) +
      '...' +
      item.tb_name.substring(item.tb_name.length - 4);
    if (item.Newr24h[0] !== '-') {
      item.Newr24h = '+' + item.Newr24h;
    }
    // 判断当前token是否已收藏
    let res = localStorage.getItem('COLLECTION_LIST');
    if (!res) {
      item.isStar = false;
    } else {
      JSON.parse(res).forEach((label, index) => {
        if (label.hash === item.tb_name) {
          item.isStar = true;
        }
      });
    }
  });
  return newList;
};
const doSeach = debounce(getTokenList, 500, true);
const goDetail = (row) => {
  // 找到链id对应的路由名称
  let Obj = chain_options.find((item: any) => item.chain_id == row.chain);
  let params: any = {
    tb: row.tb_name,
    path: Obj.name,
  };
};
</script>
<style lang="less" scoped>
@import '@/style/variables.less';
@import '@/style/flex.less';
.header-menu-search {
  display: flex;
  margin-left: 16px;
  .hover-active {
    .t-input__inner {
      background: @bg-color-secondarycontainer;
    }
    .t-icon {
      color: @brand-color !important;
    }
  }
  .circular-box {
    margin: 0 1rem 0 0.6rem;
    color: var(--td-Search-info-color-2);
    font-size: @font-size-s;
  }
  .input2-icon {
    margin-left: 7px;
    width: 1.5rem !important;
    height: 1.5rem !important;
    border-radius: 50%;
    .dja();
    svg {
      stroke: var(--td-Search-info-color-2);
    }
  }
  .header-search {
    margin-left: 20px;
    :deep(.t-input) {
      border: none;
      outline: none;
      box-shadow: none;
      transition: background @anim-duration-base linear;
      background: var(--td-search-back-2);
      border-radius: 8px;
      height: 38px;
      .t-input__inner {
        width: 115px;
        transition: background @anim-duration-base linear;
        border-radius: 16px;
      }
      &:hover {
        background: @bg-color-secondarycontainer;
        .t-input__inner {
          background: @bg-color-secondarycontainer;
        }
      }
    }
  }
  // 2
  :deep(.t-drawer__header) {
    padding: 0 !important;
    flex-direction: column;
  }

  .t-drawer {
    .header-search2 {
      :deep(.t-input) {
        height: 50px;
        border: none;
        outline: none;
        box-shadow: none;
        transition: background @anim-duration-base linear;
        .t-input__inner {
          width: 200px;
          margin-left: 10px;
          transition: background @anim-duration-base linear;
        }
        &:hover {
          background: @bg-color-secondarycontainer;
          .t-input__inner {
            background: @bg-color-secondarycontainer;
          }
        }
      }
    }
    .t-tabs {
      width: 100%;
    }
    :deep(.t-drawer__content-wrapper) {
      margin-top: 64px !important;
      width: 50vw;
      height: calc(100vh - 128px) !important;
      margin-left: 25vw;
      background: @td--Search-drawer-back-color;
      border-radius: 4px;
      .table-box {
        width: 100%;
        .total-token-info-fa {
          overflow: auto;
          height: calc(100vh - 320px);
          background: @td--Search-drawer-back-color;
          .total-token-info {
            position: relative;
            width: 98%;
            min-width: 600px;
            height: 100px;
            font-size: @font-size-base;
            overflow: hidden;
            border: 1px solid @td-Search-box-border-color-2;
            margin: 12px;
            border-radius: 10px;
            background: @td-Search-box-line-back-color;
            box-shadow: 1px 3px 5px @td-Search-shadow-color;
            display: flex;
            .header-pro {
              width: 10%;
              height: 100%;
              .dja();
            }
            .token-information {
              width: 90%;
              height: 100%;
              padding-left: 6px;
              flex-direction: column;
              .dj(space-around);
              .token-name {
                height: 20px;
                width: 70%;
                position: relative;
                :nth-child(1) {
                  color: @td-search-btn-back-1;
                }
                :nth-child(2) {
                  font-weight: bold;
                  overflow: hidden;
                  text-overflow: ellipsis;
                }
                :nth-child(3) {
                  font-weight: bold;
                  color: @td-search-btn-back-1;
                }
                :nth-child(4) {
                  font-weight: bold;
                }
                .collection-box {
                  position: absolute;
                  top: 0;
                  right: 0;
                  width: 20px;
                  height: 20px;
                  margin-top: -5px;
                  .filled-star {
                    color: var(--td-brand-color);
                  }
                }
              }
              .price-and-time {
                font-family: fiveFont !important;
                height: 20px;
                display: flex;
                font-size: @font-size-s;
                .token {
                  :nth-child(1) {
                    color: @td-search-btn-back-1;
                  }
                  :nth-child(2) {
                    font-weight: bold;
                  }
                }
                .not_first {
                  margin-left: 20px;
                }
              }
            }
            .right-btns {
              position: absolute;
              right: 0;
              .dja();
              height: 100%;
              div {
                margin-right: 12px;
              }
            }
            &:hover {
              cursor: pointer;
              border: 1px solid @main-theme-color;
              transition: all 0.5s;
            }
          }
          .loading-center2 {
            text-align: center;
            margin-top: 200px !important;
          }
        }
        .loading-center {
          .dj();
          z-index: 100;
        }
      }
    }
  }
}
</style>
