<template>
    <!-- Mian Start -->
    <u-form :model="formData" ref="formRef" :error-type="['message', 'toast']">
        <!-- 联系人 -->
        <view class="card">
            <u-form-item prop="contact">
                <view class="flex">
                    <view class="label"> 联系人 </view>
                    <u-input v-model="formData.contact" placeholder="请输入联系人" />
                </view>
            </u-form-item>
        </view>
        <!-- 手机号 -->
        <view class="card">
            <u-form-item prop="mobile">
                <view class="flex">
                    <view class="label"> 手机号 </view>
                    <u-input v-model="formData.mobile" placeholder="请输入手机号码" />
                </view>
            </u-form-item>
        </view>
        <!-- 省市区 -->
		<view class="card" v-if="platForm == 'h5'">
		    <u-form-item prop="region">
		        <view class="flex" style="width: 100%">
		            <view class="label"> 省市区 </view>
		            <view class="flex-1">
		                <add-select @change="addressChange" :crmName="formData.region"></add-select>
		            </view>
		            <u-icon name="arrow-right" size="22" color="#888888"></u-icon>
		        </view>
		    </u-form-item>
		</view>
        <view class="card" v-else>
            <u-form-item prop="region">
                <view class="flex" style="width: 100%" @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 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="text-xs normal ml-[15rpx]">设为默认</text>
        </view>
    </u-form>
    <!-- Mian End -->

    <!-- 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">
            <button
                class="bg-primary 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="#F36161"
        @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'
import { getPrivacySettion } from '@/utils/util'
import addSelect from "@/components/address-select/address-select"

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
}

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const formData = ref<FORM>({
    contact: '',
    mobile: '',
    province: '',
    provinceId: '',
    city: '',
    cityId: '',
    district: '',
    districtId: '',
    address: '',
    isDefault: 0,
    region: ''
})
const formRef = ref()
const addressId = ref<string | number>('')
const delPupop = ref<boolean | null>(false)
const platForm = ref("other")
// #ifdef H5
platForm.value = "h5"
// #endif
console.log(platForm.value)
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 = () => {
    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 == null ? "市辖区" : 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 })
    setTimeout(() => {
        uni.navigateBack()
    }, 300)
}
// 编辑地址
const handleAddressEdit = async (): Promise<void> => {
    await apiAddressEdit({ ...formData.value, userId: userInfo.value.id })
    setTimeout(() => {
        uni.navigateBack()
    }, 300)
}
// 选择省市区
const chooseLocation = async () => {
    await getPrivacySettion()
    uni.chooseLocation({
        success(res) {
            getLocation(res.latitude, res.longitude)
        },
        fail(error) {
            console.log(error)
        }
    })
}

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

// 处理接口返回的地址数据
const handleAddressInfo = (event: any) => {
    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)
    const streetName = event.amapGenCoderResponse.address.slice(idx)
    formData.value.address = streetName
}

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

//h5 地址选择器
const addressChange = async(e: any) =>{
	if (e.value == undefined) {
		return
	}
	let val = e.value.split(",")
	formData.value.cityId = val[1] + '' // 市id
	formData.value.provinceId = val[0] + '' // 省id
	formData.value.districtId = val[2] + '' // 区id
	
	formData.value.region = e.valueStr
}

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: 34rpx;
        height: 34rpx;
    }
}
</style>
