<template>
  <!-- 检索栏 -->
  <view class="search">
    <SearchNavigation />
  </view>
  <view class="box">
    <!-- 類別 -->
    <view class="button_wrap">
      <view class="button" :class="{ active: buttonType === 'gupiao' }" @click="buttonType = 'gupiao'">{{ t('market.gupiao') }}</view>
      <view class="button" :class="{ active: buttonType === 'collect' }" @click="buttonType = 'collect'">{{ t('market.collect') }}</view>
    </view>
    <!-- 主體 -->
    <scroll-view scroll-y class="content" :style="{ height: contentHeight }" @scrolltolower="scrolltolower">
      <!-- 股票 -->

      <view v-show="buttonType === 'gupiao'">
        <!-- 所有股票 -->
        <view class="gupiao_wrap">
          <view v-for="(item, index) in gupiaoList" :key="index" :class="getColor(item)" class="gupiao1" @click="goPage(`/subPackages/index/gupiaoDetail/gupiaoDetail?id=${item.id}`)">
            <div class="left">
              <image :src="item.is_zixuan ? star : star_o" mode="" @click.stop="collect(item)" />
            </div>
            <div class="right">
              <div class="title">{{ item.name }}</div>
              <div class="row">
                <div class="row" style="gap: 0.63rem; align-items: flex-start">
                  <div class="daima">{{ item.shuzidaima }}</div>
                  <img :class="item.zhangdiebaifenbi >= 0 ? 'up' : 'down'" :src="item.zhangdiebaifenbi >= 0 ? up : down" mode="widthFix" />
                </div>
                <div>
                  <div class="rate">
                    <span :class="getColor(item)">{{ item.zhangdieshu }}</span>
                    <span :class="getColor(item)">({{ item.zhangdiebaifenbi }}%)</span>
                  </div>
                  <div class="price">
                    <span :class="getColor(item)">{{ changeMoney(item.price) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </view>
        </view>
      </view>

      <!-- 收藏 -->
      <view v-show="buttonType === 'collect'">
        <!-- 前6個股票 -->
        <view class="hotlist">
          <view class="gupiao_wrap">
            <view v-for="(item, index) in ziXuanList" :key="index" class="gupiao1" @click="goPage(`/subPackages/index/gupiaoDetail/gupiaoDetail?id=${item.id}`)">
              <div class="left">
                <image :src="star" mode="" @click.stop="collect(item)" />
              </div>
              <div class="right">
                <div class="title">{{ item.name }}</div>
                <div class="row">
                  <div class="row" style="gap: 0.63rem; align-items: flex-start">
                    <div class="daima">{{ item.shuzidaima }}</div>
                    <img :class="item.zhangdiebaifenbi >= 0 ? 'up' : 'down'" :src="item.zhangdiebaifenbi >= 0 ? up : down" mode="widthFix" />
                  </div>
                  <div>
                    <div class="rate">
                      <span :class="getColor(item)">{{ item.zhangdieshu }}</span>
                      <span :class="getColor(item)">({{ item.zhangdiebaifenbi }}%)</span>
                    </div>
                    <div class="price">
                      <span :class="getColor(item)">{{ changeMoney(item.price) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </view>
            <view class="plus" @click="goPage('/subPackages/search/search')">
              <van-icon name="plus" size="1.7rem" color="#1B72E3"></van-icon>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
  <CustomTabbar :id="1" />
</template>

<script lang="ts" setup>
import CustomTabbar from '@/components/custom-tabbar/custom-tabbar.vue'
import SearchNavigation from '@/components/searchNavigation/searchNavigation.vue'
import { useCounterStore } from '@/store/store'
import { getGupiaoListApi, getZixuanlApi } from '@/api/market/market'
import { collectApi, collectDetailApi, getHotGupiaoApi } from '@/api/index/index'
import { onHide, onShow } from '@dcloudio/uni-app'
import { getColor, goPage, changeMoney } from '@/common/common'
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import socket from '@/common/socket'
import up from '@/static/image/index/up_line.png'
import down from '@/static/image/index/donw_line.png'
import star from '@/static/image/index/star.png'
import star_o from '@/static/image/index/star-o2.png'
import { showToast } from 'vant'
const { t } = useI18n()

// 熱門股票
interface hotGupiaoType {
  name: string
  shuzidaima: string
  price: string
  zhangdiebaifenbi: number | string
  zhangdieshu: number | string
  id: number
}

const hotGupiaoList = ref<Array<hotGupiaoType>>([])

// let shuzidaima = []

// 获取热门股票
const getHotGupiao = async () => {
  const res = await getHotGupiaoApi()
  hotGupiaoList.value = mapGupiaoList(res.data.result.slice(0, 3))
  console.log(hotGupiaoList.value)
}

// 页面基础配置
const store = useCounterStore()
const contentHeight = `calc(${store.pageHeight} - 10.9rem - 1rem)`
// let id: any = null
let page1 = 1
onShow(() => {
  page1 = 1
  getGupiaoList(true)
  getHotGupiao()
  getZixuanlFn()
})

onHide(() => {
  // clearInterval(id)
  socket.closeSocket()
})

const ziXuanList = ref([])

const getZixuanlFn = async () => {
  const res = await getZixuanlApi()
  if (res.code === 1) {
    ziXuanList.value = res.data.map((item) => item?.product)
  }
}

watch(ziXuanList, () => {
  mapGupiaoList(gupiaoList.value)
})

const mapGupiaoList = (arr: Array<any>) => {
  if (ziXuanList.value.length === 0) {
    arr = arr.map((item) => {
      item.is_zixuan = 0
      return item
    })
  }
  arr.forEach((element) => {
    for (let i = 0; i < ziXuanList.value.length; i++) {
      const item = ziXuanList.value[i]
      if (item.shuzidaima === element.shuzidaima) {
        element.is_zixuan = 1
        return
      } else {
        element.is_zixuan = 0
      }
    }
  })

  return arr
}

// 獲取股票列表
const gupiaoList = ref([])
const gupiaoInfo = ref({})
const pageLoading = ref(false)
const getGupiaoList = async (islun: boolean = false) => {
  pageLoading.value = true
  const res = await getGupiaoListApi(islun ? { page: 1, limit: 10 } : { page: page1, limit: 10 })
  page1++
  if (islun) {
    gupiaoList.value = mapGupiaoList([...res?.data?.data])
  } else {
    gupiaoList.value = mapGupiaoList([...gupiaoList.value, ...res?.data?.data])
  }
  // 开启socket
  socket.listenFun({ type: 'sub', params: 'stock' }, (res) => {
    res = JSON.parse(res)
    for (let i = 0; i < gupiaoList.value.length; i++) {
      if (res.Symbol === gupiaoList.value[i].shuzidaima) {
        gupiaoList.value[i].price = res.Last
        gupiaoList.value[i].zhangdieshu = res.Chg
        gupiaoList.value[i].zhangdiebaifenbi = res.ChgPct
      }
    }
    for (let i = 0; i < hotGupiaoList.value.length; i++) {
      if (res.Symbol === hotGupiaoList.value[i].shuzidaima) {
        hotGupiaoList.value[i].price = res.Last
        hotGupiaoList.value[i].zhangdieshu = res.Chg
        hotGupiaoList.value[i].zhangdiebaifenbi = res.ChgPct
      }
    }
  })

  gupiaoInfo.value = res.data
  pageLoading.value = false
}

const scrolltolower = () => {
  if (gupiaoInfo.value?.current_page < gupiaoInfo.value?.last_page && !pageLoading.value && buttonType.value === 'gupiao') {
    getGupiaoList()
  }
}

// 類別切換
const buttonType = ref('gupiao')

// 收藏股票
const collect = async (item) => {
  const res = await collectApi({ id: item.id })
  const info = await collectDetailApi({ id: item.id })
  item.is_zixuan = info.data.msg === 'yes' ? 1 : 0
  getZixuanlFn()
  showToast(res.data.msg)
}
</script>
<style scoped lang="scss">
.box {
  // background: $color-white;
  padding: 0.5rem 0.31rem 0.5rem;
  margin: 0 0.63rem;
  overflow: hidden;
}

.button_wrap {
  height: 2.13rem;
  margin: 0 0 0.5rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 0.94rem;
  .button {
    width: 50%;
    height: 2.13rem;
    border-radius: 0.5rem;
    font-size: 0.88rem;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #1c2a3b;
    border: 0.06rem solid #565358;
    color: $color-gray;
  }
  .active {
    background: $color-primary;
    border: 0.05rem solid $color-primary;
    color: $color-black;
    font-weight: 500;
  }
}
.content {
  overflow-y: scroll;

  .gupiao_wrap {
    // padding: 0rem 0.9375rem 0;
  }
  .gupiao1 {
    display: flex;
    width: 100%;
    padding: 0.38rem 0.38rem 0.38rem 0;
    margin-bottom: 0.13rem;
    border-bottom: 0.06rem solid #ffffff50;
    .left {
      width: 3.38rem;
      display: flex;
      align-items: center;
      justify-content: center;
      image {
        width: 1.75rem;
        height: 1.75rem;
        padding: 0.31rem;
      }
    }
    .right {
      // flex: 1;
      .title {
        font-size: 0.94rem;
        color: $color-white;
        font-weight: 500;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        width: 18rem;
      }
      .row {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .daima {
        font-size: 0.81rem;
        color: #afafaf;
      }
      .rate span {
        font-size: 0.75rem;
      }
      img {
        width: 3rem;
        justify-self: flex-start;
        margin-top: 0.13rem;
        margin-left: 0.63rem;
      }

      img.up {
        transform: rotateX(180deg);
      }
      img.down {
        transform: rotateX(180deg);
      }
      .price {
        font-size: 1.25rem;
        font-weight: 500;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
      .rate {
        text-align: right;
      }
    }
  }

  .plus {
    height: 5.63rem;
    margin-bottom: 0.13rem;
    border-bottom: 0.06rem solid #ffffff50;
    display: flex;
    justify-content: center;
    align-items: center;
    image {
      width: 1.31rem;
    }
  }
}
</style>
