<template>
  <view class="news">
    <!-- 顶部tab -->
    <view class="header">
      <view class="tabs">
        <view class="tabs-item" @click="tabClick('album')">
          <text :class="currTab === 'album' ? 'active-tab' : ''">产品相册</text>
        </view>
        <view class="tabs-item" @click="tabClick('article')">
          <text :class="currTab === 'article' ? 'active-tab' : ''">学术信息</text>
        </view>
      </view>
    </view>
    <view class="line" />
    <view class="content">
      <template v-if="currTab === 'album'">
        <view v-if="hasInfo">
          <albumCard
            v-for="(item, index) in albumList"
            @onDetail="onDetail"
            @shareFn="shareFn"
            :key="index"
            :item="item"
            :isLogin="isLogin"
          />
        </view>
        <noData v-else />
      </template>
      <template v-if="currTab === 'article'">
        <view class="info">
          <view class="search">
            <uv-input
              @input="searchValChange"
              placeholder="输入关键字"
              v-model="params.title"
              clearable
              :customStyle="{ height: '48rpx' }"
            >
              <template v-slot:prefix>
                <view class="area" @click="showAreaPicker">
                  <text>{{ areaSearch || '区域' }}</text>
                  <uv-icon name="arrow-down-fill" color="#999" size="10" />
                </view>
              </template>
            </uv-input>
            <!-- <view class="search-btn" @click="titleClick">搜索</view> -->
          </view>
          <view v-if="hasInfo">
            <infoCard
              v-for="(item, index) in articleList"
              @onDetail="onDetail"
              @shareFn="shareFn"
              :key="index"
              :item="item"
              :isLogin="isLogin"
            />
          </view>
          <noData v-else />
        </view>
      </template>
    </view>

    <!-- 选择地区 -->
    <uv-picker
      ref="areaPicker"
      :defaultIndex="areaIndex"
      :columns="columns"
      keyName="label"
      @confirm="areaConfirm"
    />
    <!-- 登录状态下分享弹窗 -->
    <sharePopup
      @initInfo="initInfo"
      :sharePopupType="sharePopupType"
      :sharePopupId="sharePopupId"
      :shareTitle="shareTitle"
      ref="sharePopupRef"
    />
    <Tabbar />
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onReachBottom, onShareAppMessage, onLoad, onShow } from '@dcloudio/uni-app'
import { provinces } from '@/constants/provinces'
import { getArticlePage, getAlbumPage } from '@/service/modules/news'
import infoCard from './components/infoCard.vue'
import albumCard from './components/albumCard.vue'
import noData from '@/components/noData/index.vue'
import sharePopup from '@/components/sharePopup/index.vue'
import useGetLoginStatus from '@/hooks/useGetLoginStatus'
import { useLoginStore } from '@/store/login'
import { debounce } from '@/utils/index'
import { shareArticleByIdApi, shareAlbumByIdApi } from '@/service/modules/newsDetail'

const loginStore = useLoginStore()

const currTab = ref('album')
const columns = ref([provinces])
const areaPicker = ref()

const areaSearch = ref('')
const areaIndex = ref()
const hasInfo = ref(true)

class Params {
  total = -1
  current = 1
  size = 20
  title = ''
  area = ''
}

const shareId = ref('')
const packageIdVal = ref('')
const remarkVal = ref('')
onShareAppMessage((res: any) => {
  if (res.from === 'button') {
    const { id, title, remark, packageid } = res.target.dataset
    shareId.value = id
    packageIdVal.value = packageid
    remarkVal.value = remark

    let path = ''
    if (isLogin.value) {
      const shareUserId = loginStore.currentUserInfo.userId
      shareSuccess()
      path = `/pages/news-detail/index?type=${currTab.value}&id=${id}&shareUserId=${shareUserId}&packageId=${packageid}&remark=${remark}`
    } else {
      path = `/pages/news-detail/index?type=${currTab.value}&id=${id}`
    }
    return {
      title: title,
      path: path
    }
  } else {
    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 1]
    return {
      title: '营销行为管理小助手',
      path: prevPage.route
    }
  }
})

function checkLogin() {
  if (!loginStore.isLogin) {
    uni.showToast({
      title: '请先登录',
      icon: 'none',
      duration: 800
    })
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/index'
      })
    }, 1200)
  }
  return loginStore.isLogin
}

