You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

792 lines
25 KiB

import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:huixiang/constant.dart';
import 'package:huixiang/data/activity_pos.dart';
import 'package:huixiang/data/article.dart';
import 'package:huixiang/data/banner.dart';
import 'package:huixiang/data/base_data.dart';
import 'package:huixiang/data/brand.dart';
import 'package:huixiang/data/coupon.dart';
import 'package:huixiang/data/founder.dart';
import 'package:huixiang/data/goods.dart';
import 'package:huixiang/data/goods_category.dart';
import 'package:huixiang/data/home_rank.dart';
import 'package:huixiang/data/login_info.dart';
import 'package:huixiang/data/page.dart';
import 'package:huixiang/data/user_info.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/home/home_view/discount_zone.dart';
import 'package:huixiang/home/home_view/home_recommend_goods.dart';
import 'package:huixiang/home/home_view/top_selling_list.dart';
import 'package:huixiang/home/home_view/union_entry.dart';
import 'package:huixiang/home/home_view/welfare_core.dart';
import 'package:huixiang/home/points_mall_view/points_goods_title.dart';
import 'package:huixiang/home/points_mall_view/points_goods_view.dart';
import 'package:huixiang/main.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/event_type.dart';
import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/utils/shared_preference.dart';
import 'package:huixiang/view_widget/activity_coupons.dart';
import 'package:huixiang/view_widget/activity_poster.dart';
import 'package:huixiang/view_widget/channel_dialog.dart';
import 'package:huixiang/view_widget/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/invite_success_dialog.dart';
import 'package:huixiang/view_widget/request_permission.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'home_view/happy_help_farmers.dart';
import 'home_view/shortcut_operation.dart';
class HomePage extends StatefulWidget {
final Function changeTab;
final String? invite;
final List<InterviewCouponList>? interviewCouponList;
final List<FirstLoginCouponList>? firstLoginCouponList;
HomePage(Key key, this.changeTab, {this.invite, this.interviewCouponList, this.firstLoginCouponList}) : super(key: key);
@override
State<StatefulWidget> createState() {
return HomePageState();
}
}
class HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
ApiService? apiService;
final RefreshController refreshController = RefreshController();
String? categoryId;
bool showInvite = false;
bool showNew = false;
//排序类型枚举:1-自然排序,2-销量,3-价格
int orderType = 1;
//是否降序排列
bool orderDesc = true;
List<Goods> goods = [];
List<GoodsCategory> gooodsCategorys = [];
List<BannerData> bannerData = [];
List<BannerData> activityBannerData = [];
List<Brand> brandData = [];
List<Article> articles = [];
Founder? founder;
bool isSigned = false;
int totalMsg = 0;
List<Coupon> coupons = [];
int state = 1;
HomeRank? homeRank;
UserInfo? userInfo;
dynamic mRaiseMoney = 0; //众筹金余额
int _loadCount = 0;
DioExceptionType? dioErrorType;
@override
void initState() {
super.initState();
eventBus.on<EventType>().listen((event) {
if (event.type < 3) {
setState(() {});
}
});
apiService = ApiService(
Dio(),
context: context,
token: SharedInstance.instance.token,
);
_onRefresh(isFirstIn: true);
if (showInvite) {
inviteShowAlertDialog(widget.invite, widget.interviewCouponList?[0]);
showInvite = false;
}
if ((widget.invite?.isNotEmpty ?? false) || (widget.interviewCouponList?.isNotEmpty ?? false)) {
showInvite = true;
}
}
///邀请成功
inviteShowAlertDialog(invite, InterviewCouponList? interviewCouponList) {
//显示对话框
showDialog(
context: context,
builder: (BuildContext context) {
return InviteSuccessDialog(invite, interviewCouponList);
},
);
}
///活动海报弹窗
posterShowAlertDialog(ActivityPos? activityPos, firstLoginCouponList) {
var today = DateTime.now().day;
if (SharedInstance.instance.today == today && (SharedInstance.instance.ActivityPosCode).contains("${activityPos?.code}_${SharedInstance.instance.userId};"))
return;
SharedInstance.instance.saveActivityPosCode("${SharedInstance.instance.ActivityPosCode}${activityPos?.code}_${SharedInstance.instance.userId};");
SharedInstance.instance.saveToday(today);
//显示对话框
showDialog(
context: context,
builder: (BuildContext context) {
return ActivityPoster(activityPos, firstLoginCouponList);
},
);
}
///推荐渠道弹窗
channelShowAlertDialog() {
//显示对话框
showDialog(
context: context,
builder: (BuildContext context) {
return ChannelDialog();
},
);
}
///头部banner
queryBanner() async {
try {
BaseData<PageInfo<BannerData>>? baseData = await apiService?.queryBanner({
"model": {"type": "HOME_PAGE"},
}).catchError((onError) {
dioErrorType = onError.type;
refreshController.loadFailed();
refreshController.refreshFailed();
return BaseData<PageInfo<BannerData>>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) {
bannerData = baseData?.data?.records ?? [];
// if (bannerData.length > 0) swiperController.move(0, animation: false);
}
} finally {
addLoadCount();
}
}
///宣传banner
queryActivityBanner() async {
try {
BaseData<PageInfo<BannerData>>? baseData = await apiService?.queryBanner({
"model": {"type": "HOME_STORE_PAGE"},
}).catchError((onError) {
return BaseData<PageInfo<BannerData>>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) {
activityBannerData = baseData!.data?.records ?? [];
}
} finally {
addLoadCount();
}
}
addLoadCount() {
_loadCount += 1;
if (_loadCount == 7) {
_loadCount = 0;
SmartDialog.dismiss(status: SmartStatus.loading);
String toastText = AppUtils.dioErrorTypeToString(dioErrorType);
if (toastText.isNotEmpty) {
SmartDialog.showToast(toastText, alignment: Alignment.center);
}
if (refreshController.isRefresh) refreshController.refreshCompleted();
if (mounted) setState(() {});
}
}
///推荐排行
queryRecommendRank() async {
try {
BaseData<HomeRank>? rank = await apiService?.recommendRank().catchError((onError) {
return BaseData<HomeRank>()..isSuccess = false;
});
if (rank?.isSuccess ?? false) {
homeRank = rank!.data;
}
} finally {
addLoadCount();
}
}
///积分商城商品分類列表
queryGoodsCategory() async {
try {
BaseData<PageInfo<GoodsCategory>>? dataCategory = await apiService?.goodsCategory({
"current": 1,
"map": {},
"model": {"pageNum": 1, "pageSize": 20, "searchKey": ""},
"order": "descending",
"size": 20,
"sort": "sortOrder"
}).catchError((onError) {
return BaseData<PageInfo<GoodsCategory>>()..isSuccess = false;
});
if ((dataCategory?.isSuccess ?? false) &&
(dataCategory!.data?.records?.isNotEmpty ?? false)) {
gooodsCategorys.clear();
gooodsCategorys.add(GoodsCategory()..name = S.of(context).quanbu);
gooodsCategorys.addAll(dataCategory.data?.records ?? []);
}
} finally {
addLoadCount();
}
}
///积分商城商品列表
queryPointsProductList(bool isRefresh) async {
try {
if (!isRefresh)
S.current.zhengzaijiazai.loading;
var param = {
"categoryId": categoryId ?? "",
"orderDesc": orderDesc,
"orderType": orderType,
"pageNum": 1,
"pageSize": 100,
"state": 1
};
BaseData<PageInfo<Goods>>? pageGoods = await apiService?.creditGoods(param)
.catchError((onError) {
return BaseData<PageInfo<Goods>>()..isSuccess = false;
});
if (pageGoods?.isSuccess ?? false) {
goods = pageGoods?.data?.list ?? [];
}
} finally {
if (isRefresh)
addLoadCount();
else {
SmartDialog.dismiss(status: SmartStatus.loading);
setState(() {});
}
}
}
///查询会员信息
queryUserBalance() async {
try {
BaseData<UserInfo>? baseData = await apiService?.queryInfo().catchError((onError) {
return BaseData<UserInfo>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) {
userInfo = baseData!.data;
mRaiseMoney = double.tryParse("${userInfo?.raiseMoney}") ?? 0;
}
} finally {
addLoadCount();
}
}
// /消息数量
// queryMsgStats() async {
// if (apiService == null) {
// SharedPreferences value = await SharedPreferences.getInstance();
// apiService = ApiService(
// Dio(),
// context: context,
// token: SharedInstance.instance.token,
// );
// }
// BaseData<List<MsgStats>>? baseData = await apiService?.stats().catchError((onError) {});
// if (baseData?.isSuccess ?? false) {
// setState(() {
// totalMsg = 0;
// baseData!.data?.forEach((element) {
// totalMsg += (element.number ?? 0);
// });
// });
// }
// SmartDialog.dismiss();
// }
///活动弹窗
queryActivity() async {
BaseData<ActivityPos>? baseData = await apiService?.appPopup().catchError((onError) {
return BaseData<ActivityPos>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) {
if (baseData!.data?.enabled ?? true)
posterShowAlertDialog(baseData.data, widget.firstLoginCouponList);
}
}
///核销用户优惠券
queryWiped(memberCouponId) async {
apiService ??= ApiService(
Dio(),
context: context,
token: SharedInstance.instance.token,
);
BaseData? baseData = await apiService?.wiped(memberCouponId).catchError((onError) {
return BaseData()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) {
SmartDialog.showToast("核销成功", alignment: Alignment.center);
}
}
queryCoupon() async {
try {
BaseData<PageInfo<Coupon>>? baseData = await apiService?.queryCoupon({
"centre": true,
"pageNum": 1,
"pageSize": 10,
"searchKey": "",
"state": 0
}).catchError((onError) {
return BaseData<PageInfo<Coupon>>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) {
coupons = baseData!.data?.list ?? [];
}
} finally {
addLoadCount();
}
}
_onRefresh({bool isFirstIn = false}) async {
S.current.zhengzaijiazai.loading;
dioErrorType = null;
if (isFirstIn) queryActivity();
queryBanner();
queryActivityBanner();
queryRecommendRank();
queryGoodsCategory();
queryPointsProductList(true);
queryUserBalance();
// queryMsgStats();
queryCoupon();
}
@override
void dispose() {
super.dispose();
refreshController.dispose();
}
@override
Widget build(BuildContext context) {
super.build(context);
return Column(
children: [
Expanded(
child: Container(
child: SmartRefresher(
controller: refreshController,
enablePullDown: true,
enablePullUp: false,
header: MyHeader(),
physics: BouncingScrollPhysics(),
onRefresh: _onRefresh,
child: SingleChildScrollView(
physics: NeverScrollableScrollPhysics(),
child: Column(
children: [
///banner
homeBanner(),
///吃喝玩
UnionEntry((int jpIndex) {
widget.changeTab(1, jpIndex);
}),
///快捷操作
ShortcutOperation((int jpIndex) {
widget.changeTab(1, jpIndex);
}),
///推广图
if (activityBannerData.length > 0) spread(),
// ///签到
// SignView(isSigned, (value) {
// setState(() {
// isSigned = value;
// });
// }),
///特惠专区
if (coupons.length != 0) DiscountZone(coupons),
///特惠专区-推荐商品展示
if (homeRank?.CommodityZone?.isNotEmpty ?? false)
HomeRecommendGoods(homeRank),
if (homeRank?.CommodityZone?.isEmpty ?? true)
SizedBox(
height: 20.h,
),
///助农专区
// if(mRaiseMoney != 0)
HappyHelpFarmers(),
///福利中心
WelfareCore(),
///吃喝玩商品热销榜
if (homeRank?.CommodityList?.isNotEmpty ?? false)
TopSellingList(homeRank),
// ///店铺推荐
// QuickOrder(),
// ///超级优惠券
// CouponView(),
// ///精选活动
// FeaturedActivity(),
// ///积分商城
// HomeIntegralStore(gooods),
///积分商品头Tab
PointsGoodsTitle(
gooodsCategorys,
(orderType, orderDesc) {
this.orderType = orderType;
this.orderDesc = orderDesc;
queryPointsProductList(false);
},
(index) {
categoryId = gooodsCategorys[index].id;
queryPointsProductList(false);
},
),
///积分商品列表
PointGoods(
goods,
(index) {
_toDetails(index);
},
),
],
),
),
),
),
),
SizedBox(
height: 80.h,
),
],
);
}
Widget homeBanner() {
return Container(
child: AspectRatio(
aspectRatio: 1.25,
child: bannerData.isNotEmpty
? Swiper(
pagination: SwiperPagination(
margin: EdgeInsets.only(bottom: 12.h),
alignment: Alignment.bottomCenter,
builder: DotSwiperPaginationBuilder(
size: 8,
activeSize: 8,
space: 5,
activeColor: Colors.white,
color: Colors.white.withAlpha(76),
),
),
autoplay: true,
duration: 1000,
autoplayDelay: 17000,
physics: BouncingScrollPhysics(),
itemBuilder: (context, position) {
return InkWell(
onTap: () {
bannerClick(bannerData[position]);
},
child: MImage(
bannerData[position].imgUrl ?? "",
fit: BoxFit.cover,
aspectRatio: 1.25,
errorSrc: "assets/image/default_2_1.webp",
fadeSrc: "assets/image/default_2_1.webp",
),
);
},
itemCount: bannerData.length,
)
: Image.asset(
"assets/image/default_2_1.webp",
fit: BoxFit.cover,
),
),
);
}
/// contentType 跳转类型(0:不跳转,1:积分商品,2:活动,3:文章,4:页面跳转,5:课程,7:门店跳转)
bannerClick(BannerData bannerData) async {
switch (bannerData.contentType) {
case 1:
Navigator.of(context).pushNamed(
'/router/integral_store_page',
arguments: {
"goodsId": bannerData.content,
},
);
break;
case 2:
Navigator.of(context).pushNamed(
'/router/web_page', arguments: {
"activityId": bannerData.content,
},
);
break;
case 3:
Navigator.of(context).pushNamed(
'/router/web_page', arguments: {
"articleId": bannerData.content,
},
);
break;
case 4:
String? router = bannerData.content;
if (router?.isEmpty ?? true) {
return;
}
// String router = "/router/store_order?{\"id\":\"1512378184161558528\",\"tenant\":\"1188\",\"storeName\":\"农场煮意\"}";
if (router!.contains("?")) {
String params = router.substring(router.indexOf("?") + 1);
Map map = jsonDecode(params);
Navigator.of(context).pushNamed(
router.substring(0, router.indexOf("?")),
arguments: map);
} else {
Navigator.of(context).pushNamed(router);
}
break;
case 5:
Navigator.of(context).pushNamed('/router/class_details', arguments: {
"id": bannerData.content,
});
break;
case 7:
String? router = bannerData.content;
if (router?.isEmpty ?? true) {
return;
}
String params = router!.substring(router.indexOf("?") + 1);
Map map = jsonDecode(params);
Navigator.of(context).pushNamed(
router.substring(0, router.indexOf("?")),
arguments: map,
);
break;
}
}
Widget spread() {
return Container(
width: double.infinity,
height: 85.h,
child: activityBannerData.isNotEmpty
? Swiper(
pagination: SwiperPagination(
alignment: Alignment.bottomCenter,
margin: EdgeInsets.only(
top: 5.h,
),
builder: DotSwiperPaginationBuilder(
size: 8.w,
activeSize: 8.w,
space: 5.w,
activeColor: Colors.white,
color: Colors.white.withAlpha(76),
),
),
autoplay: true,
duration: 1000,
autoplayDelay: 10000,
itemBuilder: (context, position) {
return InkWell(
onTap: () {
spreadBannerClick(activityBannerData[position]);
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 14.w),
child: MImage(
activityBannerData[position].imgUrl ?? "",
fit: BoxFit.cover,
radius: BorderRadius.circular(6),
errorSrc: "assets/image/default_2_1.webp",
fadeSrc: "assets/image/default_2_1.webp",
),
),
);
},
itemCount: activityBannerData.length,
)
: Image.asset(
"assets/image/default_2_1.webp",
fit: BoxFit.cover,
),
);
}
/// contentType 跳转类型(0:不跳转,1:积分商品,2:活动,3:文章,4:页面跳转,5:课程,7:门店跳转)
spreadBannerClick(BannerData activityBannerData) async {
switch (activityBannerData.contentType) {
case 1:
Navigator.of(context).pushNamed('/router/integral_store_page',
arguments: {"goodsId": activityBannerData.content});
break;
case 2:
Navigator.of(context).pushNamed('/router/web_page', arguments: {
"activityId": activityBannerData.content,
});
break;
case 3:
Navigator.of(context).pushNamed('/router/web_page', arguments: {
"articleId": activityBannerData.content,
});
break;
case 4:
String? router = activityBannerData.content;
if (router?.isEmpty ?? true) {
return;
}
// String router = "/router/store_order?{\"id\":\"1512378184161558528\",\"tenant\":\"1188\",\"storeName\":\"农场煮意\"}";
if (router!.contains("?")) {
String params = router.substring(router.indexOf("?") + 1);
Map map = jsonDecode(params);
Navigator.of(context).pushNamed(
router.substring(0, router.indexOf("?")),
arguments: map);
} else {
Navigator.of(context).pushNamed(router);
}
break;
case 5:
Navigator.of(context).pushNamed('/router/class_details', arguments: {
"id": activityBannerData.content,
});
break;
case 7:
String? router = activityBannerData.content;
if (router?.isEmpty ?? true) {
return;
}
String params = router!.substring(router.indexOf("?") + 1);
Map map = jsonDecode(params);
Navigator.of(context).pushNamed(
router.substring(0, router.indexOf("?")),
arguments: map,
);
break;
}
}
///扫码
toScan() async {
if (await Permission.camera.isPermanentlyDenied) {
showCupertinoDialog(
context: context,
builder: (context) {
return RequestPermission(
"assets/image/icon_camera_permission_tips.webp",
S.of(context).ninxiangjiquanxianweikaiqi,
S.of(context).weilekaipaizhaoxuanzhetouxiang,
S.of(context).kaiqiquanxian,
(result) async {
if (result) {
await openAppSettings();
}
},
heightRatioWithWidth: 0.82,
);
});
} else if (await Permission.camera.isGranted) {
// http://pos.app.gznl.top/placeorder/?tableId=1315903669597634560&tenantCode=1166&shopId=1300372027722432512
// 新版桌子码跳转
// http://miniscan.lotus-wallet.com/placeorder?tenant_code=1194&table_id=1669609340031467520&store_id=1637659387134738432
var result = await Navigator.of(context).pushNamed('/router/qr_scan');
if (result == null || result! is String || (result as String).isEmpty) {
return;
}
if (result.contains("type\":\"coupon")) {
///活动优惠券赠送弹窗
activityShowAlertDialog(result.toString());
return;
}
if (result.contains("type\":\"wiped")) {
///核销券
queryWiped(jsonDecode(result.toString())["memberCouponId"]);
return;
}
// String result = await scanner.scan();
Uri uri = Uri.parse(result);
String tableId = uri.queryParameters["tableId"] ??
uri.queryParameters["table_id"] ??
"";
String tenantCode = uri.queryParameters["tenantCode"] ??
uri.queryParameters["tenant_code"] ??
"";
String shopId = uri.queryParameters["shopId"] ??
uri.queryParameters["store_id"] ??
"";
if (tableId != "" && tenantCode != "" && shopId != "") {
Navigator.of(context).pushNamed(
'/router/store_order',
arguments: {
"id": shopId,
"tenant": tenantCode,
"storeName": "",
"tableId": int.tryParse(tableId),
},
);
}
} else {
showCupertinoDialog(
context: context,
builder: (context) {
return RequestPermission(
"assets/image/icon_camera_permission_tips.webp",
S.of(context).ninxiangjiquanxianweikaiqi,
S.of(context).weilekaipaizhaoxuanzhetouxiang,
S.of(context).kaiqiquanxian,
(result) async {
if (result) {
await Permission.camera.request();
}
},
heightRatioWithWidth: 0.82,
);
},
);
}
}
_toDetails(index) async {
Navigator.of(context).pushNamed(
'/router/integral_store_page',
arguments: {"goodsId": goods[index].id},
);
}
activityShowAlertDialog(String result) {
//显示对话框
showDialog(
context: context,
builder: (BuildContext context) {
return ActivityCoupons(result);
},
);
}
@override
bool get wantKeepAlive => true;
}