<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'">
        <!-- 前6個股票 -->
        <!-- <view class="hotlist">
          <view class="hot_gupiao_wrap">
            <view v-for="(item, index) in hotGupiaoList" :key="index" :class="getColor(item)" class="gupiao" @click="goPage(`/subPackages/index/gupiaoDetail/gupiaoDetail?id=${item.id}`)">
              <view class="flex items-center justify-between">
                <view class="title">{{ item.name }}</view>
                <view>
                  <van-icon v-if="item.is_zixuan == 0" name="star-o" size=".8rem"></van-icon>
                  <van-icon v-else name="star" size=".8rem" color="#50B0F2"></van-icon>
                </view>
              </view>
              <view class="flex justify-between">
                <view class="text-sm">{{ item.shuzidaima }}</view>
                <view class="text-sm" :class="getColor(item)">{{ item.zhangdieshu }}</view>
                <view class="text-sm" :class="getColor(item)">{{ item.zhangdiebaifenbi }}%</view>
              </view>
              <view class="flex justify-center items-center">
                <view class="text-[0.94rem]">{{ item.price }}</view>
                <text v-if="item.zhangdiebaifenbi === 0"> - </text>
                <van-icon v-else :class="getColor(item, true)" name="down" size=".75rem" />
              </view>
            </view>
          </view>

          <view v-if="gupiaoList.length > 3" class="hot_gupiao_wrap">
            <view v-for="(item, index) in gupiaoList.slice(3, 6)" :key="index" :class="getColor(item)" class="gupiao" @click="goPage(`/subPackages/index/gupiaoDetail/gupiaoDetail?id=${item.id}`)">
              <view class="flex items-center justify-between">
                <view class="title">{{ item.name }}</view>
                <view>
                  <van-icon v-if="item.is_zixuan == 0" name="star-o" size=".8rem"></van-icon>
                  <van-icon v-else name="star" size=".8rem" color="#50B0F2"></van-icon>
                </view>
              </view>
              <view class="flex justify-between">
                <view class="text-sm">{{ item.shuzidaima }}</view>
                <view class="text-sm" :class="getColor(item)">{{ item.zhangdieshu }}</view>
                <view class="text-sm" :class="getColor(item)">{{ item.zhangdiebaifenbi }}%</view>
              </view>
              <view class="flex justify-center items-center">
                <view class="text-[0.94rem]">{{ item.price }}</view>
                <text v-if="item.zhangdiebaifenbi === 0"> - </text>
                <van-icon v-else :class="getColor(item, true)" name="down" size=".75rem" />
              </view>
            </view>
          </view>
        </view> -->
        <!-- 所有股票 -->
        <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="daima">{{ item.shuzidaima }}</div>
                <div class="rate">
                  <span :class="getColor(item)">{{ item.zhangdieshu }}</span>
                  <span :class="getColor(item)">（{{ item.zhangdiebaifenbi }}%）</span>
                </div>
              </div>
              <div class="row">
                <div class="image_wrap">
                  <image :src="item.zhangdiebaifenbi > 0 ? up1 : down1" mode="widthFix" />
                </div>

                <div class="price">
                  <img v-if="item.zhangdiebaifenbi > 0" :src="up" alt="" style="width: 0.5rem; height: 0.625rem; margin-right: 0.3438rem" />
                  <img v-if="item.zhangdiebaifenbi < 0" :src="down" alt="" style="width: 0.5rem; height: 0.625rem; margin-right: 0.3438rem" />
                  <span :class="getColor(item)">{{ item.price }}{{ $t('common.unit') }}</span>
                </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="daima">{{ item.shuzidaima }}</div>
                  <div class="rate">
                    <span :class="getColor(item)">{{ item.zhangdieshu }}</span>
                    <span :class="getColor(item)">（{{ item.zhangdiebaifenbi }}%）</span>
                  </div>
                </div>
                <div class="row">
                  <div class="image_wrap">
                    <image :src="item.zhangdiebaifenbi > 0 ? up1 : down1" mode="widthFix" />
                  </div>

                  <div class="price">
                    <img v-if="item.zhangdiebaifenbi > 0" :src="up" alt="" style="width: 0.5rem; height: 0.625rem; margin-right: 0.3438rem" />
                    <img v-if="item.zhangdiebaifenbi < 0" :src="down" alt="" style="width: 0.5rem; height: 0.625rem; margin-right: 0.3438rem" />
                    <span :class="getColor(item)">{{ item.price }}{{ $t('common.unit') }}</span>
                  </div>
                </div>
              </div>
            </view>
            <view class="plus" @click="goPage('/subPackages/search/search')">
              <image :src="plus" mode="widthFix" />
            </view>
          </view>
        </view>
        <!-- <NotData v-if="ziXuanList.length === 0" /> -->
      </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 } from '@/common/common'
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import up from '@/static/image/market/up1.png'
import down from '@/static/image/market/down1.png'
import socket from '@/common/socket'
import up1 from '@/static/image/market/up.png'
import down1 from '@/static/image/market/down.png'
import star from '@/static/image/index/star.png'
import star_o from '@/static/image/index/star-o.png'
import plus from '@/static/image/market/plus2.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 - .4rem)`
// 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 {
  border-radius: 1.5625rem 1.5625rem 0 0;
}

