<template>
    <view class="m-[24rpx]">
        <!-- Mian Start -->
        <u-form :model="formData" ref="formRef" :error-type="['message', 'toast']">
            <!-- 联系人 -->
            <view class="card">
                <u-form-item prop="contact">
                    <view class="flex w-full">
                        <view class="label">联系人</view>
                        <u-input
                            v-model="formData.contact"
                            placeholder="请输入联系人"
                            class="flex-1"
                        />
                    </view>
                </u-form-item>
            </view>
            <!-- 手机号 -->
            <view class="card">
                <u-form-item prop="mobile">
                    <view class="flex w-full">
                        <view class="label">手机号</view>
                        <u-input
                            v-model="formData.mobile"
                            placeholder="请输入手机号码"
                            class="flex-1"
                        />
                    </view>
                </u-form-item>
            </view>
            <!-- 省市区 -->
            <view class="card">
                <u-form-item prop="region">
                    <view class="flex w-full" @click="chooseLocation">
                        <view class="label">省市区</view>
                        <view class="flex-1">
                            <u-input
                                @click="chooseLocation"
                                v-model="formData.region"
                                placeholder="请选择"
                                :disabled="true"
                            />
                        </view>
                        <u-icon name="arrow-right" size="22" color="#888888"></u-icon>
                    </view>
                </u-form-item>
            </view>
            <!-- 门牌号 -->
            <view class="card">
                <u-form-item prop="address">
                    <view class="flex w-full col-start">
                        <view class="label">门牌号</view>
                        <view class="flex-1 pt-[6rpx]">
                            <u-input
                                v-model="formData.address"
                                type="textarea"
                                placeholder="请选择"
                                height="124"
                            />
                        </view>
                    </view>
                </u-form-item>
            </view>
            <!-- 是否默认地址 -->
            <view class="is-default flex my-[20rpx] items-center">
                <u-checkbox shape="circle" active-color="#2468f2" v-model="formData.isDefault">
                    设为默认
                </u-checkbox>
            </view>
        </u-form>
        <!-- Mian End -->
    </view>

    <!-- Footer Start -->
    <view class="flex m-[20rpx] pt-[30rpx]">
        <!-- #ifdef H5 || MP-WEIXIN -->
        <view v-if="addressId" class="flex-1 mr-[20rpx]">
            <button
                class="bg-white text-lg text-info rounded-full leading-[80rpx] h-[80rpx]"
                @click="delPupop = true"
            >
                删除
            </button>
        </view>
        <!-- #endif -->
        <view class="flex-1 mx-[24rpx]">
            <button
                class="custom-button-bgColor text-lg text-white rounded-full leading-[80rpx] h-[80rpx]"
                @click="onSubmit"
            >
                保存
            </button>
        </view>
    </view>
    <!-- Footer End -->

    <!-- 删除地址 弹窗 Start -->
    <u-modal
        id="delete-dialog"
        v-model="delPupop"
        :showCancelButton="true"
        confirm-text="狠心删除"
        title="温馨提示"
        confirm-color="#1296DB"
        @confirm="handleAddressDel"
        @cancel="delPupop = false"
    >
        <view class="text-center p-[50rpx]">
            <text>确认删除该地址吗？</text>
        </view>
    </u-modal>
    <!-- 删除地址 弹窗 End -->
</template>

<script lang="ts" setup>
import { onLoad, onReady, onUnload } from '@dcloudio/uni-app'
import { ref } 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'

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: true,
    region: '',
    longitude: 0,
    latitude: 0
})
const formRef = ref()
const addressId = ref<string | number>('')
const delPupop = ref<boolean | null>(false)
const rules = ref<object>({
    contact: [
        { required: true, message: '请输入联系人', trigger: ['change', 'blur'] },
        {
            min: 1,
            max: 20,
            message: '输入长度不得超过20位',
            trigger: ['blur', 'change']
        }
    ],
    mobile: [
        { required: true, message: '请输入手机号码', trigger: ['change', 'blur'] },
        {
            pattern: /^1[3-9]\d{9}$/,
            transform(value: any) {
                return String(value)
            },
            message: '请输入正确的手机号'
        }
    ],
    region: [{ required: true, message: '请选择省市区', trigger: ['change', 'blur'] }],
    address: [{ required: true, message: '请输入门牌号', trigger: ['change', 'blur'] }]
})

// 处理默认地址类型值
const booleanToNumber = () => {
    return formData.value.isDefault ? 1 : 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 = () => {
    formRef.value.validate((valid: boolean) => {
        if (!valid) return false
        if (!addressId.value) handleAddressAdd()
        else handleAddressEdit()
    })
}
// 添加地址
const handleAddressAdd = async (): Promise<void> => {
    await apiAddressAdd({
        ...formData.value,
        userId: userInfo.value.id,
        isDefault: booleanToNumber()
    })
    setTimeout(() => {
        uni.navigateBack()
    }, 300)
}
// 编辑地址
const handleAddressEdit = async (): Promise<void> => {
    await apiAddressEdit({
        ...formData.value,
        userId: userInfo.value.id,
        isDefault: booleanToNumber()
    })
    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('地址', 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 {
    image {
        width: 40rpx;
        height: 40rpx;
    }
}
</style>
