<script lang="ts" setup>
import { useClipboard } from '@vueuse/core'
import { showToast } from 'vant'
import { fetchDelCollection, fetchQueryCollectionList } from '@/api/answer'
import { AiAnswerProvideKey } from '@/components/AiAnswer/type'

const { copy, isSupported } = useClipboard()

const pageNum = ref(1)
const pageSize = ref(5)
const collectionList = ref<Record<string, any>[]>([])
const collectionListTotal = ref(0)
const loading = ref(false)
const finished = ref(false)
const isEdit = ref(false)
const collectionIdList = ref<string[]>([])

function onLoad() {
  getCollectionList()
}

async function getCollectionList() {
  loading.value = true
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  }
  const res = await fetchQueryCollectionList(params)
  if (res.data) {
    collectionList.value = [...collectionList.value, ...res.data.records]
    collectionListTotal.value = res.data.total
    if (collectionList.value.length >= res.data.total) {
      finished.value = true
      loading.value = false
      return
    }
    pageNum.value++
  }
  loading.value = false
}

const active = ref('')
const showDialog = ref(false)
// collectionId: string
function onClickItem(collectionId: string) {
  if (!isEdit.value) {
    if (active.value === collectionId)
      active.value = ''
    else
      active.value = collectionId
  }
  else {
    const idx = collectionIdList.value.indexOf(collectionId)
    if (idx !== -1)
      collectionIdList.value.splice(idx, 1)
    else
      collectionIdList.value.push(collectionId)
  }
}

function onChoiceAll() {
  // console.log()
  if (collectionIdList.value.length === collectionList.value.length)
    collectionIdList.value = []

  else
    collectionIdList.value = collectionList.value.map(item => item.collectionId)
}

function removeImgTags(input: string): string {
  return input.replace(/<img[^>]*\/>/g, '')
}

function onCopy(item: any) {
  const copyText = `${item.question} \n ${removeImgTags(item.answer.split('♪')[0])}`
  if (!isSupported) {
    showToast('当前浏览器不支持复制')
    return
  }
  copy(copyText)
  showToast('复制成功')
}
const collectionIsEmpty = computed(() => collectionIdList.value.length === 0)

function onCopyAll() {
  if (collectionIsEmpty.value)
    return
  const copyText = collectionList.value.filter(item => collectionIdList.value.includes(item.collectionId)).map(item => `${item.question}\n ${removeImgTags(item.answer.split('♪')[0])}`).join('\n\n')
  if (!isSupported) {
    showToast('当前浏览器不支持复制')
    return
  }
  copy(copyText)
  showToast('复制成功')
}

const isLongPress = ref(false)
let timer: number | null = null
// const longPressDuration = 1000 // 长按的时间，单位是毫秒

// function startLongPress() {
//   if (timer === null) {
//     timer = window.setTimeout(() => {
//       isLongPress.value = true
//       // 在这里处理长按事件
//       active.value = ''
//       isEdit.value = true
//     }, longPressDuration)
//   }
// }

function cancelLongPress() {
  if (timer !== null) {
    clearTimeout(timer)
    timer = null
  }
  if (isLongPress.value)
    isLongPress.value = false
}

async function delCollection() {
  if (collectionIsEmpty.value && isEdit.value)
    return

  const res = await fetchDelCollection(isEdit.value ? collectionIdList.value : [active.value])
  if (res) {
    showDialog.value = false
    showToast('删除成功')
    collectionIdList.value = []
    collectionList.value = []
    active.value = ''
    pageNum.value = 1
    isEdit.value = false
    getCollectionList()
  }
}

provide(AiAnswerProvideKey, {
  animated: false,
})

onMounted(() => {
  getCollectionList()
})
</script>