const shareSuccess = async () => {
  let res
  if (currTab.value === 'article') {
    res = await shareArticleByIdApi(
      shareId.value,
      loginStore.currentUserInfo.userId || '',
      loginStore.currentUserInfo.userId || '',
      'share',
      packageIdVal.value,
      '',
      remarkVal.value
    )
  } else {
    res = await shareAlbumByIdApi(
      shareId.value,
      loginStore.currentUserInfo.userId || '',
      loginStore.currentUserInfo.userId || '',
      'share',
      packageIdVal.value,
      '',
      remarkVal.value
    )
  }
  if (res.code === 0) {
    uni.showToast({
      title: '分享成功',
      icon: 'none'
    })
  }

  sharePopupRef.value.close()
}

// 学术信息
const params = ref(new Params())
const articleList = ref<any[]>([])
async function getArticleList() {
  uni.showLoading()
  const res = await getArticlePage(params.value)
  if (res.data) {
    params.value.total = res.data.total
    articleList.value = articleList.value.concat(res.data.records)
    hasInfo.value = !!articleList.value.length
  }
  uni.hideLoading()
}

const tabClick = (curr: string) => {
  params.value = new Params()
  if (curr === 'article') {
    if (!checkLogin()) return
    articleList.value = []
    getArticleList()
  } else {
    albumList.value = []
    getAlbumList()
  }
  currTab.value = curr
}
const showAreaPicker = () => areaPicker.value.open()
const areaConfirm = (e: any) => {
  params.value.area = e.value[0].value === '1' ? '' : e.value[0].label
  areaSearch.value = params.value.area
  areaIndex.value = e.value.index
  articleList.value = []
  params.value.current = 1
  getArticleList()
}

const searchValChange = debounce(() => {
  params.value.current = 1
  articleList.value = []
  getArticleList()
})

const albumList = ref<any[]>([])
// 产品相册
async function getAlbumList() {
  uni.showLoading()
  const res = await getAlbumPage(params.value)
  if (res.data) {
    params.value.total = res.data.total
    albumList.value = albumList.value.concat(res.data.records)
    hasInfo.value = !!albumList.value.length
  }
  uni.hideLoading()
}
// 详情
const onDetail = (item: any) => {
  uni.navigateTo({
    url: `/pages/news-detail/index?type=${currTab.value}&id=${item.id}`
  })
}

const isLogin = ref(false)
onLoad(() => {
  getAlbumList()
})
onShow(() => {
  uni.hideTabBar()
  isLogin.value = useGetLoginStatus()
})

onReachBottom(() => {
  // hasInfo.value = true
  if (currTab.value === 'article') {
    if (articleList.value.length === params.value.total) return
    params.value.current++
    getArticleList()
  } else {
    params.value.current++
    getAlbumList()
  }
})

const sharePopupRef = ref()
const sharePopupType = ref('')
const sharePopupId = ref('')
const shareTitle = ref('')
const shareFn = (info: any) => {
  sharePopupType.value = info.type
  sharePopupId.value = info.id + ''
  shareTitle.value = info.shareTitle
}
const initInfo = () => {
  sharePopupType.value = ''
  sharePopupId.value = ''
  shareTitle.value = ''
}
</script>

<style lang="scss" scoped>
.news {
  padding-top: 100rpx;
  .header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 999;
    background-color: #fff;

    .tabs {
      margin-top: 8rpx;
      height: 80rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .tabs-item {
        flex: 1;
        text-align: center;
        color: #666;
        font-size: 28rpx;
        font-weight: 400;
        text {
          display: inline-block;
          &.active-tab {
            color: #333;
            font-weight: 600;
            position: relative;
            &::after {
              content: '';
              display: block;
              position: absolute;
              width: 50%;
              height: 6rpx;
              background-color: #6eb657;
              left: 50%;
              top: 50rpx;
              transform: translateX(-50%);
            }
          }
        }
      }
    }
  }
}

.content {
  padding: 0 30rpx;
  .info {
    .search {
      margin-top: 30rpx;
      display: flex;
      align-items: center;
      .area {
        height: 40rpx;
        margin-right: 15rpx;
        width: 160rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        border-right: 2rpx solid #999;
        text {
          margin-right: 15rpx;
        }
      }
      .search-btn {
        margin-left: 20rpx;
        color: #333;
        font-size: 32rpx;
        font-weight: 400;
      }
    }
  }
}
.line {
  height: 16rpx;
  background-color: #fafafa;
  width: 750rpx;
}
</style>
