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 { useRect } from '@vant/use'
import { postMessage } from '@/helpers/native-message'
import ColSearch from '@/components/col-search'
import { browser } from '@/helpers/utils'

export default defineComponent({
  name: 'shop-mall',
  data() {
    return {
      loading: false,
      height: 'auto' as any,
      count: 0, // 购买车数量
      advertiseList: [], // 广告列表
      productList: [], // 商品分类
      hotProductList: [], // 热门商品列表
      productCategoryList: [] // 商品分类列表
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    onSearch() {},
    async init() {
      try {
        const res = await request.get('/api-mall-portal/home/content')
        console.log(res)
        const result = res.data || {}
        this.count = 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 {
      // console.log(url)
      let dev = false
      let origin = location.origin + location.pathname + '#'
      if (!url) return

      if (url.indexOf('http') < 0) {
        url = origin + url
      }
      console.log('跳转url:', url)
      if (!browser().isApp) {
        location.href = url
        return
      }
      postMessage({
        api: 'openWebView',
        content: {
          url: url,
          orientation: 1,
          isHideTitle: false
        }
      })
    }
  },
  render() {
    return (
      <div>
        <div ref="headers">
          <ColHeader
            border={false}
            background="linear-gradient(#59e5d5, 30%, #f6f8f9)"
            onClickRight={() => this.openWebView('/cart')}
            v-slots={{
              right: () => (
                <div class={styles['icon-shop-cart']}>
                  <Badge
                    class={styles.iconBadge}
                    showZero={false}
                    offset={[-8, 8]}
                    color="rgba(236,92,50,1)"
                    content={this.count}
                  >
                    <Icon name={iconShopCart} size={30} />
                  </Badge>
                </div>
              )
            }}
            onHeaderBack={() => {
              this.$nextTick(() => {
                const { height } = useRect((this as any).$refs.headers)
                this.height = height - 1
              })
            }}
          />
        </div>
        <PullRefresh
          v-model={this.loading}
          loading-text='正在刷新...'
          success-text="刷新完成"
          onRefresh={() => this.init()}
        >
          <div
            onClick={() => {
              this.openWebView('/goodsList?input=focus')
            }}
          >
            <ColSearch
              disabled
              class={styles.searchBox}
              background="transparent"
            />
          </div>
          <Swipe
            class={styles.swipe}
            autoplay={3000}
            showIndicators={false}
            lazyRender
          >
            {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}
          />

          {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
          >
            {this.productCategoryList.length > 0 && (
              <Tab title="全部" name={0}>
                <TabList
                  isTab={true}
                  productAttributeCategoryId={0}
                  onOpenWebView={this.openWebView}
                />
              </Tab>
            )}
            {this.productCategoryList.map((item: any) => (
              <Tab title={item.name} name={item.id}>
                <TabList
                  isTab={true}
                  productAttributeCategoryId={item.id}
                  onOpenWebView={this.openWebView}
                />
              </Tab>
            ))}
          </Tabs>
        </PullRefresh>
      </div>
    )
  }
})
