<script setup lang="ts">
import LoadIcon from './components/LoadIcon.vue'
import { debounce } from '@/hooks'

import { useReward } from '@/hooks'
import { dialog } from '@/components/mj/mj-dialog'
import mailboxApi from '@/api/system/mailbox'

const OSS_URL = `${import.meta.env.VITE_OSS_URL}`

const activeClass = ref(1)
const msgRedPoint = reactive({
  sysMsg: false,
  otherMsg: false,
})
const classList = computed(() => [
  {
    id: 1,
    name: '系统',
    warning: msgRedPoint.sysMsg,
  },
  {
    id: 4,
    name: '其他',
    warning: msgRedPoint.otherMsg,
  },
])

// 切换侧边栏
async function handleSelectClass() {
  clearTimeout(timeout)
  pageLoading.value = true
  await initList()
  timeout = setTimeout(() => {
    pageLoading.value = false
  }, 500)
}

// 邮件列表
const mailList = ref<any[]>([])
const unReadNum = ref(0)
const page = reactive({
  size: 20,
  current: 1,
  total: 0,
})
const loading = ref(false)
async function getMailList() {
  const { data: res } = await mailboxApi.getMailList({
    messageTypeFlag: activeClass.value,
    ...page,
  })

  if (res.code === 200) {
    unReadNum.value = res.data.unReadSize
    mailList.value.push(...(res.data.userMessageBoxByTypeSimpleVoPageResult?.rows || []))
    page.total = res.data.userMessageBoxByTypeSimpleVoPageResult?.totalRows || 0
  }
}
const mailIconUrl = computed(() => (item: anyObj) => {
  if (item.readStatus) {
    return item.letterOpenIcon || `${OSS_URL}/icon/mail_open.svg`
  }
  return item.letterIcon || `${OSS_URL}/icon/mail_close.svg`
})

const bookSidebarRef = ref()
const scrollRef = ref()
async function handleScroll(event: any) {
  if (mailList.value.length >= page.total) return
  if (loading.value) return
  if (
    event.target.scrollTop + event.target.offsetHeight >=
    bookSidebarRef.value?.offsetHeight - 50
  ) {
    page.current++
    try {
      loading.value = true
      await getMailList()
    } catch {
      page.current--
    }
    loading.value = false
  }
}

const debounceScroll = debounce(handleScroll, 200, false)

// 当前邮件
const mailData = ref<any>({})
// 是否有奖励可领取
const hasGift = computed(() => {
  return (
    mailData.value.hasReward &&
    !mailData.value.hasPickReward &&
    mailData.value.userMessageAppendixInfo?.messageBoxRewardRets?.rewards?.length &&
    !mailData.value.userMessageAppendixInfo.rewardExpireStatus
  )
})
// 切换邮件
async function handleSelectMail(item: any) {
  if (!item) return
  const { data: res } = await mailboxApi.getMailDetail(item.id)
  if (!item.readStatus) {
    unReadNum.value--
    item.readStatus = 1
  }
  if (res.code === 200) {
    mailData.value = res.data
  }
  initMsgRedPoint()
}

const pageLoading = ref(false)
const pageError = ref(false)

async function handleMailClick(type: number) {
  const idx = mailList.value.findIndex(i => i.id === mailData.value.id)
  switch (type) {
    case 0:
      // 领取奖励
      await mailboxApi.pickMail(mailData.value.id)
      mailData.value.hasPickReward = 1
      mailList.value[idx] && (mailList.value[idx].hasPickReward = 1)
      // mailDia.show = true;
      // mailDia.data = mailData.value.userMessageAppendixInfo.messageBoxRewardRets.rewards;
      useReward({
        rewardList: mailData.value.userMessageAppendixInfo.messageBoxRewardRets.rewards,
      })
      initMsgRedPoint()
      break
    case 1:
      // 弹框提醒
      dialog.show({
        content: '确定删除该邮件吗？',
        ok: async () => {
          // 删除
          await mailboxApi.delMail(mailData.value.id)
          mailList.value.splice(idx, 1)
          page.total--
          if (idx > mailList.value.length - 1) {
            handleSelectMail(mailList.value[0])
            scrollRef.value && (scrollRef.value.scrollTop = 0)
          } else {
            handleSelectMail(mailList.value[idx])
          }
          initMsgRedPoint()
        },
      })
      break
  }
}

