view
<template>
  <view class="pd-b-px-95">
    <van-sticky>
      <view class="top-bar justify-center bg-white sh">
        <van-icon class="top-left" name="arrow-left" @tap="goBack" />
        <text class="top-center">{{ '购物车' + (state.cart.num ? `(${state.cart.num})` : '') }}</text>
        <text class="top_right" :class="[state.cart.edit ? 'text-orange' : 'text-gray']" @tap="onCartEdit">
          {{ state.cart.edit ? '完成' : '编辑' }}
        </text>
      </view>
    </van-sticky>
    <van-pull-refresh v-model="state.refresh" @refresh="cartList()">
      <view v-if="state.cart.list.length > 0">
        <view style="min-height: calc(100vh - 180px)" v-if="state.switch.newView">
          <van-cell-group inset class="mg-v-40" v-for="(bItem, index) in state.cart.list">
            <van-cell v-if="state.switch.brand" value-class="flex" :border="false">
              <van-checkbox icon-size="17px" v-model="bItem.all" @tap="() => { onCheck(bItem); onItemAll(index) }" />
              <view class="pd-l-20 text-s" @tap="goto(``)">
                {{ bItem.brand.name }}
                <van-icon name="arrow" />
              </view>
            </van-cell>
            <van-divider v-if="state.switch.brand" class="mg-v-0" />
            <van-checkbox-group icon-size="17px" v-model="bItem.select"
              :ref="(el: any) => { if (el) items[index] = el }">
              <van-swipe-cell v-for="gItem in bItem.list">
                <van-cell>
                  <view class="flex">
                    <!-- 编辑时，放开选择 -->
                    <van-checkbox :name="gItem" @tap="onCheck(bItem, gItem)"
                      :disabled="!state.cart.edit && isUnselectable(gItem)" />
                    <van-image class="pd-l-20" height="156rpx" width="156rpx" fit="cover" :src="gItem.mainImg"
                      @tap="onGood(gItem)" loading-icon="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/default1.png"
                      icon-size="156rpx" />
                    <view class="pd-l-20">
                      <view class="ellipsis text-s" style="width: calc(100vw - 360rpx);">{{ gItem.title }}</view>
                      <view class="justify-between justify-middle mg-b-10 pd-h-15 bg-gray text-ss"
                        style="border-radius: 5rpx;height: 23px" @tap="onChangeGood(bItem, gItem)">
                        <view class="ellipsis" style="width: calc(100vw - 410rpx);">{{ gItem.info }}</view>
                        <van-icon v-if="state.switch.changeGood" name="arrow-down" />
                      </view>
                      <view class="flex justify-middle">
                        <van-image width="30px" height="16px" :src="gItem.zoneIcon" />
                        <text v-if="state.switch.delivery" class="text-ss text-yellow pd-l-50">
                          交货期：{{ gItem.deliveryTimeStr }}
                        </text>
                        <text v-if="state.switch.stock" class="text-ss text-yellow pd-l-50">
                          库存：{{ gItem.stock }}
                        </text>
                      </view>
                    </view>
                  </view>
                  <view class="flex">
                    <view class="text-center mg-l-50 mg-r-20" style="width: 160rpx">
                      <text class="text-red text-ss scale-85 scale-t" v-if="!gItem.saleable">商品已下架</text>
                      <text class="text-red text-ss scale-85 scale-rt" v-else-if="gItem.moq > gItem.stock">暂时无货</text>
                      <text class="text-red text-ss scale-85 scale-rt" v-else-if="!gItem.isBrandAgent">商家未代理该品牌</text>
                    </view>
                    <view style="width: calc(100vw - 360rpx);">
                      <template v-if="gItem.salePrice !== null">
                        <view class="text-gray text-ss scale-85 scale-lt mg-t-5-m">零售价：￥{{ gItem.productPrice }}</view>
                        <view class="justify-between justify-middle mg-t-10-m">
                          <view class="text-darkGray text-bold text-ss">优惠价：￥{{ gItem.salePrice }}</view>
                          <van-stepper :disabled="isUnselectable(gItem)" v-model="gItem.productQty" theme="round"
                            button-size="15px" :before-change="(num) => beforeCartModify(num, gItem)" :min="gItem.moq"
                            :max="gItem.stock" @focus="onStepperFocus(gItem)" />
                        </view>
                      </template>
                      <template v-else>
                        <view class="justify-between justify-middle mg-t-10-m">
                          <view class="text-darkGray text-bold text-ss">零售价：￥{{ gItem.productPrice }}</view>
                          <van-stepper :disabled="isUnselectable(gItem)" v-model="gItem.productQty" theme="round"
                            button-size="15px" :before-change="(num) => beforeCartModify(num, gItem)" :min="gItem.moq"
                            :max="gItem.stock" @focus="onStepperFocus(gItem)" />
                        </view>
                      </template>
                    </view>
                  </view>
                  <view v-if="state.switch.cartRemark"
                    class="justify-middle justify-middle mg-l-80 mg-t-20 mg-b-5 pd-l-20 pd-r-10 bg-gray"
                    style="border-radius: 5rpx;height: 28px;width: calc(100vw - 235rpx);">
                    <view class="text-ss text-darkGray">商品备注</view>
                    <view class="text-ss pd-h-15 ellipsis" style="width: calc(100vw - 370rpx);"
                      @tap="onChangeRemark(gItem)">
                      <text class="text-black ellipsis" v-if="gItem.remark">{{ gItem.remark }}</text>
                      <text class="text-gray ellipsis" v-else>选填，请先和商家协商一致</text>
                    </view>
                  </view>
                </van-cell>
                <template #right>
                  <van-button class="swipe_btn" square type="primary" @tap="onCollect([gItem])">移入<br />收藏夹</van-button>
                  <van-button class="swipe_btn" type="danger" text="删除" @tap="onDelete([gItem])" />
                </template>
              </van-swipe-cell>
            </van-checkbox-group>
          </van-cell-group>
        </view>
        <view style="min-height: calc(100vh - 180px)" v-else>
          <van-cell-group class="mg-v-px-10" v-for="(bItem, index) in state.cart.list">
            <van-divider v-if="state.switch.brand" class="mg-v-0" />
            <van-checkbox-group icon-size="17px" v-model="bItem.select"
              :ref="(el: any) => { if (el) items[index] = el }">
              <van-swipe-cell v-for="gItem in bItem.list">
                <van-cell :border="false">
                  <view class="flex">
                    <van-checkbox :name="gItem" @tap="onCheck(bItem, gItem)"
                      :disabled="!state.cart.edit && (isUnselectable(gItem))" />
                    <view class="justify-middle" style="position:relative" @tap="onGood(gItem)">
                      <van-image class="pd-l-px-10" height="110px" width="110px" fit="cover" :src="gItem.mainImg"
                        loading-icon="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/default1.png" icon-size="110px" />
				  <!--购物车活动角标-->
				  <div class="sign" v-if="gItem.subScriptImgUrl">
				  <img :src="gItem.subScriptImgUrl" alt="" />
				  <div class="discount" style="color: rgba(247, 103, 67, 1)">{{gItem.discount}}</div>
				  </div>
				  <span v-for="(item,index) in gItem.leftDownIcons" :key="index" :style="{left:index*35+'px'}" style="position:absolute;bottom:0;">
					  <van-image   width="32px" height="16px"
							   :src="item" />
				  </span>
                    </view>
                    <view class="pd-l-px-10" @tap="onGood(gItem)">
                      <view class="text-m ellipsis line_over2" style="width: calc(100vw - 180px)">{{
                          gItem.title
                      }}</view>
                      <view class="justify-between justify-middle text-m" style="height: 23px">
                        <view style="width: calc(100vw - 180px);">规格：{{ gItem.info }}</view>
                      </view>
                      <template v-if="gItem.salePrice">
                        <view class="text-gray text-m mg-t-5-m" v-if="gItem.actPrice">零售价：￥{{ gItem.productPrice }}</view>
				    <view class="text-gray text-m mg-t-5-m line-through" v-else>零售价：￥{{ gItem.productPrice }}</view>
                          <view class="text-gray line-through" v-if="gItem.actPrice">优惠价：￥{{ gItem.salePrice }}</view>
				    <view class="text-orange text-m mg-t-5-m" v-else>优惠价：￥{{ gItem.salePrice }}</view>
				    <view v-if="gItem.actPrice" class="text-orange text-ss">活动价￥
					    <text class="text-bold text-l">{{ gItem.actPrice }}</text>
				    </view>
                      </template>
                      <template v-else>
				    <view v-if="gItem.actPrice">
					    <view class="text-gray text-ss line-through">零售价￥{{ gItem.productPrice }}</view>
					    <view class="text-orange text-ss">活动价￥
						    <text class="text-bold text-l">{{ gItem.actPrice }}</text>
					    </view>
				    </view>
				    <text v-else class="text-orange text-m mg-t-5-m" >零售价￥{{ gItem.productPrice }}</text>
                      </template>
                    </view>
                  </view>
                </van-cell>
                <van-divider class="mg-v-0" />
                <van-cell>
                  <view class="justify-between">
                    <view>
                      <text class="text-red text-l" v-if="!gItem.saleable">商品已下架</text>
                      <text class="text-red text-l" v-else-if="gItem.moq > gItem.stock">暂时无货</text>
                      <text class="text-red text-l" v-else-if="!gItem.isBrandAgent">商家未代理该品牌</text>
                      <text class="text-l" v-else>商品可售</text>
                    </view>
                    <van-stepper :disabled="isUnselectable(gItem)" v-model="gItem.productQty" button-size="25px"
                      input-width="60px" :before-change="(num) => beforeCartModify(num, gItem)" :min="gItem.moq"
                      :max="gItem.stock" @focus="onStepperFocus(gItem)" />
                  </view>
                  <view v-if="state.switch.cartRemark"
                    class="justify-middle justify-middle mg-l-80 mg-t-20 mg-b-5 pd-l-20 pd-r-10 bg-gray"
                    style="border-radius: 5rpx;height: 28px;width: calc(100vw - 235rpx);">
                    <view class="text-ss text-darkGray">商品备注</view>
                    <view class="text-ss pd-h-15 ellipsis" style="width: calc(100vw - 370rpx);"
                      @tap="onChangeRemark(gItem)">
                      <text class="text-black ellipsis" v-if="gItem.remark">{{ gItem.remark }}</text>
                      <text class="text-gray ellipsis" v-else>选填，请先和商家协商一致</text>
                    </view>
                  </view>
                </van-cell>
                <view class="text-red text-ss pd-h-10 pd-v-15" style="background: #fffaf7">
                  工厂库存：{{ gItem.stock }}
                </view>
                <template #right>
                  <van-button class="swipe_btn" square type="primary" @tap="onCollect([gItem])">移入<br />收藏夹</van-button>
                  <van-button class="swipe_btn" type="danger" text="删除" @tap="onDelete([gItem])" />
                </template>
              </van-swipe-cell>
            </van-checkbox-group>
          </van-cell-group>
        </view>
      </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.cart.list.length > 0"
      class="mg-b-px-50 pd-l-30 pd-r-20 custom-width justify-between sh-t">
      <van-checkbox class="text-m" icon-size="17px" v-model="state.all" @tap="onItemAll()">全选</van-checkbox>
      <view class="justify-between justify-middle">
        <template v-if="state.cart.edit">
          <van-action-bar-button style="width: 180rpx;" type="danger" text="删除"
            @tap="ask('是否删除选中商品', onDelete, selected)" />
          <van-action-bar-button style="width: 180rpx;" type="warning" text="移入收藏夹"
            @tap="ask('是否收藏选中商品', onCollect, selected)" />
        </template>
        <template v-else>
          <view class="text-right text-black pd-r-20">
            <view class="text-m">合计:<text class="text-orange">￥</text><text class="text-orange text-xl text-bold">{{ state.sum }}</text></view>
            <view v-if="state.switch.discount" class="text-s">已优惠:￥<text class="text-l text-bold">0.00</text></view>
          </view>
          <van-action-bar-button style="width: 220rpx;" color="#ff6600" type="primary" :text="`去结算(${selected.length})`"
            @tap="onCartCheck(selected)" />
        </template>
      </view>
    </van-action-bar>
    <van-dialog v-model:show="state.remark.show" show-cancel-button @confirm="onSetRemark">
      <van-field v-model="state.remark.value" rows="3" autosize type="textarea" placeholder="选填，请先和商家协商一致" />
    </van-dialog>
    <van-form @submit="onNumChange" class="round">
      <van-dialog class="withBg pd-b-px-70" v-model:show="state.num.show" theme="round-button" width="264px">
        <template #title>
          <view class="pd-h-px-20">
            <view class="mg-t-px-10-m text-bold">设置商品数量</view>
            <!-- 起订量固定为1就不提示了 -->
            <view class="text-gray text-s" style="min-height: 20px;">库存：{{ state.num.gItem.stock }}</view>
          </view>
        </template>
        <view class="pd-h-px-20 pd-v-px-10">
          <van-field v-model="state.num.value" ref="numField" :class="{ 'field-focus': state.focus == 'num' }"
            type="digit" placeholder="请输入商品数量" @focus="onFocus('num')" @blur="onFocus('')" clearable autocomplete="off"
            clear-trigger="always" />
        </view>
        <template #footer>
          <van-action-bar class="pd-h-px-15 pd-b-px-15">
            <van-action-bar-button type="warning" text="取消" @tap="state.num.show = false" />
            <van-action-bar-button type="danger" text="保存" native-type="submit" />
          </van-action-bar>
        </template>
      </van-dialog>
    </van-form>
  </view>
