<script setup lang="ts">
import LoadIcon from '@/page/system/mailbox/components/LoadIcon.vue'
import { debounce, useAudio, XMessage } from '@/hooks'
import sentenceCollectApi from '@/api/subject/sentenceCollect'

const OSS_URL = `${import.meta.env.VITE_OSS_URL}`
// 搜索
const searchMsg = ref('')

// 列表
const list = ref<anyObj>([])
const page = reactive({
  size: 10,
  current: 1,
  total: 0,
})
const loading = ref(false)
async function getList() {
  const { data: res } = await sentenceCollectApi.getLangSenseCollectList({
    ...page,
    searchInput: searchMsg.value,
  })
  if (res.code === 200) {
    list.value.push(...(res.data.rows || []))
    page.total = res.data.totalRows || 0
  }
}
const scrollBoxRef = ref()
async function handleScroll(event: any) {
  if (list.value.length >= page.total) return
  if (loading.value) return
  if (event.target.scrollTop + event.target.offsetHeight >= scrollBoxRef.value?.offsetHeight - 50) {
    page.current++
    try {
      loading.value = true
      await getList()
    } catch {
      page.current--
    }
    loading.value = false
  }
}

const debounceScroll = debounce(handleScroll, 200, false)

// 当前选中项
const active = ref<anyObj>({})
// 播放音频
let player: anyObj = {}
function playAudio(url: string) {
  player.src = url
  player.play()
}

function handlePlay(item: anyObj) {
  if (!item.filePath && !item.voicePath) return XMessage.error('该句子暂无可播放音频')
  active.value = item
  playAudio(item.filePath || item.voicePath)
}
const debounceHandlePlay = debounce(handlePlay, 500)

const itemBg = computed(() => {
  return (id: any) => {
    if (id === active.value.sentenceId) {
      return `url(${OSS_URL}/urm/sentence_collect_list_item_active_bg.svg),url(${OSS_URL}/urm/sentence_collect_list_right_active_bg.svg)`
    } else {
      return `url(${OSS_URL}/urm/sentence_collect_list_item_bg.svg),url(${OSS_URL}/urm/sentence_collect_list_right_bg.svg)`
    }
  }
})

// 收藏/取消操作
function handleCollect(item: anyObj) {
  if (item.noCollect) {
    item.noCollect = false
    sentenceCollectApi.collectSentence({ sentenceId: [item.sentenceId] })
  } else {
    item.noCollect = true
    sentenceCollectApi.cancelCollectSentence({ sentenceId: [item.sentenceId] })
  }
}
const debounceHandleCollect = debounce(handleCollect, 500)

const pageLoading = ref(false)
const emptyType = ref(1)
// 初始化列表
async function initList(type = false) {
  if (pageLoading.value) return
  pageLoading.value = true
  list.value = []
  active.value = {}
  page.current = 1
  try {
    await getList()
    // emptyText.value = type ? '搜索内容为空哦～' : '还没有收藏句子哦～';
    emptyType.value = type ? 1 : 2
  } catch {
    // emptyText.value = '网络出问题了啦～';
    emptyType.value = 0
  }
  pageLoading.value = false
}

// (() => {
//     // initList();
//     nextTick(() => {
//         player = useAudio({
//             autoplay: false,
//         });
//     });
// })();

onMounted(() => {
  player = useAudio({
    autoplay: false,
  })
})

onActivated(() => {
  searchMsg.value = ''
  player = useAudio({
    autoplay: false,
  })
  initList()
})

onDeactivated(() => {
  player.pause()
})