const debounceMailClick = debounce(handleMailClick, 500)

async function handleAllClick(type: number) {
  switch (type) {
    case 0:
      // eslint-disable-next-line no-case-declarations
      const { data: res } = await mailboxApi.pickMailAllRewards({
        messageTypeFlag: activeClass.value,
      })
      if (res.code === 200) {
        mailList.value.forEach(i => (i.readStatus = 1))
        // 确认一键领取
        mailboxApi.pickMailAll({
          timeFlag: res.data.timeFlag,
          messageTypeFlag: activeClass.value,
        }) // 有无奖励都调用这个接口
        if (res.data.rewards.length) {
          // mailDia.show = true;
          // mailDia.data = res.data.rewards;
          useReward({
            rewardList: res.data.rewards,
          })

          mailData.value.hasPickReward = 1
          mailList.value.forEach(i => (i.hasPickReward = 1))
        }
      }
      break
    case 1:
      // 删除已读
      dialog.show({
        content: '确定删除所有已读邮件吗？',
        ok: async () => {
          await mailboxApi.delMailAll({ messageTypeFlag: activeClass.value })
          initList()
        },
      })
      break
  }
  initMsgRedPoint()
}
const debounceAllClick = debounce(handleAllClick, 500)

// 图片预览dia
const imgView = reactive({
  show: false,
  url: '',
})

function toViewImg(url: string) {
  imgView.show = true
  imgView.url = url
}

// 初始化列表
async function initList() {
  mailList.value = []
  page.current = 1
  try {
    await getMailList()
    if (mailList.value.length) {
      await handleSelectMail(mailList.value[0])
    }
  } catch {
    pageError.value = true
  }
}
// 信箱未读提示
async function initMsgRedPoint() {
  const {
    data: { data: res },
  } = await mailboxApi.getMsgRedPoint()
  msgRedPoint.sysMsg = res.sysMsg
  msgRedPoint.otherMsg = res.otherMsg
}