<template>
  <div class="collection-list-page-wrap">
    <img class="bg" src="@/assets/images/bg@2x.png" alt="">
    <div class="content">
      <div v-show="loading" class="skeleton">
        <div class="item">
          <van-skeleton title :row="6" />
        </div>
        <div class="item">
          <van-skeleton title :row="12" />
        </div>
        <div class="item">
          <van-skeleton title :row="4" />
        </div>
      </div>
      <van-list
        v-if="collectionList.length > 0"
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div
          v-for="(item, index) in collectionList"
          :key="index" class="collection-list-page-item no-select"
          @click="onClickItem(item.collectionId)"
          @touchmove="cancelLongPress"
          @touchcancel="cancelLongPress"
        >
          <div v-if="isEdit" class="check-box-wrap">
            <SvgIcon v-if="!collectionIdList.includes(item.collectionId)" name="noCheckIcon" size="18px" />
            <SvgIcon v-else name="checkIcon" size="18px" />
          </div>
          <div class="inner" :class="{ active: item.collectionId === active }">
            <div class="collection-list-page-item__question">
              <div>
                <SvgIcon name="qIcon" size="16px" />
              </div>
              <span> {{ item.question }}</span>
            </div>
            <div class="collection-list-page-item__answer">
              <div>
                <SvgIcon name="aIcon" size="16px" />
              </div>
              <div class="collection-list-page-item__answer-content">
                <AnswerShower :stream-answer="item.answer" />
                <AttachmentParser :stream-attachment="item.attachmentList" />
              </div>
            </div>
            <div class="collection-list-page-item__time">
              {{ item.collectionTime }}
            </div>
            <div v-show="item.collectionId === active" class="collection-list-page-item__operate">
              <SvgIcon name="delIcon" size="22px" @click.stop="showDialog = true" />
              <span>|</span>
              <SvgIcon name="copyIcon" size="22px" @click.stop="onCopy(item)" />
            </div>
          </div>
        </div>
      </van-list>

      <div v-if="!loading && collectionList.length === 0" class="empty">
        <img src="@/assets/images/no-data.png" alt="">
        <p>暂无收藏记录</p>
      </div>
    </div>

    <div v-if="isEdit" class="operate-bar">
      <div class="top-line" />
      <div class="choice-all" @click="onChoiceAll">
        <SvgIcon v-if="collectionIdList.length !== collectionList.length" name="noCheckIcon" size="20px" />
        <SvgIcon v-else name="checkIcon" size="20px" />
        <span>全选</span>
      </div>
      <div class="btns-wrap">
        <div class="del" :class="{ disabled: collectionIsEmpty }" @click="collectionIdList.length !== 0 ? showDialog = true : null">
          删除
        </div>
        <div class="copy" :class="{ disabled: collectionIsEmpty }" @click="onCopyAll">
          复制
        </div>
      </div>
    </div>

    <van-dialog v-model:show="showDialog" :show-cancel-button="false" :show-confirm-button="false">
      <div class="del-dialog">
        <h3>是否删除选中的收藏记录？</h3>
        <div class="btn-wrap">
          <div @click="delCollection">
            确认删除
          </div>
          <div @click="showDialog = false">
            取消
          </div>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<style lang="scss">
