<template>
    <view class="bg-[var(--page-bg-color)] min-h-[100vh] overflow-hidden address-edit" :style="themeColor()">
        <u-form labelPosition="left" :model="formData" errorType='toast' :rules="rules" ref="formRef">
            <view class="sidebar-margin card-template mt-[var(--top-m)] py-[20rpx]">
                <view>
                    <u-form-item label="收货人" prop="consignee" labelWidth="200rpx">
                        <u-input fontSize="28rpx" v-model.trim="formData.consignee" border="none" clearable
                            maxlength="25" placeholderStyle="color: #888" placeholder="请输入收货人姓名" />
                    </u-form-item>
                </view>
                <view class="mt-[16rpx]">
                    <u-form-item label="手机号码" prop="phone" labelWidth="200rpx">
                        <u-input fontSize="28rpx" v-model.trim="formData.phone" maxlength="11" border="none" clearable
                            placeholder="请输入手机号码" placeholderStyle="color: #888" />
                    </u-form-item>
                </view>
                <view class="mt-[16rpx]">
                    <u-form-item label="选择地区" prop="provincialCityCountry" labelWidth="200rpx">
                        <view class="flex w-full items-center h-[52rpx]" @click="selectArea">
                            <view v-if="!formData.provincialCityCountry" class="text-[#888] text-[28rpx] flex-1">请选择地区
                            </view>
                            <view v-else class="text-[28rpx] flex-1 leading-[1.4]">{{ formData.provincialCityCountry }}
                            </view>
                        </view>
                    </u-form-item>
                </view>
                <view class="mt-[16rpx]">
                    <u-form-item label="详细地址" prop="address" labelWidth="200rpx">
                        <u-input fontSize="28rpx" v-model="formData.address" border="none" clearable maxlength="120"
                            placeholder="请填写详细地址" placeholderStyle="color: #888" />
                    </u-form-item>
                </view>
            </view>
            <view class="sidebar-margin card-template mt-[var(--top-m)] py-[10rpx]">
                <u-form-item label="设为默认地址" prop="name" :border-bottom="false" labelWidth="200rpx">
                    <u-switch v-model="formData.defaultAddress" size="20" :activeValue="0" :inactiveValue="1"
                        activeColor="var(--primary-color)" inactiveColor="var(--temp-bg)" />
                </u-form-item>
            </view>
        </u-form>
        <view class="w-full footer">
            <view
                class="py-[var(--top-m)] px-[var(--sidebar-m)] footer w-full fixed bottom-30 left-0 right-0 box-border">
                <button hover-class="none"
                    class="primary-btn-bg !text-[#fff] h-[80rpx] leading-[80rpx] rounded-[100rpx] text-[26rpx] font-500"
                    @click="save" :disabled="btnDisabled" :loading="operateLoading"
                    :class="{ 'opacity-50': btnDisabled }">保存
                </button>
            </view>
        </view>
        <cityPicker :column="column" :default-value="defaultValue" :mask-close-able="maskCloseAble" @confirm="confirm"
            @cancel="cancel" :visible="visible" />
    </view>

</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { redirect } from '@/utils/common'
import { addAddress, editAddress, getAddressInfo } from '@/app/api/member'
import cityPicker from '@/uni_modules/piaoyi-cityPicker/components/piaoyi-cityPicker/piaoyi-cityPicker'

const column = ref(3)
const defaultValue = ref<any>(null)
const maskCloseAble = ref<any>(true)
const visible = ref<any>(false)
const formData: any = ref({
    consignee: '', phone: '', provincialNo: '', cityNo: '', countryNo: '', provincialCityCountry: '', address: '', defaultAddress: 0
})

const formRef: any = ref(null)
const source = ref('')
const btnDisabled = ref(false)

onLoad((data: any) => {
    if (data.id) {
        getAddressInfo(data.id).then((res: any) => {
            res.data.defaultAddress = Number(res.data.defaultAddress)
            res.data && Object.assign(formData.value, res.data)
        })
    } else {
        formData.value = {
            consignee: '', phone: '', provincialNo: '', cityNo: '', countryNo: '', provincialCityCountry: '', address: '', defaultAddress: 0
        }
    }
})

const rules = computed(() => {
    return {
        'consignee': {
            type: 'string',
            required: true,
            message: '请输入收货人姓名',
            trigger: ['blur', 'change'],
        },
        'phone': [
            {
                type: 'string',
                required: true,
                message: '请输入手机号码',
                trigger: ['blur', 'change'],
            },
            {
                validator(rule: any, value: any, callback: any) {
                    let mobile = /^1[3-9]\d{9}$/;
                    if (!mobile.test(value)) {
                        callback(new Error('请输入正确的手机号'))
                    } else {
                        callback()
                    }
                }
            }
        ],
        'provincialCityCountry': {
            validator() {
                let bool = true;
                if (uni.$u.test.isEmpty(formData.value.provincialCityCountry)) {
                    bool = false;
                }
                return bool
            },
            message: '请选择地区'
        },
        'address': {
            type: 'string',
            required: true,
            message: '请填写详细地址',
            trigger: ['blur', 'change']
        }
    }
})

const cancel = () => {
    visible.value = false
}

const confirm = (res: any) => {
    formData.value.provincialCityCountry = res.provinceName + '/' + res.cityName + '/' + res.areaName
    formData.value.provincialNo = parseAreaCode(res.code).province;
    formData.value.cityNo = parseAreaCode(res.code).city;
    formData.value.countryNo = res.code;
    visible.value = false
}

const parseAreaCode = (code: any) => {
    const provinceCode = code.substring(0, 2) + '0000';
    const cityCode = code.substring(0, 4) + '00';
    const districtCode = code;
    return {
        province: provinceCode,
        city: cityCode,
        district: districtCode
    };
}

const selectArea = () => {
    visible.value = true
}

const operateLoading = ref(false)
const save = () => {
    const save = formData.value.id ? editAddress : addAddress
    formRef.value.validate().then(() => {
        if (operateLoading.value) return
        operateLoading.value = true

        btnDisabled.value = true

        save(formData.value).then((res: any) => {
            operateLoading.value = false
            setTimeout(() => {
                btnDisabled.value = false
                if (source.value == 'shop_order_payment') {
                    const selectAddress = uni.getStorageSync('selectAddressCallback')
                    if (selectAddress) {
                        selectAddress.address_id = res.data.id || formData.value.id
                        uni.setStorage({
                            key: 'selectAddressCallback',
                            data: selectAddress,
                            success() {
                                redirect({ url: selectAddress.back, mode: 'redirectTo' })
                            }
                        })
                    }
                } else {
                    redirect({
                        url: '/app/pages/member/address',
                        mode: 'redirectTo',
                        param: { source: source.value }
                    })
                }
            }, 1000)
        }).catch(() => {
            operateLoading.value = false
            btnDisabled.value = false
        })
    })
}

</script>

<style lang="scss" scoped>
.address-edit :deep(.u-form-item__body__left__content__label) {
    font-size: 28rpx !important;
}

.address-edit :deep(.u-form-item__body__right) {
    display: flex;
}

.footer {
    height: calc(100rpx + var(--top-m) + var(--top-m) + constant(safe-area-inset-bottom)) !important;
    height: calc(100rpx + var(--top-m) + var(--top-m) + env(safe-area-inset-bottom)) !important;
}

.borders {
    border: 1px solid var(--primary-color);
}
</style>
