import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/home/home_view/discount_zone.dart';
import 'package:huixiang/home/home_view/home_banner.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/data/activity_pos.dart';
import 'package:huixiang/retrofit/data/article.dart';
import 'package:huixiang/retrofit/data/banner.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/brand.dart';
import 'package:huixiang/retrofit/data/coupon.dart';
import 'package:huixiang/retrofit/data/founder.dart';
import 'package:huixiang/retrofit/data/goods.dart';
import 'package:huixiang/retrofit/data/goods_category.dart';
import 'package:huixiang/retrofit/data/login_info.dart';
import 'package:huixiang/retrofit/data/msg_stats.dart';
import 'package:huixiang/retrofit/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/event_type.dart';
import 'package:huixiang/view_widget/activity_coupons.dart';
import 'package:huixiang/view_widget/activity_poster.dart';
import 'package:huixiang/view_widget/classic_header.dart';
import 'package:huixiang/view_widget/invite_success_dialog.dart';
import 'package:huixiang/view_widget/new_people_reward.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 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.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;

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

    eventBus.on<EventType>().listen((event) {
      if (event.type < 3) {
        setState(() {});
      }
    });
    queryMsgStats();
    queryActivity();
    queryCoupon();

    if ((widget.invite ?? "") != "" ||
        widget.interviewCouponList != null &&
            widget.interviewCouponList.length > 0) showInvite = true;

    if (widget.firstLoginCouponList != null && widget.firstLoginCouponList.length > 0)
      showNew = true;


  }

  ///邀请成功
  inviteShowAlertDialog(invite, InterviewCouponList interviewCouponList) {
    //显示对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return InviteSuccessDialog(invite, interviewCouponList);
      },
    );
  }

  ///新用户奖励弹窗
  newShowAlertDialog(newUserCouponList) {
    //显示对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return NewPeopleReward(newUserCouponList);
      },
    );
  }

  ///活动海报弹窗
  posterShowAlertDialog(ActivityPos activityPos) {
    SharedPreferences.getInstance().then((value) {
      if((value.getString("ActivityPosCode") ?? "").contains("${activityPos.code}_${value.getString("userId")};"))
        return;
      value.setString("ActivityPosCode", "${(value.getString("ActivityPosCode")??"")}${activityPos.code}_${value.getString("userId")};");
      //显示对话框
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return ActivityPoster(activityPos);
        },
      );
    });
  }

  final SwiperController controller = SwiperController();

  String categoryId;
  int pageNum = 1;
  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<Brand> brandData = [];
  List<Article> articles = [];
  List<Goods> gooods = [];
  Founder founder;
  bool isSigned = false;
  int totalMsg = 0;
  List<Coupon> coupons = [];
  int state = 1;

  queryHome() async {
    // EasyLoading.show(status: S.of(context).zhengzaijiazai);

    final SharedPreferences value = await SharedPreferences.getInstance();
    apiService = ApiService(Dio(),
        context: context, token: value.getString('token'), showLoading: false);

    final BaseData brand =
        await apiService.queryHomeBrand().catchError((onError) {
      refreshController.refreshFailed();
    });
    if (brand != null && brand.isSuccess) {
      brandData.clear();
      brandData.addAll((brand.data["brandList"] as List<dynamic>)
          .map((e) => Brand.fromJson(e))
          .toList());
      founder = Founder.fromJson(brand.data["founder"]);
    }

    final BaseData<PageInfo<Article>> article = await apiService.queryArticle({
      "pageNum": 1,
      "pageSize": 3,
      "searchKey": "",
      "state": 1,
      "type": 2
    }).catchError((onError) {
      refreshController.refreshFailed();
    });
    articles.clear();
    if (article != null && article.isSuccess) {
      articles.addAll(article.data.list);
    }

    final BaseData<PageInfo<Goods>> goodsData = await apiService.creditGoods({
      "orderDesc": true,
      "orderType": 1,
      "pageNum": 1,
      "pageSize": 10,
      "state": 1
    }).catchError((onError) {
      refreshController.refreshFailed();
    });
    if (goodsData != null && goodsData.isSuccess) {
      gooods.clear();
      gooods.addAll(goodsData.data.list);
    }

    BaseData<PageInfo<GoodsCategory>> dataCategory =
        await apiService.goodsCategory({
      "current": 1,
      "map": {},
      "model": {"pageNum": 1, "pageSize": 20, "searchKey": ""},
      "order": "descending",
      "size": 20,
      "sort": "sortOrder"
    }).catchError((onError) {
      refreshController.loadFailed();
      refreshController.refreshFailed();
    });

    if (dataCategory != null &&
        dataCategory.isSuccess &&
        dataCategory.data != null &&
        dataCategory.data.records != null &&
        dataCategory.data.records.length > 0) {
      gooodsCategorys.clear();
      gooodsCategorys.add(GoodsCategory(name: S.of(context).quanbu));
      gooodsCategorys.addAll(dataCategory.data.records);
    }

    var param = {
      "categoryId": categoryId ?? "",
      "orderDesc": orderDesc,
      "orderType": orderType,
      "pageNum": pageNum,
      "pageSize": 10,
      "state": 1
    };
    BaseData<PageInfo<Goods>> pageGoods =
        await apiService.creditGoods(param).catchError((onError) {
      refreshController.loadFailed();
      refreshController.refreshFailed();
    });
    EasyLoading.dismiss();
    if (pageGoods != null && pageGoods.isSuccess) {
      if (pageNum == 1) {
        goods.clear();
      }
      goods.addAll(pageGoods.data.list);
      refreshController.refreshCompleted();
      refreshController.loadComplete();
      if (pageGoods.data.pageNum == pageGoods.data.pages) {
        refreshController.loadNoData();
      } else {
        pageNum += 1;
      }
    } else {
      refreshController.loadFailed();
      refreshController.refreshFailed();
    }

    final BaseData<PageInfo<BannerData>> baseData =
        await apiService.queryBanner({
      "model": {"type": "HOME_PAGE"},
    }).catchError((onError) {
      refreshController.refreshFailed();
    });
    if (baseData != null && baseData.isSuccess) {
      bannerData.clear();
      bannerData.addAll(baseData.data.records);
      refreshController.refreshCompleted();
      if (bannerData.length > 0) controller.move(0, animation: false);
    } else {
      refreshController.refreshFailed();
    }
    EasyLoading.dismiss();
    if (showInvite) {
      inviteShowAlertDialog(widget.invite, widget.interviewCouponList[0]);
      showInvite = false;
    }
    if (showNew) {
      newShowAlertDialog(widget.firstLoginCouponList);
      showNew = false;
    }
  }

  ///消息数量
  queryMsgStats() async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString("token"),
      );
    }
    BaseData<List<MsgStats>> baseData = await apiService.stats().catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      setState(() {
        totalMsg = 0;
        baseData.data.forEach((element) {
          totalMsg += element.number;
        });
      });
    }
    EasyLoading.dismiss();
  }

  ///活动弹窗
  queryActivity() async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString("token"),
        showLoading: true
      );
    }
    BaseData<ActivityPos> baseData =
    await apiService.appPopup().catchError((onError) {
    });
    if (baseData != null && baseData.isSuccess) {
      if(baseData.data?.enabled ?? true)
        posterShowAlertDialog(baseData.data);
    }
  }

  ///核销用户优惠券
  queryWiped(memberCouponId) async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString("token"),
      );
    }
    BaseData baseData = await apiService.wiped(memberCouponId).catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      SmartDialog.showToast("核销成功", alignment: Alignment.center);
    } else {
      SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
    }
  }

  queryCoupon() async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString("token"),
      );
    }
    BaseData<PageInfo<Coupon>> baseData = await apiService.queryCoupon({
      "centre": true,
      "pageNum": pageNum,
      "pageSize": 10,
      "searchKey": "",
      "state": 0
    }).catchError((onError) {
      refreshController.refreshFailed();
      refreshController.loadFailed();
    });
    if (pageNum == 1) coupons.clear();
    if (baseData != null && baseData.isSuccess) {
      coupons.addAll(baseData.data.list);
      refreshController.refreshCompleted();
      refreshController.loadComplete();
      if (baseData.data.pageNum == baseData.data.pages) {
        refreshController.loadNoData();
      } else {
        pageNum += 1;
      }
      setState(() {});
    } else {
      refreshController.refreshFailed();
      refreshController.loadFailed();
    }
  }

  _onRefresh(){
    queryHome();
    queryMsgStats();
    queryCoupon();
  }

  @override
  void dispose() {
    super.dispose();
    if (refreshController != null) refreshController.dispose();
  }

  final RefreshController refreshController = RefreshController();

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Column(
      children: [
        // MyAppBar(
        //   title: "首页",
        //   leading: false,
        //   actions: [
        //     Container(
        //       height: 24,
        //       alignment: Alignment.center,
        //       margin: EdgeInsets.only(
        //         right: 12.w,
        //       ),
        //       child: GestureDetector(
        //           onTap: () {
        //             Navigator.of(context).pushNamed('/router/system_msg_page').then((value) {
        //               setState(() {
        //                 totalMsg = 0;
        //               });
        //             });
        //             // Navigator.of(context).pushNamed('/router/web_turntable_activity');
        //           },
        //           child: Container(
        //             height: 24,
        //             alignment:Alignment.center,
        //             child:Stack(
        //               children: [
        //                 SvgPicture.asset(
        //                   "assets/svg/tixing.svg",
        //                   width: 24,
        //                   height: 24,
        //                 ),
        //                 if(totalMsg != 0)
        //                 Container(
        //                   width:36,
        //                   alignment: Alignment.topRight,
        //                   child:Container(
        //                       width:22,
        //                       height:14,
        //                       decoration: BoxDecoration(
        //                         borderRadius: BorderRadius.circular(100),
        //                         border: Border.all(
        //                           width: 1,
        //                           color: Colors.white,
        //                           style: BorderStyle.solid,
        //                         ),
        //                         color:Color(0xFFFF441A),
        //                       ),
        //                       child:RoundButton(
        //                         text:totalMsg.toString(),
        //                         textColor: Colors.white,
        //                         fontWeight: MyFontWeight.regular,
        //                         backgroup: Color(0xFFFF441A),
        //                         fontSize:8.sp,
        //                         radius: 100,
        //                       )
        //                   ),
        //                 )
        //               ],
        //             ),
        //           )
        //       )
        //     ),
        //     Container(
        //       margin: EdgeInsets.only(right: 16.w),
        //       child: GestureDetector(
        //         onTap: () {
        //           toScan();
        //         },
        //         child: SvgPicture.asset(
        //           "assets/svg/saoyisao.svg",
        //           width: 24,
        //           height: 24,
        //         ),
        //       ),
        //     ),
        //   ],
        // ),
        Expanded(
          child: Container(
            child: SmartRefresher(
              controller: refreshController,
              enablePullDown: true,
              enablePullUp: false,
              header: MyHeader(),
              physics: BouncingScrollPhysics(),
              onRefresh: () {
                setState(() {_onRefresh();
                });
              },
              child: SingleChildScrollView(
                physics: NeverScrollableScrollPhysics(),
                child: FutureBuilder(
                  future:queryHome(),
                  builder: (context, snapshot) {
                    return Column(
                      children: [
                        ///banner
                        HomeBanner(bannerData, controller),

                        ///吃喝玩
                        UnionEntry(() {
                          widget.changeTab(1);
                        }),

                        ///快捷操作
                        ShortcutOperation(() {
                          widget.changeTab(1);
                        }),

                        ///推广图
                        spread(),

                        // ///签到
                        // SignView(isSigned, (value) {
                        //   setState(() {
                        //     isSigned = value;
                        //   });
                        // }),

                        ///特惠专区
                        DiscountZone(coupons),

                        ///推荐商品展示
                        HomeRecommendGoods(),

                        ///福利中心
                        WelfareCore(),

                        ///吃喝玩商品热销榜
                        TopSellingList(),

                        // ///店铺推荐
                        // QuickOrder(),

                        // ///超级优惠券
                        // CouponView(),

                        // ///精选活动
                        // FeaturedActivity(),

                        // ///积分商城
                        // HomeIntegralStore(gooods),

                        ///积分商品头Tab
                        PointsGoodsTitle(
                          gooodsCategorys,
                          (orderType, orderDesc) {
                            this.orderType = orderType;
                            this.orderDesc = orderDesc;
                            setState(() {});
                          },
                          (index) {
                            categoryId = gooodsCategorys[index].id;
                            pageNum = 1;
                            setState(() {});
                          },
                        ),

                        ///积分商品列表
                        PointGoods(
                          goods,
                          (index) {
                            _toDetails(index);
                          },
                        ),
                      ],
                    );
                  },
                ),
              ),
            ),
          ),
        ),
        SizedBox(
          height: 76.h,
        ),
      ],
    );
  }

  Widget spread(){
    return Container(
      width: double.infinity,
      height: 100.h,
      margin: EdgeInsets.symmetric(horizontal: 14.w),
      child: GestureDetector(
        onTap: (){
          // Navigator.of(context).pushNamed('/router/invite_friends');
          Navigator.of(context).pushNamed('/router/mine_greenery');
        },
        child: ClipRRect(
          child:Image.asset(
            "assets/image/icon_story_td.webp",
            width:double.infinity,
            fit: BoxFit.cover,
            height:80.h,
          ),
          borderRadius: BorderRadius.circular(6.w),
        ),
      ),
    );
  }

  ///扫码
  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
      var result = await Navigator.of(context).pushNamed('/router/qr_scan');
      if(result.toString().contains("type\":\"coupon")){
        ///活动优惠券赠送弹窗
        activityShowAlertDialog(result.toString());
        return;
      }if(result.toString().contains("type\":\"wiped")){
        ///核销券
        queryWiped(jsonDecode(result.toString())["memberCouponId"]);
        return;
      }
      // String result = await scanner.scan();
      Uri uri = Uri.parse(result);
      String tableId = uri.queryParameters["tableId"];
      String tenantCode = uri.queryParameters["tenantCode"];
      String shopId = uri.queryParameters["shopId"];
      if (tableId != null &&
          tableId != "" &&
          tenantCode != null &&
          tenantCode != "" &&
          shopId != null &&
          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;
}