.button_wrap {
  height: 2.13rem;
  margin: 0 0.94rem 0.5rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 0.94rem;
  .button {
    width: 50%;
    height: 2.13rem;
    border-radius: 0.7rem;
    font-size: 0.88rem;
    color: $color-black;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 0.06rem solid $color-primary;
  }
  .active {
    background: $color-primary;
    color: #fff;
    font-weight: 500;
  }
}
.content {
  overflow-y: scroll;
  .hotlist {
    .hot_gupiao_wrap {
      display: flex;
      padding: 0.44rem 0.69rem 0;
      flex-wrap: wrap;
      .gupiao {
        width: 32%;
        height: 4.56rem;
        border-radius: 0.94rem;
        padding: 0.09rem 0.19rem;
        margin: 0 0.6667% 0.41rem;

        .title {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      > .up {
        background-color: #fff3f5;
        border-radius: 0.625rem;
        background-size: 100%;
        background-repeat: no-repeat;
        background-position: bottom;
      }
      > .down {
        background-color: #e8f7ef;
        border-radius: 0.625rem;
        background-size: 100%;
        background-repeat: no-repeat;
        background-position: bottom;
      }
    }
    .hot_gupiao_wrap + .hot_gupiao_wrap {
      padding-top: 0;
    }
  }

  .gupiao_wrap {
    padding: 0rem 0.9375rem 0;
    .gupiao {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0.6875rem 0 0.5625rem 0;
      background-color: rgb(10, 31, 54, 0.8);
      border-radius: 0.625rem;
      margin-bottom: 0.31rem;
      .zixuan {
        width: 2.125rem;
        height: 2.125rem;
      }
      .title {
        color: #fff;
        font-size: 0.875rem;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        font-weight: 500;
      }
      .code {
        color: #a0a5b0;
        font-size: 0.75rem;
      }
    }
  }
  .gupiao1 {
    display: flex;
    width: 100%;
    border-bottom: 0.06rem solid #ffffff50;
    padding: 0.38rem 0.38rem 0.38rem 0;
    background: #fafafa;
    box-shadow: 0rem 0.13rem 0.19rem 0rem rgba(0, 0, 0, 0.05);
    border-bottom: 0.06rem solid rgba(20, 20, 20, 0.14);
    margin-bottom: 0.13rem;
    border-radius: 0.7rem;
    .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-black;
        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;
      }
      image {
        width: 6.88rem;
      }
      .price {
        font-size: 1.25rem;
        font-weight: 500;
        display: flex;
        align-items: center;
      }
    }
  }

  .plus {
    height: 5.63rem;
    border-bottom: 0.06rem solid #ffffff50;
    padding: 0.38rem 0.38rem 0.38rem 0;
    background: #fafafa;
    box-shadow: 0rem 0.13rem 0.19rem 0rem rgba(0, 0, 0, 0.05);
    border-bottom: 0.06rem solid rgba(20, 20, 20, 0.14);
    display: flex;
    justify-content: center;
    align-items: center;
    background: #f8fafc;
    border-radius: 0.7rem;
    image {
      width: 1.31rem;
    }
  }
}
</style>
