<template>
  <full-page pageStyle="background:#f5f5f5">
    <view class="bg-white shadow-lg" :style="elderVarStyle">
      <view class="flex items-center px-15 py-12 border-b" @click="chooseLocation()">
        <view class="flex-shrink-0 text-base text-dark">所在地区：</view>
        <view class="w-0 flex-grow text-base truncate" :class="form.region.length ? 'text-dark' : 'text-gray'">
          {{ form.region.join('-') || '请选择所在地区' }}
        </view>
        <uni-icons type="arrowright" size="20" color="#999"></uni-icons>
      </view>
      <view class="flex items-center px-15 py-12 border-b">
        <view class="flex-shrink-0 text-base text-dark">详细地址：</view>
        <view class="flex-grow">
          <input type="text" v-model="form.address" class="text-base w-full" placeholder-class="text-gray text-base"
            placeholder="请输入详细地址" />
        </view>
      </view>
      <view class="flex items-center px-15 py-12 border-b">
        <view class="flex-shrink-0 text-base text-dark">收货人：</view>
        <view class="flex-grow">
          <input type="text" v-model="form.name" class="text-base w-full" placeholder-class="text-gray text-base"
            placeholder="请输入收货人" />
        </view>
      </view>
      <view class="flex items-center px-15 py-12">
        <view class="flex-shrink-0 text-base text-dark">手机号：</view>
        <view class="flex-grow">
          <input type="digit" v-model="form.phone" class="text-base w-full" placeholder-class="text-gray text-base"
            placeholder="请输入手机号" />
        </view>
      </view>
    </view>
    <view class="mt-15 bg-white shadow-lg flex items-center justify-between px-15 py-12" :style="elderVarStyle">
      <view class="flex-shrink-0 text-base text-dark">默认收货地址：</view>
      <switch :checked="form.isDefault" @change="onIsDefaultChange" />
    </view>
    <view class="mt-15 p-15 text-danger">
      <view class="text-base leading-normal">地址管理规则:</view>
      <view class="text-base leading-normal">1、每人最多可保存3个常用地址;</view>
      <view class="text-base leading-normal">2、任意变更操作(删除/修改)后，地址信息将锁定30天无法变更，请谨慎操作。</view>
    </view>

    <template #footer>
      <footer-button text="保存" @onClick="save" />
    </template>
    <!-- <empty-data v-if="list.length === 0" /> -->
  </full-page>
</template>
<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import useElder from '@/hooks/useElder';
import useUser from '@/hooks/useUser';
import { get, remove } from '@/utils/cache';
import { toast, loading, hideLoading } from '@/utils/widget';
import { isMobile } from '@/utils/validator';
import { addAddress, updateAddress } from '@/utils/api';

import fullPage from '@/components/full-page.vue';
import footerButton from '@/components/footer-button.vue';

const defaultRegion = ['浙江', '绍兴'];
const { elderVarStyle } = useElder();
const { userInfo } = useUser();
const id = ref('');
const form = ref({
  region: [],
  address: '',
  name: '',
  phone: '',
  latitude: '',
  longitude: '',
  isDefault: false,
})
const disablePicker = ref(false)


function initForm() {
  const data = get('current-address');
  if (data && data.id === id.value) {
    form.value.region = data.region;
    form.value.address = data.address;
    form.value.name = data.name;
    form.value.phone = data.phone;
    form.value.latitude = data.latitude;
    form.value.longitude = data.longitude;
    form.value.isDefault = data.isDefault;
  }
  remove('current-address');
}

function onIsDefaultChange(e) {
  form.value.isDefault = e.detail.value;
}

function chooseLocation() {
  //#ifdef MP-ALIPAY
  if (disablePicker.value) return;
  disablePicker.value = true;
  uni.chooseLocation({
    success: (res) => {
      const { provinceName, cityName, adName, latitude, longitude, address } = res;
      form.value.region = [provinceName, cityName, adName];
      form.value.address = address;
      form.value.latitude = latitude;
      form.value.longitude = longitude;
    },
    complete: () => {
      disablePicker.value = false;
    }
  })
  //#endif
}

async function save() {
  if (form.value.region.length === 0) {
    toast('请选择所在地区');
    return;
  }
  if (form.value.address.trim() === '') {
    toast('请输入详细地址');
    return;
  }
  if (!(form.value.latitude > 0 && form.value.longitude > 0)) {
    toast('请选择具体位置');
    return;
  }
  if (form.value.name.trim() === '') {
    toast('请输入收货人');
    return;
  }
  if (form.value.phone.trim() === '') {
    toast('请输入手机号');
    return;
  }
  if (!isMobile(form.value.phone.trim())) {
    toast('请输入有效的手机号');
    return;
  }
  const data = {
    accountId: userInfo.value.userId,
    region: form.value.region,
    address: form.value.address.trim(),
    name: form.value.name.trim(),
    phone: form.value.phone.trim(),
    latitude: form.value.latitude,
    longitude: form.value.longitude,
    isDefault: form.value.isDefault,
  }
  if (id.value) {
    data.id = id.value;
  }
  loading('请求中...')
  const res = await (id.value ? updateAddress(data) : addAddress(data))
  hideLoading()
  if (res && res.success) {
    toast('保存成功');
    uni.$emit('change-account-address')
    uni.navigateBack();
  } else {
    toast(res && res.message ? res.message : '保存失败');
  }
}

onLoad(options => {
  id.value = options.id || '';
  uni.setNavigationBarTitle({
    title: id.value ? '编辑收货地址' : '新增收货地址'
  })
  id.value ? initForm() : '';
})

</script>
<style lang="scss" scoped></style>