Skip to content

Commit

Permalink
Merge pull request Mkyupark#27 from Mkyupark/gumaehwakjung
Browse files Browse the repository at this point in the history
gumaehwakjung
  • Loading branch information
MINSIX committed Dec 1, 2023
2 parents 7ca1d5f + 9c84d2a commit e46b728
Show file tree
Hide file tree
Showing 3 changed files with 180 additions and 73 deletions.
3 changes: 3 additions & 0 deletions lib/pages/chatroom/chatlist.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class _ChatListState extends State<ChatList> {
String rname = rooms[index]['rname'];
String uid1 = rooms[index]['uid1'];
String uid2 = rooms[index]['uid2'];
String id=rooms[index]['id'];


if (currentUser != null && rname.contains(currentUser.nickName)) {
Expand All @@ -55,6 +56,7 @@ class _ChatListState extends State<ChatList> {
rname: rooms[index]['rname'],
uid1: rooms[index]['uid1'],
uid2: rooms[index]['uid2'],
id:id,
),),);
},
);
Expand All @@ -71,6 +73,7 @@ class _ChatListState extends State<ChatList> {
rname: rooms[index]['rname'],
uid1: rooms[index]['uid2'],
uid2: rooms[index]['uid1'],
id:id,
),),);

},
Expand Down
145 changes: 119 additions & 26 deletions lib/pages/chatroom/chatroom.dart
Original file line number Diff line number Diff line change
@@ -1,53 +1,146 @@
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:hakgeun_market/models/user.dart';
import 'package:hakgeun_market/provider/user_provider.dart';

class ChatRoom extends StatefulWidget {

const ChatRoom(
{Key? key, required this.rname, required this.uid1, required this.uid2});
{Key? key, required this.rname, required this.uid1, required this.uid2,required this.id});

final String rname;
final String uid1;
final String uid2;

final String id;
@override
_ChatRoomState createState() => _ChatRoomState(rname, uid1, uid2);
_ChatRoomState createState() => _ChatRoomState(rname, uid1, uid2,id);
}

class _ChatRoomState extends State<ChatRoom> {
_ChatRoomState(this.rname, this.uid1, this.uid2);
final UserProvider _userProvider = UserProvider();

_ChatRoomState(this.rname, this.uid1, this.uid2,this.id);

final String rname;
final String uid1;
final String uid2;

final String id;
final TextEditingController _controller = TextEditingController();
late CollectionReference<Map<String, dynamic>> messages;
late ScrollController _scrollController;

@override
void initState() {
super.initState();

_scrollController = ScrollController();
messages = FirebaseFirestore.instance
.collection('chatRooms')
.doc(rname)
.collection('messages');

// Load messages and scroll to the bottom when done
messages.orderBy('timestamp').get().then((querySnapshot) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_scrollToBottom();
});
@override
void initState() {
super.initState();

_scrollController = ScrollController();
messages = FirebaseFirestore.instance
.collection('chatRooms')
.doc(rname)
.collection('messages');

// Load messages and scroll to the bottom when done
messages.orderBy('timestamp').get().then((querySnapshot) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_scrollToBottom();
});
});

_loadGoodsTitle(); // Load goods title
}

Future<void> _loadGoodsTitle() async {
try {
QuerySnapshot querySnapshot = await FirebaseFirestore.instance
.collection('goods')
.where('id', isEqualTo: id)
.get();

if (querySnapshot.docs.isNotEmpty) {
setState(() {
goodsTitle = querySnapshot.docs[0]['title'];
documentReference = querySnapshot.docs[0].reference;
});
}
} catch (e) {
print("Error fetching goods data: $e");
// Handle the error accordingly
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(rname),
String goodsTitle = ""; // Initialize goodsTitle
late DocumentReference? documentReference=null;
Color buttonColor = Colors.grey; // Initial color
bool isButtonClicked = false;
@override
Widget build(BuildContext context) {
UserModel? currentUser = _userProvider.user;

return Scaffold(
appBar: AppBar(
title: Text(goodsTitle.isNotEmpty ? goodsTitle : "Loading..."),
backgroundColor: Colors.green,
actions: [
if (currentUser != null && documentReference != null)
FutureBuilder<DocumentSnapshot>(
future: documentReference!.get(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
DocumentSnapshot documentSnapshot = snapshot.data as DocumentSnapshot;

String buyer = documentSnapshot['buyer'] ?? ""; // Get the 'buyer' field, default to empty string if null

return Visibility(
visible: currentUser.nickName == documentSnapshot['saler'],
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 8.0),
child: ElevatedButton(
onPressed: isButtonClicked || buyer.isNotEmpty
? null // Disable the button if it's already clicked or buyer is not empty
: () async {
String saler = documentSnapshot['saler'];
// Check if 'saler' field is available in the document
if (documentSnapshot.exists &&
documentSnapshot.data() != null &&
documentSnapshot['saler'] != null) {
// Check if 'saler' is the same as currentUser.nickName and 'buyer' field is empty
if (currentUser.nickName == saler && buyer.isEmpty) {
// 버튼이 눌렸을 때의 동작
// 예: 거래 확정 동작 수행
await documentReference!.update({'buyer': uid2});
print('Firestore update successful'); // Debug statement
setState(() {
// Change the button color after it's clicked
buttonColor = Colors.grey; // Change it to the desired color
isButtonClicked = true; // Disable the button
print('Button state updated'); // Debug statement
});
}
}
},
style: ElevatedButton.styleFrom(
primary: buyer.isNotEmpty ? Colors.grey : Colors.orange, // Use Colors.grey if 'buyer' is not empty
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0), // 둥근 모서리 적용
),
),
child: const Text(
"거래 확정",
style: TextStyle(
color: Colors.white, // 글자색 설정
),
),
),
),
);
} else {
// You can return a loading indicator or an empty container while waiting for the data.
return Container();
}
},
),
],
),
body: Column(
children: [
Expand Down Expand Up @@ -213,4 +306,4 @@ class _ChatRoomState extends State<ChatRoom> {
curve: Curves.easeOut,
);
}
}
}
105 changes: 58 additions & 47 deletions lib/pages/detail.dart
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,22 @@ class _DetailState extends State<Detail> {

return "${nicknames[0]}_${nicknames[1]}";
}

