import ColHeader from '@/components/col-header'
import {
  Badge,
  Dialog,
  Divider,
  Icon,
  Image,
  PullRefresh,
  Sticky,
  Swipe,
  SwipeItem,
  Tab,
  Tabs
} from 'vant'
import { defineComponent } from 'vue'
import HotGoods from './components/hot-goods'
import MenuList from './components/menu-list'
import TabList from './components/tab-list'
import styles from './index.module.less'
import iconShopCart from './images/icon-shop-cart.png'
import request from '@/helpers/request'
import {
  listenerMessage,
  postMessage,
  removeListenerMessage
} from '@/helpers/native-message'
import ColSearch from '@/components/col-search'
import { browser, setAuth } from '@/helpers/utils'
import { cartCount, getCartCount } from './shop-mall'
import TheHomeHeader from './components/TheHomeHeader'

export default defineComponent({
  name: 'shop-mall',
  data() {
    return {
      loading: false,
      height: 'auto' as any,
      count: 0, // 购买车数量
      advertiseList: [], // 广告列表
      productList: [], // 商品分类
      hotProductList: [], // 热门商品列表
      productCategoryList: [] // 商品分类列表
    }
  },
  mounted() {
    this.init()

    console.log(this.$route.query)
    // if (browser().ios) {
    document.addEventListener('visibilitychange', event => {
      if (!document.hidden) {
        getCartCount()
        const tabFirst = this.$refs.tabFirst as any
        tabFirst?.onSearch()
      }
    })
    // }
    //  else {
    //   listenerMessage('UpdateToken', result => {
    //     if (result?.content.token) {
    //       setAuth(result?.content.token)
    //     }
    //     getCartCount()
    //     const tabFirst = this.$refs.tabFirst as any
    //     tabFirst?.onSearch()
    //   })
    // }
  },
  unmounted() {
    // removeListenerMessage('UpdateToken', () => {})
  },
  methods: {
    onRefresh() {
      this.productCategoryList = []
      this.$nextTick(() => {
        this.init()
      })
      const tabFirst = this.$refs.tabFirst as any
      tabFirst?.onSearch()
    },
    async init() {
      try {
        const res = await request.get('/api-mall-portal/home/content')
        const result = res.data || {}
        this.count = result.count
        cartCount.value = result.count
        this.advertiseList = result.advertiseList
        const category = result.productCategoryList || []
        const categoryResult: any = []
        while (category.length > 0) {
          const chunk = category.splice(0, 5)
          categoryResult.push(chunk)
        }
        this.productList = categoryResult
        this.hotProductList = result.hotProductList || []
        this.productCategoryList = result.productAttributeCategoryList || []
      } catch {}
      setTimeout(() => {
        this.loading = false
      }, 500)
    },
    openWebView(url: string): void {
      try {
        this.$router.push(url)
      } catch (error) {}
    }
  },
  render() {
    return (
      <div class={styles.shopMall}>
        <TheHomeHeader
          onCart={() => this.openWebView('/cart')}
          onSearch={() => this.openWebView('/goodsList?input=focus')}
          onMore={action => {
            if (!action) return
            this.openWebView(action.url)
          }}
        />
        <PullRefresh
          v-model={this.loading}
          loading-text="正在刷新..."
          success-text="刷新完成"
          onRefresh={() => this.onRefresh()}
        >
          <div class={styles.hotContent}>
            <Swipe class={styles.swipe} autoplay={3000} showIndicators={false}>
              {this.advertiseList.map((item: any) => (
                <SwipeItem onClick={() => this.openWebView(item.url)}>
                  <Image
                    class={styles.swipeItemImg}
                    src={item.pic}
                    fit="fill"
                  />
                </SwipeItem>
              ))}
            </Swipe>

            <MenuList
              productList={this.productList}
              onOpenWebView={this.openWebView}
            />
          </div>

          {this.hotProductList.length === 3 && (
            <HotGoods
              hotProductList={this.hotProductList}
              onOpenWebView={this.openWebView}
            />
          )}

          <Tabs
            shrink
            lineWidth={25}
            background={'#f6f8f9'}
            color="var(--van-primary)"
            class={styles.tabs}
            sticky
            offsetTop={this.height}
            lazyRender
          >
            <Tab title="全部" name={0}>
              <TabList
                ref="tabFirst"
                isTab={true}
                showAdd={false}
                productAttributeCategoryId={0}
                onOpenWebView={this.openWebView}
              />
            </Tab>
            {this.productCategoryList.map((item: any) => (
              <Tab title={item.name} name={item.id}>
                <TabList
                  isTab={true}
                  showAdd={false}
                  productAttributeCategoryId={item.id}
                  onOpenWebView={this.openWebView}
                />
              </Tab>
            ))}
          </Tabs>
        </PullRefresh>
      </div>
    )
  }
})
