<template>
  <view class="fav_box">
    <van-sticky>
      <view class="top-bar justify-center bg-white sh">
        <van-icon class="top-left" name="arrow-left" @tap="goBack" />
        <view class="top-center">
          <van-tabs class="top_tab" v-model:active="state.tab.active">
            <van-tab v-for="item in state.tab.list" :title="item.title" :name="item.name" />
          </van-tabs>
        </view>
        <view class="top-right" @tap="onEdit">
          <view class="text-m" :class="[state.edit ? 'text-orange' : 'text-gray']">{{ state.edit ? '完成' : '编辑' }}</view>
        </view>
      </view>
    </van-sticky>
    <view v-show="state.tab.active == 'product'">
      <van-pull-refresh v-model="state.product.refresh" @refresh="favProductList()">
        <view v-if="state.product.list.length > 0">
          <van-checkbox-group class="pd-b-px-50" v-model="state.product.selected"
            style="min-height: calc(100vh - 180px)">
            <template v-for="gItem in state.product.list">
              <view class="text-blue pd-v-10 pd-h-25" v-if="gItem.splitTitle">
                {{ gItem.splitTitle }}
              </view>
              <van-swipe-cell v-else>
                <van-cell class="pd-l-0">
                  <view class="flex">
                    <view class="justify-center" style="width: 40px" v-if="state.edit">
                      <van-checkbox icon-size="17px" :name="gItem" @tap="onProductCheck()" />
                    </view>
                    <view v-else style="margin-left: 28rpx"/>
                    <view class="justify-middle" style="position:relative" @tap="onProduct(gItem)">
                      <van-image height="88px" width="88px" fit="cover" :src="gItem.imgPath"
                        loading-icon="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/default1.png" icon-size="88px" />
                    </view>
                    <view class="pd-l-20" @tap="onProduct(gItem)">
                      <view class="text-m ellipsis line_over2 pd-b-25" style="width: calc(100vw - 340rpx);min-height: 36px">
                        {{ gItem.title }}
                      </view>
                      <view class="justify-between justify-middle text-s">
                        <text style="width: calc(100vw - 340rpx);">规格：{{ gItem.size }}</text>
                      </view>
                      <template v-if="gItem.salePrice">
				    <div v-if="gItem.actPrice">
					    <text class="text-gray text-s mg-t-5-m pd-r-10 line-through">优惠价：￥{{ gItem.salePrice }}</text>
					    <text class="text-gray text-s mg-t-5-m ">零售价：￥{{ gItem.productPrice }}</text>
				    </div>
				    <div v-else>
					    <text class="text-orange text-s mg-t-5-m pd-r-10">优惠价：￥{{ gItem.salePrice }}</text>
					    <text class="text-gray text-s mg-t-5-m line-through">零售价：￥{{ gItem.productPrice }}</text>
				    </div>
                      </template>
                      <template v-else>
                        <text class="text-gray text-s mg-t-5-m line-through" v-if="gItem.actPrice" >零售价：￥{{ gItem.productPrice }}</text>
				    <text class="text-orange text-s mg-t-5-m" v-if="!gItem.actPrice" >零售价：￥{{ gItem.productPrice }}</text>
                      </template>
				  <p v-if="gItem.actPrice" class="text-orange text-s mg-t-5-m text-bold" style="margin-top: .1rem">活动价：￥{{ gItem.actPrice }}</p>
                    </view>
                  </view>
                  <template #right-icon>
                    <view class="justify-middle">
                      <img @tap="cartAdd(gItem.skuId)" wi src="/static/img/car_search.png" style="width: 1.8rem">
                    </view>
                  </template>
                </van-cell>
                <template #right>
                  <van-button class="swipe_btn" type="danger" text="删除" @tap="productDel([gItem])" />
                </template>
              </van-swipe-cell>
            </template>
          </van-checkbox-group>
        </view>
        <view v-else class="justify-center" style="min-height: calc(100vh - 180px)">
          <van-empty description="您还没有收藏商品" />
          <van-button class="text-l" color="linear-gradient(315deg, #FE521F 0%, #FE7902 100%)" round block
            style="width: 240rpx" @tap="goto('/')">
            去逛逛
          </van-button>
        </view>
      </van-pull-refresh>
      <van-action-bar v-if="state.product.list.length > 0 && state.edit"
        class="pd-l-30 custom-width justify-between pd-r-20 sh-t">
        <van-checkbox class="text-m" icon-size="17px" v-model="state.product.all" @tap="onProductAll()">全选
        </van-checkbox>
        <van-action-bar-button style="width: 240rpx;" type="danger" text="取消收藏"
          @tap="askSelected('商品', productDel, state.product.selected)" />
      </van-action-bar>
    </view>
    <view v-show="state.tab.active == 'brand'">
      <van-pull-refresh v-model="state.brand.refresh" @refresh="favBrandList()">
        <view v-if="state.brand.list.length > 0">
          <van-checkbox-group class="pd-b-px-50" v-model="state.brand.selected" style="min-height: calc(100vh - 180px)">
            <template v-for="bItem in state.brand.list">
              <van-swipe-cell>
                <van-cell class="pd-l-0">
                  <view class="flex">
                    <view class="justify-center" style="width: 40px" v-if="state.edit">
                      <van-checkbox icon-size="17px" :name="bItem" @tap="onBrandCheck()" />
                    </view>
                    <view v-else style="margin-left: 28rpx"/>
                    <view class="justify-middle" style="position:relative" @tap="onBrand(bItem)">
                      <van-image height="88px" width="88px" fit="cover" :src="bItem.imgPath"
                        loading-icon="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/default1.png" icon-size="88px" />
                    </view>
                    <view class="pd-l-20" @tap="onBrand(bItem)">
                      <view class="text-m ellipsis line_over2 pd-v-20" style="width: calc(100vw - 160px);min-height: 36px">
                        {{ bItem.name }}
                      </view>
                      <text class="text-gray text-s mg-t-5-m">商品数量：{{ bItem.sales }}</text>
                    </view>
                  </view>
                </van-cell>
                <template #right>
                  <van-button class="swipe_btn" type="danger" text="删除" @tap="brandDel([bItem])" />
                </template>
              </van-swipe-cell>
            </template>
          </van-checkbox-group>
        </view>
        <view v-else class="justify-center" style="min-height: calc(100vh - 180px)">
          <van-empty description="您还没有收藏品牌" />
          <van-button class="text-l" color="linear-gradient(315deg, #FE521F 0%, #FE7902 100%)" round block
            style="width: 240rpx" @tap="goto('/')">
            去逛逛
          </van-button>
        </view>
      </van-pull-refresh>
      <van-action-bar v-if="state.brand.list.length > 0 && state.edit"
        class="pd-l-30 custom-width justify-between pd-r-20 sh-t">
        <van-checkbox class="text-s" icon-size="17px" v-model="state.brand.all" @tap="onBrandAll()">全选
        </van-checkbox>
        <van-action-bar-button style="width: 240rpx;" type="danger" text="取消收藏"
          @tap="askSelected('品牌', brandDel, state.brand.selected)" />
      </van-action-bar>
    </view>
  </view>
