import { shallowRef, reactive, computed } from 'vue'
import { loginStore } from '@/stores'
import { userReceiveInfo, delUserReceiveInfo, userReceiveIsDefault } from '@/services/api/user'

const { userId } = loginStore.$mapGetters()

export function useAddressForm(selectedRow?: Model.UserReceiveInfoRsp) {
    const loading = shallowRef(false)

    const formData = reactive<Proto.UserReceiveInfoReq>({
        ReceiveInfoId: 0,
        UserID: userId.value,
        CardTypeID: 0,
        ReceiverName: '',
        CardNum: '',
        PhoneNum: '',
        Address: '',
        TakeRemark: '',
    })

    if (selectedRow?.autoid) {
        ({
            autoid: formData.ReceiveInfoId,
            userid: formData.UserID,
            receivername: formData.ReceiverName,
            cardtypeid: formData.CardTypeID,
            cardnum: formData.CardNum,
            phonenum: formData.PhoneNum,
            countryid: formData.CountryID,
            provinceid: formData.ProvinceID,
            cityid: formData.CityID,
            districtid: formData.DistrictID,
            address: formData.Address,
            takeremark: formData.TakeRemark,
        } = selectedRow)
    }

    // 地区名称
    const regionName = computed(() => {
        const { provincename, cityname, districtname } = selectedRow ?? {}
        if (provincename || cityname || districtname) {
            return [provincename, cityname, districtname].join(' ')
        }
        return ''
    })

    const addOrUpdate = () => {
        loading.value = true
        return userReceiveInfo({
            data: formData,
            complete: () => {
                loading.value = false
            }
        })
    }

    const deleteAddress = () => {
        loading.value = true
        return delUserReceiveInfo({
            data: {
                ReceiveInfoId: formData.ReceiveInfoId
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    const updateAddressIsDefault = () => {
        loading.value = true
        return userReceiveIsDefault({
            data: {
                UserId: userId.value,
                AutoId: formData.ReceiveInfoId
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formData,
        regionName,
        addOrUpdate,
        deleteAddress,
        updateAddressIsDefault,
    }
}