This commit is contained in:
oneao committed 2026-04-20 22:03:40 +08:00
1 parent 6d54a9e407
commit f59d5c4f59
6 files changed
+791 -372

No files matched your search

+151 -18
View File
@@ -1,32 +1,165 @@
import React, { useEffect } from "react";
import React, { useEffect, useState } from "react";
import LayoutView from "@/components/layout/view";
import EmptyState from "@/components/EmptyStatus";
import { s3ListBucketsApi } from "@/request/api";
import { loadDataApi } from "@/request/api";
import { View, Text, TouchableOpacity } from "react-native";
import { useFamilyStore } from "@/store";
export default function Home() {
// const [dailyData, setDailyData] = useState<any>(null);
const familyStore = useFamilyStore();
const [family, setFamily] = useState<any>({});
const [duration, setDuration] = useState({
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
});
// useEffect(() => {
// fetchDailyInfo()
// .then((res: any) => {
// if (res?.code === "1") {
// console.log(res);
// setDailyData(res);
// }
// })
// .catch(() => {});
// }, []);
const mockMembers = [
{ name: "张三", online: true },
{ name: "李四", online: false },
{ name: "王五", online: true },
];
async function loadFamilyData() {
const res = await loadDataApi({
view_name: "b_family",
search_condition: "id = ?",
search_columns: [],
order_by: "",
args: [familyStore.currentFamily?.family_id],
});
if (res.isSuccess && res.data.length > 0) {
setFamily(res.data[0]);
}
}
function calcDuration(startTime: string) {
const start = new Date(startTime).getTime();
const now = Date.now();
let diff = Math.floor((now - start) / 1000);
const days = Math.floor(diff / (3600 * 24));
diff %= 3600 * 24;
const hours = Math.floor(diff / 3600);
diff %= 3600;
const minutes = Math.floor(diff / 60);
const seconds = diff % 60;
return { days, hours, minutes, seconds };
}
useEffect(() => {
s3ListBucketsApi().then((res) => {
console.log(res);
});
loadFamilyData();
}, []);
useEffect(() => {
if (!family.create_time) return;
const timer = setInterval(() => {
setDuration(calcDuration(family.create_time));
}, 1000);
return () => clearInterval(timer);
}, [family.create_time]);
return (
<LayoutView>
<LayoutView.ScrollView>
<EmptyState type="loading" />
{/* 🌸 顶部情绪背景区 */}
<View
style={{
paddingTop: 60,
paddingBottom: 40,
alignItems: "center",
backgroundColor: "#FFF3F6",
borderBottomLeftRadius: 30,
borderBottomRightRadius: 30,
}}
>
<Text style={{ fontSize: 22, fontWeight: "600", color: "#333" }}>
{family.name || "我们的家庭"}
</Text>
<Text style={{ fontSize: 12, color: "#999", marginTop: 6 }}>在一起的第</Text>
{/* 💖 超大核心数字(恋爱记风格) */}
<Text
style={{
fontSize: 56,
fontWeight: "700",
color: "#FF5C8A",
marginTop: 8,
}}
>
{duration.days}
</Text>
<Text style={{ fontSize: 14, color: "#999" }}>天</Text>
</View>
{/* ⏱ 小时间补充 */}
<View style={{ flexDirection: "row", justifyContent: "center", marginTop: 20 }}>
<Text style={{ fontSize: 14, color: "#666" }}>
{duration.hours}时 {duration.minutes}分 {duration.seconds}秒
</Text>
</View>
{/* 💕 情侣/家庭状态区 */}
<View
style={{
marginTop: 30,
marginHorizontal: 20,
backgroundColor: "#fff",
borderRadius: 20,
padding: 16,
shadowColor: "#000",
shadowOpacity: 0.05,
shadowRadius: 10,
elevation: 2,
}}
>
<Text style={{ fontSize: 12, color: "#999", marginBottom: 10 }}>我们的状态</Text>
<View style={{ flexDirection: "row", justifyContent: "space-between" }}>
<Text>家庭成员</Text>
<Text style={{ fontWeight: "600" }}>{mockMembers.length} 人</Text>
</View>
<View style={{ flexDirection: "row", justifyContent: "space-between", marginTop: 8 }}>
<Text>在线人数</Text>
<Text style={{ fontWeight: "600", color: "#FF5C8A" }}>
{mockMembers.filter((m) => m.online).length} 人
</Text>
</View>
</View>
{/* 💌 邀请区(恋爱记风格按钮) */}
<View style={{ paddingHorizontal: 20, marginTop: 20 }}>
<TouchableOpacity
style={{
backgroundColor: "#FF5C8A",
padding: 14,
borderRadius: 30,
alignItems: "center",
}}
>
<Text style={{ color: "#fff", fontWeight: "600" }}>邀请家人加入</Text>
</TouchableOpacity>
</View>
{/* 🔑 邀请码(弱化但温柔) */}
<View style={{ alignItems: "center", marginTop: 20 }}>
<Text style={{ fontSize: 12, color: "#999" }}>邀请码</Text>
<Text style={{ fontSize: 18, fontFamily: "monospace", marginTop: 4 }}>AB12CD</Text>
</View>
{/* 🕊 底部情绪提示 */}
<View style={{ alignItems: "center", marginTop: 30, marginBottom: 40 }}>
<Text style={{ fontSize: 12, color: "#ccc" }}>💖 一起走过的每一天都值得记录</Text>
</View>
</LayoutView.ScrollView>
</LayoutView>
);
+150 -167
View File
@@ -5,10 +5,10 @@ import { Button, LinkButton, ControlField, Checkbox, Spinner } from "heroui-nati
import { IconQq, IconWeixin } from "@/components/iconfont";
import { useState } from "react";
import { FadeIn } from "react-native-reanimated";
import { useUserStore } from "@/store";
import { useUserStore, useFamilyStore } from "@/store";
import { useRouter } from "expo-router";
// import ExpoQQ from "expo-qq";
// import ExpoWeChat from "expo-wechat";
import ExpoQQ from "expo-qq";
import ExpoWeChat from "expo-wechat";
import { useEvent } from "expo";
import { toast } from "sonner-native";
import { loginQqApi, loginWxApi } from "@/request/api";
@@ -16,6 +16,7 @@ import { loginQqApi, loginWxApi } from "@/request/api";
export default function Login() {
const router = useRouter();
const userStore = useUserStore();
const familyStore = useFamilyStore();
const [loading, setLoading] = useState(false);
const [isAgreed, setIsAgreed] = useState(true);
@@ -26,195 +27,182 @@ export default function Login() {
});
// 登录
// const onLoginFinished = useEvent(ExpoQQ, "onLoginFinished");
// const onGetUserInfo = useEvent(ExpoQQ, "onGetUserInfo");
// const authResult = useEvent(ExpoWeChat, "onAuthResult");
const onLoginFinished = useEvent(ExpoQQ, "onLoginFinished");
const onGetUserInfo = useEvent(ExpoQQ, "onGetUserInfo");
const authResult = useEvent(ExpoWeChat, "onAuthResult");
// useEffect(() => {
// ExpoQQ.init("102826474", "");
// ExpoWeChat.registerApp("wxdab3e21a1f7e392f", "");
// }, []);
useEffect(() => {
ExpoQQ.init("102826474", "");
ExpoWeChat.registerApp("wxdab3e21a1f7e392f", "");
}, []);
// // 微信登录
// async function handleLoginWechat() {
// if (loading) {
// return;
// }
// setLoading(true);
// 微信登录
async function handleLoginWechat() {
if (loading) {
return;
}
setLoading(true);
// // 检查微信是否安装
// const isInstalled = await ExpoWeChat.isWXAppInstalled();
// if (!isInstalled) {
// toast.warning(onLoginFinished?.errorMessage || "请先安装微信");
// setLoading(false);
// return;
// }
// 检查微信是否安装
const isInstalled = await ExpoWeChat.isWXAppInstalled();
if (!isInstalled) {
toast.warning(onLoginFinished?.errorMessage || "请先安装微信");
setLoading(false);
return;
}
// setForm((val) => ({
// ...val,
// type: 0,
// }));
setForm((val) => ({
...val,
type: 0,
}));
// ExpoWeChat.sendAuthRequest("snsapi_userinfo", "state123");
// }
ExpoWeChat.sendAuthRequest("snsapi_userinfo", "state123");
}
// // QQ 登录
// async function handleLoginQQ() {
// if (loading) {
// return;
// }
// setLoading(true);
// setForm((val) => ({
// ...val,
// type: 1,
// }));
// await ExpoQQ.login(["get_user_info"]);
// }
/**
* {"code": 1000, "data": {"avatar": "http://thirdqq.qlogo.cn/ek_qqapp/AQHVialeUibE42oV8RvTTVZ4tyRlPYeJrUibWTwtCPfV68E4rSzn9cw00GkXQ3QDTiawwhjoqQb7/100",
* "nickname": "Zhang", "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImlkIjo3OTY0NTY3MTI3ODU5ODl9LCJpYXQiOjE3NzY1ODU2MDR9.ZwmN5_0MGrP9dYpn3quK94HXMG3QYKmAq7wnP5X68dY", "userId": 796456712785989}, "isSuccess": true, "message": "success", "track_id": "djIRo23SZlA160zBTH2DX-kxeuLApKTNyZdxqqauSMk"}
*/
function handleTest() {
// QQ 登录
async function handleLoginQQ() {
if (loading) {
return;
}
setLoading(true);
setTimeout(() => {
requestAnimationFrame(() => {
userStore.setUserInfo({
id: 779895419121733,
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImlkIjo3OTY0NTY3MTI3ODU5ODl9LCJpYXQiOjE3NzY1ODU2MDR9.ZwmN5_0MGrP9dYpn3quK94HXMG3QYKmAq7wnP5X68dY",
nickname: "Zhang",
avatar:
"http://thirdqq.qlogo.cn/ek_qqapp/AQHVialeUibE42oV8RvTTVZ4tyRlPYeJrUibWTwtCPfV68E4rSzn9cw00GkXQ3QDTiawwhjoqQb7/100",
});
userStore.setAuthExpired(false);
// router.replace("/(tabs)/home");
router.replace("/family/entry");
});
setLoading(false);
}, 2000);
setForm((val) => ({
...val,
type: 1,
}));
await ExpoQQ.login(["get_user_info"]);
}
// useEffect(() => {
// if (!onLoginFinished) {
// return;
// }
useEffect(() => {
if (!onLoginFinished) {
return;
}
// if (!onLoginFinished.success) {
// toast.warning(onLoginFinished?.errorMessage || "授权失败,请检查手机是否安装 QQ 或确认授权");
// setLoading(false);
// return;
// }
if (!onLoginFinished.success) {
toast.warning(onLoginFinished?.errorMessage || "授权失败,请检查手机是否安装 QQ 或确认授权");
setLoading(false);
return;
}
// const fetchUserInfo = async () => {
// try {
// const tokenInfo = await ExpoQQ.getLoginTokenInfo();
// if (!tokenInfo.openId) {
// toast.warning(tokenInfo?.errorMessage || "授权失败,请检查手机是否安装 QQ 或确认授权");
// setLoading(false);
// return;
// }
const fetchUserInfo = async () => {
try {
const tokenInfo = await ExpoQQ.getLoginTokenInfo();
if (!tokenInfo.openId) {
toast.warning(tokenInfo?.errorMessage || "授权失败,请检查手机是否安装 QQ 或确认授权");
setLoading(false);
return;
}
// setForm((val) => ({
// ...val,
// openid: String(tokenInfo.openId),
// }));
setForm((val) => ({
...val,
openid: String(tokenInfo.openId),
}));
// await ExpoQQ.sendGetUserInfoReq();
// } catch (e) {
// console.log(e);
await ExpoQQ.sendGetUserInfoReq();
} catch (e) {
console.log(e);
// setLoading(false);
// }
// };
setLoading(false);
}
};
// fetchUserInfo();
// }, [onLoginFinished]);
fetchUserInfo();
}, [onLoginFinished]);
// // QQ登录
// useEffect(() => {
// const handleLogin = async () => {
// if (!onGetUserInfo) {
// setLoading(false);
// return;
// }
// QQ登录
useEffect(() => {
const handleLogin = async () => {
if (!onGetUserInfo) {
setLoading(false);
return;
}
// try {
// const loginRes = await loginQqApi({
// openid: form.openid,
// nickname: onGetUserInfo.nickname || "",
// avatar: onGetUserInfo.figureurlQq_2 || onGetUserInfo.figureurl_2,
// });
try {
const loginRes = await loginQqApi({
openid: form.openid,
nickname: onGetUserInfo.nickname || "",
avatar: onGetUserInfo.figureurlQq_2 || onGetUserInfo.figureurl_2,
});
// console.log(loginRes);
if (loginRes.isSuccess) {
requestAnimationFrame(() => {
userStore.setUserInfo({
token: loginRes.data.token,
id: loginRes.data.userId,
nickname: loginRes.data.nickname,
avatar: loginRes.data.avatar,
});
// if (loginRes.isSuccess) {
// requestAnimationFrame(() => {
// userStore.setUserInfo({
// token: loginRes.data.token,
// id: loginRes.data.userId,
// nickname: loginRes.data.nickname,
// avatar: loginRes.data.avatar,
// });
userStore.setAuthExpired(false);
// userStore.setAuthExpired(false);
// router.replace("/(tabs)/home");
// });
// }
// } catch (err) {
// console.error("登录接口出错", err);
// } finally {
// setLoading(false);
// }
// };
if (loginRes.data.family_id === 0) {
router.replace("/family/entry");
} else {
familyStore.setCurrentFamily({
family_id: loginRes.data.family_id,
});
// handleLogin();
// }, [onGetUserInfo]);
router.replace("/(tabs)/home");
}
});
}
} catch (err) {
console.error("登录接口出错", err);
} finally {
setLoading(false);
}
};
// // 微信登录
// useEffect(() => {
// if (!authResult) return;
handleLogin();
}, [onGetUserInfo]);
// const handleLogin = async () => {
// if (authResult.errorCode === 0) {
// try {
// const loginRes = await loginWxApi({
// code: authResult.code,
// });
// 微信登录
useEffect(() => {
if (!authResult) return;
// if (loginRes.isSuccess) {
// requestAnimationFrame(() => {
// userStore.setUserInfo({
// token: loginRes.data.token,
// id: loginRes.data.userId,
// nickname: loginRes.data.nickname,
// avatar: loginRes.data.avatar,
// });
const handleLogin = async () => {
if (authResult.errorCode === 0) {
try {
const loginRes = await loginWxApi({
code: authResult.code,
});
// userStore.setAuthExpired(false);
// router.replace("/(tabs)/home");
// });
// }
// } catch (err) {
// console.error("登录接口出错", err);
// } finally {
// setLoading(false);
// }
// } else {
// console.log("授权失败:", authResult.errorMessage);
// setLoading(false);
// }
// };
if (loginRes.isSuccess) {
requestAnimationFrame(() => {
userStore.setUserInfo({
token: loginRes.data.token,
id: loginRes.data.userId,
nickname: loginRes.data.nickname,
avatar: loginRes.data.avatar,
});
// handleLogin();
// }, [authResult]);
userStore.setAuthExpired(false);
if (loginRes.data.family_id === 0) {
router.replace("/family/entry");
} else {
familyStore.setCurrentFamily({
family_id: loginRes.data.family_id,
});
router.replace("/(tabs)/home");
}
});
}
} catch (err) {
console.error("登录接口出错", err);
} finally {
setLoading(false);
}
} else {
console.log("授权失败:", authResult.errorMessage);
setLoading(false);
}
};
handleLogin();
}, [authResult]);
return (
<>
@@ -234,7 +222,7 @@ export default function Login() {
</View>
<View className="flex flex-col gap-4">
{/* <Button onPress={handleLoginWechat}>
<Button onPress={handleLoginWechat}>
{loading ? (
<Spinner entering={FadeIn.delay(50)} color="white" />
) : (
@@ -246,11 +234,6 @@ export default function Login() {
<Button variant="outline" onPress={handleLoginQQ}>
{loading ? <Spinner entering={FadeIn.delay(50)} /> : <IconQq />}
<Button.Label>QQ</Button.Label>
</Button> */}
<Button variant="outline" onPress={handleTest}>
{loading ? <Spinner entering={FadeIn.delay(50)} /> : <IconQq />}
<Button.Label>Test</Button.Label>
</Button>
</View>
+280
View File
@@ -0,0 +1,280 @@
import { useEffect } from "react";
import { Stack } from "expo-router";
import { Image, Text, View } from "react-native";
import { Button, LinkButton, ControlField, Checkbox, Spinner } from "heroui-native";
import { IconQq, IconWeixin } from "@/components/iconfont";
import { useState } from "react";
import { FadeIn } from "react-native-reanimated";
import { useUserStore } from "@/store";
import { useRouter } from "expo-router";
import ExpoQQ from "expo-qq";
import ExpoWeChat from "expo-wechat";
import { useEvent } from "expo";
import { toast } from "sonner-native";
import { loginQqApi, loginWxApi } from "@/request/api";
export default function Login() {
const router = useRouter();
const userStore = useUserStore();
const [loading, setLoading] = useState(false);
const [isAgreed, setIsAgreed] = useState(true);
const [form, setForm] = useState({
type: 0,
openid: "",
code: "",
});
// 登录
// const onLoginFinished = useEvent(ExpoQQ, "onLoginFinished");
// const onGetUserInfo = useEvent(ExpoQQ, "onGetUserInfo");
// const authResult = useEvent(ExpoWeChat, "onAuthResult");
// useEffect(() => {
// ExpoQQ.init("102826474", "");
// ExpoWeChat.registerApp("wxdab3e21a1f7e392f", "");
// }, []);
// // 微信登录
// async function handleLoginWechat() {
// if (loading) {
// return;
// }
// setLoading(true);
// // 检查微信是否安装
// const isInstalled = await ExpoWeChat.isWXAppInstalled();
// if (!isInstalled) {
// toast.warning(onLoginFinished?.errorMessage || "请先安装微信");
// setLoading(false);
// return;
// }
// setForm((val) => ({
// ...val,
// type: 0,
// }));
// ExpoWeChat.sendAuthRequest("snsapi_userinfo", "state123");
// }
// // QQ 登录
// async function handleLoginQQ() {
// if (loading) {
// return;
// }
// setLoading(true);
// setForm((val) => ({
// ...val,
// type: 1,
// }));
// await ExpoQQ.login(["get_user_info"]);
// }
/**
* {"code": 1000, "data": {"avatar": "http://thirdqq.qlogo.cn/ek_qqapp/AQHVialeUibE42oV8RvTTVZ4tyRlPYeJrUibWTwtCPfV68E4rSzn9cw00GkXQ3QDTiawwhjoqQb7/100",
* "nickname": "Zhang", "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImlkIjo3OTY0NTY3MTI3ODU5ODl9LCJpYXQiOjE3NzY1ODU2MDR9.ZwmN5_0MGrP9dYpn3quK94HXMG3QYKmAq7wnP5X68dY", "userId": 796456712785989}, "isSuccess": true, "message": "success", "track_id": "djIRo23SZlA160zBTH2DX-kxeuLApKTNyZdxqqauSMk"}
*/
function handleTest() {
if (loading) {
return;
}
setLoading(true);
setTimeout(() => {
requestAnimationFrame(() => {
userStore.setUserInfo({
id: 779895419121733,
token:
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImlkIjo3OTY0NTY3MTI3ODU5ODl9LCJpYXQiOjE3NzY1ODU2MDR9.ZwmN5_0MGrP9dYpn3quK94HXMG3QYKmAq7wnP5X68dY",
nickname: "Zhang",
avatar:
"http://thirdqq.qlogo.cn/ek_qqapp/AQHVialeUibE42oV8RvTTVZ4tyRlPYeJrUibWTwtCPfV68E4rSzn9cw00GkXQ3QDTiawwhjoqQb7/100",
});
userStore.setAuthExpired(false);
// router.replace("/(tabs)/home");
router.replace("/family/entry");
});
setLoading(false);
}, 2000);
}
// useEffect(() => {
// if (!onLoginFinished) {
// return;
// }
// if (!onLoginFinished.success) {
// toast.warning(onLoginFinished?.errorMessage || "授权失败,请检查手机是否安装 QQ 或确认授权");
// setLoading(false);
// return;
// }
// const fetchUserInfo = async () => {
// try {
// const tokenInfo = await ExpoQQ.getLoginTokenInfo();
// if (!tokenInfo.openId) {
// toast.warning(tokenInfo?.errorMessage || "授权失败,请检查手机是否安装 QQ 或确认授权");
// setLoading(false);
// return;
// }
// setForm((val) => ({
// ...val,
// openid: String(tokenInfo.openId),
// }));
// await ExpoQQ.sendGetUserInfoReq();
// } catch (e) {
// console.log(e);
// setLoading(false);
// }
// };
// fetchUserInfo();
// }, [onLoginFinished]);
// // QQ登录
// useEffect(() => {
// const handleLogin = async () => {
// if (!onGetUserInfo) {
// setLoading(false);
// return;
// }
// try {
// const loginRes = await loginQqApi({
// openid: form.openid,
// nickname: onGetUserInfo.nickname || "",
// avatar: onGetUserInfo.figureurlQq_2 || onGetUserInfo.figureurl_2,
// });
// console.log(loginRes);
// if (loginRes.isSuccess) {
// requestAnimationFrame(() => {
// userStore.setUserInfo({
// token: loginRes.data.token,
// id: loginRes.data.userId,
// nickname: loginRes.data.nickname,
// avatar: loginRes.data.avatar,
// });
// userStore.setAuthExpired(false);
// router.replace("/(tabs)/home");
// });
// }
// } catch (err) {
// console.error("登录接口出错", err);
// } finally {
// setLoading(false);
// }
// };
// handleLogin();
// }, [onGetUserInfo]);
// // 微信登录
// useEffect(() => {
// if (!authResult) return;
// const handleLogin = async () => {
// if (authResult.errorCode === 0) {
// try {
// const loginRes = await loginWxApi({
// code: authResult.code,
// });
// if (loginRes.isSuccess) {
// requestAnimationFrame(() => {
// userStore.setUserInfo({
// token: loginRes.data.token,
// id: loginRes.data.userId,
// nickname: loginRes.data.nickname,
// avatar: loginRes.data.avatar,
// });
// userStore.setAuthExpired(false);
// router.replace("/(tabs)/home");
// });
// }
// } catch (err) {
// console.error("登录接口出错", err);
// } finally {
// setLoading(false);
// }
// } else {
// console.log("授权失败:", authResult.errorMessage);
// setLoading(false);
// }
// };
// handleLogin();
// }, [authResult]);
return (
<>
<Stack.Screen
options={{
animation: "fade",
}}
/>
<View className="flex-1 bg-white px-6 justify-center">
<View className="items-center mb-12">
<Image
source={require("@/static/images/logo.png")}
className="w-20 h-20 mb-4"
resizeMode="contain"
/>
<Text className="text-xl font-semibold text-gray-900">Welcome to Allapp</Text>
</View>
<View className="flex flex-col gap-4">
{/* <Button onPress={handleLoginWechat}>
{loading ? (
<Spinner entering={FadeIn.delay(50)} color="white" />
) : (
<IconWeixin color="white" />
)}
<Button.Label>WeChat</Button.Label>
</Button>
<Button variant="outline" onPress={handleLoginQQ}>
{loading ? <Spinner entering={FadeIn.delay(50)} /> : <IconQq />}
<Button.Label>QQ</Button.Label>
</Button> */}
<Button variant="outline" onPress={handleTest}>
{loading ? <Spinner entering={FadeIn.delay(50)} /> : <IconQq />}
<Button.Label>Test</Button.Label>
</Button>
</View>
<ControlField
isSelected={isAgreed}
onSelectedChange={setIsAgreed}
className="items-start mt-10"
>
<ControlField.Indicator>
<Checkbox className="w-5 h-5 rounded-sm" />
</ControlField.Indicator>
<View className="flex-row flex-wrap flex-1 gap-1">
<Text className="text-sm text-muted">登录即表示你同意我们的</Text>
<LinkButton size="sm">
<LinkButton.Label className="text-accent">用户协议</LinkButton.Label>
</LinkButton>
<Text className="text-sm text-muted">和</Text>
<LinkButton size="sm">
<LinkButton.Label className="text-accent">隐私政策</LinkButton.Label>
</LinkButton>
</View>
</ControlField>
</View>
</>
);
}
+200 -173
View File
@@ -4,20 +4,17 @@ import { Stack } from "expo-router";
import EmptyState from "@/components/EmptyStatus";
import {
Button,
Separator,
Spinner,
Chip,
BottomSheet,
Label,
TextField,
Input,
InputOTP,
type InputOTPRef,
PressableFeedback,
useBottomSheetAwareHandlers,
} from "heroui-native";
import { PlusIcon, HousePlusIcon } from "lucide-react-native";
import { getUniqueIdApi, loadDataApi, loadDataBySqlApi, saveDataApi } from "@/request/api";
import { getUniqueIdApi, loadDataApi, saveDataApi } from "@/request/api";
import { useUserStore, useFamilyStore } from "@/store";
import { toast } from "sonner-native";
import { generateCode } from "@/utils/common";
@@ -86,6 +83,14 @@ export default function EntryFamily() {
const [createLoading, setCreateLoading] = useState(false);
const createInputRef = useRef<any>(null);
useEffect(() => {
if (familyStore.inFamily()) {
toast.warning("你已经有家庭了");
router.replace("/home");
}
}, []);
useEffect(() => {
if (showCreate) {
requestAnimationFrame(() => {
@@ -114,10 +119,56 @@ export default function EntryFamily() {
}
}, [showJoin]);
// 是否已有家庭
async function getUserFamily() {
const res = await loadDataApi({
view_name: "b_family_member",
search_condition: "user_id = ?",
order_by: "",
search_columns: ["family_id"],
args: [userStore.userInfo.id],
});
if (!res.isSuccess) return null;
return res.data?.[0]?.family_id || null;
}
// 跳转封装
function enterFamily(familyId: number) {
familyStore.setCurrentFamily({ family_id: familyId });
requestAnimationFrame(() => {
router.replace("/home");
});
}
async function generateInviteCode() {
for (let i = 0; i < 5; i++) {
const code = generateCode(6);
const res = await loadDataApi({
view_name: "b_family",
search_condition: "invite_code = ?",
order_by: "",
search_columns: ["id"],
args: [code],
});
if (!res.isSuccess) throw new Error("邀请码校验失败");
if (res.data.length === 0) {
return code;
}
}
throw new Error("邀请码生成失败");
}
async function handleCreate() {
if (createLoading) return;
if (createForm.name === "") {
if (!createForm.name.trim()) {
toast.warning("空间名称不能为空");
return;
}
@@ -125,116 +176,61 @@ export default function EntryFamily() {
setCreateLoading(true);
try {
// 检查是否存在该家庭
const memberRes = await loadDataApi({
view_name: "b_family_member",
search_condition: "user_id = ?",
search_columns: ["family_id"],
order_by: "",
args: [userStore.userInfo.id],
});
if (!memberRes.isSuccess) {
return;
}
if (memberRes.data.length > 0) {
const existFamilyId = await getUserFamily();
if (existFamilyId) {
toast.warning("你已经有家庭了");
familyStore.setCurrentFamily({
family_id: memberRes.data[0].family_id,
});
requestAnimationFrame(() => {
router.replace("/home");
});
enterFamily(existFamilyId);
return;
}
let inviteCode = "";
let isExist = true;
const inviteCode = await generateInviteCode();
// 循环生成直到不存在
while (isExist) {
inviteCode = generateCode(6);
const res = await loadDataBySqlApi({
sql: `SELECT 1 FROM b_family WHERE invite_code = ? LIMIT 1`,
args: [inviteCode],
});
if (!res.isSuccess) {
throw new Error("校验邀请码失败");
}
isExist = res.data.length > 0;
}
// 创建
const autoRes = await getUniqueIdApi(2);
if (!autoRes.isSuccess) {
return;
}
if (!autoRes.isSuccess) return;
const familyId = autoRes.data[0];
const familyMemberId = autoRes.data[1];
const [familyId, memberId] = autoRes.data;
// 插入空间
const requestData = [];
requestData.push({
table_name: "b_family",
key_field: "id",
inserts: [
{
id: familyId,
name: createForm.name,
invite_code: inviteCode,
owner_id: userStore.userInfo.id,
},
],
updates: [],
deletes: [],
});
// 插入空间用户
requestData.push({
table_name: "b_family_member",
key_field: "id",
inserts: [
{
id: familyMemberId,
family_id: familyId,
user_id: userStore.userInfo.id,
role: 0,
nickname: userStore.userInfo.nickname,
},
],
updates: [],
deletes: [],
});
const saveRes = await saveDataApi(requestData);
const saveRes = await saveDataApi([
{
table_name: "b_family",
key_field: "id",
inserts: [
{
id: familyId,
name: createForm.name,
invite_code: inviteCode,
owner_id: userStore.userInfo.id,
},
],
updates: [],
deletes: [],
},
{
table_name: "b_family_member",
key_field: "id",
inserts: [
{
id: memberId,
family_id: familyId,
user_id: userStore.userInfo.id,
role: 0,
nickname: userStore.userInfo.nickname,
},
],
updates: [],
deletes: [],
},
]);
if (saveRes.isSuccess) {
toast.success("创建成功");
setShowCreate(false);
setCreateForm({ name: "" });
setCreateForm({
name: "",
});
familyStore.setCurrentFamily({
family_id: familyId,
});
requestAnimationFrame(() => {
router.replace("/home");
});
enterFamily(familyId);
}
} catch (e) {
console.log(e);
console.error(e);
} finally {
setCreateLoading(false);
}
@@ -258,91 +254,56 @@ export default function EntryFamily() {
setJoinLoading(true);
try {
const res = await loadDataBySqlApi({
sql: ` SELECT
s.id,
s.name,
EXISTS (
SELECT 1
FROM space_member sm
WHERE sm.space_id = s.id
AND sm.user_id = ?
) AS is_joined
FROM space s
WHERE s.invite_code = ?
LIMIT 1;
`,
args: [userStore.userInfo.id, code],
const existFamilyId = await getUserFamily();
if (existFamilyId) {
toast.warning("你已经有家庭了");
enterFamily(existFamilyId);
return;
}
const res = await loadDataApi({
view_name: "b_family",
search_condition: "invite_code = ?",
order_by: "",
search_columns: ["id"],
args: [code],
});
if (!res.isSuccess) return;
const row = res.data?.[0];
const family = res.data?.[0];
if (!row) {
if (!family) {
toast.warning("邀请码无效");
return;
}
if (row.is_joined) {
toast.warning("你已经在该空间了");
return;
}
const autoRes = await getUniqueIdApi(1);
if (!autoRes.isSuccess) {
return;
}
if (!autoRes.isSuccess) return;
// 设置是否是默认空间
let isDefault = false;
const defaultRes = await loadDataApi({
view_name: "v_user_spaces",
search_condition: `v_user_id = ?`,
search_columns: ["v_is_default"],
order_by: "",
args: [userStore.userInfo.id],
});
if (!defaultRes.isSuccess) {
return;
}
if (defaultRes.data.length == 0) {
isDefault = true;
}
// 加入
const requestData = [];
requestData.push({
table_name: "space_member",
key_field: "id",
inserts: [
{
id: autoRes.data[0],
space_id: row.id,
user_id: userStore.userInfo.id,
role: 1,
is_default: isDefault ? 1 : 0,
sort_number: defaultRes.data.length,
member_name: userStore.userInfo.nickname,
},
],
updates: [],
deletes: [],
});
const saveRes = await saveDataApi(requestData);
const saveRes = await saveDataApi([
{
table_name: "b_family_member",
key_field: "id",
inserts: [
{
id: autoRes.data[0],
family_id: family.id,
user_id: userStore.userInfo.id,
role: 1,
nickname: userStore.userInfo.nickname,
},
],
updates: [],
deletes: [],
},
]);
if (saveRes.isSuccess) {
toast.success("加入成功");
toast.success("加入家庭成功");
setShowJoin(false);
setJoinForm({ invite_code: "" });
setJoinForm({
invite_code: "",
});
enterFamily(family.id);
}
} catch (e) {
console.error(e);
@@ -352,6 +313,12 @@ export default function EntryFamily() {
}
}
function handleToLogin() {
requestAnimationFrame(() => {
router.replace("/auth/login");
});
}
return (
<>
<Stack.Screen
@@ -373,7 +340,12 @@ export default function EntryFamily() {
<Button.Label>创建家庭</Button.Label>
</Button>
<Button variant="outline">
<Button
variant="outline"
onPress={() => {
setShowJoin(true);
}}
>
<HousePlusIcon size={20} />
<Button.Label>加入家庭</Button.Label>
</Button>
@@ -384,7 +356,12 @@ export default function EntryFamily() {
<View className="flex-1 h-px bg-muted/30" />
</View>
<TouchableOpacity onPress={() => {}} className="items-center py-2">
<TouchableOpacity
onPress={() => {
handleToLogin();
}}
className="items-center py-2"
>
<Text className="text-sm text-muted">重新登录</Text>
</TouchableOpacity>
</View>
@@ -426,6 +403,56 @@ export default function EntryFamily() {
</BottomSheet.Content>
</BottomSheet.Portal>
</BottomSheet>
<BottomSheet
isOpen={showJoin}
onOpenChange={(val) => {
setShowJoin(val);
}}
>
<BottomSheet.Portal>
<BottomSheet.Overlay />
<BottomSheet.Content
animation={"disabled"}
enableBlurKeyboardOnGesture
keyboardBlurBehavior="restore"
>
<View>
<TextField>
<Label>邀请码</Label>
<BottomSheetTextInputOTP
ref={joinInputRef}
maxLength={6}
value={joinForm.invite_code}
onChange={(val) => {
setJoinForm({
invite_code: val,
});
}}
>
<InputOTP.Group>
<InputOTP.Slot index={0} />
<InputOTP.Slot index={1} />
<InputOTP.Slot index={2} />
</InputOTP.Group>
<InputOTP.Separator />
<InputOTP.Group>
<InputOTP.Slot index={3} />
<InputOTP.Slot index={4} />
<InputOTP.Slot index={5} />
</InputOTP.Group>
</BottomSheetTextInputOTP>
</TextField>
<Button className="mt-3" onPress={handleJoin}>
{joinLoading && <Spinner entering={FadeIn.delay(50)} color="white" />}
<Button.Label>加入</Button.Label>
</Button>
</View>
</BottomSheet.Content>
</BottomSheet.Portal>
</BottomSheet>
</>
);
}
+9 -8
View File
@@ -1,16 +1,17 @@
export interface LoginQqParams {
openid: string
nickname: string
avatar: string
openid: string;
nickname: string;
avatar: string;
}
export interface LoginWxParams {
code: string
code: string;
}
export interface LoginResult {
token: string
userId: number
nickname: string
avatar: string
token: string;
userId: number;
nickname: string;
avatar: string;
family_id: number;
}