Future<bool> _AddChatCnt()async{
try{
QuerySnapshot<Object?> querySnapshot = await FirebaseFirestore.instance
.collection('goods')
.where('id', isEqualTo: goodsData!.id)
.get();
DocumentReference<Object?> documentReference = querySnapshot.docs[0].reference;
await documentReference.update({
'chatCnt':(int.parse(goodsData!.chatCnt!)+1).toString(),
});
return true;
}catch(e){
print("조회수 증가 오류 발생: $e");
return false;
}
}
// 채팅방이 이미 존재하는지 확인하는 함수
Future<bool> _checkIfChatRoomExists(String chatRoomName) async {
try {
Expand All @@ -64,7 +79,7 @@ class _DetailState extends State<Detail> {

// 채팅방을 생성하는 함수
Future<void> _createChatRoom(
String chatRoomName, String rname, String uid1, String uid2) async {
String chatRoomName, String rname, String uid1, String uid2,String id) async {
try {
// Firestore에서 chatRooms 컬렉션에 새 문서를 생성합니다.
DocumentReference chatRoomRef =
Expand All @@ -75,6 +90,7 @@ class _DetailState extends State<Detail> {
'rname': rname,
'uid1': uid1,
'uid2': uid2,
'id':goodsData!.id,
});

// "messages" 서브컬렉션을 추가합니다.
Expand Down Expand Up @@ -540,52 +556,46 @@ class _DetailState extends State<Detail> {
.grey // Change the color to grey if usernames match, 판매완료시에도 바꿈.
: Colors.green, // Use green otherwise
),
child: isSoldOut
? const Text(
"판매완료",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 16,
),
)
: GestureDetector(
onTap: goodsData!.saler == currentUser?.nickName
? null // Disable onTap if usernames match
: () async {
// Your existing onTap logic here
String chatRoomName = _generateChatRoomName(
goodsData!.saler ?? "NULL",
currentUser!.nickName);
bool roomExists =
await _checkIfChatRoomExists(
chatRoomName);
if (!roomExists) {
await _createChatRoom(
chatRoomName,
chatRoomName,
goodsData!.saler ?? "NULL",
currentUser.nickName);
}
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => ChatRoom(
rname: chatRoomName,
uid2: goodsData!.saler ?? "NULL",
uid1: currentUser.nickName,
),
),
child: GestureDetector(
onTap: goodsData!.saler == currentUser!.nickName
? null // Disable onTap if usernames match
: () async {
// Your existing onTap logic here
String chatRoomName = _generateChatRoomName(
goodsData!.saler ?? "NULL",
currentUser!.nickName);
bool roomExists =
await _checkIfChatRoomExists(chatRoomName);
if (!roomExists) {
await _createChatRoom(
chatRoomName,
chatRoomName,
goodsData!.saler ?? "",
currentUser.nickName,
goodsData!.id??"",
);
},
child: const Text(
"채팅으로 거래하기",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 16,
),
),
),
await _AddChatCnt();
}
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => ChatRoom(
rname: chatRoomName,
uid2: goodsData!.saler ?? "",
uid1: currentUser.nickName,
id:goodsData!.id!,
),
),
);
},
child: const Text(
"채팅으로 거래하기",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 16,
),
),
),
),
],
),
Expand Down Expand Up @@ -729,3 +739,4 @@ class _DetailState extends State<Detail> {
}
}
}

0 comments on commit e46b728

Please sign in to comment.