</template>

<script setup lang="ts">
import api from '@/api';
import { Toast } from "vant";
import { computed, nextTick, onBeforeMount, reactive, ref } from 'vue';
import { Dialog } from "vant";
import { PageUtils } from '@/utils/utils';
const state = reactive({
  cart: {
    num: 0,
    edit: false,
    list: [] as any,
  },
  all: false,
  remark: {
    show: false,
    gItem: {} as any,
    value: ''
  },
  num: {
    show: false,
    value: '',
    gItem: {} as any
  },
  focus: '',
  loading: false,
  loadingSon: {
    num: false
  },
  refresh: false,
  sum: 0,
  switch: {
    changeGood: false, // 变更规格
    cartRemark: false, // 购物车备注
    delivery: false, // 交货期
    brand: false, // 品牌
    discount: false, // 优惠价
    // ----旧----
    stock: true, // 库存
    // ----新UI----
    newView: false
  },
})
const items: any = ref([])
const numField: any = ref()
const selected = computed(() => {
  if (!state.cart.list) return []
  let _list: any = []
  state.cart.list.forEach((item: any) => _list.push(...item.select))
  if (!state.cart.edit) {
    nextTick(() => {
      onSettle(selected.value)
    })
  }
  return _list
})
const emit = defineEmits(["setCartCount"]);

