import { request } from './request';

export async function getAddress(ctx:any) {
    try {
        if (!ctx) return;

        wx.showLoading({ title: "获取地址中..." });

        const tempAddress = wx.getStorageSync("tempAddress");
        const tempAddressId = wx.getStorageSync("tempAddressId");

        if (tempAddress && tempAddressId) {
            ctx.setData({
                defualtAddress: tempAddress,
                addressId: tempAddressId
            });

            wx.removeStorageSync("tempAddress");
            wx.removeStorageSync("tempAddressId");
            return;
        }

        const localAddress = wx.getStorageSync("defualtAddress");
        const localAddressId = wx.getStorageSync("addressId");

        if (localAddress && localAddressId) {
            ctx.setData({
                defualtAddress: localAddress,
                addressId: localAddressId
            });
            return;
        }

        const res = await request<any>({
            options: {
                url: "/app/member-address/search",
                data: {
                    id: Number(wx.getStorageSync("mbuId")),
                },
            },
        });

        // @ts-ignore
        const defualtAddressObj = res.data?.find((item: any) => item.defaultStatus === true);

        if (defualtAddressObj) {
            const str = `${defualtAddressObj.location.join("")}${defualtAddressObj.address}`;

            ctx.setData({
                defualtAddress: str,
                addressId: defualtAddressObj.id,
            });

            wx.setStorageSync("addressId", defualtAddressObj.id);
            wx.setStorageSync("defualtAddress", str);
        } else {
            ctx.setData({
                defualtAddress: "未设置地址",
                addressId: null,
            });
        }
    } catch (err) {
        wx.showToast({
            icon: "none",
            title: "获取收货地址失败！",
        });
    } finally {
        wx.hideLoading();
    }
}
