<template>
  <view class="page-container">
    <scroll-view class="address-edit-page" direction="vertical">
    <view class="form-group">
      <view class="form-item">
        <text class="label">鏀惰揣浜?/text>
        <input class="input" v-model="formData.name" placeholder="璇峰～鍐欐敹璐т汉濮撳悕" />
      </view>
      <view class="form-item">
        <text class="label">鎵嬫満鍙风爜</text>
        <input class="input" v-model="formData.phone" type="number" maxlength="11" placeholder="璇峰～鍐欐墜鏈哄彿鐮? />
      </view>
      <view class="form-item">
        <text class="label">鎵?鍦ㄥ湴鍖?/text>
        <input class="input" v-model="regionString" placeholder="鐪佸競鍖哄幙銆佷埂闀囩瓑" />
      </view>
      <view class="form-item">
        <text class="label">璇︾粏鍦板潃</text>
        <input class="input" v-model="formData.detail" placeholder="琛楅亾銆佹ゼ鐗屽彿绛? />
      </view>
    </view>
    
    <view class="form-group">
      <view class="form-item">
        <text class="label">鏅鸿兘濉啓</text>
        <textarea class="smart-textarea" v-model="smartInput" placeholder="绮樿创濮撳悕+鐢佃瘽+鍦板潃锛岃嚜鍔ㄨ瘑鍒～鍏? @input="parseSmartInput" maxlength="200"></textarea>
        <text class="smart-tip">绀轰緥锛氬紶涓?13800138000 鍖椾含甯傛湞闃冲尯涓夐噷灞疭OHO A搴?/text>
      </view>
      <view class="form-item">
        <text class="label">鏍囩</text>
        <view class="tags-container">
          <text 
            v-for="tag in tags" 
            :key="tag" 
            class="tag-item"
            :class="{ active: formData.label === tag }"
            @click="selectTag(tag)"
          >{{ tag }}</text>
        </view>
      </view>
      <view class="form-item switch-item">
        <text class="label">璁句负榛樿鏀惰揣鍦板潃</text>
        <switch :checked="formData.isDefault" color="#ff5000" @change="onSwitchChange" />
      </view>
    </view>
    
    <view class="footer-btn">
        <button class="save-btn" @click="saveAddress">淇濆瓨</button>
        <button v-if="isEdit" class="delete-btn" @click="deleteAddress">鍒犻櫎鏀惰揣鍦板潃</button>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="uts">
