import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.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/retrofit/data/activity.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/miNiDetail.dart';
import 'package:huixiang/retrofit/data/shoppingCart.dart';
import 'package:huixiang/retrofit/data/store_info.dart';
import 'package:huixiang/retrofit/min_api.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/store/store_view/people_num.dart';
import 'package:huixiang/store/store_view/product_sku.dart';
import 'package:huixiang/store/store_view/red_dot_page.dart';
import 'package:huixiang/store/store_view/shop_car.dart';
import 'package:huixiang/store/store_view/store_info.dart';
import 'package:huixiang/store/store_view/store_order_list.dart';
import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_tab.dart';
import 'package:huixiang/view_widget/receive_success.dart';
import 'package:huixiang/view_widget/round_button.dart';
import 'package:intl/intl.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../retrofit/data/settleOrderInfo.dart';
import '../view_widget/settlement_tips_dialog.dart';

class StoreOrderPage extends StatefulWidget {
  final Map<String, dynamic> arguments;

  StoreOrderPage({this.arguments});

  @override
  State<StatefulWidget> createState() {
    return _StoreOrderPage();
  }
}

class _StoreOrderPage extends State<StoreOrderPage>
    with TickerProviderStateMixin {
  TabController tabcontroller;
  ApiService apiService;
  MinApiService minService;
  StoreInfo storeInfo;
  List<Activity> activitys;
  StoreOrderListPage storeOrderListPage;
  ScrollPhysics scrollPhysics = NeverScrollableScrollPhysics();

  ScrollController controller = ScrollController();
  ShoppingCart shopCarGoods;
  int tableId = 0;
  String parentId = "";
  String parentCode = "";
  String tenant = "";
  String storeId = "";
  int numberOfPeople = 0;
  String vipLevelName;
  MemberVo memberVo;
  MiNiDetail miNiDetail;

  ///小程序token
  String minToken;
  String pName;
  String pid;
  String cName;
  String cid;

  GlobalKey _key = GlobalKey();
  Offset _endOffset;
  double rightOffset = 23.0;

  @override
  void initState() {
    super.initState();
    _onRefresh();
    tableId = widget.arguments["tableId"] ?? 0;
    tenant = widget.arguments["tenant"];
    storeId = widget.arguments["id"];
    WidgetsBinding.instance.addPostFrameCallback((c) {
      // 获取「购物车」的位置
      _endOffset = (_key.currentContext.findRenderObject() as RenderBox)
          .localToGlobal(Offset.zero)+
          Offset(rightOffset, 0.0);
    });

    debugPrint(
        "store_param  tableId:$tableId  tenant:$tenant  storeId:$storeId");

    if (tabcontroller == null)
      tabcontroller = TabController(
        length: 1,
        vsync: this,
      );

    // SharedPreferences.getInstance().then((value) {
    //   minLogin(value);
    // });

  }

  _onRefresh() async{
    SharedPreferences value = await SharedPreferences.getInstance();
    if (value.getString("storeInfo_${storeId}") != null) {
      storeInfo = StoreInfo.fromJson(jsonDecode(value.getString('storeInfo_${storeId}')));
      setState(() {});
    }
    minLogin(value);
  }

  /// 小程序登录
  minLogin(SharedPreferences shared) async {
    EasyLoading.show(
        status: S.of(context).zhengzaijiazai,
        maskType: EasyLoadingMaskType.black);
    apiService = ApiService(
      Dio(),
      context: context,
      token: shared.getString('token'),
    );
    apiService.minLogin(storeId).catchError((onError) {
      SmartDialog.showToast(AppUtils.dioErrorTypeToString(onError.type),
          alignment: Alignment.center);
      debugPrint(onError);
    }).then((baseData) async {
      if (baseData != null && baseData.isSuccess) {
        Map<String, dynamic> minStoreInfo = baseData.data;
        minToken = minStoreInfo["token"];
        await queryStoreInfo();
        SharedPreferences.getInstance().then(
          (value) => {
            value.setString('minToken', minToken),
            value.setString('tenant', tenant),
            value.setString('storeId', storeId),
          },
        );
        minService = MinApiService(
          Dio(),
          context: context,
          token: minToken,
          tenant: tenant,
          storeId: storeId,
        );

        queryMemberInfo();

        queryShopCar().then((value) {
          this.shopCarGoods = value;
          setState(() {});
        });
        if (tableId > 0) {
          getParentInfo();
        }
      }
    });
  }

  ///会员信息
  queryMemberInfo() async {
    BaseData baseData = await minService.memberInfo().catchError((error) {
      debugPrint(error);
    });
    if (baseData != null && baseData.isSuccess) {
      SharedPreferences.getInstance().then(
        (value) => {
          value.setString('minMember', jsonEncode(baseData.data)),
        },
      );
      memberVo = MemberVo.fromJson(baseData.data);
    }
  }

  ///获取父订单(火锅订单加菜前调用)
  getParentInfo() async {
    BaseData baseData =
        await minService.getParentInfo("$tableId").catchError((error) {
      debugPrint(error);
    });
    if (baseData != null && baseData.isSuccess) {
      if (baseData.data != null) {
        parentId = baseData.data["id"];
        parentCode = baseData.data["parentCode"];
      } else {
        ///TODO: 没有父订单,
        queryStoreInfo1();
      }
    }
  }

  ///获取桌子信息
  queryStoreInfo1() async {
    BaseData baseData = await minService.queryStoreInfo1({
      "getCoupon": true,
      "storeId": storeId,
      "tableId": tableId,
    }).catchError((error) {
      debugPrint(error);
    });
    if (baseData != null && baseData.isSuccess) {
      StoreInfo storeInfo = StoreInfo.fromJson(baseData.data);
      if (storeInfo.storeTable != null) {
        showPeopleNum(storeInfo.storeTable.tableName);
      }
    }
  }

  /// 查询店铺信息
  queryStoreInfo() async {
    BaseData baseData =
        await apiService.queryStoreInfo(storeId).catchError((error) {
      debugPrint(error);
    });
    if (baseData != null && baseData.isSuccess) {
      storeInfo = StoreInfo.fromJson(baseData.data);
      activitys = storeInfo.informationVOPageVO.list
          .map((e) => Activity.fromJson(e))
          .toList();
      if (mounted) {
        setState(() {});
      }
      SharedPreferences.getInstance().then(
            (value) => {
          value.setString('storeInfo_${storeId}', jsonEncode(baseData.data)),
        },
      );
    }
  }

  RefreshController refreshController;
  bool dialogShowing = false;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          if (dialogShowing) {
            debugPrint("ssssasdadsasdadasd");
            SmartDialog.dismiss();
            return false;
          } else {
            return false;
          }
        },
        child: Container(
            color: Colors.white,
            child: Stack(
              children: [
                Positioned(
                  left: 0,
                  right: 0,
                  top: 0,
                  bottom: 54.h,
                  child: NestedScrollView(
                    controller: controller,
                    dragStartBehavior: DragStartBehavior.start,
                    physics: BouncingScrollPhysics(),
                    headerSliverBuilder:
                        (BuildContext context, bool innerScrolled) {
                      return [
                        SliverOverlapAbsorber(
                          handle:
                              NestedScrollView.sliverOverlapAbsorberHandleFor(
                                  context),
                          sliver: SliverAppBar(
                            expandedHeight: (storeInfo != null &&
                                    storeInfo.couponVOList != null)
                                ? 400.h
                                : 395.h,
                            floating: false,
                            snap: false,
                            pinned: true,
                            stretch: false,
                            brightness: Brightness.light,
                            leading: GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {
                                Navigator.of(context).pop();
                              },
                              child: Container(
                                width: double.infinity,
                                height: double.infinity,
                                color: Colors.transparent,
                                alignment: Alignment.centerRight,
                                margin: EdgeInsets.only(left: 10.w),
                                padding: EdgeInsets.all(10.h),
                                child: Icon(
                                  Icons.arrow_back_ios,
                                  color: Colors.black,
                                  size: 24,
                                ),
                              ),
                            ),
                            flexibleSpace: FlexibleSpaceBar(
                              title: Title(controller,
                                  storeInfo != null ? storeInfo.storeName : '',
                                  (alpha) {
                                setState(() {
                                  if (alpha == 1)
                                    scrollPhysics = BouncingScrollPhysics();
                                  else
                                    scrollPhysics =
                                        NeverScrollableScrollPhysics();
                                });
                              }),
                              collapseMode: CollapseMode.pin,
                              stretchModes: [
                                StretchMode.zoomBackground,
                                StretchMode.fadeTitle,
                                StretchMode.blurBackground,
                              ],
                              background: Container(
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(8.w),
                                ),
                                child: Stack(
                                  children: [
                                    Positioned(
                                      child: Column(
                                        children: [
                                          buildSwiper(),
                                          Expanded(
                                            child: Container(
                                              color: Colors.transparent,
                                            ),
                                            flex: 1,
                                          ),
                                        ],
                                      ),
                                      top: 0,
                                      bottom: 0,
                                      left: 0,
                                      right: 0,
                                    ),
                                    Positioned(
                                      child: Container(
                                        decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius:
                                              BorderRadius.circular(8.w),
                                        ),
                                        child: Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.start,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            ///门店信息
                                            StoreInfoView(
                                              storeInfo,
                                              widget.arguments["distance"],
                                            ),
                                            // Padding(padding:EdgeInsets.only(left: 14.w),
                                            // child: Text(
                                            //   S.of(context).diandan,
                                            //   style: TextStyle(
                                            //     fontWeight: MyFontWeight.bold,
                                            //     fontSize: 15.sp,
                                            //     color: Color(0xFF000000),
                                            //   ),
                                            // ),),
                                            // Container(
                                            //   width:22.w,
                                            //   height: 3.h,
                                            //   color: Color(0xFF32A060),
                                            //   margin: EdgeInsets.only(top: 5.h,left: 14.w),
                                            // ),
                                            // ///门店对应优惠券
                                            // if (storeInfo != null &&
                                            //     storeInfo.couponVOList != null)
                                            //   UnionCoupon(
                                            //     storeInfo,
                                            //     _receiveCoupon,
                                            //     coupon: true,
                                            //   ),
                                            //
                                            // if (storeInfo == null ||
                                            //     storeInfo.couponVOList == null)
                                            //   SizedBox(
                                            //     height: 8,
                                            //   ),
                                            //
                                            // ///门店对应VIP信息
                                            // Vip(storeInfo, () {}, false),
                                          ],
                                        ),
                                      ),
                                      top: 233.h,
                                      bottom: 0,
                                      left: 0,
                                      right: 0,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            backgroundColor: Color(0x33FAFAFA),
                            centerTitle: false,
                            elevation: 0,
                            bottom: PreferredSize(
                              preferredSize: Size(
                                MediaQuery.of(context).size.width,
                                38.h,
                              ),
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 10.w),
                                width: MediaQuery.of(context).size.width,
                                child: Theme(
                                    data: ThemeData(
                                      splashColor: Colors.transparent,
                                      // 点击时的水波纹颜色设置为透明
                                      highlightColor:
                                          Colors.transparent, // 点击时的背景高亮颜色设置为透明
                                    ),
                                    child: TabBar(
                                      controller: tabcontroller,
                                      automaticIndicatorColorAdjustment: true,
                                      isScrollable: true,
                                      indicatorWeight: 3,
                                      indicatorColor: Color(0xFF32A060),
                                      labelPadding: EdgeInsets.only(
                                        left: 8.w,
                                        right: 8.w,
                                      ),
                                      indicatorSize: TabBarIndicatorSize.label,
                                      unselectedLabelStyle: TextStyle(
                                        fontSize: 15.sp,
                                        fontWeight: FontWeight.w400,
                                      ),
                                      labelStyle: TextStyle(
                                        color: Colors.black,
                                        fontSize: 18.sp,
                                        fontWeight: FontWeight.bold,
                                      ),
                                      labelColor: Colors.black,
                                      tabs: [
                                        MyTab(text: S.of(context).diandan),
                                        // MyTab(text: ""),
                                      ],
                                    )),
                              ),
                            ),
                          ),
                        ),
                      ];
                    },
                    body:

                        ///点餐
                        TabBarView(
                      physics: NeverScrollableScrollPhysics(),
                      children: [
                        ///点餐
                        StoreOrderListPage(
                            widget.arguments,
                            activitys,
                            storeInfo,
                            shopCarGoods,
                            controller,
                            minToken,
                            tenant,
                            tableId,
                            _endOffset,
                            _queryMiNiDetail, () {
                          queryShopCar().then((value) {
                            this.shopCarGoods = value;
                            setState(() {});
                          });
                        }, scrollPhysics),

                        ///星店活动,
                        // StoreActivity(
                        //   widget.arguments,
                        //   activitys,
                        // ),
                      ],
                      controller: tabcontroller,
                    ),
                  ),
                  /*SmartRefresher(
            controller: refreshController =
                RefreshController(initialRefresh: false),
            enablePullDown: true,
            enablePullUp: false,
            header: MyHeader(),
            physics: BouncingScrollPhysics(),
            onRefresh: () {
              queryStoreInfo();
            },
            child:
          ),*/
                ),
                Positioned(
                  bottom: 30,
                  left: 0,
                  right: 0,
                  child: Stack(
                    alignment: Alignment.bottomLeft,
                    children: [
                      Container(
                        margin: EdgeInsets.symmetric(horizontal: 14),
                        height: 45.h,
                        // color: Color(0xFFFAFAFA),
                        decoration: BoxDecoration(
                          color: Color(0xFF383A38),
                          borderRadius: BorderRadius.circular(100),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            SizedBox(
                              width: 45.w,
                            ),
                            Text.rich(
                              TextSpan(children: [
                                TextSpan(
                                  text: "¥ ",
                                  style: TextStyle(
                                      fontSize: 12.sp,
                                      color: Color(0xFFFFFFFF),
                                      fontWeight: MyFontWeight.bold),
                                ),
                                TextSpan(
                                  text: shopCarGoods != null
                                      ? shopCarGoods.cartSum
                                      : "0.0",
                                  style: TextStyle(
                                      fontSize: 20.sp,
                                      fontFamily: 'JDZhengHT',
                                      color: Color(0xFFFFFFFF),
                                      fontWeight: MyFontWeight.medium),
                                ),
                              ]),
                            ),
                            Spacer(),
                            GestureDetector(
                              onTap: () {
                                if (AppUtils.compareTime(
                                        storeInfo.openStartTime,
                                        DateFormat('HH:mm:ss')
                                            .format(DateTime.now())) &&
                                    (!AppUtils.compareTime(
                                        storeInfo.openEndTime,
                                        DateFormat('HH:mm:ss')
                                            .format(DateTime.now())))) {
                                  toDownOrder();
                                } else
                                  SmartDialog.showToast(
                                      "营业时间:${storeInfo.openStartTime}-${storeInfo.openEndTime}",
                                      alignment: Alignment.center);
                              },
                              child: RoundButton(
                                width: 103.w,
                                height: 54.h,
                                text: S.current.jiesuan,
                                textColor: Colors.white,
                                fontWeight: MyFontWeight.bold,
                                backgroup: Color(0xFF32A060),
                                radius: 100,
                                fontSize: 16.sp,
                                padding: EdgeInsets.symmetric(vertical: 5.h),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Stack(
                        children: <Widget>[
                          InkWell(
                            onTap: () {
                              if (count() != 0) showShoppingCart();
                            },
                            child: Image.asset(
                              "assets/image/shopping_bag.webp",
                              width: 57.w,
                              height: 57.h,
                              fit: BoxFit.fitWidth,
                            ),
                          ),
                          if (count() != 0)
                            Positioned(
                              right: 0,
                              // top: 14,
                              child: RoundButton(
                                width: 17.w,
                                height: 17.h,
                                text: "${count()}",
                                textColor: Colors.white,
                                fontWeight: MyFontWeight.regular,
                                backgroup: Color(0xFFF65720),
                                fontSize: 12.sp,
                                radius: 100,
                              ),
                            ),
                        ],
                        key: _key,
                      ),
                    ],
                  ),
                ),
              ],
            )));
  }

  ///领取优惠券
  _receiveCoupon(couponId) async {
    BaseData baseData = await apiService.receiveCoupon(couponId);
    if (baseData != null && baseData.isSuccess) {
      queryStoreInfo();
      showAlertDialog();
    }
  }

  /// 领取成功弹窗
  showAlertDialog() {
    //显示对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return ReceiveSuccess();
      },
    );
  }

  ///显示选择人数的弹窗
  showPeopleNum(String tableName) async {
    var people = await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return PeopleNumView(tableName);
      },
    );

    if (people != null && people > 0) {
      setState(() {
        this.numberOfPeople = people;
      });
    } else {
      Navigator.of(context).pop();
    }
  }

  ///计算个数
  int count() {
    if (shopCarGoods == null ||
        shopCarGoods.shoppingCartSkuItemList == null ||
        shopCarGoods.shoppingCartSkuItemList.length == 0) return 0;
    int count = 0;
    shopCarGoods.shoppingCartSkuItemList.forEach((element) {
      count += element.buyNum;
    });
    return count;
  }

  ///去下单结算页面
  toDownOrder() async {
    int num = count();

    if (parentId == null || parentId == "") {
      if (num == 0) {
        SmartDialog.showToast("请先选择您要购买的商品!~", alignment: Alignment.center);
        return;
      }
    }

    await Navigator.of(context).pushNamed(
      '/router/settlement',
      arguments: {
        "storeInfo": storeInfo,
        "tableId": tableId,
        "parentCode": parentCode,
        "parentId": parentId,
        // "pName": pName,
        "pid": pid,
        // "cName": cName,
        "cid": cid,
        "shoppingCart": shopCarGoods,
        "numberOfPeople": numberOfPeople,
        "distance": widget.arguments["distance"],
        "vipLevelName": memberVo?.memberRankVo?.rankName ?? "",
        "isVips": memberVo?.isVip ?? false,
        "subscribeParam": miNiDetail?.subscribeParam,
      },
    );

    if ((miNiDetail?.subscribeParam?.isEnableSubscribe ?? false) == true) {
      clearShopCar();
      this.shopCarGoods = await queryShopCar();
    }

    if (tableId > 0) {
      getParentInfo();
    }
    queryShopCar().then((value) {
      this.shopCarGoods = value;
      setState(() {});
    });
  }

  Widget buildSwiper() {
    return Container(
      width: double.infinity,
      height: 235.h,
      child: Swiper(
        pagination: SwiperPagination(
          alignment: Alignment.bottomCenter,
          builder: DotSwiperPaginationBuilder(
            size: 8.w,
            activeSize: 8.w,
            space: 5.w,
            activeColor: Colors.white,
            color: Colors.white.withAlpha(76),
          ),
        ),
        autoplay: (storeInfo?.bannerList?.length ?? 0) == 0 ? false : true,
        duration: 1000,
        autoplayDelay: 2000,
        itemBuilder: (context, position) {
          return Container(
            child: MImage(
              (storeInfo != null &&
                      storeInfo.bannerList != null &&
                      position < storeInfo.bannerList.length)
                  ? storeInfo.bannerList[position].imgUrl
                  : "",
              height: 230.h,
              width: double.infinity,
              fit: BoxFit.cover,
              radius: BorderRadius.zero,
              errorSrc: "assets/image/default_2_1.webp",
              fadeSrc: "assets/image/default_2_1.webp",
            ),
          );
        },
        itemCount: (storeInfo != null && storeInfo.bannerList != null)
            ? storeInfo.bannerList.length
            : 1,
      ),
    );
  }

  /// 购物车的key,用于刷新UI
  GlobalKey shopCartKey = GlobalKey();

  ///购物车弹窗
  showShoppingCart() {
    queryShopCar().then((value) {
      this.shopCarGoods = value;
      dialogShowing = true;
      //使用showModalBottomSheet加载弹窗才有效
      showModalBottomSheet(
          backgroundColor: Colors.transparent,
          context: context,
          //点击背景弹窗是否关闭
          // isDismissible: true,
          builder: (_) {
            return ShopCar(
              shopCartKey,
              this.shopCarGoods,
              clearShopCar,
              toDownOrder,
              shopCartAdd,
              shopCartReduce,
            );
          });
      // SmartDialog.show(
      //   widget: ShopCar(
      //     shopCartKey,
      //     this.shopCarGoods,
      //     clearShopCar,
      //     toDownOrder,
      //     shopCartAdd,
      //     shopCartReduce,
      //   ),
      //   onDismiss: () {
      //     dialogShowing = false;
      //   },
      //   alignmentTemp: Alignment.bottomCenter,
      // );
    });
  }

  ///清空购物车
  clearShopCar() async {
    // EasyLoading.show(status: S.current.zhengzaijiazai);
    BaseData<bool> baseData = await minService.clearShoppingCart(storeId);
    if (baseData.isSuccess) {
      shopCarGoods = null;
      setState(() {});
    }
  }

  ///选规格
  _queryMiNiDetail(String id, int count) async {
    //加红点抛物线动画,故单规格加购时不显示加载中
    // EasyLoading.show(status: S.current.zhengzaijiazai, maskType: EasyLoadingMaskType.black);
    if (count < 0) {
      shopCarGoods.shoppingCartSkuItemList.forEach((element) async {
        if (element.productId == id) {
          await shopCartReduce(element,count: count);
          setState(() {});
        }
      });
      return;
    }
    BaseData<MiNiDetail> baseData = await minService.miNiDetail(id);
    // EasyLoading.dismiss();
    if (baseData != null && baseData.isSuccess) {
      miNiDetail = baseData.data;
      showStoreSelector(baseData.data, id, count);
    }
  }

  ///选规格弹窗
  showStoreSelector(MiNiDetail miNiDetail, String id, int count) async {
    if (miNiDetail.attrList != null && miNiDetail.attrStyle == 0) {
      _addShopCar(miNiDetail, [], count);
    } else {
      EasyLoading.dismiss();
      dialogShowing = true;
      showModalBottomSheet(
          backgroundColor: Colors.transparent,
          context: context,
          isDismissible: false,
          builder: (_) {
            return ProductSku(
              miNiDetail,
              shopCarGoods,
              id,
              _addShopCar,
              add,
              reduce,
            );
          });
    }
  }

  ///添加购物车
  Future _addShopCar(MiNiDetail miNiDetail, selectSkus, int count) async {
    ProductSkuVOListBean productSku;
    if (selectSkus != null && selectSkus.length == 0) {
      productSku = miNiDetail.productSkuVOList.first;
    } else {
      productSku = miNiDetail.productSkuVOList.firstWhere((element) {
        bool gg = true;
        selectSkus.forEach((element1) {
          if (element.skuNameStr.indexOf(element1) < 0) {
            gg = false;
            return gg;
          }
        });
        return gg;
      });
    }
    if (productSku == null) return;
    String skuId = productSku.id;
    String skuValue = selectSkus
        .toString()
        .replaceAll("[", "")
        .replaceAll("]", "")
        .replaceAll(",", "");

    if ((miNiDetail.subscribeParam.isEnableSubscribe ?? false) == true) {
      clearShopCar();
    }

    if (miNiDetail != null) {
      BaseData<List<ShoppingCart>> baseDate = await minService.addShoppingCart({
        "storeId": storeInfo.id,
        "storeName": storeInfo.storeName ?? "",
        "numberOfPeople": numberOfPeople,
        "tableId": tableId,
        "parentId": parentId,
        "parentCode": parentCode,
        "shoppingCartSkuItemList": [
          {
            "buyNum": count,
            "id": skuId,
            "productId": miNiDetail.id,
            "productName": miNiDetail.productName,
            "skuName": skuValue,
            "storeId": storeInfo.id,
            "skuPrice": productSku.skuPrice,
            "skuStock": productSku.skuStock,
            "tableId": tableId,
          },
        ],
      });
      // EasyLoading.dismiss();
      if (baseDate != null && baseDate.isSuccess) {
        this.shopCarGoods = await queryShopCar();
        if ((miNiDetail.subscribeParam.isEnableSubscribe ?? false) == true)
          toDownOrder();
        setState(() {});
      } else {
        SmartDialog.show(
          widget: SettlementTips(
                () {},
            text: "${baseDate.msg.replaceAll("~", ",") + "请重新加购商品"}",
          ),
        );
      }
    }
  }

  ///查询购物车
  Future<ShoppingCart> queryShopCar() async {
    pName = ""; //活动
    pid = ""; //活动
    cName = ""; //优惠券
    cid = ""; //优惠券
    if (storeInfo?.posType?.code == "NORMALSTORE" && tableId == 0) {
      return null;
    }
    BaseData<List<ShoppingCart>> baseDate =
        await minService.getShoppingCart(tableId);
    if (baseDate != null &&
        baseDate.isSuccess &&
        baseDate.data != null &&
        baseDate.data.length > 0) {
      if (baseDate.data[0].selectDiscount == 1) {
        baseDate.data[0].couponList.forEach((element) {
          if (element.isMaxCoupon) {
            // cName = element.promotionName;
            cid = element.id;
          }
        });
      } else if (baseDate.data[0].selectDiscount == 2) {
        baseDate.data[0].promotionInfoList.forEach((element) {
          if (element.isMaxPromotion) {
            // pName = element.name;
            pid = element.id;
          }
        });
      }
      return baseDate.data[0];
    } else {
      return null;
    }
  }

  ///购物车➕1
  Future<ShoppingCart> shopCartAdd(
      ShoppingCartSkuItemListBean cartSkuItem) async {
    Map<String, dynamic> shopCarTemp = shopCarGoods.toJson();
    cartSkuItem.buyNum += 1;
    shopCarTemp["shoppingCartSkuItemList"] = [cartSkuItem.toJson()];
    BaseData<List<ShoppingCart>> baseDate =
        await minService.shoppingCartSingle(shopCarTemp);
    if (baseDate.isSuccess) {
      this.shopCarGoods = await queryShopCar();
      if (shopCartKey != null) {
        shopCartKey.currentState.setState(() {});
      }
    } else {
      this.shopCarGoods = await queryShopCar();
      if (shopCartKey != null) {
        shopCartKey.currentState.setState(() {});
      }
      if (baseDate != null
          && baseDate.msg != null
          && baseDate.msg != "") {
        SmartDialog.showToast(
          "${baseDate.msg}",
          alignment: Alignment.center,
        );
      }
    }
    setState(() {});
    return this.shopCarGoods;
  }

  ///购物车➖1
  Future<ShoppingCart> shopCartReduce(
      ShoppingCartSkuItemListBean cartSkuItem,{int count = 1}) async {
    Map<String, dynamic> shopCarTemp = shopCarGoods.toJson();
    cartSkuItem.buyNum -= (count>0) ? ((cartSkuItem.minQty>1 && cartSkuItem.buyNum == cartSkuItem.minQty) ? cartSkuItem.minQty: count) : -count;
    shopCarTemp["shoppingCartSkuItemList"] = [cartSkuItem.toJson()];
    BaseData<List<ShoppingCart>> baseDate =
        await minService.shoppingCartSingle(shopCarTemp);
    if (baseDate.isSuccess) {
      EasyLoading.dismiss();
      this.shopCarGoods = await queryShopCar();
      if (shopCartKey?.currentState != null) {
        shopCartKey.currentState.setState(() {});
      }
      setState(() {});
    }
    return this.shopCarGoods;
  }

  ///商品➕1
  add(MiNiDetail miNiDetail, selectSkus) async {
    ProductSkuVOListBean productSku =
        miNiDetail.productSkuVOList.firstWhere((element) {
      return skuY(element, selectSkus);
    });

    if (productSku == null) return;
    String skuId = productSku.id;
    if (shopCarGoods == null) {
      await _addShopCar(miNiDetail, selectSkus, 1);
      return;
    }
    int shopSkuIndex = shopCarGoods.shoppingCartSkuItemList
        .indexWhere((element) => skuId == element.id);
    Map<String, dynamic> shopCarTemp = shopCarGoods.toJson();
    shopCarGoods.tableId = "$tableId";

    if (shopSkuIndex >= 0) {
      shopCarGoods.shoppingCartSkuItemList[shopSkuIndex].buyNum += 1;
      ShoppingCartSkuItemListBean cartSkuItem = shopCarGoods
          .shoppingCartSkuItemList
          .firstWhere((element) => skuId == element.id);
      shopCarTemp["shoppingCartSkuItemList"] = [cartSkuItem.toJson()];
    } else {
      await _addShopCar(miNiDetail, selectSkus, 1);
      return;
    }

    BaseData<List<ShoppingCart>> baseDate =
        await minService.shoppingCartSingle(shopCarTemp);
    if (baseDate.isSuccess) {
      this.shopCarGoods = await queryShopCar();
      debugPrint("count.toString()");
      setState(() {});
    } else {
      SmartDialog.showToast(baseDate.msg, alignment: Alignment.center);
    }
  }

  int countMinQty = 1;

  ///商品➖1
  reduce(MiNiDetail miNiDetail, selectSkus) async {
    ProductSkuVOListBean productSku =
        miNiDetail.productSkuVOList.firstWhere((element) {
          countMinQty = element.minQty;
      return skuY(element, selectSkus);
    });

    if (productSku == null) return;
    String skuId = productSku.id;
    if (shopCarGoods == null) {
      await _addShopCar(miNiDetail, selectSkus, 1);
      return;
    }
    ShoppingCartSkuItemListBean shopSkuItem = shopCarGoods
        .shoppingCartSkuItemList
        .firstWhere((element) => skuId == element.id);
    int shopSkuIndex = shopCarGoods.shoppingCartSkuItemList
        .indexWhere((element) => skuId == element.id);

    if (shopSkuItem != null) {
      if (shopSkuItem.buyNum > 1) {
        shopCarGoods.shoppingCartSkuItemList[shopSkuIndex].buyNum -= (countMinQty > 1 && countMinQty ==shopSkuItem.buyNum) ? countMinQty:1;
      }
    } else {
      await _addShopCar(miNiDetail, selectSkus, 1);
      return;
    }
    shopCarGoods.tableId = "$tableId";

    Map<String, dynamic> shopCarTemp = shopCarGoods.toJson();
    ShoppingCartSkuItemListBean cartSkuItem = shopCarGoods
        .shoppingCartSkuItemList
        .firstWhere((element) => skuId == element.id);
    shopCarTemp["shoppingCartSkuItemList"] = [cartSkuItem.toJson()];

    BaseData<List<ShoppingCart>> baseDate =
        await minService.shoppingCartSingle(shopCarTemp);
    if (baseDate.isSuccess) {
      queryShopCar().then((value) {
        this.shopCarGoods = value;
        setState(() {});
      });
    } else {
      SmartDialog.showToast(baseDate.msg, alignment: Alignment.center);
    }
  }

  bool skuY(ProductSkuVOListBean productSku, selectSkus) {
    bool gg = true;
    selectSkus.forEach((element1) {
      if (productSku.skuNameStr.indexOf(element1) < 0) {
        gg = false;
        return gg;
      }
    });
    return gg;
  }
}

