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

  https://www.mall4j.com/

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

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

<template>
  <view class="Mall4j page-modify-address">
    <view class="addr-info">
      <view class="addr-info-item">
        <view class="title">
          {{ $t('shouHuoRen') }}
        </view>
        <input
          v-model="userAddrOrder.receiver"
          type="text"
          class="input-text"
          maxlength="20"
          :placeholder="$t('qingShuRuShouHuoRenXingMing')"
        >
      </view>
      <view class="addr-info-item">
        <view class="title">
          {{ $t('shouJiHao') }}
        </view>
        <input
          v-model="userAddrOrder.mobile"
          type="text"
          maxlength="11"
          class="input-text"
          :placeholder="$t('qingShuRuShouJiHaoMa')"
        >
      </view>
      <view
        class="addr-info-item"
        @tap="handleShowAddrPicker"
      >
        <view class="title">
          {{ $t('suoZaiDiQu') }}
        </view>
        <view :class="['text', dvyType == 4 ? 'gray': '']">
          {{ `${userAddrOrder.province} ${userAddrOrder.city} ${ userAddrOrder.area}` }}
        </view>
        <view
          v-if="dvyType != 4"
          class="icon"
        />
      </view>
      <view class="addr-info-item">
        <view class="title">
          {{ $t('xiangXiDiZhi') }}
        </view>
        <input
          v-model="userAddrOrder.addr"
          :disabled="dvyType == 4"
          type="text"
          :class="['input-text', dvyType == 4 ? 'gray': '']"
          :placeholder="$t('qingShuRuXiangXiDiZhi')"
        >
      </view>
    </view>
    <view
      class="submit-btn"
      @tap="submit"
    >
      {{ $t('queDing') }}
    </view>
    <address-picker
      v-show="showAddrPicker"
      ref="addressPickerRef"
      @get-addr-data="handleGetAddrData"
      @cancel="handleHideAddrPicker"
    />
  </view>
</template>

<script setup>

const Data = reactive({
  showAddrPicker: false,
  userAddrOrder: {},
  orderNumber: '',
  orderId: '',
  // 是否在发货页面修改地址
  shipping: false,
  // 配送方式
  dvyType: ''
})

const { showAddrPicker, userAddrOrder, dvyType } = toRefs(Data)

onLoad((options) => {
  Data.orderNumber = options.orderNumber
  Data.orderId = options.orderId
  Data.shipping = Boolean(options.shipping)
  Data.userAddrOrder = uni.getStorageSync('bbcUserAddrOrder')
  Data.dvyType = options.dvyType
})

onShow(() => {
  uni.setNavigationBarTitle({
    title: $t('xiuGaiDiZhi')
  })
})

const addressPickerRef = ref()
/**
 * 显示地区picker
 */
const handleShowAddrPicker = () => {
  if (Data.dvyType != 4) {
    Data.showAddrPicker = true
    const addrIds = [Data.userAddrOrder.provinceId, Data.userAddrOrder.cityId, Data.userAddrOrder.areaId]
    nextTick(() => {
      addressPickerRef.value.init(addrIds)
    })
  }
}

/**
 * 隐藏地区picker
 */
const handleHideAddrPicker = () => {
  Data.showAddrPicker = false
}

/**
 * 选择地区回调
 */
const handleGetAddrData = (data) => {
  Data.userAddrOrder = Object.assign(Data.userAddrOrder, data)
  handleHideAddrPicker()
}

/**
 * 提交修改
 */
const submit = () => {
  if (!Data.userAddrOrder.receiver.trim()) {
    uni.showToast({
      title: $t('qingShuRuShouHuoRen'),
      icon: 'none'
    })
    return
  }
  const reg = /^(?:(?:\+|00)86)?1\d{2}([\d*]{4})\d{4}$/
  if (!reg.test(Data.userAddrOrder.mobile)) {
    uni.showToast({
      title: $t('qingShuRuZhengQueDeShouJiHao'),
      icon: 'none'
    })
    return
  }
  if (!Data.userAddrOrder.addr.trim()) {
    uni.showToast({
      title: $t('qingShuRuXiangXiDiZhi-0'),
      icon: 'none'
    })
    return
  }
  if (Data.dvyType == 4) {
    confirmChangeAddress()
    return
  }
  getChangeAmount()
}

/**
 * 查询修改订单地址后的运费
 */
const getChangeAmount = () => {
  uni.showLoading()
  http.request({
    url: '/order/order/getChangeAmount',
    method: 'GET',
    data: {
      areaId: Data.userAddrOrder.areaId,
      orderId: Data.orderId,
      orderNumber: Data.orderNumber
    }
  }).then(({ data }) => {
    uni.hideLoading()
    let msg = ''
    if (!data.isCheck) {
      msg = $t('addrChangeAmountTips1')
    } else {
      const amount = data.freeAmount
      msg = $t('addrChangeAmountTips2').replace('[more/less]', amount > 0 ? $t('duo') : $t('shao')).replace('[amount]', Math.abs(amount))
    }
    uni.showModal({
      title: $t('tiShi'),
      content: msg,
      success: (modalRes) => {
        if (modalRes.confirm) {
          confirmChangeAddress()
        }
      }
    })
  }).catch(errMsg => {
    uni.hideLoading()
    uni.showToast({
      title: errMsg.data.msg,
      icon: 'none',
      duration: 1500
    })
  })
}

/**
 * 确认修改
 */
const confirmChangeAddress = () => {
  http.request({
    url: '/order/order/changeUserAddr',
    method: 'PUT',
    data: {
      orderId: Data.orderId,
      orderNumber: Data.orderNumber,
      userAddrOrder: Data.userAddrOrder
    }
  }).then(({ data }) => {
    uni.showToast({
      title: data,
      icon: 'none',
      mask: true,
      success: () => {
        const url = Data.shipping ? '/package-order/pages/order-shipping/order-shipping' : '/package-order/pages/order-detail/order-detail'
        if (Data.shipping) uni.removeStorageSync('bbcSelectedDelivery')
        setTimeout(() => {
          uni.redirectTo({
            url: `${url}?orderNumber=${Data.orderNumber}`
          })
        }, 1200)
      }
    })
  }).catch(errMsg => {
    uni.showToast({
      title: errMsg.data.data,
      icon: 'none',
      mask: true,
      success: () => {
        const url = Data.shipping ? '/package-order/pages/order-shipping/order-shipping' : '/package-order/pages/order-detail/order-detail'
        if (Data.shipping) uni.removeStorageSync('bbcSelectedDelivery')
        setTimeout(() => {
          uni.redirectTo({
            url: `${url}?orderNumber=${Data.orderNumber}`
          })
        }, 1200)
      }
    })
  })
}
</script>

<style lang="scss" scoped>
@use "modify-address";
</style>
