<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.price }}</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.zhangdieshu }}</view>
                <text v-if="item.zhangdiebaifenbi === 0"> - </text>
                <van-icon v-else :class="getColor(item, true)" name="down" size=".75rem" />
                <!-- <img src="" style="width: 70.847px; height: 30px" /> -->
              </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.price }}</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.zhangdieshu }}</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="gupiao" @click="goPage(`/subPackages/index/gupiaoDetail/gupiaoDetail?id=${item.id}`)">
            <view class="mr-[0.63rem]">
              <!-- <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> -->
              <img v-if="item.is_zixuan == 0" :src="zixuan1" alt="" srcset="" class="zixuan" />
              <img v-else :src="zixuan" alt="" srcset="" class="zixuan" />
            </view>
            <view class="flex flex-col justify-between h-full flex-1 overflow-hidden pr-[.5rem]">
              <view class="title">{{ item.name }}</view>
              <view class="code">{{ item.shuzidaima }}</view>
            </view>
            <view class="items-center h-full flex-1">
              <view class="flex items-center h-full flex-1">
                <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" />
                <view class="text-[1rem]" :class="getColor(item)" style="font-size: 1rem; font-weight: 600; line-height: 1.5rem">{{ item.zhangdieshu }}</view>
                <text v-if="item.zhangdiebaifenbi === 0"> - </text>
                <!-- <van-icon v-else :class="getColor(item, true)" name="down" size=".75rem" /> -->
              </view>
              <view class="text-lg" :class="getColor(item)" style="font-size: 0.75rem; font-weight: 500">{{ item.zhangdiebaifenbi }}%</view>
            </view>
            <view class="text-right">
              <view class="text-lg" :class="getColor(item)" style="font-size: 1rem; font-weight: 600">{{ item.price }}</view>
            </view>
          </view>
        </view>
      </view>

      <!-- 收藏 -->
      <view v-show="buttonType === 'collect'">
        <!-- 前6個股票 -->
        <view class="hotlist">
          <view class="hot_gupiao_wrap">
            <view v-for="(item, index) in ziXuanList" :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.price }}</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.zhangdieshu }}</view>
                <text v-if="item.zhangdiebaifenbi === 0"> - </text>
                <van-icon v-else :class="getColor(item, true)" name="down" size=".75rem" />
              </view>
            </view>
            <view class="plus gupiao bg-[#fff]" @click="goPage('/subPackages/search/search')">
              <van-icon name="plus" />
            </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 { 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 zixuan from '@/static/image/market/zixuan.png'
import up from '@/static/image/market/up1.png'
import down from '@/static/image/market/down1.png'
import zixuan1 from '@/static/image/market/zixuan1.png'
import socket from '@/common/socket'
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()
  for (const i in res.data.result) {
    res.data.result[i].zhangdieshu = Number(res.data.result[i].zhangdieshu).toFixed(1)
    res.data.result[i].zhangdiebaifenbi = Number(res.data.result[i].zhangdiebaifenbi).toFixed(1)
    res.data.result[i].price = Number(res.data.result[i].price).toFixed(1)
  }
  hotGupiaoList.value = mapGupiaoList(res.data.result.slice(0, 3))
  console.log('hot', hotGupiaoList)
}