onBeforeMount(() => {
  const { token } = uni.getStorageSync("user") || {};
  if (token) {
    cartList()
  } else {
      if(window.__wxjs_environment === 'miniprogram'){
          window._wx.miniProgram.redirectTo({ url: "/pages/login/login" })
	}else {
          Dialog.confirm({
              message: '您尚未登录，请前往登录',
              title: "提示",
              cancelButtonText: '返回首页'
          }).then(() => {
              uni.reLaunch({
                  url: '/pages/login/login'
              })
          }).catch(() => {
              uni.reLaunch({
                  url: '/'
              })
          });
	}
  }
})

function onCartEdit() {
  // 从编辑状态返回时，去除不可选商品
  if (state.cart.edit) {
    state.cart.list.forEach((bItem: any) => {
      const select: any = []
      bItem.select.forEach((gItem: any) => {
        if (!isUnselectable(gItem)) select.push(gItem)
      })
      bItem.select = select
    })
  }
  state.cart.edit = !state.cart.edit
  onCheck()
}
function isUnselectable(gItem: any) {
  return !gItem.saleable || gItem.moq > gItem.stock || !gItem.isBrandAgent
}
/**
 * 
 * 有{index}单个品牌的选择按钮-需要勾选那“一个品牌”的“全部商品”
 * 有{}全选按钮-需要设置“全部品牌”、“全部商品”
 *  */
