<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-select-store container">
    <view v-if="!isMap">
      <view
        v-if="isHaveStation && pageType !== 'receiveInfo'"
        class="search"
      >
        <image
          src="@/package-user/static/images/search.png"
          class="img"
        />
        <input
          v-model="searchStationName"
          class="input"
          placeholder="搜索地址或门店"
          @focus="searchStore"
          @confirm="search()"
        >
      </view>

      <!-- 搜索历史 -->
      <view
        v-if="pageType === 'searchStore' && showSearchHistoryList.length > 0"
        class="search-con"
      >
        <view class="search-tit">
          <view class="text">
            历史搜索
          </view>
          <view
            class="del"
            @tap="clearSearchHistory"
          >
            <image src="@/static/images/del.png" />
          </view>
        </view>
        <view class="search-history">
          <block
            v-for="(item, index) in showSearchHistoryList"
            :key="index"
          >
            <view
              class="item"
              @tap="clickKeywordSearch"
            >
              {{ item }}
            </view>
          </block>
        </view>
      </view>
      <!-- 搜索历史end -->

      <!-- 门店列表 -->
      <view
        v-if="pageType === 'changeStore'"
        class="select-store store-list-box"
      >
        <view
          v-if="stationList.length"
          class="store-list"
        >
          <view class="list-tit flex-sb">
            <view>当前地址附近门店</view>
            <view
              class="flex-sb"
              @tap="onSelectLoaction"
            >
              <image
                class="relocation-icon"
                src="@/package-user/static/images/location.png"
                mode="aspectFit"
              />
              <text>重新定位</text>
            </view>
          </view>
          <block
            v-for="(item, index) in stationList"
            :key="index"
          >
            <store-item
              :item="item"
              @get-station-item="onGetStationItem"
            />
          </block>
        </view>
        <!-- 空列表或加载全部提示 -->
        <empty-all-tips
          v-if="isLoaded"
          :is-empty="!stationList.length"
        />
      </view>
      <!-- 门店列表end -->

      <view
        v-if="pageType === 'receiveInfo'"
        class="select-store"
        :class="{'not-have-station':!isHaveStation}"
      >
        <view class="store-list">
          <view class="list-tit flex-sb">
            <view>收货人信息</view>
            <view
              class="flex-sb"
              @tap="changeUser"
            >
              <text class="more-tit">
                更换
              </text>
              <image
                class="relocation-icon more"
                src="@/static/images/back.png"
                mode="aspectFit"
              />
            </view>
          </view>
          <view class="re-info">
            <input
              v-model="stationInfo.name"
              maxlength="15"
              type="text"
              class="input re-input"
              placeholder="收货人名称"
            >
            <input
              v-model="stationInfo.userMobile"
              type="number"
              maxlength="11"
              class="input re-input"
              placeholder="收货人号码"
            >
          </view>
        </view>
        <view
          v-if="isHaveStation"
          class="store-list"
        >
          <view class="list-tit flex-sb">
            <view>当前门店</view>
            <view
              class="flex-sb"
              @tap="changeStore"
            >
              <text class="more-tit">
                更换
              </text>
              <image
                class="relocation-icon more"
                src="@/static/images/back.png"
                mode="aspectFit"
              />
            </view>
          </view>
          <store-item :item="selStationItem" />
        </view>
        <view
          v-if="!isHaveStation && isLoaded"
          class="not-search-empty"
        >
          <view>
            <image
              src="@/static/empty-img/search-empty.png"
              mode="aspectFit"
            />
          </view>
          <text class="ntxt">
            当前区域暂无门店
          </text>
        </view>
      </view>

      <view
        v-if="pageType === 'receiveInfo'"
        class="foot-btn"
      >
        <view
          class="btn"
          @tap="onSaveAndUse"
        >
          确定
        </view>
      </view>
    </view>
    <!-- #ifdef APP-PLUS -->
    <!-- 腾讯地图组件 -->
    <view
      v-if="isMap"
      class="map"
    >
      <view
        class="goOut"
        @click="isMapReturn"
      >
        {{ $t('Back') }}
      </view>
      <web-map
        v-if="isMap"
        @on-get-location="onGetLocation"
      />
    </view>
    <!-- end 腾讯地图组件 -->
    <!-- #endif -->
  </view>
