CarBrands.vue 9.65 KB
<template>
  <view>
    <MessageBox ref="carBrandListVisible" position="bottom" :isFooter="false" title="请选择车品牌" @close="clickClose">
      <view class="select-box">
        <view class="select-item" :class="{ checked: carBrand == item.name }" @click="selectCar(item)"
          v-for="(item, index) in carBrandList" :key="index">
          {{ item.name }}
        </view>
      </view>
    </MessageBox>
    <MessageBox ref="carBoxVisible" position="bottom" :isFooter="false" title="请选择车系" :maxHeight="1000" back
      @close="closeCarBoxVisible">
      <view class="select-box">
        <view class="select-item" :class="{ checked: carModel == item.name }" @click="handleSelect(item)"
          v-for="(item, index) in carlist" :key="index">
          {{ item.name }}
        </view>
      </view>
    </MessageBox>
  </view>

</template>

<script type='text/ecmascript-6'>
import materialCache from '@/utils/materialCache'

export default {
  name: 'CarBrands',
  props: {
    carBrandKey: {//品牌key
      type: String,
      default: 'carBrand'
    },
    carModelKey: {//车型key
      type: String,
      default: 'carModel'
    },
    echoData: {
      type: Object,
      default: () => ({})
    },
    customBoolean: Boolean,
    linkage: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      carlist: [],
      selectItem: {},
      clickFlga: false,
      carBrandListOff: false
    }
  },
  watch: {
    watchStatus: {
      immediate: true,
      handler(newval) {
        this.close()
      }
    },
  },
  computed: {
    watchStatus() {
      return this.$store.state.user.historyStatus
    },
    carModel() {
      return this.customBoolean ? this.echoData[this.carModelKey] : this.$store.state.user.customerInfo.carModel
    },
    carBrandList() {
      return this.$store.state.user.carBrands || []
    },
    carBrand() {
      return this.customBoolean ? this.echoData[this.carBrandKey] : this.$store.state.user.customerInfo.carBrand
    },
    boutiqueDefaultCarBrandId() {
      return this.$store.state.user.boutiqueDefaultCarBrandId
    },
    defaultCarId() {
      return this.$store.state.user.defaultCarId || ''
    }
  },
  mounted() {
  },
  beforeDestroy() {
    this.cancelPendingRequests()
  },
  methods: {
    autoSelect() {
      const { carBrandList, boutiqueDefaultCarBrandId, defaultCarId } = this
      let carIndex = 0
      if (boutiqueDefaultCarBrandId) carIndex = carBrandList.findIndex(e => e.id == boutiqueDefaultCarBrandId)
      if (carIndex < 0) carIndex = 0
      if (carBrandList.length) this.selectCar(carBrandList[carIndex], true, defaultCarId)
    },
    async open() {
      const requestId = (this._brandRequestId || 0) + 1
      this._brandRequestId = requestId
      this.$store.dispatch('setCarBrandOpenStatus', true)
      // 已有品牌先展示,离线时不再触发品牌接口。
      const { carBrand } = this
      if (carBrand) {
        const { carBrandList } = this,
          item = carBrandList.find(e => e.name == carBrand)
        if (item && carBrandList.length == 1) this.selectCar(item)
        else {
          this.$refs.carBrandListVisible.open()
          this.carBrandListOff = true
        }
      } else {
        this.$refs.carBrandListVisible.open()
        this.carBrandListOff = true
      }
      if (!await materialCache.getNetworkStatus() || this._brandRequestId !== requestId) return
      try {
        const { shopMerchantId } = uni.$storage.get('userInfo') || {}
        const { data } = await uni.$api.commonApi.getMerchantCarBrandList([shopMerchantId])
        if (this._brandRequestId !== requestId) return
        const carBrandList = []
        ;(data?.[0]?.carBrandList || []).forEach(brand => {
          ;(brand.childs || []).forEach(child => {
            carBrandList.push({ ...child, brandName: brand.name, brandId: brand.id })
          })
        })
        this.$store.dispatch('setCarBrandsList', carBrandList)
        uni.$storage.set('carBrandList', carBrandList)
      } catch (error) {
        // 刷新失败时保留当前可用的品牌列表。
      }
    },
    async selectCar(e, auto = false, carId) {
      if (!e.brandId || !e.id) return uni.showToast({
        title: "车型ID或品牌ID为空",
        icon: "none",
      });
      let { clickFlga } = this,
        index = 0
      if (clickFlga) return
      this.clickFlga = true
      const requestId = (this._carRequestId || 0) + 1
      this._carRequestId = requestId
      const isCurrent = () => this._carRequestId === requestId
      // 进入车系选择过程中保持弹层打开态,避免「查看长图」按钮冒出来
      this.$store.dispatch('setCarBrandOpenStatus', true)
      this.selectItem = {
        carBrand: e.brandName,
        carBrandId: e.brandId,
        carChildsBrandName: e.name,
        carChildsBrandId: e.id
      }
      const cacheKey = `${e.id}_${e.brandId}_carlist`
      const refreshIds = this._carRefreshIds || (this._carRefreshIds = new Map())
      const refreshId = (refreshIds.get(cacheKey) || 0) + 1
      refreshIds.set(cacheKey, refreshId)
      const isLatestRefresh = () => refreshIds.get(cacheKey) === refreshId
      const carList = uni.getStorageSync(cacheKey)
      const hasCache = Array.isArray(carList) && carList.length > 0
      if (hasCache) {
        this.clickFlga = false
        this.carlist = carList
        if (auto && carList.length) {
          if (carId) index = carList.findIndex(i => i.id == carId)
          if (index < 0) index = 0
          this.handleSelect(carList[index])
        }
        else this.$refs.carBoxVisible.open()
      } else {
        this.carlist = []
        if (!auto) uni.showLoading({
          mask: true
        })
      }
      try {
        const online = await materialCache.getNetworkStatus()
        // 缓存已自动选中时仍允许后台刷新,弹层状态只由当前选择更新。
        if (!isLatestRefresh() || (!isCurrent() && !hasCache)) return
        if (!online) {
          if (!hasCache) uni.showToast({ title: '该品牌车系尚未缓存,请联网后重试', icon: 'none' })
          return
        }
        const res = await uni.$api.commonApi.getCarBrandsList({
          brandId: e.brandId,
          childBrandId: e.id
        })
        if (!isLatestRefresh()) return
        if (Array.isArray(res)) uni.setStorageSync(cacheKey, res)
        if (!isCurrent()) return
        const nextList = Array.isArray(res) ? res : []
        this.carlist = nextList
        if (!hasCache) {
          if (auto && nextList.length) {
            if (carId) index = nextList.findIndex(i => i.id == carId)
            if (index < 0) index = 0
            this.handleSelect(nextList[index])
          } else {
            this.$store.dispatch('setCarBrandOpenStatus', true)
            this.$refs.carBoxVisible.open()
          }
        }
      } catch (error) {
        // 请求过程中断网时保留已展示的缓存。
      } finally {
        if (isCurrent()) {
          this.clickFlga = false
          uni.hideLoading()
        }
      }
    },
    cancelPendingRequests() {
      this._brandRequestId = (this._brandRequestId || 0) + 1
      this._carRequestId = (this._carRequestId || 0) + 1
      if (this.clickFlga) uni.hideLoading()
      this.clickFlga = false
    },
    handleSelect(item) {
      this.cancelPendingRequests()
      const customerInfo = { ...this.$store.state.user.customerInfo },
        { selectItem, linkage } = this
      Object.assign(customerInfo, {
        carModel: item.name,
        carModelId: item.id,
        carBrand: selectItem.carChildsBrandName,
        carBrandId: selectItem.carChildsBrandId,
        oneCarBrand: selectItem.carBrand,
        oneCarBrandId: selectItem.carBrandId
      })
      if (linkage) {
        uni.$logger.local.info(`选择车:
      carModel:${item.name},
      carModelId: ${item.id},
      carBrand:${customerInfo.carBrand},
      carBrandId:${customerInfo.carBrandId},
      oneCarBrand:${customerInfo.oneCarBrand},
      oneCarBrandId:${customerInfo.oneCarBrandId}`)
        this.$store.dispatch('setCustomerInfo', customerInfo)
        this.$store.dispatch('setCurrentCarInfo', selectItem)
        this.$store.dispatch('updateViewKey')
      }
      this.$refs.carBoxVisible?.close();
      this.$refs.carBrandListVisible?.close();
      this.carBrandListOff = false
      this.$store.dispatch('setCarBrandOpenStatus', false)
      this.$emit('select', {
        ...item,
        ...selectItem
      })
    },
    close() {
      this.cancelPendingRequests()
      this.$refs?.carBoxVisible?.close();
      this.$refs?.carBrandListVisible?.close()
      this.carBrandListOff = false
      this.$store.dispatch('setCarBrandOpenStatus', false)

    },
    closeCarBoxVisible() {
      this.cancelPendingRequests()
      // 关车系弹窗:若还要从品牌列表回来,保持打开态;否则关闭
      if (this.carBrandListOff) {
        this.$store.dispatch('setCarBrandOpenStatus', true)
        return
      }
      this.$store.dispatch('setCarBrandOpenStatus', false)
      this.$emit('close')
    },
    clickClose() {
      this.cancelPendingRequests()
      this.carBrandListOff = false
      this.$store.dispatch('setCarBrandOpenStatus', false)
      this.$emit('close')
    },
  }
}
</script>

<style scoped lang='scss'>
.select-box {
  margin: toRpx(40) 0;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: toRpx(32);
  overflow-y: scroll;
  max-height: 50vh;
  padding-bottom: toRpx(60);

  .select-item {
    text-align: center;
    height: toRpx(68);
    line-height: toRpx(44);
    opacity: 1;
    border: toRpx(2) solid #dce0e6;
    color: #333;
    font-size: toRpx(32);
    border-radius: toRpx(8);

    &.checked {
      border: toRpx(2) solid #292d33;
    }
  }
}
</style>