function onItemAll(index?: number) {
  if (state.cart.edit) {
    nextTick(() => {
      if (index != undefined) {
        const bItem = state.cart.list[index]
        bItem.select = bItem.all ? bItem.list : []
      } else {
        state.cart.list.forEach((bItem: any) => {
          bItem.select = state.all ? bItem.list : []
          bItem.all = state.all
        })
      }
    })
  } else {
    nextTick(() => {
      if (index != undefined) {
        const bItem = state.cart.list[index]
        if (bItem.all) {
          // 选择能选上的
          const select: any = []
          bItem.list.forEach((gItem: any) => {
            if (!isUnselectable(gItem)) select.push(gItem)
          })
          bItem.select = select
        } else {
          bItem.select = []
        }
      } else {
        if (state.all) {
          state.cart.list.forEach((bItem: any) => {
            bItem.all = true
            // 选择能选上的
            const select: any = []
            bItem.list.forEach((gItem: any) => {
              if (!isUnselectable(gItem)) select.push(gItem)
            })
            bItem.select = select
          })
        } else {
          state.cart.list.forEach((bItem: any) => {
            bItem.all = false
            bItem.select = []
          })
        }
      }
    })
  }
}
function goto(url: any) {
  url && uni.navigateTo({ url })
}
function onChangeRemark(gItem: any) {
  state.remark.value = gItem.remark
  state.remark.gItem = gItem
  state.remark.show = true
}
function onSetRemark() {
  state.remark.gItem.remark = state.remark.value
  state.remark.gItem = undefined
  state.remark.show = true
}
function beforeCartModify(num: number, gItem: any): any {
  if (state.loading) return
  state.loading = true
  return new Promise((resolve, reject) => {
    api.cartModify({
      cartId: gItem.cartId,
      link: uni.getStorageSync('subdomain'),
      productQty: num
    })
      .then(() => {
        state.loading = false
        if (selected.value.find((item: any) => item.cartId == gItem.cartId)) {
          onSettle(selected.value)
        }
        resolve(true)
      })
      .catch(() => {
        state.loading = false
        reject(false)
      })
  });
}
function onCartCheck(list: Array<any>) {
    // 暂时屏蔽功能
    // const isWxjs_environment = uni.getStorageSync("isWxjs_environment") || false;
    // if(isWxjs_environment){
    //     Toast.loading({
    //         message: '正在优化订单，暂时无法支付！',
    //         forbidClick: true,
    //     });
    //     return
    // }

  if (state.loading) return
  if (list.length == 0) {
    Toast('请选择商品')
    return
  }
  state.loading = true
  api.cartCheck({
    cartIds: list.map((item: any) => item.cartId),
    link: uni.getStorageSync('subdomain')
  })
    .then(() => {
      let carts = []
      list.forEach(item => {
        carts.push({ cartId: item.cartId, count: item.productQty, skuId: item.skuId })
      })
      state.loading = false
      uni.navigateTo({
        url: '/pages/order/beforeconfirm?list=' + encodeURIComponent(JSON.stringify(carts)),
      })
    })
    .catch(() => {
      state.loading = false
    })
}
function onSettle(list: Array<any>) {
  if (state.loading) return
  if (list.length == 0) {
    state.sum = 0
    return
  }
  state.loading = true
  api.cartSettle({
    cartIds: list.map((item: any) => item.cartId),
    link: uni.getStorageSync('subdomain')
  })
    .then((data: any) => {
      state.sum = data.settlePrice
      state.loading = false
    })
    .catch(() => {
      state.loading = false
    })
}
function onDelete(list: Array<any>) {
  if (state.loading) return
  state.loading = true
  api.cartRemove(list.map((item: any) => item.cartId))
    .then(() => {
      state.loading = false
      cartList()
    })
    .catch(() => {
      state.loading = false
    })
}
function onCollect(list: Array<any>) {
  if (state.loading) return
  state.loading = true
  api.productFav({
    link: uni.getStorageSync('subdomain'),
    skuIds: list.map((item: any) => item.skuId)
  }).then((data: any) => {
    state.loading = false
    onDelete(list)
  }).catch(() => {
    state.loading = false
  })
}
/**
 *  ---这个函数只计算checkBox的勾选状态---
 *  有{bItem,gItem(变更勾选状态)}单个商品选择-(会影响那一个商品对应“一个品牌”、“全选”勾选状态>所以重新计算)
 *  有{bItem(变更勾选状态)}单个品牌选择-(会影响“全选”勾选状态>所以重新计算)
 *  有{}-编辑状态变更时-(重新计算“全部品牌”、“全选”勾选状态)
 *  */
