<template>
  <view class="Mall4j page-edit-address">
    <view v-if="!isMap">
      <view class="item">
        <view class="text">
          收件人
        </view>
        <input
          v-model="consignee"
          type="text"
          maxlength="20"
          placeholder-style="color:#999"
          class="input"
          placeholder="请输入收件人名称"
        >
      </view>
      <view class="item">
        <view class="text">
          手机号
        </view>
        <input
          v-model="mobile"
          type="number"
          maxlength="11"
          placeholder-style="color:#999"
          class="input"
          placeholder="请输入联系手机号"
        >
      </view>
      <view class="item">
        <view class="text">
          所在地区
        </view>
        <view class="text-arrow">
          <view
            v-if="province"
            class="area-text"
            @tap="showPicker=true"
          >
            {{ province }} {{ city }} {{ area }}
          </view>
          <view
            v-else
            class="placeholder-text"
            @tap="showPicker=true"
          >
            选择地区
          </view>
          <address-picker
            v-if="showPicker"
            :show-picker="showPicker"
            :addr-ids="addrIds"
            @set-address-info="onAddressPickerConfirm"
          />
        </view>
      </view>
      <view class="item">
        <view class="text">
          详细地址
        </view>
        <textarea
          v-model="addr"
          class="textarea"
          maxlength="50"
          placeholder-style="color:#999"
          placeholder="详细地址、街道、门牌号等，5-50字"
        />
        <view
          class="local"
          @tap="onSelLocation"
        >
          <image
            class="icon"
            src="@/static/images/my-address.png"
          />
        </view>
      </view>
      <view
        v-if="showSetDefault"
        class="item"
      >
        <view class="text">
          设为默认
        </view>
        <checkbox-group
          class="set-default"
          @change="onSetDefaultAddr"
        >
          <label class="check-label">
            <checkbox
              class="check"
              color="#fff"
              :class="{'checked':Boolean(isDefault)}"
              :checked="Boolean(isDefault)"
            />
          </label>
        </checkbox-group>
      </view>

      <view class="btn-box">
        <view
          class="save"
          @tap="onSaveAddress"
        >
          保存地址
        </view>
        <view
          v-if="addrId && !isDefault"
          class="del"
          @tap="onHandleShowPop"
        >
          删除地址
        </view>
      </view>
    </view>

    <!-- #ifdef APP-PLUS -->
    <!-- 腾讯地图组件 -->
    <view
      v-if="isMap"
      class="map"
    >
      <web-map
        v-if="isMap"
        @on-get-location="onGetLocation"
      />
    </view>
    <!-- end 腾讯地图组件 -->
    <!--  #endif -->

    <!-- 确认删除弹窗 -->
    <confirm-pop
      :show-pop="showPop"
      :pop-content="popContent"
      @handle-pop-cancel="onPopCancel"
      @handle-pop-confirm="onPopConfirm"
    />
  </view>
</template>

<script setup>
import { wgs84togcj02, gcj02tobd09 } from '@/utils/locTrans'
const domainAddress = import.meta.env.VITE_APP_DOMAIN_ADDRESS

const addrId = ref(0)
const showPicker = ref(false)
const addrIds = ref([])
let provinceId = 0
let cityId = 0
let areaId = 0
const province = ref('')
const city = ref('')
const area = ref('')
const consignee = ref('')
const mobile = ref('')
const addr = ref('')
let lat = ''
let lng = ''
const showSetDefault = ref(false)
const isDefault = ref(0) // 是否为默认地址
let saveing = false // 是否正在保存地址
const showPop = ref(false)
const popContent = reactive({
  title: '是否确定删除该地址？',
  content: '删除地址后将无法恢复， 请您慎重考虑'
})
const name = ref('')// 详细地址
const isMap = ref(false)
const key = import.meta.env.VITE_APP_MAP_KEY

/**
   * 生命周期函数--监听页面加载
   */
onLoad(async (options) => {
  await onGetAddressList()
  if (options.addrId) {
    addrId.value = options.addrId
    if (!options.module) {
      onGetAddressById()
    } else {
      onAfterLoc(options)
    }
  } else {
    uni.setNavigationBarTitle({
      title: '新建地址'
    })
  }
})

/**
 * 获取到定位后的回调
 * loc 定位信息
 */