</template>

<script setup>
import storeItem from '@/package-user/components/store-item/index'
import Big from 'big.js'
import * as locTrans from '@/utils/locTrans'

const domainAddress = import.meta.env.VITE_APP_DOMAIN_ADDRESS

let shopId // 店铺id
let lat = '' // 纬度
let lng = '' // 经度
const searchStationName = ref('') // 自提点名称
const stationList = ref([]) // 自提点列表
let current = 1
const showSearchHistoryList = ref([]) // 搜索历史列表
let pages = 1
const pageType = ref('changeStore')
const selStationItem = ref({}) // 选择的自提点item
let orderEntry = 0
const key = import.meta.env.VITE_APP_MAP_KEY
const isMap = ref(false)
// eslint-disable-next-line no-unused-vars
let isLoad = false
const isLoaded = ref(false)
const isHaveStation = ref(false)
let redirect = null // 跳转地址

const stationInfo = reactive({
  name: '',
  userMobile: ''
}) // 提货人信息
const setStationInfo = (val) => {
  if (val) {
    stationInfo.name = val.name
    stationInfo.userMobile = val.userMobile
  }
}

watch(() => pageType.value, (val) => {
  let tit = ''
  switch (val) {
    case 'changeStore':
      tit = '门店列表'
      break
    case 'searchStore':
      tit = '搜索门店'
      break
    case 'receiveInfo':
      tit = '收货信息'
      break
  }
  // 头部导航标题
  uni.setNavigationBarTitle({
    title: tit
  })
})

let stationId = null
onLoad((options) => {
  if (options.shopId) {
    shopId = Number(options.shopId)
  }
  if (options.orderEntry) {
    orderEntry = options.orderEntry
  }
  if (options.redirect) {
    redirect = decodeURIComponent(options.redirect)
    uni.setStorageSync('cloudSubmitOrderRedirect', redirect)
  } else {
    redirect = uni.getStorageSync('cloudSubmitOrderRedirect')
  }
  if (options.addrId && options.state !== '1') {
    getDefaultAddress(options.addrId)
  }
  if (options.state === '1') {
    const _stationInfo = uni.getStorageSync('cloudSelStationInfo')
    selStationItem.value = _stationInfo.selStationItem
    stationId = _stationInfo.selStationItem.stationId
    if (typeof selStationItem.value.timeInfo === 'string') {
      selStationItem.value.timeInfo = JSON.parse(selStationItem.value.timeInfo)
    }
    selStationItem.value.operationState = getOperationState(selStationItem.value.timeInfo?.shopTime[0], selStationItem.value.timeInfo?.shopTime[1])
    if (selStationItem.value.distance > 1000) {
      selStationItem.value.distance = new Big(selStationItem.value.distance)
      // 保留两位小数
      Big.DP = 2
      // 向下取整
      // big.RM = 3
      selStationItem.value.distance = selStationItem.value.distance.div(1000).valueOf()
      selStationItem.value.distanceCont = selStationItem.value.distance + 'km'
    } else {
      selStationItem.value.distanceCont = selStationItem.value.distance + 'm'
    }

    setStationInfo(_stationInfo.userInfo)
    pageType.value = 'receiveInfo'
  }
  // #ifdef H5
  if (!options.module) {
    // 获取地理位置信息
    onGetCurrentLocation()
  } else {
    onConfirmLocation({
      latitude: options.latng.split(',')[0],
      longitude: options.latng.split(',')[1]
    })
  }
  // #endif

  let isApp = false

  // #ifdef APP-PLUS
  isApp = true
  // #endif

  // #ifndef H5
  if (isApp) {
    util.getUserAuth(onGetCurrentLocation)
  } else {
    onGetCurrentLocation()
  }
  // #endif
})