function onCheck(bItem?: any, gItem?: any) {
  if (state.cart.edit) {
    nextTick(() => {
      let all = true
      // gItem单个商品选择选择时，重新计算bItem单个品牌勾选
      if (gItem && bItem) {
        if (bItem.select.length != bItem.list.length) {
          bItem.all = false
        } else {
          bItem.all = true
        }
      } else if (!gItem && !bItem) {
        state.cart.list.forEach((bItem: any) => {
          // 是否单个品牌全选
          if (bItem.select.length == bItem.list.length) {
            bItem.all = true
          } else {
            bItem.all = false
          }
        })
      }

      // 重新计算全选按钮
      all = !state.cart.list.find((_bItem: any) => {
        return !_bItem.all
      })
      state.all = all
    })
  } else {
    nextTick(() => {
      let all = true
      if (gItem && bItem) {
        // gItem单个商品选择选择时，重新计算bItem单个品牌勾选
        if (bItem.select.length != bItem.selectableNum) {
          bItem.all = false
        } else if (bItem.selectableNum == 0) {
          bItem.all = false // 无意义，因为非编辑状态，它一直为false
        } else {
          bItem.all = true
        }
      } else if (!gItem && !bItem) {
        state.cart.list.forEach((bItem: any) => {
          // 是否单个品牌全选
          if (bItem.select.length == bItem.selectableNum) {
            bItem.all = true
          } else {
            bItem.all = false
          }
        })
      }
      // 重新计算全选按钮
      all = !state.cart.list.find((_bItem: any) => {
        // 因为selectableNum=0的品牌一直为false，跳过这些品牌
        return _bItem.selectableNum != 0 && !_bItem.all
      })
      state.all = all
    })
  }
}
function onChangeGood(bItem: any, gItem: any) {
  if (!state.switch.changeGood) false
  console.log('ljong:onChangeGood', bItem, gItem)
}
function cartList() {
  if (state.loading) return
  state.loading = true
  api.cartList({ link: uni.getStorageSync('subdomain') })
    .then((data: any) => {
      state.all = false
      // 这个结构是为了之后准备的
      state.cart.num = data.total
      emit("setCartCount", state.cart.num)
      state.cart.list = data.goods.map((item: any, index: number) => {
        return {
          all: false,
          select: [],
          selectableNum: (!item.saleable || 1 > item.stock || !item.isBrandAgent) ? 0 : 1, // 运算出可选数量
          brand: {
            name: '新版本-品牌名',
            id: item.brandId
          },
          list: [{
              leftDownIcons:item.leftDownIcons,
              subScriptImgUrl:item.subScriptImgUrl,
              discount:item.discount,
              actPrice:item.actPrice,
            cartId: item.cartId,
            skuId: item.skuId,
            title: item.title,
            info: item.size,
            mainImg: item.mainImg,
            zoneIcon: item.zoneIcon,
            deliveryTimeStr: '', // 新版本-备注
            salePrice: item.salePrice,
            stock: item.stock,
            productPrice: item.productPrice,
            productQty: item.productQty,
            remark: '', // 新版本-备注
            moq: 1, // B端没有限制
            spuId: item.spuId,
            saleable: item.saleable,
            isBrandAgent: item.isBrandAgent
          }]
        }
      })
    }).finally(() => {
      state.loading = false
      state.refresh = false
    })
}
function onGood(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 ask(message: string, fn: Function, ...arg: any) {
  if (selected.value.length == 0) {
    Toast('请勾选商品')
    return
  }
  Dialog.confirm({
    message,
    title: "提示"
  }).then(() => {
    fn(...arg)
  })
}
function onStepperFocus(gItem: any) {
  state.num.gItem = gItem
  state.num.show = true
  setTimeout(() => {
    numField.value && numField.value.focus()
    state.num.value = gItem.productQty
  })
}
function onFocus(focus: string) {
  state.focus = focus
}
function goBack() {
  PageUtils.goBack()
}
function onNumChange() {
  if (state.num.value === '' || state.num.value === undefined || state.num.value === null) {
    Toast('请输入商品数量')
  } else if (state.num.gItem.moq > state.num.value) {
    Toast('不能小于起订量' + state.num.gItem.moq)
  } else if (state.num.gItem.stock < state.num.value) {
    Toast('不能大于库存' + state.num.gItem.stock)
  } else {
    if (state.loadingSon.num) return
    state.loadingSon.num = true
    const orignNum = state.num.gItem.productQty
    state.num.gItem.productQty = state.num.value
    beforeCartModify(Number(state.num.value), state.num.gItem).then(() => {
      state.num.show = false
    }).catch(() => {
      // 改回去
      state.num.gItem.productQty = orignNum
    }).finally(() => {
      state.loadingSon.num = false
    })
  }
}
</script>

<style lang="scss" scoped>
	.sign {
		position: absolute;
		right: 1.8vw;
		top: 0;
		width: 40px;
		text-align: center;

		img {
			width: 40px;
			margin-bottom: -18px;
		}

		.discount {
			font-family: MiSans-Semibold;
			text-shadow: 0.5px 0.5px #ddd;
			color: #A532E0;
			font-weight: 1000;
			font-size: 12px;
		}
	}
.swipe_btn {
  height: 100%;
  width: 100rpx;
  padding: 0;
  font-size: 26rpx;
}
.top_right {
  position: absolute;
  right: 10px;
}
</style>