import { ref, reactive, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { supabaseService, AddAddressParams, UpdateAddressParams } from '@/utils/supabaseService.uts'

type Address = {
  id: string
  name: string
  phone: string
  province: string
  city: string
  district: string
  detail: string
  isDefault: boolean
  label?: string
}

const isEdit = ref(false)
const addressId = ref('')
const regionString = ref('')
const tags = ['瀹?, '鍏徃', '瀛︽牎']
const smartInput = ref('')

type AddressForm = {
    name: string
    phone: string
    detail: string
    isDefault: boolean
    label: string
}

const formData = reactive({
  name: '',
  phone: '',
  detail: '',
  isDefault: false,
  label: ''
} as AddressForm)

const loadAddress = async (id: string) => {
  try {
    // 浠嶴upabase鍔犺浇鍦板潃璇︽儏
    const address = await supabaseService.getAddressById(id)
    if (address != null) {
      formData.name = address.recipient_name
      formData.phone = address.phone
      formData.detail = address.detail_address
      formData.isDefault = address.is_default
      formData.label = address.label ?? ''
      regionString.value = `${address.province} ${address.city} ${address.district}`.trim()
    } else {
      // 濡傛灉Supabase娌℃湁鎵惧埌锛屽皾璇曚粠鏈湴瀛樺偍鍔犺浇
      const storedAddresses = uni.getStorageSync('addresses')
      if (storedAddresses != null) {
        const addresses = JSON.parse(storedAddresses as string) as Address[]
        const localAddress = addresses.find(item => item.id === id)
        if (localAddress != null) {
          formData.name = localAddress.name
          formData.phone = localAddress.phone
          formData.detail = localAddress.detail
          formData.isDefault = localAddress.isDefault
          formData.label = localAddress.label ?? ''
          regionString.value = `${localAddress.province} ${localAddress.city} ${localAddress.district}`.trim()
        }
      }
    }
  } catch (error) {
    console.error('鍔犺浇鍦板潃璇︽儏澶辫触:', error)
    // 澶辫触鏃朵粠鏈湴瀛樺偍鍔犺浇
    const storedAddresses = uni.getStorageSync('addresses')
    if (storedAddresses != null) {
      try {
        const addresses = JSON.parse(storedAddresses as string) as Address[]
        const address = addresses.find(item => item.id === id)
        if (address != null) {
          formData.name = address.name
          formData.phone = address.phone
          formData.detail = address.detail
          formData.isDefault = address.isDefault
          formData.label = address.label ?? ''
          regionString.value = `${address.province} ${address.city} ${address.district}`.trim()
        }
      } catch (e) {
        console.error('瑙ｆ瀽鏈湴鍦板潃鏁版嵁澶辫触', e)
      }
    }
  }
}

onLoad((options) => {
  if (options['id'] != null) {
    isEdit.value = true
    addressId.value = options['id'] as string
    loadAddress(addressId.value)
  }
})

const selectTag = (tag: string) => {
  if (formData.label === tag) {
    formData.label = ''
  } else {
    formData.label = tag
  }
}

const onSwitchChange = (e: UniSwitchChangeEvent) => {
  formData.isDefault = e.detail.value
}

const saveAddress = async () => {
  if (formData.name == '') {
    uni.showToast({ title: '璇峰～鍐欐敹璐т汉', icon: 'none' })
    return
  }
  if (formData.phone == '') {
    uni.showToast({ title: '璇峰～鍐欐墜鏈哄彿鐮?, icon: 'none' })
    return
  }
  if (regionString.value == '') {
    uni.showToast({ title: '璇峰～鍐欐墍鍦ㄥ湴鍖?, icon: 'none' })
    return
  }
  if (formData.detail == '') {
    uni.showToast({ title: '璇峰～鍐欒缁嗗湴鍧?', icon: 'none' })
    return
  }
  
  // 绠?鍗曡В鏋愬湴鍖猴紙杩欓噷绠?鍖栧鐞嗭紝瀹為檯搴斾娇鐢ㄩ?夋嫨鍣級
  const regions = regionString.value.split(' ')
  const province = regions[0] ?? ''
  const city = regions[1] ?? ''
  const district = regions.slice(2).join(' ')

  // 鏋勫缓鍦板潃瀵硅薄
  const addressData = {
    recipient_name: formData.name,
    phone: formData.phone,
    province: province,
    city: city,
    district: district,
    detail_address: formData.detail,
    postal_code: '', // 濡傛灉闇?瑕佸彲浠ユ坊鍔犻偖鏀跨紪鐮佸瓧娈?
    is_default: formData.isDefault,
    label: formData.label
  } as AddAddressParams

  let success = false
  
  if (isEdit.value) {
    // 鏇存柊鍦板潃
    const updateData = {
        recipient_name: formData.name,
        phone: formData.phone,
        province: province,
        city: city,
        district: district,
        detail_address: formData.detail,
        postal_code: '',
          is_default: formData.isDefault,
          label: formData.label
      } as UpdateAddressParams
      success = await supabaseService.updateAddress(addressId.value, updateData)
  } else {
    // 娣诲姞鏂板湴鍧?
    success = await supabaseService.addAddress(addressData)
  }

  if (success) {
    // 鍚屾椂鏇存柊鏈湴瀛樺偍浣滀负缂撳瓨
    const storedAddresses = uni.getStorageSync('addresses')
    let addresses: Address[] = []
    if (storedAddresses != null) {
      try {
        addresses = JSON.parse(storedAddresses as string) as Address[]
      } catch (e) {
        addresses = []
      }
    }
    
    // 濡傛灉璁句负榛樿锛屽彇娑堝叾浠栭粯璁?
    if (formData.isDefault) {
      addresses.forEach(item => {
        item.isDefault = false
      })
    }
    
    if (isEdit.value) {
      const index = addresses.findIndex(item => item.id === addressId.value)
      if (index !== -1) {
        addresses[index] = {
          ...addresses[index],
          name: formData.name,
          phone: formData.phone,
          province: province,
          city: city,
          district: district,
          detail: formData.detail,
          isDefault: formData.isDefault,
          label: formData.label
        }
      }
    } else {
      const newAddress: Address = {
        id: `addr_${Date.now()}`, // 涓存椂ID锛屽疄闄呯敱Supabase鐢熸垚
        name: formData.name,
        phone: formData.phone,
        province: province,
        city: city,
        district: district,
        detail: formData.detail,
        isDefault: formData.isDefault,
        label: formData.label
      }
      addresses.push(newAddress)
    }
    
    uni.setStorageSync('addresses', JSON.stringify(addresses))
    
    uni.showToast({
      title: '淇濆瓨鎴愬姛',
      icon: 'success'
    })
    
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } else {
    console.error('淇濆瓨鍦板潃澶辫触')
    uni.showToast({
      title: '淇濆瓨澶辫触',
      icon: 'none'
    })
  }
}

const parseSmartInput = () => {
  const input = smartInput.value.trim()
  if (input == '') return
  
  // 鎻愬彇鎵嬫満鍙?
  const phoneRegex = /(1[3-9]\d{9})/
  const phoneMatch = input.match(phoneRegex)
  if (phoneMatch != null) {
    formData.phone = phoneMatch[0] ?? ''
  }
  
  // 鎻愬彇濮撳悕锛堝彇绗竴涓?-4浣嶄腑鏂囷級
  const nameRegex = /([\u4e00-\u9fa5]{2,4})/
  const nameMatch = input.match(nameRegex)
  if (nameMatch != null) {
    formData.name = nameMatch[0] ?? ''
  }
  
  // 鍘绘帀濮撳悕鍜岀數璇濆悗鍓╀綑浣滀负鍦板潃
  let addrText = input
  if (formData.name != '') addrText = addrText.replace(formData.name, '')
  if (formData.phone != '') addrText = addrText.replace(formData.phone, '')
  addrText = addrText.replace(/[锛?;锛沑s]+/g, ' ').trim()
  
  // 瑙ｆ瀽鐪佸競鍖?
  const pattern1 = /^(.*?鐪??(.*?甯??(.*?[鍖哄幙])?(.*)$/
  const m = addrText.match(pattern1)
  if (m != null) {
    const province = m[1] ?? ''
    const city = m[2] ?? ''
    const district = m[3] ?? ''
    const detail = m[4] ?? ''
    regionString.value = `${province.trim()} ${city.trim()} ${district.trim()}`.trim()
    formData.detail = detail.trim()
  } else {
    formData.detail = addrText
  }
}
const deleteAddress = () => {
  uni.showModal({
    title: '鎻愮ず',
    content: '纭畾瑕佸垹闄よ鍦板潃鍚楋紵',
    success: (res: UniShowModalResult) => {
      if (res.confirm) {
        // 璋冪敤Supabase鏈嶅姟鍒犻櫎鍦板潃
        supabaseService.deleteAddress(addressId.value).then((success) => {
          if (success) {
            // 鍚屾椂浠庢湰鍦板瓨鍌ㄤ腑绉婚櫎
            const storedAddresses = uni.getStorageSync('addresses')
            if (storedAddresses != null) {
              try {
                let addresses = JSON.parse(storedAddresses as string) as Address[]
                addresses = addresses.filter(item => item.id !== addressId.value)
                uni.setStorageSync('addresses', JSON.stringify(addresses))
              } catch (e) {
                console.error('瑙ｆ瀽鏈湴鍦板潃鏁版嵁澶辫触', e)
              }
            }
            
            uni.showToast({
              title: '鍒犻櫎鎴愬姛',
              icon: 'success'
            })
            
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          } else {
            console.error('鍒犻櫎鍦板潃澶辫触')
            uni.showToast({
              title: '鍒犻櫎澶辫触',
              icon: 'none'
            })
          }
        })
      }
    }
  })
}
</script>

<style>
.page-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.address-edit-page {
    flex: 1; /* Replace min-height: 100vh */
}

.form-group {
  background-color: white;
  margin-bottom: 15px;
  padding: 0 15px;
}

.form-item {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
  padding: 15px 0;
}

.form-item:last-child {
  border-bottom: none;
}

.label {
  width: 80px;
  font-size: 15px;
  color: #333;
}

.input {
  flex: 1;
  font-size: 15px;
  color: #333;
}

.switch-item {
  justify-content: space-between;
}

.tags-container {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
}

.tag-item {
  font-size: 12px;
  color: #666;
  border: 1px solid #ddd;
  padding: 4px 12px;
  border-radius: 15px;
  margin-right: 10px;
}

.tag-item.active {
  background-color: #ff5000;
  color: white;
  border-color: #ff5000;
}

.footer-btn {
  margin-top: 30px;
  padding: 0 15px;
}

.save-btn {
  background-color: #ff5000;
  color: white;
  border-radius: 25px;
  font-size: 16px;
  height: 44px;
  line-height: 44px;
  border: none;
  margin-bottom: 15px;
}

.delete-btn {
  background-color: white;
  color: #333;
  border-radius: 25px;
  font-size: 16px;
  height: 44px;
  line-height: 44px;
  border: 1px solid #ddd;
}
</style>