const initLoading = ref(true)
let timeout: any = null
onActivated(async () => {
  initLoading.value = true
  initMsgRedPoint()
  await initList()
  timeout = setTimeout(() => {
    initLoading.value = false
  }, 500)
})
onUnmounted(() => {
  clearTimeout(timeout)
})
</script>
<template>
  <div
    class="uncomplete"
    :style="{
      'background-image': `url(${OSS_URL}/urm/mail_bg.svg)`,
    }"
  >
    <div v-if="!initLoading" class="hidden_scroll">
      <div
        class="book"
        :style="{
          'background-image': `url(${OSS_URL}/urm/book_bg.svg)`,
        }"
      >
        <template v-if="mailList.length && !pageLoading">
          <div class="book-left">
            <div
              :data-content="`邮件数量：${unReadNum}/${page.total}`"
              class="mail-num px-mail-num"
            >
              邮件数量：<span style="color: #fbfb0c">{{ unReadNum }}</span
              >/{{ page.total }}
            </div>
            <div ref="scrollRef" class="book-sidebar hidden_scroll" @scroll="debounceScroll">
              <div ref="bookSidebarRef" class="scroll-box">
                <div
                  v-for="i in mailList"
                  :key="i.id"
                  :class="{
                    'book-sidebar-item': true,
                    active: mailData.id === i.id,
                    unready: i.readStatus,
                    pointer: true,
                  }"
                  :style="{
                    'background-image':
                      mailData.id === i.id
                        ? `url(${OSS_URL}/urm/mailbox_sidebar_active_bg.svg)`
                        : i.readStatus
                          ? `url(${OSS_URL}/urm/mailbox_sidebar_ready_bg.svg)`
                          : `url(${OSS_URL}/urm/mailbox_sidebar_bg.svg)`,
                  }"
                  @click="handleSelectMail(i)"
                >
                  <div class="icon">
                    <img class="mail-icon" :src="mailIconUrl(i)" />
                    <Icon
                      v-if="i.hasReward"
                      :name="!i.hasPickReward && !i.expireFlag ? 'gift_bottom' : 'gift_bottom_got'"
                      class="gift-icon"
                      width="67"
                    ></Icon>
                  </div>
                  <div class="info">
                    <div class="info-title">{{ i.title || '无标题' }}</div>
                    <div class="info-time">
                      {{ i.publishTime }}
                    </div>
                  </div>
                </div>
              </div>
              <LoadIcon v-if="loading"></LoadIcon>
            </div>

            <div class="sidebar-btns">
              <div
                class="btn primary pointer"
                :style="{
                  'background-image': `url(${OSS_URL}/urm/mailbox-primary-btn.svg)`,
                }"
                @click="debounceAllClick(0)"
              >
                一键已读
              </div>
              <div
                class="btn success pointer"
                :style="{
                  'background-image': `url(${OSS_URL}/urm/mailbox-success-btn.svg)`,
                }"
                @click="debounceAllClick(1)"
              >
                删除已读
              </div>
            </div>
          </div>
          <div class="book-main">
            <div class="info flex-end">
              <div class="info-title">{{ mailData.title || '无标题' }}</div>
              <div class="info-time">
                {{ mailData.publishTime }}
              </div>
            </div>
            <div class="info center">
              <div class="info-name">
                <span style="color: #999">来自：</span>{{ mailData.senderName }}
              </div>
              <div v-if="mailData.expireDay" class="info-name">
                奖励有效期：{{ mailData.expireDay }}天
              </div>
            </div>
            <div class="content hidden_scroll">
              {{ mailData.content }}
            </div>
            <!-- 附件 -->
            <div
              v-if="
                mailData.userMessageAppendixInfo?.messageBoxRewardRets?.rewards?.length ||
                mailData.userMessageAppendixInfo?.imageResource
              "
              class="appendix-list"
            >
              <div class="tab">
                <div
                  class="tab-icon"
                  :style="{
                    'background-image': `url(${OSS_URL}/urm/mailbox_tab.png)`,
                  }"
                >
                  <img class="icon" :src="`${OSS_URL}/icon/link.svg`" />
                  附件
                </div>
              </div>
              <div class="gift-list hidden_scroll_x">
                <!-- 附件图片列表 -->
                <template v-if="mailData.userMessageAppendixInfo?.imageResource">
                  <div
                    v-for="i in mailData.userMessageAppendixInfo.imageResource.split(',')"
                    :key="i"
                    :class="{ 'gift-list-item': true, pointer: true }"
                    @click.capture="toViewImg(i)"
                  >
                    <img :src="`${OSS_URL}/urm/mailbox_append_img.svg`" />
                  </div>
                </template>
                <!-- 附件奖励列表 -->
                <template v-if="mailData.userMessageAppendixInfo?.messageBoxRewardRets?.rewards">
                  <div
                    v-for="(i, idx) in mailData.userMessageAppendixInfo.messageBoxRewardRets
                      .rewards"
                    :key="idx"
                    :class="{ 'gift-list-item': true }"
                  >
                    <img :src="i.rewardResourceUrl" />
                    <span
                      v-if="i.count > 1"
                      :data-content="i.count"
                      class="gift-list-item-count px-gift-list-item-count"
                      >{{ i.count }}</span
                    >
                    <div v-if="mailData.hasPickReward" class="check-mask">
                      <img :src="`${OSS_URL}/icon/check_mark.svg`" />
                    </div>
                    <div
                      v-if="mailData.userMessageAppendixInfo?.rewardExpireStatus"
                      class="check-mask"
                    >
                      已过期
                    </div>
                  </div>
                </template>
              </div>
            </div>
            <div class="btn-box">
              <mj-button
                v-if="hasGift"
                :size="48"
                :height="108"
                :width="386"
                @click="debounceMailClick(0)"
                >领取奖励</mj-button
              >
              <mj-button
                v-else
                type="danger"
                :size="48"
                :height="108"
                :width="386"
                @click="debounceMailClick(1)"
                >删除邮件</mj-button
              >
            </div>
          </div>
        </template>
        <Empty
          v-else
          class="book-empty"
          :type="pageLoading ? 'loading' : pageError ? 'network' : 'email'"
        ></Empty>
      </div>
    </div>
    <div class="top">
      <BackBar leftText="信箱" class="backBar" />
    </div>
    <div class="main">
      <div class="main-sidebar">
        <Sidebar
          v-model="activeClass"
          :config="classList as any"
          @handle-change="handleSelectClass"
        ></Sidebar>
      </div>
      <Empty v-if="initLoading" class="page-empty" type="loading"></Empty>
    </div>
    <ImgView v-model="imgView.show" :url="imgView.url"></ImgView>
  </div>