const onAfterLoc = (loc) => {
  addrId.value = uni.getStorageSync('cloudAddrInfo').addrId
  mobile.value = uni.getStorageSync('cloudAddrInfo').mobile
  consignee.value = uni.getStorageSync('cloudAddrInfo').consignee
  isDefault.value = uni.getStorageSync('cloudAddrInfo').isDefault
  if (loc && loc.module === 'locationPicker') { // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
    addr.value = loc.addr
    lat = loc.latng.split(',')[0]
    lng = loc.latng.split(',')[1]
    isMap.value = false
    util.area(loc.addr, loc.name).then(res => {
      if (!res) return
      const addrReplacrstr = res[0].name + res[1].name + res[2].name
      addr.value = addr.value.replace(addrReplacrstr, '') || loc.name
      province.value = res[0].name
      city.value = res[1].name
      area.value = res[2].name
      provinceId = res[0].areaId
      cityId = res[1].areaId
      areaId = res[2].areaId
      provArray.value = res[3]
      cityArray.value = res[4]
      areaArray.value = res[5]
    })
  }
}

/**
 * 地区缓存
 */
const onGetAddressList = () => {
  return new Promise(resolve => {
    const params = {
      url: '/mall4cloud_order/area/list',
      method: 'GET',
      data: {}
    }
    if (!uni.getStorageSync('cloudProvArray')) {
      http.request(params).then(res => {
        uni.setStorageSync('cloudProvArray', res)
        resolve()
      })
    } else {
      resolve()
    }
  })
}
/**
   * 地区弹窗确认按钮
   */
const onAddressPickerConfirm = (selectedAddrInfo, isChange) => {
  if (isChange) {
    area.value = selectedAddrInfo.area
    areaId = selectedAddrInfo.areaId
    city.value = selectedAddrInfo.city
    cityId = selectedAddrInfo.cityId
    province.value = selectedAddrInfo.province
    provinceId = selectedAddrInfo.provinceId
    addrIds.value = [selectedAddrInfo.provinceId, selectedAddrInfo.cityId, selectedAddrInfo.areaId]
  }
  showPicker.value = false
}

/**
 * 默认地址复选框切换
 */
const onSetDefaultAddr = () => {
  const flag = Boolean(!isDefault.value)
  isDefault.value = flag ? 1 : 0
}
/**
 * 删除地址
 */
const onDelAddress = () => {
  const params = {
    url: '/mall4cloud_user/user_addr?addrId=' + addrId.value,
    method: 'DELETE'
  }
  http.request(params).then(() => {
    uni.showToast({
      title: '删除成功',
      icon: 'none',
      mask: true
    })
    showPop.value = false
    setTimeout(() => {
      uni.navigateBack({
        delta: 1
      })
    }, 1200)
  })
}

/**
 * 显示弹窗
 */
const onHandleShowPop = () => {
  showPop.value = true
}

/**
 * 弹窗取消
 */
const onPopCancel = () => {
  showPop.value = false
}
/**
 * 弹窗确认
 */
const onPopConfirm = () => {
  onDelAddress()
}

const provArray = ref()
const cityArray = ref()
const areaArray = ref()
const onGetLocation = (loc) => {
  // #ifdef H5 || APP-PLUS
  addr.value = loc.poiaddress
  lat = loc.latlng.lat
  lng = loc.latlng.lng
  name.value = loc.poiname
  isMap.value = false
  // #endif

  // #ifdef MP-WEIXIN
  const municipality = '北京市|天津市|上海市|重庆市' // 直辖市
  const rex = new RegExp(`(${municipality})+(?=${municipality})`)
  lat = loc.latitude // 纬度
  lng = loc.longitude // 经度
  addr.value = loc.address?.replace(rex, '') // 详细地址
  name.value = loc.name // 详细地址
  // #endif

  util.area(addr.value, name.value).then(res => {
    if (!res) return
    addr.value = addr.value.replace(res[0].name + res[1].name + res[2].name, '') || res.poiname
    province.value = res[0].name
    city.value = res[1].name
    area.value = res[2].name
    provinceId = res[0].areaId
    cityId = res[1].areaId
    areaId = res[2].areaId
    provArray.value = res[3]
    cityArray.value = res[4]
    areaArray.value = res[5]
  })
  const locationInfo = { latitude: lat, longitude: lng }
  let locationRes
  // #ifdef H5 || APP-PLUS
  locationRes = gcj02tobd09(wgs84togcj02(locationInfo))
  // #endif

  // #ifdef MP-WEIXIN
  locationRes = gcj02tobd09(locationInfo)
  // #endif
  lat = locationRes.latitude
  lng = locationRes.longitude
}