onShow(() => {
  // 头部导航标题
  const stationInfoPar = uni.getStorageSync('cloudStationAddress') || stationInfo
  setStationInfo(stationInfoPar)
  uni.removeStorageSync('cloudStationAddress')

  if (uni.getStorageSync('curStoreUserInfo')) {
    setStationInfo(uni.getStorageSync('curStoreUserInfo'))
    uni.removeStorageSync('curStoreUserInfo')
  }
})

/**
 * 页面上拉触底事件的处理函数
 */
onReachBottom(() => {
  if (current < pages) {
    current = current + 1
    onGetUserStation()
  }
})

/**
 * 获取当前地理位置
 */
const onGetCurrentLocation = () => {
  uni.showLoading()
  uni.getLocation({
    type: 'wgs84', // 默认为 wgs84 返回 gps 坐标，gcj02 返回国测局坐标，可用于 uni.openLocation 的坐标，app平台高德SDK仅支持返回gcj02
    altitude: true,
    isHighAccuracy: true,
    highAccuracyExpireTime: 3500,
    success: (res) => {
      uni.hideLoading()
      if (res) {
        onConfirmLocation(res)
      }
    },
    fail: (res) => {
      // eslint-disable-next-line no-console
      console.log('获取定位失败！', res)
      uni.showToast({
        title: '获取定位失败！',
        icon: 'none',
        duration: 1500
      })
    },
    complete: () => {
      uni.hideLoading()
    }
  })
  // #ifdef APP-PLUS || MP-WEIXIN
  // #endif
}
/**
 * 打开地图选择地址
 */
const onSelectLoaction = () => {
  // 重置当前页码
  current = 1
  // #ifdef H5
  uni.setStorageSync('curStoreUserInfo', stationInfo)
  const routes = getCurrentPages() // 获取当前打开过的页面路由数组
  const curRoute = routes[routes.length - 1].route
  const backUrl = encodeURIComponent(domainAddress + '/' + curRoute + '?orderEntry=' + orderEntry + '&shopId=' + shopId)
  window.location.replace(`https://apis.map.qq.com/tools/locpicker?search=1&type=0&backurl=${backUrl}&key=${key}&referer=myapp`)
  // #endif

  // #ifdef APP-PLUS
  isMap.value = true
  // #endif

  // #ifdef MP-WEIXIN
  uni.chooseLocation({
    success: (res) => {
      onGetLocation(res)
    },
    fail: () => {
      uni.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.userLocation']) {
            uni.authorize({
              scope: 'scope.userLocation',
              success: () => {
                uni.chooseLocation({
                  success: (res) => {
                    onGetLocation(res)
                  }
                })
              },
              fail: () => {
                uni.showToast({
                  title: $t('authorityTips'),
                  icon: 'none'
                })
              }
            })
          }
        }
      })
    }
  })
  // #endif
}
/**
 * 确认地址
 */
const onGetLocation = (loc) => {
  // #ifdef H5 || APP-PLUS
  lat = loc.latlng.lat
  lng = loc.latlng.lng
  isMap.value = false
  // #endif

  // #ifdef MP-WEIXIN
  lat = loc.latitude // 纬度
  lng = loc.longitude // 经度
  // #endif

  onConfirmLocation({ latitude: lat, longitude: lng })
}

// 获取默地址
const getDefaultAddress = (addrId) => {
  const params = {
    url: '/tmerclub_user/user_addr',
    method: 'GET',
    data: {
      addrId
    }
  }
  http.request(params).then((res) => {
    uni.getStorageSync({
      name: res.consignee,
      userMobile: res.mobile
    })
  })
}

