<template>
    <w-page-common btnText="确认" @submit="onSubmit">
        <TCard>
            <TInputField
                v-model="formData.contact"
                label="联系人"
                placeholder="请填写联系人姓名"
                inputAlign="left"
            />
            <TInputField
                v-model="formData.mobile"
                label="联系电话"
                placeholder="请填写联系电话"
                inputAlign="left"
                :maxlength="11"
            />
            <TSelectField
                label="所在区域"
                placeholder="请选择所在区域"
                @on-click="chooseLocation"
                v-model="formData.region"
            />
            <TInputField
                v-model="formData.address"
                label="详细地址"
                placeholder="请填写详细地址"
                inputAlign="left"
            />
        </TCard>
        <!-- 是否默认地址 -->
        <view class="is-default flex m-[20rpx]" @click="booleanToNumber">
            <image
                v-if="formData.isDefault === 1"
                src="/static/images/icon_select.png"
                mode=""
            ></image>
            <image
                v-if="formData.isDefault === 0"
                src="/static/images/icon_unselect.png"
                mode=""
            ></image>
            <text class="normal ml-[15rpx]">设为默认</text>
        </view>
        <template #btn>
            <view class="page-common-footer px-[20rpx]">
                <!-- #ifdef H5 || MP-WEIXIN -->
                <view v-if="addressId" class="flex-1 mr-[20rpx]">
                    <button
                        :plain="true"
                        class="bg-error text-lg text-white rounded-full leading-[80rpx]"
                        @click="delPupop = true"
                    >
                        删除
                    </button>
                </view>
                <!-- #endif -->
                <view class="flex-1">
                    <button
                        class="bg-primary text-lg text-white rounded-full leading-[80rpx]"
                        @click="onSubmit"
                    >
                        保存
                    </button>
                </view>
            </view>
        </template>
        <w-confirm-popup
            contentText="确认删除该地址吗？"
            v-model="delPupop"
            @confirm="handleAddressDel"
        />
    </w-page-common>
</template>

<script lang="ts" setup>
import { onLoad, onReady, onUnload } from '@dcloudio/uni-app'
import { ref, unref } from 'vue'
import { getGeocoderCoordinate, getGeocoder } from '@/api/app'
import { apiAddressDetail, apiAddressEdit, apiAddressAdd, apiAddressDel } from '@/api/user'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import { toast } from '@/utils/util'

type FORM = {
    contact: string // 联系方式
    mobile: string | number // 手机号码
    province: string | number // 省
    provinceId: string | number // 省
    city: string | number // 市
    cityId: string | number // 市
    district: string | number // 区
    districtId: string | number // 区
    address: string // 详细地址
    isDefault: number | boolean // 是否默认
    region: string
    longitude: number // 经度
    latitude: number // 纬度
}

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const formData = ref<FORM>({
    contact: '',
    mobile: '',
    province: '',
    provinceId: '',
    city: '',
    cityId: '',
    district: '',
    districtId: '',
    address: '',
    isDefault: 0,
    region: '',
    longitude: 0,
    latitude: 0
})
const formRef = ref()
const addressId = ref<string | number>('')
const delPupop = ref<boolean | null>(false)
// 处理默认地址类型值
const booleanToNumber = () => {
    if (!formData.value.isDefault) {
        formData.value.isDefault = 1
    } else {
        formData.value.isDefault = 0
    }
}

// 获取地址详情
const getAddressDetail = async (): Promise<void> => {
    formData.value = await apiAddressDetail({ id: addressId.value })
    formData.value.region = `${formData.value.province} ${formData.value.city} ${formData.value.district}`
}