.del-dialog {
  width: 100%;
  height: 154px;
  display: flex;
  align-items: center;
  flex-direction: column;
  h3 {
    font-family:
      PingFangSC,
      PingFang SC;
    font-weight: 600;
    font-size: 16px;
    color: #0e2120;
    line-height: 22px;
    margin-top: 32px;
  }
  .btn-wrap {
    display: flex;
    align-items: center;
    > div {
      margin-top: 32px;
      &:first-child {
        width: 110px;
        height: 36px;
        background: #29b6fd;
        border-radius: 18px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 15px;
        color: #ffffff;
        line-height: 18px;
        text-align: center;
        font-style: normal;
      }
      &:last-child {
        width: 110px;
        height: 36px;
        border-radius: 18px;
        border: 1px solid #d5d9d8;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 15px;
        color: #768180;
        line-height: 18px;
        text-align: center;
        font-style: normal;
        margin-left: 12px;
      }
    }
  }
}
body {
  background: #f8f8f8 !important;
}
.collection-list-page-wrap {
  width: 100%;
  height: 100vh;
  overflow-y: hidden;
  overflow-x: hidden;
  box-sizing: border-box;
  // padding: 16px 20px;
  position: relative;
  .bg {
    width: 100%;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1;
  }
  .skeleton {
    position: relative;
    z-index: 3;
    .item {
      background-color: #fff;
      margin-bottom: 12px;
      box-sizing: border-box;
      border: 1px solid #f6f7f9;
      padding: 18px 12px;
      border-radius: 18px;
    }
  }
  .content {
    position: relative;
    z-index: 3;
    width: 100%;
    height: 100%;
    overflow-x: hidden;
    overflow-y: scroll;
    padding: 16px 20px;
    box-sizing: border-box;
  }
  .content::-webkit-scrollbar {
    display: none;
  }
  .empty {
    margin-top: 120px;
    display: flex;
    align-items: center;
    flex-direction: column;
    img {
      width: 120px;
      height: 120px;
    }
    p {
      font-weight: 400;
      font-size: 13px;
      color: #9699a0;
      line-height: 20px;
      margin-top: 12px;
    }
  }
  .operate-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 52px;
    background: #ffffff;
    box-sizing: border-box;
    padding: 0 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    // border-top: 1px solid #e3f2f2;
    .top-line {
      width: 301px;
      height: 1px;
      background: rgba(227, 242, 242, 0.5);
      position: absolute;
      top: -1px;
      left: 50%;
      margin-left: -150px;
    }
    .choice-all {
      font-family:
        PingFangSC,
        PingFang SC;
      font-weight: 400;
      font-size: 13px;
      color: #393d46;
      line-height: 20px;
      display: flex;
      align-items: center;
      > span {
        margin-left: 8px;
      }
    }
    .btns-wrap {
      display: flex;
      .del {
        width: 120px;
        height: 36px;
        background: #29a794;
        border-radius: 18px;
        display: flex;
        align-items: center;
        font-weight: 400;
        font-size: 13px;
        color: #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
        &.disabled {
          opacity: 0.6;
        }
      }
      .copy {
        width: 120px;
        height: 36px;
        background: #ffffff;
        border-radius: 18px;
        border: 1px solid rgba(41, 167, 148, 0.3);
        font-weight: 400;
        font-size: 13px;
        color: #29a794;
        line-height: 18px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 16px;
        &.disabled {
          opacity: 0.6;
        }
      }
    }
  }
}
.collection-list-page-item {
  display: flex;
  align-items: center;
  .check-box-wrap {
    margin-right: 12px;
    display: flex;
  }
  .inner {
    position: relative;
    background: #fff;
    border-radius: 12px;
    font-family:
      PingFangSC,
      PingFang SC;
    font-weight: 400;
    font-size: 13px;
    color: #393d46;
    line-height: 20px;
    text-align: justify;
    font-style: normal;
    margin-bottom: 12px;
    box-sizing: border-box;
    border: 1px solid #f6f7f9;
    padding: 18px 12px;
    transition: all 0.4s;
    &.active {
      background: #ffffff;
      border: 1px solid #29b6fd;
    }
  }

  .collection-list-page-item__question {
    font-size: 14px;
    color: #393d46;
    font-weight: 500;
    display: flex;
    align-items: flex-start;
    margin-bottom: 8px;
    > div {
      position: relative;
      top: 1px;
    }
    > span {
      margin-left: 8px;
    }
  }
  .collection-list-page-item__answer {
    display: flex;
    align-items: flex-start;
    .collection-list-page-item__answer-content {
      margin-left: 8px;
    }
  }
  .collection-list-page-item__time {
    font-family:
      PingFangSC,
      PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: #b2b8c1;
    box-sizing: border-box;
    padding-left: 24px;
    margin-top: 16px;
  }
  .collection-list-page-item__operate {
    position: absolute;
    right: 12px;
    bottom: 16px;
    display: flex;
    align-items: center;
    font-size: 10px;
    color: #e9ebf1;
    > span {
      margin: 0 6px;
    }
  }
}
</style>