const isMapReturn = () => {
  uni.setNavigationBarTitle({
    title: $t('selectPickUpPoint')
  })
  isMap.value = false
}

/**
 * 转换经纬度请求自提点列表
 * @param locationRes 当前定位信息
 */
const onConfirmLocation = (locationRes) => {
  let locationObj
  // #ifdef APP-PLUS || MP-WEIXIN
  locationObj = locTrans.gcj02tobd09(locTrans.wgs84togcj02(locationRes))
  // #endif

  // #ifdef H5
  locationObj = locTrans.gcj02tobd09(locationRes)
  // #endif

  lat = locationObj.latitude
  lng = locationObj.longitude
  onGetUserStation()
}

/**
 * 请求自提点列表
 */
const onGetUserStation = (isSearch) => {
  isLoaded.value = false
  const stationSpuList = uni.getStorageSync('orderSkuList')
  http.request({
    url: '/tmerclub_order/station/user_station',
    method: 'POST',
    data: {
      stationSpuList: stationSpuList || [],
      lat: lat || 23.151021, // 纬度 '23.151021',
      lng: lng || 113.326621, // 经度 '113.326621',
      stationName: '',
      shopId,
      pageDTO: {
        pageNum: 1,
        pageSize: 10
      }
    }
  }).then(
    (res) => {
      isLoaded.value = true
      if (!isSearch && !(res.list && res.list.length)) {
        isHaveStation.value = false
        pageType.value = 'receiveInfo'
        return
      }
      isHaveStation.value = true
      res.list.forEach((el) => {
        el.timeInfo = JSON.parse(el.timeInfo)
        el.operationState = getOperationState(el.timeInfo.shopTime[0], el.timeInfo.shopTime[1])
        el.timeInfo.startTime = formatDuring(
          el.timeInfo.shopTime[0]
        ).dateStr2 // 自提点开始时间
        el.timeInfo.endTime = formatDuring(
          el.timeInfo.shopTime[1]
        ).dateStr2 // 自提点结束时间
        if (el.stationStartTime === 1) {
          // var nowdate = formatDuring(new Date()).date1
        }
        if (el.distance > 1000) {
          el.distance = new Big(el.distance)
          // 保留两位小数
          Big.DP = 2
          // 向下取整
          // big.RM = 3
          el.distance = el.distance.div(1000).valueOf()
          el.distanceCont = el.distance + 'km'
        } else {
          el.distanceCont = el.distance + 'm'
        }
      })
      selStationItem.value = res.list.find(i => i.stationId === stationId)
      stationList.value = current === 1 ? res.list : stationList.value.concat(res.list)
      pages = res.pages
      isLoad = true
    }
  ).catch(() => {
    isLoad = true
    uni.showToast({
      title: $t('serverWrong'),
      icon: 'none'
    })
  })
}

const clickKeywordSearch = (name) => {
  searchStationName.value = name
  search()
}

// 搜索页面
const searchStore = () => {
  pageType.value = 'searchStore'
  searchStationName.value = ''
  showSearchHistoryList.value = uni.getStorageSync('storesSearchHistory') || []
}

// 切换门店
const changeStore = () => {
  pageType.value = 'changeStore'
  selStationItem.value = {}
  search()
}

const changeUser = () => {
  uni.navigateTo({
    url: '/package-user/pages/address-list/address-list?selectAddress=1'
  })
}

// 删除搜索历史
const clearSearchHistory = () => {
  uni.removeStorageSync('storesSearchHistory')
  showSearchHistoryList.value = []
}

// 获取营业状态
const getOperationState = (startTime, endTime) => {
  const timeS = new Date(startTime)
  const timeE = new Date(endTime)
  const timeSH = timeS.getHours()
  const timeSM = timeS.getMinutes()
  const timeEH = timeE.getHours()
  const timeEM = timeE.getMinutes()
  const nowHours = new Date().getHours()
  const nowMinutes = new Date().getMinutes()
  // 营业状态
  let operationState = 0
  if (nowHours >= timeSH && nowHours <= timeEH) {
    operationState = 1
    if (nowHours === timeSH && nowMinutes < timeSM) {
      operationState = 0
    }
    if (nowHours === timeEH && nowMinutes > timeEM) {
      operationState = 0
    }
  }
  return operationState
}