class Title extends StatefulWidget {
  final ScrollController controller;
  final String title;
  final Function scrollChange;

  Title(this.controller, this.title, this.scrollChange);

  @override
  State<StatefulWidget> createState() {
    return _Title();
  }
}

class _Title extends State<Title> {
  double alpha = 0;

  @override
  void initState() {
    super.initState();
    widget.controller.addListener(() {
      double maxScrollExtent = widget.controller.position.maxScrollExtent;
      double alphaHeight = (kToolbarHeight) / 2;
      double alphaProgress = maxScrollExtent - widget.controller.offset;
      double alphaTemp = 0;
      if (alphaProgress <= 1) {
        alphaTemp = 1;
      } else if (alphaProgress <= alphaHeight) {
        alphaTemp =
            (((alphaHeight - alphaProgress) / alphaHeight) > 0.5) ? 1 : 0;
      } else {
        alphaTemp = 0;
      }
      if (alpha != alphaTemp && mounted) {
        alpha = alphaTemp;
        print("object:  $alpha");
        widget.scrollChange(alpha);
        setState(() {});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(bottom: 38.h),
      child: alpha == 0
          ? null
          : Text(
              widget.title ?? "",
              style: TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.bold,
                fontSize: 18.sp,
              ),
            ),
    );
  }
}