import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:fluwx/fluwx.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/user_info.dart';
import 'package:huixiang/retrofit/data/wx_pay.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/utils/min.dart';
import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:huixiang/view_widget/receiving_method_dialog.dart';
import 'package:huixiang/view_widget/round_button.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

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

  ///兑换订单
  ExchangeOrderPage({this.arguments});

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

class _ExchangeOrderPage extends State<ExchangeOrderPage> {
  ApiService apiService;
  int buyNum = 1;
  var checkIndex = 3;
  UserInfo userInfo;
  dynamic payListen;
  dynamic mBalance = 0;
  String happyBean;
  String points;

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

    SharedPreferences.getInstance().then((value) => {
          apiService = ApiService(Dio(),
              context: context, token: value.getString("token")),
          points = UserInfo.fromJson(jsonDecode(value.getString('user'))).points,
          happyBean = UserInfo.fromJson(jsonDecode(value.getString('user'))).happyBean,
          queryUserBalance(),
        });

    payListen = weChatResponseEventHandler.listen((event) async {
      print("payCallback: ${event.errCode}");
      if (event.errCode == 0) {
        String realPay = handleNeedPay();
        Navigator.of(context).popAndPushNamed(
          '/router/exchange_order_success_page',
          arguments: {
            "id": widget.arguments["goodsId"],
            "price": realPay.contains("积分")
                ? realPay.substring(0, realPay.indexOf("积分"))
                : "0",
            "points": points,
            "happyBean":happyBean,
            "realPay": realPay,
            "payChannel": widget.arguments["payChannel"],
          },
        );
      } else {
        SmartDialog.showToast("支付失败", alignment: Alignment.center);
        return;
      }
    });
  }

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

  queryUserBalance() async {
    BaseData<UserInfo> baseData =
        await apiService.queryInfo().catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      userInfo = baseData.data;
      mBalance = double.tryParse(userInfo.money);
      if (mounted) setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: MyAppBar(
          title: S.of(context).dingdanqueren,
          titleColor: Colors.black,
          titleSize: 18.sp,
          background: Color(0xFFFAFAFA),
          leadingColor: Colors.black,
        ),
        body: Stack(
          children: [
            SingleChildScrollView(
                physics: BouncingScrollPhysics(),
                child: Column(
                  children: [
                    // widget.arguments["useTyped"] == 1 ?
                    Container(
                      margin: EdgeInsets.only(
                          left: 16, right: 16, top: 26, bottom: 8),
                      padding: EdgeInsets.all(20),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withAlpha(12),
                            offset: Offset(0, 3),
                            blurRadius: 14,
                            spreadRadius: 0,
                          )
                        ],
                        borderRadius: BorderRadius.all(Radius.circular(8)),
                      ),
                      child: Column(
                        children: [
                          Row(
                            children: [
                              Image.asset(
                                "assets/image/icon_order_exchange_info.webp",
                                width: 24,
                                height: 24,
                              ),
                              SizedBox(width: 4),
                              Text(
                                S.of(context).duihuanxinxi,
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16,
                                    color: Color(0xFF353535)),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: 18.h,
                          ),
                          GestureDetector(
                            onTap: () {
                              setState(() {
                                // showAlertDialog();
                              });
                            },
                            child: Row(
                              children: [
                                Text(
                                  S.of(context).lingqufangshi,
                                  style: TextStyle(
                                    fontSize: 14.sp,
                                    color: Color(0xFF353535),
                                  ),
                                ),
                                SizedBox(
                                  width: 12.w,
                                ),
                                Expanded(
                                    child: Text(
                                  widget.arguments["useTyped"] == 1
                                      ? S.of(context).ziti
                                      : widget.arguments["useTyped"] == 2
                                          ? S.of(context).peisong
                                          : S.of(context).xianshangfafang,
                                  style: TextStyle(
                                    fontSize: 14.sp,
                                    color: Color(0xFF353535),
                                  ),
                                )),
                                // Icon(
                                //   Icons.keyboard_arrow_right,
                                //   size: 16,
                                //   color: Color(0xFF32A060),
                                // ),
                              ],
                            ),
                          ),
                          Visibility(
                            child: SizedBox(
                              height: 13.h,
                            ),
                            visible: widget.arguments["useTyped"] != 3,
                          ),
                          Visibility(
                            child: Row(
                              children: [
                                Text(
                            widget.arguments[
                            "useTyped"] ==
                                1?S.of(context).zitidizhi:"收货地址",
                                  style: TextStyle(
                                    fontSize: 14.sp,
                                    color: Color(0xFF353535),
                                  ),
                                ),
                                SizedBox(
                                  width: 12.w,
                                ),
                                Expanded(
                                  child: GestureDetector(
                                    onTap: () {
                                      toAddressPicker();
                                    },
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.end,
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        Expanded(
                                          child: Text(
                                            (address != null && address != "")
                                                ? address
                                                : widget.arguments[
                                                            "useTyped"] ==
                                                        1
                                                    ? S
                                                        .of(context)
                                                        .qingxuanzhemendian
                                                    : widget.arguments[
                                                                "useTyped"] ==
                                                            2
                                                        ? S
                                                            .of(context)
                                                            .qingxuanzeshouhuodizhi
                                                        : S.of(context).xuni,
                                            overflow: TextOverflow.ellipsis,
                                            style: TextStyle(
                                              fontSize: 14.sp,
                                              color: Color(0xFF32A060),
                                            ),
                                          ),
                                          flex: 1,
                                        ),
                                        Icon(
                                          Icons.keyboard_arrow_right,
                                          size: 16,
                                          color: Color(0xFF32A060),
                                        ),
                                      ],
                                    ),
                                  ),
                                  flex: 1,
                                ),
                              ],
                            ),
                            visible: widget.arguments["useTyped"] != 3,
                          ),
                          SizedBox(
                            height: 12.h,
                          ),
                          Row(
                            children: [
                              Visibility(
                                visible: widget.arguments["useTyped"] != 3,
                                child: Text(
                                  widget.arguments["useTyped"] == 1?S.of(context).zitishijian:"发货时间",
                                  style: TextStyle(
                                      fontSize: 14.sp,
                                      color: Color(0xFF353535)),
                                ),
                              ),
                              Visibility(
                                visible: widget.arguments["useTyped"] != 3,
                                child: SizedBox(
                                  width: 12.w,
                                ),
                              ),
                              Text(
                                widget.arguments["useTyped"] == 1
                                    ? S.of(context).duihuanhouwugegongzuori
                                    : widget.arguments["useTyped"] == 2
                                        ? S.of(context).duihuanhoufahuo
                                        : S.of(context).feishiwushangpin,
                                style: TextStyle(
                                    fontSize: 14.sp,
                                    color: widget.arguments["useTyped"] == 3
                                        ? Color(0xFF32A060)
                                        : Color(0xFF353535)),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    // :
                    // // Container(
                    // //   margin:
                    // //   EdgeInsets.only(left: 16, right: 16, top: 26, bottom: 8),
                    // //   padding: EdgeInsets.all(20),
                    // //   decoration: BoxDecoration(
                    // //     color: Colors.white,
                    // //     boxShadow: [
                    // //       BoxShadow(
                    // //         color: Colors.black.withAlpha(12),
                    // //         offset: Offset(0, 3),
                    // //         blurRadius: 14,
                    // //         spreadRadius: 0,
                    // //       )
                    // //     ],
                    // //     borderRadius: BorderRadius.all(Radius.circular(8)),
                    // //   ),
                    // //   child: Column(
                    // //     mainAxisAlignment: MainAxisAlignment.spaceAround,
                    // //     crossAxisAlignment: CrossAxisAlignment.start,
                    // //     children: [
                    // //       Row(
                    // //         children: [
                    // //           Image.asset(
                    // //             "assets/image/icon_order_exchange_info.webp",
                    // //             width: 24,
                    // //             height: 24,
                    // //           ),
                    // //           SizedBox(width: 4),
                    // //           Text(
                    // //             S.of(context).duihuanxinxi,
                    // //             style: TextStyle(
                    // //                 fontWeight: FontWeight.bold,
                    // //                 fontSize: 16,
                    // //                 color: Color(0xFF353535)),
                    // //           ),
                    // //         ],
                    // //       ),
                    // //       SizedBox(
                    // //         height: 18.h,
                    // //       ),
                    // //       Row(
                    // //         children: [
                    // //           Text(
                    // //             S.of(context).lingqufangshi,
                    // //             style: TextStyle(
                    // //               fontSize: 14.sp,
                    // //               color: Color(0xFF353535),
                    // //             ),
                    // //           ),
                    // //           SizedBox(
                    // //             width: 12.w,
                    // //           ),
                    // //           Text(
                    // //             widget.arguments["useTyped"] == 1
                    // //                 ? S.of(context).ziti
                    // //                 : widget.arguments["useTyped"] == 2
                    // //                 ? S.of(context).peisong
                    // //                 : S.of(context).xianshangfafang,
                    // //             style: TextStyle(
                    // //               fontSize: 14.sp,
                    // //               color: Color(0xFF353535),
                    // //             ),
                    // //           ),
                    // //         ],
                    // //       ),
                    // //       SizedBox(
                    // //         height: 12.h,
                    // //       ),
                    // //       Text(
                    // //         "非实物商品兑换后领取到卡包即可使用!",
                    // //         style: TextStyle(
                    // //             fontSize: 14.sp,
                    // //             color: Color(0xFF32A060),
                    // //             fontWeight: MyFontWeight.medium
                    // //         ),
                    // //       ),
                    // //     ],
                    // //   ),
                    // // ),
                    // Container(
                    //     margin: EdgeInsets.only(
                    //         left: 16, right: 16, top: 26, bottom: 8),
                    //     padding: EdgeInsets.all(20),
                    //     decoration: BoxDecoration(
                    //       color: Colors.white,
                    //       boxShadow: [
                    //         BoxShadow(
                    //           color: Colors.black.withAlpha(12),
                    //           offset: Offset(0, 3),
                    //           blurRadius: 14,
                    //           spreadRadius: 0,
                    //         )
                    //       ],
                    //       borderRadius:
                    //           BorderRadius.all(Radius.circular(8)),
                    //     ),
                    //     child: Column(
                    //       children: [
                    //         Row(
                    //           children: [
                    //             Image.asset(
                    //               "assets/image/icon_order_exchange_info.webp",
                    //               width: 24,
                    //               height: 24,
                    //             ),
                    //             SizedBox(width: 4),
                    //             Text(
                    //               S.of(context).duihuanxinxi,
                    //               style: TextStyle(
                    //                   fontWeight: FontWeight.bold,
                    //                   fontSize: 16,
                    //                   color: Color(0xFF353535)),
                    //             ),
                    //           ],
                    //         ),
                    //         SizedBox(
                    //           height: 18.h,
                    //         ),
                    //         GestureDetector(
                    //           onTap: () {
                    //             setState(() {
                    //               showAlertDialog();
                    //             });
                    //           },
                    //           child: Row(
                    //             children: [
                    //               Text(
                    //                 S.of(context).lingqufangshi,
                    //                 style: TextStyle(
                    //                   fontSize: 14.sp,
                    //                   color: Color(0xFF353535),
                    //                 ),
                    //               ),
                    //               SizedBox(
                    //                 width: 12.w,
                    //               ),
                    //               Expanded(
                    //                   child: Text(
                    //                 widget.arguments["useTyped"] == 1
                    //                     ? S.of(context).ziti
                    //                     : widget.arguments["useTyped"] == 2
                    //                         ? S.of(context).peisong
                    //                         : S.of(context).xianshangfafang,
                    //                 style: TextStyle(
                    //                   fontSize: 14.sp,
                    //                   color: Color(0xFF353535),
                    //                 ),
                    //               )),
                    //               Icon(
                    //                 Icons.keyboard_arrow_right,
                    //                 size: 16,
                    //                 color: Color(0xFF32A060),
                    //               ),
                    //             ],
                    //           ),
                    //         ),
                    //         Visibility(
                    //           child: SizedBox(
                    //             height: 13.h,
                    //           ),
                    //           visible: widget.arguments["useTyped"] != 3,
                    //         ),
                    //         Visibility(
                    //           child: Row(
                    //             children: [
                    //               Text(
                    //                 "收货地址",
                    //                 style: TextStyle(
                    //                   fontSize: 14.sp,
                    //                   color: Color(0xFF353535),
                    //                 ),
                    //               ),
                    //               SizedBox(
                    //                 width: 12.w,
                    //               ),
                    //               Expanded(
                    //                 child: GestureDetector(
                    //                   onTap: () {
                    //                     toAddressPicker();
                    //                   },
                    //                   child: Row(
                    //                     mainAxisAlignment:
                    //                         MainAxisAlignment.end,
                    //                     crossAxisAlignment:
                    //                         CrossAxisAlignment.end,
                    //                     mainAxisSize: MainAxisSize.min,
                    //                     children: [
                    //                       Expanded(
                    //                         child: Text(
                    //                           (address != null &&
                    //                                   address != "")
                    //                               ? address
                    //                               : widget.arguments[
                    //                                           "useTyped"] ==
                    //                                       1
                    //                                   ? S
                    //                                       .of(context)
                    //                                       .qingxuanzhemendian
                    //                                   : widget.arguments[
                    //                                               "useTyped"] ==
                    //                                           2
                    //                                       ? S
                    //                                           .of(context)
                    //                                           .qingxuanzeshouhuodizhi
                    //                                       : S
                    //                                           .of(context)
                    //                                           .xuni,
                    //                           overflow:
                    //                               TextOverflow.ellipsis,
                    //                           style: TextStyle(
                    //                             fontSize: 14.sp,
                    //                             color: Color(0xFF32A060),
                    //                           ),
                    //                         ),
                    //                         flex: 1,
                    //                       ),
                    //                       Icon(
                    //                         Icons.keyboard_arrow_right,
                    //                         size: 16,
                    //                         color: Color(0xFF32A060),
                    //                       ),
                    //                     ],
                    //                   ),
                    //                 ),
                    //                 flex: 1,
                    //               ),
                    //             ],
                    //           ),
                    //           visible: widget.arguments["useTyped"] != 3,
                    //         ),
                    //         SizedBox(
                    //           height: 12.h,
                    //         ),
                    //       ],
                    //     ),
                    //   ),
                    Container(
                      margin: EdgeInsets.only(
                          left: 16, right: 16, top: 8, bottom: 16),
                      padding: EdgeInsets.all(20),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withAlpha(12),
                            offset: Offset(0, 3),
                            blurRadius: 14,
                            spreadRadius: 0,
                          )
                        ],
                        borderRadius: BorderRadius.all(Radius.circular(8)),
                      ),
                      child: Column(
                        children: [
                          Row(
                            children: [
                              Image.asset(
                                "assets/image/icon_order_commodity_info.webp",
                                width: 24,
                                height: 24,
                              ),
                              SizedBox(width: 4),
                              Text(
                                S.of(context).duihuanshangpinxiangqing,
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16,
                                  color: Color(0xFF353535),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: 18,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisSize: MainAxisSize.max,
                            children: [
                              MImage(
                                widget?.arguments["image"] ?? "",
                                width: 80,
                                height: 80,
                                fit: BoxFit.cover,
                                errorSrc: "assets/image/default_1.webp",
                                fadeSrc: "assets/image/default_1.webp",
                              ),
                              Expanded(
                                child: Container(
                                  height: 80.h,
                                  margin: EdgeInsets.only(left: 16.w),
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: [
                                      Text(
                                        widget.arguments["name"],
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                            fontSize: 14.sp,
                                            fontWeight: FontWeight.bold,
                                            color: Color(0xFF353535)),
                                      ),
                                      // SizedBox(
                                      //   height: 4.h,
                                      // ),
                                      // Text(
                                      //   "x1",
                                      //   style: TextStyle(
                                      //       fontSize: 12.sp,
                                      //       color: Color(0xFF727272)),
                                      // ),
                                    ],
                                  ),
                                ),
                                flex: 1,
                              )
                            ],
                          ),
                          SizedBox(
                            height: 12.h,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                "应付数额",
                                style: TextStyle(
                                    fontSize: 14,
                                    color: Color(0xFF353535),
                                    fontWeight: MyFontWeight.regular),
                              ),
                              SizedBox(
                                width: 12,
                              ),
                              Text(
                                // widget.arguments["payType"] == 1
                                //     ? "${(double.parse(widget.arguments["oneBean"] ?? "0") * buyNum).toInt()}印章"
                                //     : (widget.arguments["payType"] == 2 ?"${(double.parse(widget.arguments["onePrice"]) * buyNum).toInt()}积分"
                                //   :((widget.arguments["price"] == null ||
                                //                 widget.arguments["price"] == "0"
                                //             ? (widget.arguments["oneBean"] != "0" && double.parse(userInfo?.happyBean ?? "0") <= double.parse(widget.arguments["oneBean"] ??"0")
                                //     ? "${AppUtils.calculateDouble(double.parse(widget.arguments["oneBean"] ?? "0") * buyNum)}印章"
                                //     :(widget.arguments["onePrice"] != "0" && double.parse(userInfo?.points ?? "0") <= double.parse(widget.arguments["onePrice"])
                                //     ?"${AppUtils.calculateDouble(double.parse(widget.arguments["onePrice"]) * buyNum)}积分"
                                //     :"${AppUtils.calculateDouble(double.parse(widget.arguments["oneMoney"]) * buyNum)}元"))
                                //             : "${(double.parse(widget.arguments["price"]) * buyNum).toInt()}积分") +
                                //         (widget.arguments["money"] == null ||
                                //                 widget.arguments["money"] ==
                                //                     "0.00"
                                //             ? ""
                                //             : " + ${AppUtils.calculateDouble(double.tryParse(widget.arguments["money"]) * buyNum) ?? 0}元"))),
                                payableAmount(),
                                style: TextStyle(
                                  fontSize: 12,
                                  decoration: (widget.arguments["payType"] ==
                                              4 &&
                                          ((widget.arguments["price"] != "0" && widget.arguments["money"] != "0.00"
                                              || (widget.arguments["oneBean"] ?? "0") != "0"
                                              || widget.arguments["onePrice"] != "0")))
                                      ? TextDecoration.lineThrough
                                      : TextDecoration.none,
                                  fontFamily: 'JDZhengHT',
                                  color: Color(0xFF32A060),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: 12,
                          ),
                          if (widget.arguments["payType"] == 4 &&
                              (widget.arguments["price"] != "0" &&
                                      widget.arguments["money"] != "0.00" ||
                                  (widget.arguments["oneBean"] ?? "0") != "0" ||
                                  widget.arguments["onePrice"] != "0"))
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Text(
                                  payableAmount().contains("印章")? "现金抵扣印章":"现金抵扣积分",
                                  style: TextStyle(
                                      fontSize: 14,
                                      color: Color(0xFF353535),
                                      fontWeight: MyFontWeight.regular),
                                ),
                                SizedBox(
                                  width: 12,
                                ),
                                Text(
                                  "${AppUtils.calculateDouble(double.parse(widget.arguments["oneMoney"]) * buyNum)}元",
                                  style: TextStyle(
                                    fontSize: 12,
                                    fontFamily: 'JDZhengHT',
                                    color: Colors.black,
                                  ),
                                ),
                              ],
                            ),
                          SizedBox(
                            height: 12,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                "合计",
                                style: TextStyle(
                                    fontSize: 14.sp,
                                    color: Color(0xFF353535),
                                    fontWeight: MyFontWeight.regular),
                              ),
                              SizedBox(
                                width: 12.w,
                              ),
                              Text(
                                handleNeedPay(),
                                style: TextStyle(
                                    fontFamily: 'JDZhengHT',
                                    fontSize: 12.sp,
                                    color: Color(0xFF32A060)),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    // Container(
                    //   margin: EdgeInsets.only(left: 16, right: 16, bottom: 8),
                    //   padding: EdgeInsets.all(20),
                    //   decoration: BoxDecoration(
                    //     color: Colors.white,
                    //     boxShadow: [
                    //       BoxShadow(
                    //         color: Colors.black.withAlpha(12),
                    //         offset: Offset(0, 3),
                    //         blurRadius: 14,
                    //         spreadRadius: 0,
                    //       )
                    //     ],
                    //     borderRadius: BorderRadius.all(Radius.circular(8)),
                    //   ),
                    //   child: Column(
                    //     children: [
                    //       Row(
                    //         children: [
                    //           Expanded(
                    //               child: Text(
                    //             "兑换数量",
                    //             style: TextStyle(
                    //                 fontWeight: MyFontWeight.regular,
                    //                 fontSize: 14.sp,
                    //                 color: Color(0xFF353535)),
                    //           )),
                    //           InkWell(
                    //             onTap: () {
                    //               setState(() {
                    //                 if (buyNum > 1) buyNum -= 1;
                    //               });
                    //             },
                    //             child: Image.asset(
                    //               "assets/image/reduce.webp",
                    //               width: 22,
                    //               height: 22,
                    //             ),
                    //           ),
                    //           Container(
                    //             width: 30,
                    //             alignment: Alignment.center,
                    //             child: Text(
                    //               buyNum.toString(),
                    //               style: TextStyle(
                    //                 color: Colors.black,
                    //                 fontSize: 14.sp,
                    //                 fontWeight: MyFontWeight.medium,
                    //               ),
                    //             ),
                    //           ),
                    //           InkWell(
                    //             onTap: () {
                    //               setState(() {
                    //                 if (widget.arguments["payType"] == 1
                    //                     ? (double.parse(widget
                    //                                 .arguments["oneBean"]) *
                    //                             (buyNum + 1)) >
                    //                         double.parse(happyBean)
                    //                     : (widget.arguments["payType"] == 2
                    //                         ? (double.parse(widget.arguments[
                    //                                     "onePrice"]) *
                    //                                 (buyNum + 1)) >
                    //                             double.parse(points)
                    //                         : (widget.arguments["price"] ==
                    //                                     null ||
                    //                                 widget.arguments["price"] ==
                    //                                     "0"
                    //                             ? false
                    //                             : (double.parse(widget
                    //                                         .arguments["price"]) *
                    //                                     (buyNum + 1)) >
                    //                                 double.parse(points)))) {
                    //                   SmartDialog.showToast("您的积分不足",
                    //                       alignment: Alignment.center);
                    //                   return;
                    //                 }
                    //                 buyNum += 1;
                    //               });
                    //             },
                    //             child: Image.asset(
                    //               "assets/image/add.webp",
                    //               width: 22,
                    //               height: 22,
                    //             ),
                    //           ),
                    //         ],
                    //       ),
                    //     ],
                    //   ),
                    // ),
                    if (widget.arguments["payType"] == 4 ||
                        (widget.arguments["payType"] == 3 &&
                            widget.arguments["money"] != "0.00"))
                      Container(
                        width: double.infinity,
                        margin: EdgeInsets.only(
                          left: 16.w,
                          right: 16.w,
                          top: 12.h,
                          bottom: 20.h,
                        ),
                        padding: EdgeInsets.only(
                          left: 16.w,
                          right: 16.w,
                          top: 20.h,
                          bottom: 20.h,
                        ),
                        decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: Color(0x000000).withAlpha(25),
                              offset: Offset(0, 1),
                              blurRadius: 12.0,
                            ),
                          ],
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: EdgeInsets.only(bottom: 16.h),
                              child: Text(
                                S.of(context).zhifufangshi,
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  color: Colors.black,
                                  fontWeight: MyFontWeight.regular,
                                ),
                              ),
                            ),
                            GestureDetector(
                              onTap: () {
                                setState(() {
                                  checkIndex = 1;
                                });
                                // widget.payChannelCheck(4);
                              },
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  checkPayView(1),
                                  Expanded(
                                    child: Container(),
                                    flex: 1,
                                  ),
                                  Text(
                                    "¥$mBalance",
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      color: Color(0xff353535),
                                      fontFamily: 'JDZhengHT',
                                      fontWeight: MyFontWeight.medium,
                                    ),
                                  ),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Text(
                                    S.of(context).huixiangqianbao,
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      color: Color(0xff353535),
                                      fontWeight: MyFontWeight.semi_bold,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(
                              height: 10.h,
                            ),
                            // GestureDetector(
                            //   onTap: () {
                            //     setState(() {
                            //       checkIndex = 2;
                            //     });
                            //   },
                            //   child: Row(
                            //     mainAxisAlignment: MainAxisAlignment.center,
                            //     crossAxisAlignment: CrossAxisAlignment.center,
                            //     children: [
                            //       checkPayView(2),
                            //       Expanded(
                            //         child: Container(),
                            //         flex: 1,
                            //       ),
                            //       Text(
                            //         "¥$balance",
                            //         style: TextStyle(
                            //           fontSize: 14.sp,
                            //           color: Color(0xff353535),
                            //           fontWeight: MyFontWeight.semi_bold,
                            //         ),
                            //       ),
                            //       SizedBox(
                            //         width: 10,
                            //       ),
                            //       Text(
                            //         S.of(context).dianpuyue,
                            //         style: TextStyle(
                            //           fontSize: 14.sp,
                            //           color: Color(0xff353535),
                            //           fontWeight: MyFontWeight.semi_bold,
                            //         ),
                            //       ),
                            //     ],
                            //   ),
                            // ),
                            SizedBox(
                              height: 10.h,
                            ),
                            GestureDetector(
                              onTap: () {
                                setState(() {
                                  checkIndex = 3;
                                });
                              },
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  checkPayView(3),
                                  Spacer(),
                                  Image.asset("assets/image/icon_we_chat.webp"),
                                  Padding(
                                    padding: EdgeInsets.only(left: 8.w),
                                    child: Text(
                                      S.of(context).weixinzhifu,
                                      style: TextStyle(
                                        fontSize: 14.sp,
                                        color: Color(0xff353535),
                                        fontWeight: MyFontWeight.semi_bold,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    SizedBox(height: 100.h)
                  ],
                )),
            Align(
                alignment: Alignment.bottomCenter,
                child: Container(
                  height: 54.h,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(45),
                  ),
                  margin:
                      EdgeInsets.only(bottom: 20.h, left: 16.w, right: 16.w),
                  child: Row(
                    children: [
                      Spacer(),
                      Padding(
                          padding: EdgeInsets.only(top: 7, right: 16),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                S.of(context).heji,
                                style: TextStyle(
                                  fontSize: 12.sp,
                                  fontWeight: MyFontWeight.regular,
                                  color: Colors.black,
                                ),
                              ),
                              Text(
                                handleNeedPay(),
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  fontWeight: MyFontWeight.medium,
                                  color: Color(0xFF32A060),
                                ),
                              ),
                            ],
                          )),
                      GestureDetector(
                        onTap: () {
                          if (!storeIsSelected) return;
                          creditOrder();
                        },
                        child: Container(
                          width: 103.w,
                          height: 54.h,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            color: Color(0xFF32A060),
                            borderRadius: BorderRadius.only(
                              bottomRight: Radius.circular(45),
                              topRight: Radius.circular(45),
                            ),
                          ),
                          child: Text(
                            widget.arguments["payType"] == 4 ||
                                    (widget.arguments["payType"] == 3 &&
                                        widget.arguments["money"] != "0.00")
                                ? S.current.jiesuan
                                : S.current.duihuan,
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: MyFontWeight.regular,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ))
          ],
        ));
  }

  ///领取方式弹窗
  showAlertDialog() {
    //显示对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return ReceivingMethodDialog(widget.arguments["useTyped"], (value) {
          setState(() {
            widget.arguments["useTyped"] = value;
          });
        });
      },
    );
  }

  ///应付数额价格显示
  String payableAmount() {
    if (widget.arguments["payType"] == 0) return "";
    if (widget.arguments["payType"] == 1) {
      return "${(double.parse(widget.arguments["oneBean"] ?? "0") * buyNum).toInt()}印章";
    } else if (widget.arguments["payType"] == 2) {
      return "${(double.parse(widget.arguments["onePrice"]) * buyNum).toInt()}积分";
    } else if (widget.arguments["payType"] == 3) {
      return "${(double.parse(widget.arguments["price"]) * buyNum).toInt()}积分" + " + ${AppUtils.calculateDouble(double.tryParse(widget.arguments["money"]) * buyNum) ?? 0}元";
    } else if (widget.arguments["payType"] == 4) {
      if ((widget.arguments["oneBean"] ?? "0") != "0") {
        return "${AppUtils.calculateDouble(double.parse(widget.arguments["oneBean"] ?? "0") * buyNum)}印章";
      } else if (widget.arguments["onePrice"] != "0") {
        return "${AppUtils.calculateDouble(double.parse(widget.arguments["onePrice"]) * buyNum)}积分";
      } else if ((widget.arguments["price"] != null || widget.arguments["price"] != "0") && (widget.arguments["money"] != null || widget.arguments["money"] != "0.00")) {
        if(widget.arguments["price"] == "0"){
          return "${AppUtils.calculateDouble(double.parse(widget.arguments["oneMoney"]) * buyNum)}元";
        }
        return "${(double.parse(widget.arguments["price"]) * buyNum).toInt()}积分" + " + ${AppUtils.calculateDouble(double.tryParse(widget.arguments["money"]) * buyNum) ?? 0}元";
      }
    }
  }

  ///总价支付价格
  String handleNeedPay() {
    if (widget.arguments["payType"] == 0) return "";
    if (widget.arguments["payType"] == 1) {
      return "${(double.parse(widget.arguments["oneBean"]) * buyNum).toInt()}印章";
    }
    if (widget.arguments["payType"] == 2) {
      return S.of(context).jifen_(
          (double.parse(widget.arguments["onePrice"]) * buyNum).toInt());
    } else if (widget.arguments["payType"] == 3) {
      return (widget.arguments["price"] == null ||
                  widget.arguments["price"] == "0"
              ? ""
              : "${(double.parse(widget.arguments["price"]) * buyNum).toInt()}积分") +
          (widget.arguments["money"] == null ||
                  widget.arguments["money"] == "0.00"
              ? ""
              : " + ${AppUtils.calculateDouble(double.tryParse(widget.arguments["money"]) * buyNum) ?? 0}元");
    } else if (widget.arguments["payType"] == 4) {
      return "${AppUtils.calculateDouble(double.tryParse(widget.arguments["oneMoney"]) * buyNum) ?? 0}元";
    }
  }

  Widget checkPayView(var index) {
    return Container(
      padding: EdgeInsets.only(right: 16.w),
      alignment: Alignment.center,
      child: Image.asset(
        checkIndex != index
            ? "assets/image/icon_radio_unselected.webp"
            : "assets/image/icon_radio_selected.webp",
        width: 15.w,
        height: 15.h,
      ),
    );
  }

  var storeIsSelected = true;
  String storeId;
  String address;
  String userAddressId;

  toAddressPicker() async {
    if (widget.arguments["useTyped"] == 1) {
      dynamic result =
          await Navigator.of(context).pushNamed('/router/store_selector_page',arguments: {"creditGoodsId":widget.arguments["goodsId"]});
      if (result == null) return;
      storeId = result["id"];
      address = result["address"];
    } else if (widget.arguments["useTyped"] == 2) {
      dynamic result = await Navigator.of(context).pushNamed(
          '/router/manage_address_page',
          arguments: {"isSelector": true});
      if (result == null) return;
      userAddressId = result["id"];
      address = result["address"];
    }
    setState(() {});
  }

  ///创建积分订单
  creditOrder() async {
    if (widget.arguments["useTyped"] == 1 &&
        (storeId == null || storeId == "")) {
      SmartDialog.showToast("请选择一个门店", alignment: Alignment.center);
      return;
    }
    if (widget.arguments["useTyped"] == 2 &&
        (userAddressId == null || userAddressId == "")) {
      SmartDialog.showToast("请选择一个收货地址", alignment: Alignment.center);
      return;
    }
    BaseData baseDate = await apiService.creditOrder({
      "goodsId": widget.arguments["goodsId"],
      "isOneSell": widget.arguments["payType"] != 3,

      ///增加集换卡,该字段去掉改用payType
      // "isPoints": !handleNeedPay().contains("元"),
      "payType": (widget.arguments["payType"] == 1)
          ? 2
          : ((widget.arguments["payType"] == 2) ? 1 : 3),
      "number": 1,
      "useTyped": widget.arguments["useTyped"],
      "payChannel":
          handleNeedPay().contains("元") ? (checkIndex == 3 ? "1" : "4") : "0",
      if (widget.arguments["useTyped"] == 1) "storeId": storeId,
      if (widget.arguments["useTyped"] == 2) "userAddressId": userAddressId,
    });
    if (baseDate.isSuccess) {
      String realPay = handleNeedPay();
      if ((widget.arguments["payType"] == 4 ||
              (widget.arguments["payType"] == 3 &&
                  widget.arguments["money"] != "0.00")) &&
          checkIndex == 3) {
        // if(Platform.isAndroid){
        //   if (!(await Min.isInitialize())) {
        //     // 小程序的微信支付和app的充值支付使用同一个WXPayEntryActivity回调,
        //     // 然而充值时小程序未初始化会导致回调内部代码调用getPackage空指针,
        //     // 故而在此初始化一下
        //     await Min.initialize();
        //   }
        // }
        WxPay wxPay = WxPay.fromJson(baseDate.data);
        await registerWxApi(
          appId: wxPay.appId,
          doOnAndroid: true,
          universalLink: "https://hx.lotus-wallet.com/app/",
        );
        payWithWeChat(
          appId: wxPay.appId,
          partnerId: wxPay.partnerId,
          prepayId: wxPay.prepayId,
          packageValue: wxPay.packageValue,
          nonceStr: wxPay.nonceStr,
          timeStamp: int.tryParse(wxPay.timeStamp),
          sign: wxPay.sign,
        );
        return;
      }
      await Navigator.of(context)
          .pushNamed('/router/exchange_order_success_page', arguments: {
        "price": realPay.contains(S.of(context).jifen)
            ? realPay.substring(0, realPay.indexOf(S.of(context).jifen))
            : "0",
        "happyBeanPrice":realPay.contains("印章")
            ? realPay.substring(0, realPay.indexOf("印章"))
            : "0",
        "realPay": realPay,
        "points": points,
        "happyBean":happyBean,
        "payChannel": widget.arguments["payChannel"],
        "id": baseDate.data
      });
      points = "${int.tryParse(points) - int.tryParse(widget.arguments["price"])}";
      happyBean = "${int.tryParse(happyBean) - int.tryParse(widget.arguments["price"])}";
      Navigator.of(context).pop();
    } else {
      SmartDialog.showToast(baseDate.msg, alignment: Alignment.center);
    }
  }
}