/**
 * 时间转换
 */
const formatDuring = (mss) => {
  const time = new Date(mss)
  const year = time.getFullYear() // getFullYear方法以四位数字返回年份
  const month = time.getMonth() + 1 // getMonth方法从 Date 对象返回月份 (0 ~ 11)，返回结果需要手动加一
  const days = time.getDate() // getDate方法从 Date 对象返回一个月中的某一天 (1 ~ 31)
  const hours = time.getHours() // getHours方法返回 Date 对象的小时 (0 ~ 23)
  const minutes = time.getMinutes() // getMinutes方法返回 Date 对象的分钟 (0 ~ 59)
  const seconds = time.getSeconds() // getSeconds方法返回 Date 对象的秒数 (0 ~ 59)
  const data = {}
  data.year = year
  data.month = month < 10 ? '0' + month : month
  data.days = days < 10 ? '0' + days : days
  data.hours = hours < 10 ? '0' + hours : hours
  data.minutes = minutes < 10 ? '0' + minutes : minutes
  data.seconds = seconds < 10 ? '0' + seconds : seconds
  return {
    date1: data.year + '-' + data.month + '-' + data.days,
    dateStr: data.hours + ':' + data.minutes + ':' + data.seconds,
    dateStr2: data.hours + ':' + data.minutes
  }
}

const search = () => {
  current = 1
  stationList.value = []
  searchStationName.value = searchStationName.value.trim()
  if (searchStationName.value) {
    let showSearchHistoryList = uni.getStorageSync('storesSearchHistory') || []
    showSearchHistoryList = showSearchHistoryList.filter(item => item !== searchStationName.value)
    showSearchHistoryList.unshift(searchStationName.value)
    if (showSearchHistoryList.length > 10) {
      showSearchHistoryList.pop()
    }
    uni.setStorageSync('storesSearchHistory', showSearchHistoryList)
  }
  pageType.value = 'changeStore'
  onGetUserStation(1)
}

/**
 * 获取当前选中的自提点item
 */
const onGetStationItem = (item) => {
  selStationItem.value = item
  pageType.value = 'receiveInfo'
}

/**
 * 保存并使用
 */
const onSaveAndUse = () => {
  if (JSON.stringify(selStationItem.value) == '{}' && isHaveStation.value) {
    uni.showToast({
      title: '请选择自提点',
      icon: 'none',
      duration: 1500
    })
    return
  }
  if (!stationInfo.name.trim() || !stationInfo.userMobile) {
    uni.showToast({
      title: '请输入完整收货人信息',
      icon: 'none',
      duration: 1500
    })
    return
  }
  if (!util.checkPhoneNumber(stationInfo.userMobile)) {
    uni.showToast({
      title: '请输入正确收货人号码',
      icon: 'none',
      duration: 1500
    })
    return
  }
  const obj = {
    selStationItem: selStationItem.value,
    userInfo: stationInfo,
    stationStockStatus: selStationItem.value.hasStock !== 0 ? 2 : 1
  }
  uni.setStorageSync('cloudSelStationInfo', obj)
  uni.setStorageSync('cloudIsHaveStation', isHaveStation.value)

  uni.removeStorageSync('cloudSubmitOrderRedirect')

  // 若没有上一页且有跳转地址，则跳转到指定地址  否则返回上一页
  if (getCurrentPages().length < 2 && redirect) {
    uni.redirectTo({
      url: redirect
    })
    return
  }
  uni.navigateBack({ delta: 1 })
}

</script>

<style lang="scss" scoped>
@use "./select-store.scss";
</style>