onUnmounted(() => {
  player.destroy()
})
</script>
<template>
  <div class="sentence-collect">
    <div class="top">
      <BackBar leftText="句子箱" class="backBar" />
    </div>
    <div class="sentence-collect-main">
      <div class="search">
        <div class="search-box">
          <input
            v-model="searchMsg"
            placeholder="请输入你要查的中文或英文"
            @keydown.enter="initList(true)"
          />
          <Icon class="pointer" name="search" width="40" @click="initList"></Icon>
        </div>
      </div>
      <div
        class="sentence-collect-main-list"
        :style="{
          'background-image': `url(${OSS_URL}/urm/sentence_collect_bg.png)`,
        }"
      >
        <div class="sentence-collect-main-list-top"></div>
        <div v-if="list.length" class="list-box">
          <div class="list hidden_scroll" @scroll="debounceScroll">
            <div ref="scrollBoxRef" class="scroll-box">
              <div
                v-for="i in list"
                :key="i.sentenceId"
                :class="[
                  'list-item',
                  'poninter',
                  active.sentenceId === i.sentenceId ? 'active' : '',
                ]"
                :style="{
                  'background-image': itemBg(i.sentenceId),
                }"
                @click="debounceHandlePlay(i)"
              >
                <div class="collect-icon poninter" @click.stop="debounceHandleCollect(i)">
                  <Icon :name="i.noCollect ? `collect_grey` : `collect_yellow`" width="80"></Icon>
                  <div class="text" :data-content="i.noCollect ? `收藏` : `取消收藏`">
                    {{ i.noCollect ? `收藏` : `取消收藏` }}
                  </div>
                </div>
                <div class="content">
                  <div class="content-en">{{ i.content }}</div>
                  <div class="content-zh">{{ i.znDesc }}</div>
                </div>
              </div>
            </div>
            <LoadIcon v-if="loading"></LoadIcon>
          </div>
        </div>
        <Empty
          v-else
          class="empty"
          :type="
            pageLoading ? 'loading' : emptyType ? (emptyType === 1 ? 'search' : 'learn') : 'network'
          "
        ></Empty>
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss">
.sentence-collect {
  @include main_bg;
  height: 100%;
  min-height: 100vh;
  overflow: hidden;
  box-sizing: border-box;
  line-height: 1.5;
  .top {
    position: absolute;
    padding: 3vh 64px 0;
    z-index: 10;
    // margin-bottom: 24px;
  }
  &-main {
    width: 100%;
    height: 100%;
    padding: 2.67vh 64px 2.67vh 64px;
    display: flex;
    // width: 100%;
    // height: 100%;
    display: flex;
    flex-direction: column;
    align-items: flex-end;

    .search {
      // width: 100%;
      height: 8vh;
    }
    .search-box {
      display: flex;
      width: 792px;
      height: 6.67vh;
      flex-shrink: 0;
      background: rgba(0, 0, 0, 0.35);
      border: 0.33vh solid rgba(255, 255, 255, 0.85);
      // filter: drop-shadow(0px 2px 2px rgba(0, 0, 0, 0.25));
      padding: 1.67vh 40px;
      border-radius: 6.67vh;
      margin-bottom: 1.33vh;
      input {
        width: 100%;
        height: 100%;
        background-color: transparent;
        outline: none;
        color: #fff;
        font-family: Arial;
        font-size: 2.33vh;
        font-weight: 700;
        line-height: 1.5; /* 150% */
        &::placeholder {
          color: #ccc;
          font-family: 'Alibaba Health Font 2.0 CN';
          font-size: 2.33vh;
          font-weight: 300;
        }
      }
    }
    &-list {
      position: relative;
      width: 149.15vh;
      height: 86vh;
      max-height: 86.58vh;
      // aspect-ratio: 1802 / 1039;
      background-repeat: no-repeat;
      background-size: 100% 100%;
      background-position: center;
      margin: 0 auto;
      .empty {
        position: relative;
        z-index: 1;
        height: 86.43%;
        :deep(.empty-box) {
          top: 50%;
          transform: translate(-50%, -50%);
        }
      }
      &-top {
        height: 13.57%;
      }
      .list-box {
        position: relative;
        height: 86.43%;
        z-index: 1;
        padding: 3.33vh;
      }
      .list {
        height: 100%;
        .list-item {
          cursor: pointer;
          position: relative;
          box-sizing: border-box;
          width: 100%;
          padding: 1.83vh 24px;
          display: flex;
          align-items: center;
          background-color: #fff;
          border-radius: 2.67vh;
          margin-bottom: 1.33vh;
          background-repeat: no-repeat;
          background-position:
            -6px -6px,
            right 50%;
          background-size:
            40vh 9.42vh,
            19.42vh 22.58vh;
          box-shadow: 0 0.33vh 0.33vh rgba(0, 0, 0, 0.15);
          border: 0.5vh solid transparent;
          &.active {
            border: 0.5vh solid #fff01f;
          }

          .collect-icon {
            width: 6.67vh;
            height: 8vh;
            position: relative;
            .text {
              position: absolute !important;
              left: 50%;
              bottom: 0;
              transform: translate(-50%);
              width: 100px;
              color: #fff;
              text-align: center;
              font-family: $font-special;
              font-size: 1.67vh;
              line-height: 1.5;
              @include font-stroke($font-color, 2px);
            }
          }
          .content {
            margin-left: 48px;
            &-en {
              color: $font-color;
              font-family: Arial;
              font-size: 2.67vh;
              font-style: normal;
              font-weight: 700;
              margin-bottom: 0.67vh;
            }
            &-zh {
              color: $font-color;
              font-family: 'OPPO Sans';
              font-size: 2vh;
              font-style: normal;
              font-weight: 400;
            }
          }
        }
      }
    }
  }
}
</style>