// 校验
const onSubmit = () => {
    const form = unref(formData)
    if (!form.contact) return toast('请填写联系人姓名')
    else if (!form.mobile) return toast('请填写联系人姓名')
    else if (!form.region) return toast('请选择所在区域')
    if (form.mobile && !/^1[3-9]\d{9}$/.test(form.mobile)) {
        return toast('请填写正确的手机号')
    }
    if (!addressId.value) handleAddressAdd()
    else handleAddressEdit()
}
// 添加地址
const handleAddressAdd = async (): Promise<void> => {
    await apiAddressAdd({ ...formData.value, userId: userInfo.value.id })
    setTimeout(() => {
        uni.navigateBack()
    }, 300)
}
// 编辑地址
const handleAddressEdit = async (): Promise<void> => {
    await apiAddressEdit({ ...formData.value, userId: userInfo.value.id })
    setTimeout(() => {
        uni.navigateBack()
    }, 300)
}
// 选择省市区
const chooseLocation = () => {
    uni.chooseLocation({
        success(res) {
            getLocation(res.name, res.latitude, res.longitude)
        },
        fail(error) {
            console.log(error)
        }
    })
}

// 逆解析地址
const getLocation = async (name: string, latitude: string | number, longitude: string | number) => {
    try {
        const res1 = await getGeocoderCoordinate({
            lat: latitude,
            lng: longitude
        })
        handleAddressInfo(name, res1, longitude, latitude)
    } catch (error) {
        console.log('地址逆解析', error)
    }
}

// 处理接口返回的地址数据
const handleAddressInfo = (name: string, event: any, longitude: number, latitude: number) => {
    let cityId = event.cityId
    const adInfo = event.amapGenCoderResponse.amapAddressComponent
    if (cityId == 110000 || cityId == 310000 || cityId == 210000 || cityId == 410000) {
        cityId = cityId * 1
        cityId += 100
    }
    formData.value.cityId = cityId + '' // 市id
    formData.value.provinceId = event.provinceId + '' // 省id
    formData.value.districtId = event.districtId + '' // 区id
    formData.value.region = `${adInfo.province} ${adInfo.city} ${adInfo.district}` //省 市 区
    // 地址截取门牌号
    const idx = event.amapGenCoderResponse.address.indexOf(adInfo.street)
    let streetName = event.amapGenCoderResponse.address.slice(idx)
    if (name) {
        streetName = name // name是地图器选择时，选中的名称或街道名称
    }
    formData.value.address = streetName
    formData.value.longitude = longitude.toFixed(10) // 经度
    formData.value.latitude = latitude.toFixed(10) // 纬度
    console.log('formData.value', formData.value)

    // console.log('地址', name, event)
}

// 删除地址
const handleAddressDel = async (): Promise<void> => {
    try {
        await apiAddressDel({ id: addressId.value })
        setTimeout(() => {
            uni.navigateBack()
        }, 300)
    } catch (error) {
        console.log(error)
    }
}

onLoad((options: { id?: number }) => {
    addressId.value = Number(options.id)
    if (options.id) {
        uni.setNavigationBarTitle({
            title: '编辑地址'
        })
        getAddressDetail()
    } else {
        uni.setNavigationBarTitle({
            title: '添加地址'
        })
        let wxAddress = uni.getStorageSync('wxAddress')
        console.log('wxAddress', wxAddress)
        if (!wxAddress) return
        wxAddress = JSON.parse(wxAddress)
        formData.value.contact = wxAddress.name
        formData.value.mobile = wxAddress.mobile
        getLocation(wxAddress.latitude, wxAddress.longitude)
    }
})

onReady(() => {
    // formRef.value?.setRules(rules.value)
})

onUnload(() => {
    uni.removeStorageSync('wxAddress')
})
</script>
<style lang="scss">
.card {
    margin: 20rpx;
    margin-bottom: 0;
    padding: 0 24rpx;
    border-radius: 14rpx;
    background-color: #ffffff;

    .label {
        color: #222222;
        font-size: 28rpx;
        margin-right: 30rpx;
        line-height: 70rpx;
    }
}

.is-default {
    align-items: center;
    image {
        width: 40rpx;
        height: 40rpx;
    }
}
</style>