/**
 * 保存地址
 */
const onSaveAddress = () => {
  // 数据校验
  if (!consignee.value.trim()) {
    uni.showToast({
      title: '请输入收件人姓名',
      icon: 'none',
      mask: true
    })
    return
  }

  if (consignee.value?.length < 2) {
    uni.showToast({
      title: '收件人姓名需在2到20个字符之间',
      icon: 'none',
      mask: true
    })
    return
  }
  if (!util.checkPhoneNumber(mobile.value)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none',
      mask: true
    })
    return
  }
  if (!provinceId || !cityId || !areaId) {
    uni.showToast({
      title: '请选择完整地区信息',
      icon: 'none',
      mask: true
    })
    return
  }
  if (!addr.value.trim() || addr.value?.length < 5) {
    uni.showToast({
      title: '请输入字数在5-50之间的详细地址',
      icon: 'none',
      mask: true
    })
    return
  }

  if (saveing) {
    return
  }
  saveing = true
  // 保存地址
  const params = {
    url: '/mall4cloud_user/user_addr',
    method: addrId.value ? 'PUT' : 'POST',
    data: {
      addr: addr.value,
      addrId: addrId.value,
      area: area.value,
      areaId,
      city: city.value,
      cityId,
      consignee: consignee.value,
      isDefault: isDefault.value,
      lat,
      lng,
      mobile: mobile.value,
      province: province.value,
      provinceId
    }
  }
  http.request(params).then(() => {
    uni.showToast({
      title: '保存成功',
      icon: 'none',
      mask: true
    })
    setTimeout(() => {
      // 普通h5返回上一页
      // #ifdef H5
      history.back()
      // #endif
      // 微信小程序与APP返回上一页
      // #ifdef MP-WEIXIN || APP-PLUS
      uni.navigateBack({
        delta: 1
      })
      // #endif
      saveing = false
    }, 1200)
  }).catch(err => {
    saveing = false
    uni.showToast({
      title: err.msg || 'Error',
      icon: 'none'
    })
  })
}

/**
 * 根据地址id获取地址信息
 */
const onGetAddressById = () => {
  const params = {
    url: '/mall4cloud_user/user_addr',
    method: 'GET',
    data: {
      addrId: addrId.value
    }
  }
  http.request(params).then(res => {
    addrIds.value = [res.provinceId, res.cityId, res.areaId]
    province.value = res.province
    city.value = res.city
    area.value = res.area
    provinceId = res.provinceId
    cityId = res.cityId
    areaId = res.areaId
    consignee.value = res.consignee
    mobile.value = res.mobile
    addr.value = res.addr
    lat = res.lat
    lng = res.lng
    isDefault.value = res.isDefault
    showSetDefault.value = !res.isDefault
  })
}

/**
 * 选择定位信息
 */
const onSelLocation = util.debounce(function () {
  const routes = getCurrentPages() // 获取当前打开过的页面路由数组
  const curRoute = '/' + routes[routes.length - 1].route
  // #ifdef H5
  uni.setStorageSync('cloudAddrInfo', { addrId: addrId.value, mobile: mobile.value, consignee: consignee.value, isDefault: isDefault.value })
  const backUrl = encodeURIComponent(domainAddress + curRoute + '?addrId=' + addrId.value || 0)

  uni.getLocation({
    type: 'gcj02',
    altitude: true,
    success: res => {
      // 在指定位置附近进行位置选择,coord用英文逗号分隔，纬度在前，经度在后
      const coord = [res.latitude, res.longitude].join(',')
      setTimeout(() => {
        window.location.replace(`https://apis.map.qq.com/tools/locpicker?search=1&type=0&backurl=${backUrl}&key=${key}&referer=myapp&coord=${coord}`)
      }, 10)
    },
    fail: () => {
      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.authorize({
    scope: 'scope.userLocation',
    success: () => {
      uni.chooseLocation({
        success: (res) => {
          onGetLocation(res)
        },
        fail: (err) => {
          if (err.errMsg !== 'chooseLocation:fail cancel') {
            uni.showToast({
              title: '定位失败',
              icon: 'none'
            })
          }
        }
      })
    },
    fail: () => {
      uni.showToast({
        title: '请在「右上角」 - 「设置」授予位置信息权限',
        icon: 'none'
      })
    }
  })
  // #endif
})

</script>

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