// 页面基础配置
const store = useCounterStore()
const contentHeight = `calc(100vh - ${store.tabbarHeight} - 3.13rem - 2.91rem)`
// 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) {
    const list = res.data.map((item) => item?.product)
    for (const i in list) {
      list[i].zhangdieshu = Number(list[i].zhangdieshu).toFixed(1)
      list[i].zhangdiebaifenbi = Number(list[i].zhangdiebaifenbi).toFixed(1)
      list[i].price = Number(list[i].price).toFixed(1)
    }
    ziXuanList.value = list
  }
  console.log(res)
}

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
      }
      // if (item?.is_zixuan !== 1) {
      //   item.is_zixuan = 0
      // }
    }
  })

  console.log(arr)

  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 })
  for (const i in res.data.data) {
    res.data.data[i].zhangdieshu = Number(res.data.data[i].zhangdieshu).toFixed(1)
    res.data.data[i].zhangdiebaifenbi = Number(res.data.data[i].zhangdiebaifenbi).toFixed(1)
    res.data.data[i].price = Number(res.data.data[i].price).toFixed(1)
  }
  // if (!islun) {
  page1++
  // }
  if (islun) {
    gupiaoList.value = mapGupiaoList([...res?.data?.data])
  } else {
    gupiaoList.value = mapGupiaoList([...gupiaoList.value, ...res?.data?.data])
  }
  // shuzidaima = res.data.data.map((item) => item.shuzidaima)
  // 开启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

        gupiaoList[i].zhangdieshu = Number(gupiaoList[i].zhangdieshu).toFixed(1)
        gupiaoList[i].zhangdiebaifenbi = Number(gupiaoList[i].zhangdiebaifenbi).toFixed(1)
        gupiaoList[i].price = Number(gupiaoList[i].price).toFixed(1)
        // console.log(res, 'socket res')
        // return
      }
    }
    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
        // console.log(res, 'socket res')
        // return
      }
    }
    // gupiaoList.value.map((itme) => {
    //   if (res.Symbol === itme.shuzidaima) {
    //     return { ...itme, price: res.Last, zhangdieshu: res.Chg, zhangdiebaifenbi: res.ChgPct }
    //   }
    //   return itme
    // })
    // console.log(JSON.parse(res), 'socket res')
  })

  gupiaoInfo.value = res.data
  // if (page === 1) {
  //   gupiaoList.value = [...res?.data?.data]
  // } else {
  //   gupiaoList.value = [...gupiaoList.value, ...res?.data?.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')
</script>
<style scoped lang="scss">
.search {
  height: 2.91rem;
}

.box {
  // background: rgb(13, 38, 67, 0.7);
  margin-top: 0.9375rem;
  border-radius: 1.5625rem 1.5625rem 0 0;
}

.button_wrap {
  display: flex;
  padding: 0.94rem 1.25rem;
  .button {
    width: 6.875rem;
    height: 2.125rem;
    color: #fff;
    border-radius: 1.25rem;
    margin-right: 0.88rem;
    // padding: 0 0.5rem;
    background: #08182b;
    // width: 5.94rem;
    // height: 1.25rem;
    line-height: 2.125rem;
    text-align: center;
    font-size: 0.875rem;
  }
  .active {
    background-color: $uni-color-primary;
    color: #fff;
  }
}
.content {
  overflow-y: scroll;
  .hotlist {
    .hot_gupiao_wrap {
      display: flex;
      padding: 0.44rem 0.69rem 0;
      // justify-content: space-between;
      flex-wrap: wrap;
      .gupiao {
        width: 32%;
        height: 4.56rem;
        border-radius: 0.94rem;
        // box-shadow: 0px 0px 5px 2px #f4f4f4;
        padding: 0.09rem 0.19rem;
        margin: 0 0.6667% 0.41rem;

        .title {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      > .up {
        background-color: #fff3f5;
        // background-image: url('/src/static/image/market/up.png');
        border-radius: 0.625rem;
        background-size: 100%;
        background-repeat: no-repeat;
        background-position: bottom;
      }
      > .down {
        background-color: #e8f7ef;
        border-radius: 0.625rem;
        // background-image: url('/src/static/image/market/down.png');
        background-size: 100%;
        background-repeat: no-repeat;
        background-position: bottom;
      }
    }
    .hot_gupiao_wrap + .hot_gupiao_wrap {
      padding-top: 0;
    }
    .plus {
      border: 0.03rem solid #eceded;
      margin: 0.16rem 0.06rem;
      display: flex;
      -webkit-box-align: center;
      -webkit-align-items: center;
      align-items: center;
      -webkit-box-pack: center;
      -webkit-justify-content: center;
      justify-content: center;
    }
  }

  .gupiao_wrap {
    padding-top: 0.3rem;
    padding: 0.3rem 0.9375rem 0;
    .gupiao {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0.6875rem 1rem 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;
      }
    }
  }
}
</style>