</template>
<style scoped lang="scss">
@mixin book_style {
  position: fixed;
  width: 133.5vh;
  height: 94vh;
  left: 290px;
  top: 3.33vh;
}

.uncomplete {
  // @include main_bg;
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
  background-repeat: no-repeat;
  background-size: cover;
  .book {
    box-sizing: border-box;
    @include book_style;
    // margin: 0 20px 0 186px;
    background-repeat: no-repeat;
    background-position: top left;

    background-size: 100%;
    padding: 7.5vh 11.17vh 6.33vh 8.67vh;
    display: flex;
    z-index: 2;
    &-left {
      width: 37.75vh;
      position: relative;
      z-index: 1;
    }
    .mail-num {
      color: #fff;
      font-family: $font-special;
      font-size: 2.33vh;
      font-style: normal;
      font-weight: 500;
      line-height: 3.5vh; /* 150% */
      margin-left: 2.83vh;
      margin-bottom: 0.42vh;
    }
    .px-mail-num {
      @include font-stroke(#40aff5);
    }
    .sidebar-btns {
      height: 6.67vh;
      display: flex;
      margin: 1vh 0;

      .btn {
        cursor: pointer;
        width: 19.33vh;
        height: 6.67vh;
        font-family: $font-text;
        font-size: 2.67vh;
        padding: $space-2_h 0;
        cursor: pointer;
        line-height: 1.5;
        text-align: center;
        background-repeat: no-repeat;
        background-position: center;
        background-size: 100%;
        &.success {
          margin-left: -0.5vh;
        }
        &.primary {
          margin-right: -0.5vh;
        }
      }
    }

    &-sidebar {
      width: 37.75vh;
      height: calc(100% - 12.33vh);
      flex-shrink: 0;
      &-item {
        position: relative;
        box-sizing: border-box;
        height: 9.67vh;
        flex-shrink: 0;
        margin-bottom: 1.33vh;
        // border-radius: 32px;
        background-color: #fff;
        box-shadow: 0 0.33vh 0.17vh 0 rgba(0, 0, 0, 0.15);
        background-repeat: no-repeat;
        background-position: 26.17vh center;
        background-size: 134px, 13vh;
        padding: 0.83vh;
        display: flex;
        overflow: hidden;
        border: 0.5vh solid transparent;

        &.unready {
          background-color: #dcdff5;
        }
        &.active {
          background-color: #fff;
          border-color: rgb(255, 240, 31);
          // background-position:
          //     center,
          //     314px center;
          // background-size: 100%, 134px, 156px;
        }
        &:last-child {
          margin-bottom: 0;
        }
        .icon {
          width: 7vh;
          height: 7vh;
          flex-shrink: 0;
          background: #1c2a3a;

          margin-right: 1.33vh;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          .gift-icon {
            position: absolute;
            bottom: -0.5vh;
            right: -0.5vh;
          }
          .mail-icon {
            width: 4.67vh;
            height: 4.67vh;
          }
        }
        &.active {
          .icon {
            background: linear-gradient(249deg, #4de798 26.9%, #a2fb6e 79.86%);
          }
        }
        .info {
          width: calc(100% - 100px);
          &-title {
            color: $font-color;
            font-family: $font-text;
            font-size: 2.67vh;
            font-style: normal;
            font-weight: 400;
            line-height: 4vh; /* 150% */
            @include single_ellipsis;
          }

          &-time {
            font-size: 2vh;
          }
        }
      }
    }
    &-main {
      position: relative;
      z-index: 1;
      margin-left: 5.33vh;
      padding-top: 3.33vh;
      width: calc(100% - 40vh);
      display: flex;
      flex-direction: column;
      .info {
        flex-shrink: 0;
        padding: 1.33vh 0;
        display: flex;
        justify-content: space-between;

        &.flex-end {
          align-items: end;
          border-bottom: 0.17vh solid rgba(0, 0, 0, 0.45);
        }
        &.center {
          align-items: center;
          border-bottom: 0.08vh solid rgba(0, 0, 0, 0.45);
        }
        &-title {
          color: $font-color;
          font-family: $font-text;
          font-size: 4vh;
          font-style: normal;
          font-weight: 400;
          line-height: 6vh; /* 150% */
          // width: 500px;
          width: calc(100% - 23vh);
          margin-right: 1vh;
          @include single_ellipsis;
        }
        &-name {
          color: #666;
          font-family: $font-text;
          font-size: 2.67vh;
          font-style: normal;
          font-weight: 400;
          line-height: 4vh; /* 150% */
          margin-right: 1vh;
          @include single_ellipsis;
          &:first-child {
            width: calc(100% - 350px);
          }
        }
        &-time {
          font-family: $font-text;
          font-size: 2vh;

          line-height: 3vh; /* 150% */
          @include single_ellipsis;
        }
      }
      .content {
        color: #333;
        font-family: $font-text;
        font-size: 2.67vh;
        font-style: normal;
        font-weight: 400;
        line-height: 4vh; /* 150% */
        margin: 2.67vh 0;
        text-indent: 2em;
        // min-height: 240px;
        // max-height: calc(100% - 106px - 81px - 120px);
        flex: 1;
        // @include multiple_ellipsis(11);
        &.paper {
          height: 8vh;
          @include multiple_ellipsis(2);
        }
      }
      // &:has(.appendix-list) {
      //     .content {
      //         @include multiple_ellipsis(6);
      //     }
      // }
      // 附件
      .appendix-list {
        width: calc(100%);
        .gift-list {
          display: flex;
          width: calc(100%);
          &-item {
            position: relative;
            width: 10vh;
            height: 10vh;
            border-radius: 1.33vh;
            margin-right: 1.67vh;
            flex-shrink: 0;
            overflow: hidden;
            &:last-child {
              margin-right: 0;
            }
            img {
              width: 100%;
              height: 100%;
              object-fit: contain;
            }
            .check-mask {
              position: absolute;
              top: 0;
              left: 0;
              width: 100%;
              height: 100%;
              border-radius: 1.33vh;
              border: 0.17vh solid #fff;
              background: rgba(0, 0, 0, 0.45);
              backdrop-filter: blur(2px);
              display: flex;
              justify-content: center;
              align-items: center;
              color: #fff;
              text-shadow: 0 0.17vh 0.17vh rgba(0, 0, 0, 0.25);
              font-family: $font-special;
              font-size: 2vh;
              font-style: normal;
              font-weight: 400;
              line-height: 3vh; /* 150% */
              img {
                width: 6.67vh;
                height: 6.67vh;
              }
            }
            .px-gift-list-item-count {
              @include font-stroke;
            }
            .gift-list-item-count {
              position: absolute;
              bottom: 0;
              right: 0.5vh;
              color: #fff;
              text-align: right;
              font-family: $font-special;
              font-size: 2vh;
              font-style: normal;
              font-weight: 400;
              line-height: 1.5;
            }
          }
        }
      }
      .tab {
        // padding-top: 32px;
        margin-bottom: 2.67vh;
        &-icon {
          box-sizing: border-box;
          width: 19vh;
          height: 4.33vh;
          background-position: center;
          background-repeat: no-repeat;
          background-size: 100%;
          padding: 0.17vh 0 0.17vh 4.67vh;
          color: $font-color;
          font-family: 'PingFang SC';
          font-size: 2.67vh;
          font-style: normal;
          font-weight: 500;
          line-height: 4vh; /* 150% */
          display: flex;
          align-items: center;
          .icon {
            width: 2.67vh;
            height: 2.67vh;
            margin-right: 0.67vh;
          }
        }
      }
      .btn-box {
        flex-shrink: 0;
        box-sizing: border-box;
        padding-top: 1.33vh;
        display: flex;
        justify-content: flex-end;
        padding-bottom: 2.33vh;
      }
    }
  }

  .top {
    position: absolute;
    padding: 3vh $space-6 0;
  }

  .main {
    height: calc(100% - 8.5vh);
    padding-left: $space-6;
    padding-right: 20px;
    position: relative;
    top: 7.83vh;

    &-sidebar {
      position: absolute;
      left: $space-6;
      top: 5.5vh;
      height: calc(100% - 5.5vh);
    }
    .hidden_scroll {
      height: 100%;
    }
  }
  :deep(.book-empty) {
    @include book_style;
    // &.empty {
    //     margin-left: 220px;
    // }
    // &.loading {
    //     margin-left: 220px;
    // }
  }
}
.info-time {
  color: #999;
  font-family: $font-text;
  font-size: 1.67vh;
  font-style: normal;
  font-weight: 400;
  line-height: 2.5vh; /* 150% */
  margin-top: 0.5vh;
  span {
    margin-right: 24px;
  }
}
</style>