</template>

<script setup lang="ts">
import api from '@/api'
import { nextTick, onBeforeMount, reactive } from 'vue';
import { PageUtils } from '@/utils/utils';
import { Dialog, Toast } from 'vant'
const state = reactive({
    aa:['https://img.edsmall.com/ewy/resource/image/5e41e82b-6d58-4090-8de7-ec726f144acc.png','https://img.edsmall.com/ewy/resource/image/5e41e82b-6d58-4090-8de7-ec726f144acc.png'],
  tab: {
    active: 'product',
    list: [
      { title: '商品', name: 'product' },
      { title: '店铺', name: 'brand' }
    ]
  },
  product: {
    all: false,
    selected: [] as any,
    loading: false,
    list: [] as any,
    orignList: [] as any,
    refresh: false
  },
  brand: {
    all: false,
    selected: [] as any,
    loading: false,
    list: [] as any,
    refresh: false
  },
  edit: false,
})

onBeforeMount(() => {
  favProductList()
  favBrandList()
})

function goBack() {
  PageUtils.goBack()
}
function favProductList() {
  let weekAgo: any = new Date().getTime() - (7 * 24 * 60 * 60 * 1000)
  if (state.product.loading) return
  state.product.loading = true
  api.favProductList({ link: uni.getStorageSync('subdomain') }).then((data: any) => {
    const list = []
    if (data.length > 0) {
      list.push({ splitTitle: '#最近1周' })
    }
    data.forEach((item: any) => {
      if (weekAgo && weekAgo > item.addDate) {
        list.push({ splitTitle: '#1周之后' })
        weekAgo = undefined
        list.push(item)
      } else {
        list.push(item)
      }
    })
    state.product.all = false
    state.product.selected = []
    state.product.orignList = data
    state.product.list = list
  }).finally(() => {
    state.product.refresh = false
    state.product.loading = false
  })
}
function favBrandList() {
  if (state.brand.loading) return
  state.brand.loading = true
  api.favBrandList({ link: uni.getStorageSync('subdomain') }).then((data: any) => {
    state.brand.all = false
    state.brand.selected = []
    state.brand.list = data
  }).finally(() => {
    state.brand.refresh = false
    state.brand.loading = false
  })
}
function goto(url: any) {
  url && uni.navigateTo({ url })
}
function onProduct(gItem: any) {
  if (!gItem.saleable) {
    Toast('商品已下架');
  } else if (gItem.moq > gItem.stock) {
    Toast('暂时无货');
  } else if (!gItem.isBrandAgent) {
    Toast('商家未代理该品牌');
  } else {
    goto(`/pages/good/detail?skuId=${gItem.skuId}&spuId=${gItem.spuId}`)
  }
}
function productDel(list: Array<any>) {
  const skuIds = list.map((item: any) => item.skuId)
  if (state.product.loading) return
  state.product.loading = true
  api.productDel({ skuIds }).then((data: any) => {
    state.product.loading = false
    favProductList()
  }).catch(() => {
    state.product.loading = false
  })
}
function brandDel(list: Array<any>) {
  const brandIds = list.map((item: any) => item.brandId)
  if (state.brand.loading) return
  state.brand.loading = true
  api.brandDel({ brandIds }).then((data: any) => {
    state.brand.loading = false
    favBrandList()
  }).catch(() => {
    state.brand.loading = false
  })
}
function onEdit() {
  state.edit = !state.edit
}
function askSelected(targetName: string, fn: Function, selected: any) {
  if (selected.length == 0) {
    Toast('请勾选' + targetName)
    return
  }
  Dialog.confirm({
    message: '是否取消收藏选中' + targetName,
    title: "提示"
  }).then(() => {
    fn(selected)
  })
}
function onProductAll() {
  if (state.product.all) {
    state.product.selected = [...state.product.orignList]
  } else {
    state.product.selected = []
  }
}
function onBrandAll() {
  if (state.brand.all) {
    state.brand.selected = [...state.brand.list]
  } else {
    state.brand.selected = []
  }
}
function cartAdd(skuId: string) {
  if (state.product.loading) return
  state.product.loading = true
  api.cartAdd({
    skuId: skuId,
    link: uni.getStorageSync('subdomain'),
    productQty: 1, // B端去除起订量限制 skuData.value.moq
  }).then(() => {
    Toast.success('加入购物车')
  }).finally(() => {
    state.product.loading = false
  })
}
function onProductCheck() {
  nextTick(() => {
    if (state.product.selected.length == state.product.orignList.length) {
      state.product.all = true
    } else {
      state.product.all = false
    }
  })
}
function onBrand(bItem: any) {
  if (!bItem.isBrandAgent) {
    Toast('商家未代理该品牌');
  } else {
    goto(`/pages/good/brandShop?brandId=${bItem.brandId}`)
  }
}
function onBrandCheck() {
  nextTick(() => {
    if (state.brand.selected.length == state.brand.list.length) {
      state.brand.all = true
    } else {
      state.brand.all = false
    }
  })
}
</script>

<style lang="scss" scoped>
.top_tab {
  width: 50vw;
}

.fav_box {
  .van-cell {
    line-height: 18px !important;
  }
}

.swipe_btn {
  height: 100%;
  width: 100rpx;
  padding: 0;
  font-size: 26rpx;
}
</style>
