<template>
	<view class="form-page">
		<view class="form-card">
			<view class="form-row">
				<text class="form-row__label form-row__label--req">收货人</text>
				<input v-model="form.consigneeName" class="form-row__input" placeholder="请输入收货人" />
			</view>
			<view class="form-row">
				<text class="form-row__label form-row__label--req">手机号</text>
				<input
					v-model="form.mobile"
					class="form-row__input"
					type="number"
					maxlength="11"
					placeholder="11 位手机号"
				/>
			</view>
			<region-fields v-model="region" />
			<view class="form-row form-row--col">
				<text class="form-row__label form-row__label--req">详细地址</text>
				<input
					v-model="form.detailAddress"
					class="form-row__input"
					placeholder="街道、门牌号等"
				/>
			</view>
			<view class="form-row">
				<text class="form-row__label">设为默认</text>
				<switch :checked="form.isDefault === '1'" color="#2e7d32" @change="onDefaultChange" />
			</view>
		</view>
		<view class="form-footer">
			<button class="form-footer__btn" :disabled="saving" @click="handleSave">
				{{ saving ? '保存中…' : '保 存' }}
			</button>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getAddressList, addAddress, updateAddress } from '@/api/member'
import { ensureApiToken } from '@/utils/apiAuth'
import { validateMobile } from '@/utils/memberValidate'
import { loadRegionCascaderTree, findRegionPath } from '@/utils/region'
import RegionFields from '@/components/mine/RegionFields.vue'
import { useActionGuard } from '@/utils/actionGuard'

const saveGuard = useActionGuard()
const saving = saveGuard.locked

const mode = ref('add')
const addressId = ref(null)

const form = reactive({
  consigneeName: '',
  mobile: '',
  detailAddress: '',
  isDefault: '0'
})

const region = ref({
  regionCode: '',
  regionName: '',
  pathCodes: []
})

onLoad((options) => {
  if (!ensureApiToken()) return
  mode.value = options.mode === 'edit' ? 'edit' : 'add'
  if (options.id) {
    addressId.value = Number(options.id)
    uni.setNavigationBarTitle({ title: '编辑地址' })
    loadDetail()
  } else {
    uni.setNavigationBarTitle({ title: '新增地址' })
  }
})

function loadDetail() {
  Promise.all([getAddressList(), loadRegionCascaderTree()])
    .then(([addrRes, { raw }]) => {
      const rows = addrRes.data || []
      const item = rows.find((r) => r.addressId === addressId.value)
      if (!item) return
      form.consigneeName = item.consigneeName || ''
      form.mobile = item.mobile || ''
      form.detailAddress = item.detailAddress || ''
      form.isDefault = item.isDefault === '1' ? '1' : '0'
      const code = item.regionCode || ''
      region.value = {
        regionCode: code,
        regionName: item.regionName || '',
        code,
        name: item.regionName || '',
        pathCodes: code ? findRegionPath(raw, code) || [] : []
      }
    })
    .catch(() => {})
}

function onDefaultChange(e) {
  form.isDefault = e.detail.value ? '1' : '0'
}

function validate() {
  if (!(form.consigneeName || '').trim()) {
    uni.showToast({ title: '请输入收货人', icon: 'none' })
    return false
  }
  const m = validateMobile(form.mobile)
  if (m) {
    uni.showToast({ title: m, icon: 'none' })
    return false
  }
  if (!(region.value.regionCode || '').trim()) {
    uni.showToast({ title: '请选择所在地区', icon: 'none' })
    return false
  }
  if (!(region.value.regionName || '').trim()) {
    uni.showToast({ title: '请选择所在地区', icon: 'none' })
    return false
  }
  if (!(form.detailAddress || '').trim()) {
    uni.showToast({ title: '请输入详细地址', icon: 'none' })
    return false
  }
  return true
}

function buildPayload() {
  return {
    addressId: mode.value === 'edit' ? addressId.value : undefined,
    consigneeName: form.consigneeName.trim(),
    mobile: form.mobile.trim(),
    regionCode: region.value.regionCode,
    regionName: region.value.regionName,
    detailAddress: form.detailAddress.trim(),
    isDefault: form.isDefault
  }
}

function handleSave() {
  saveGuard.run(async () => {
    if (!validate()) return
    const api = mode.value === 'edit' ? updateAddress : addAddress
    await api(buildPayload())
    uni.showToast({ title: '保存成功', icon: 'none' })
    setTimeout(() => uni.navigateBack(), 600)
  })
}
</script>

<style lang="scss" scoped>
@import '@/styles/mine.scss';
</style>
