import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/order/order_view/order_address.dart';
import 'package:huixiang/order/order_view/order_commodity.dart';
import 'package:huixiang/order/order_view/order_info.dart';
import 'package:huixiang/order/order_view/order_pay_selected.dart';
import 'package:huixiang/order/order_view/order_status.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/order_info.dart';
import 'package:huixiang/retrofit/min_api.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/icon_text.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../retrofit/data/user_info.dart';
import '../utils/flutter_utils.dart';
import '../view_widget/classic_header.dart';
import '../view_widget/my_footer.dart';
import 'order_utils.dart';

class OrderDetailPage extends StatefulWidget {
  final arguments;

  OrderDetailPage({this.arguments});

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

class _OrderDetailPage extends State<OrderDetailPage> {
  ApiService apiService;
  MinApiService minService;
  int jumpState;
  final RefreshController refreshController = RefreshController();
  UserInfo userInfo;

  @override
  void initState() {
    super.initState();
    jumpState = widget.arguments["jumpState"];
    SharedPreferences.getInstance().then((value) {
      EasyLoading.show(status: S.of(context).zhengzaijiazai,maskType: EasyLoadingMaskType.black);
      apiService = ApiService(Dio(),
          context: context, token: value.getString("token"),);
      queryDetails();
      queryUserBalance();
    });
  }

  /// 小程序登录
  minLogin() async {
    apiService.minLogin(orderInfo.storeId).catchError((onError) {
      debugPrint(onError);
    }).then((baseData) {
      if (baseData != null && baseData.isSuccess) {
        Map<String, dynamic> minStoreInfo = baseData.data;
        String minToken = minStoreInfo["token"];
        String tenant = orderInfo.tenantCode;
        String storeId = orderInfo.storeId;
        SharedPreferences.getInstance().then(
          (value) => {
            value.setString('minToken', minToken),
            value.setString('tenant', tenant),
            value.setString('storeId', storeId),
          },
        );
        minService = MinApiService(
          Dio(),
          // showLoading:true,
          context: context,
          token: minToken,
          tenant: tenant,
          storeId: storeId,
        );
      }
    });
  }

  ///查询用户信息
  queryUserBalance() async {
    BaseData<UserInfo> baseData =
    await apiService.queryInfo().catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      userInfo = baseData.data;
      if (mounted) setState(() {});
    }else {
      SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
    }
  }

  OrderInfo orderInfo;
  int payStatus = 0;
  int orderStatus = 0;
  int sendStatus = 0;
  int isTakeOut = 0;
  int refundStatus = 0;

  queryDetails() async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(Dio(),
          context: context,
          token: value.getString("token"),
          showLoading: false);
    }
    BaseData<OrderInfo> baseData = await apiService
        .orderDetail(widget.arguments["id"])
        .catchError((error) {
      SmartDialog.showToast(AppUtils.dioErrorTypeToString(error.type),
          alignment: Alignment.center);
      refreshController.refreshFailed();
      refreshController.loadFailed();
    });
    if (baseData != null && baseData.isSuccess) {
      orderInfo = baseData.data;
      payStatus = orderInfo.payStatus;
      orderStatus = orderInfo.orderStatus;
      sendStatus = orderInfo.sendStatus;
      isTakeOut = orderInfo.isTakeOut;
      refundStatus = orderInfo.refundStatus;
      // storeType = orderInfo.storeVO.posType.code;
      print("order refund_status: $refundStatus");
      print("order payStatus: $payStatus");
      print("order orderStatus: $orderStatus");
      print("order sendStatus: $sendStatus");
      print("order isTakeOut: $isTakeOut");

      minLogin();
      if (mounted)
        setState(() {
          statusTitle();
        });
      EasyLoading.dismiss();
      refreshController.refreshCompleted();
      refreshController.loadComplete();
    } else {
      EasyLoading.dismiss();
      SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
      refreshController.refreshFailed();
      refreshController.loadFailed();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Stack(
        children: [
          Container(
            // height: (orderStatus >= 4 ? 118.h : 118.h) +
            //     MediaQuery.of(context).padding.top +
            //     kToolbarHeight +
            //     48.h,
            // color: Color(0xFF3A405A),
            // width: MediaQuery.of(context).size.width,
            decoration: BoxDecoration(
              image: DecorationImage(
                fit: BoxFit.fill,
                image: AssetImage("assets/image/settlement_bg.webp"),
              ),
            ),
            width: double.infinity,
            height: 375.h,
          ),
          Scaffold(
            backgroundColor: Colors.transparent,
            appBar: MyAppBar(
              title: "订单详情",
              titleColor: Colors.white,
              background: Colors.transparent,
              leadingColor: Colors.white,
              brightness: Brightness.dark,
            ),
            body: SmartRefresher(
              controller: refreshController,
              enablePullDown: true,
              enablePullUp: false,
              header: MyHeader(
                color: Colors.white,
              ),
              footer: CustomFooter(
                builder: (context, mode) {
                  return MyFooter(mode);
                },
              ),
              onRefresh:(){
                queryDetails();
              },
              physics: BouncingScrollPhysics(),
              scrollController: ScrollController(),
              child:SingleChildScrollView(
                physics: BouncingScrollPhysics(),
                child: Column(
                  children: [
                    ///订单状态显示
                    OrderStatus(
                      orderStatus,
                      isTakeOut,
                      sendStatus,
                      payStatus,
                      refundStatus,
                      title,
                      center,
                      orderInfo,
                    ),


                    ///订单取货地址,或, 收货地址
                    if(orderInfo != null && orderInfo.addressExt != null)
                      OrderAddress(
                          orderStatus,
                          isTakeOut,
                          sendStatus,
                          payStatus,
                          refundStatus,
                          title,
                          center,
                          paySelected,
                          _orderCancel,
                          orderInfo,
                          jumpState
                      ),

                    ///订单商品
                    if(orderInfo != null)
                      OrderCommodity(orderInfo),

                    ///显示订单信息
                    if(orderInfo != null)
                      OrderInfoView(orderInfo, isTakeOut),

                    Container(
                      height: 42.h,
                    ),
                  ],
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  String title = "";
  String center = "";

  paySelected() async {
    var payChannel = await showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) {
        return OrderPaySelected(userInfo);
      },
    );
    if (payChannel != null && payChannel > 0) {
      OrderUtils.carryOnPay(payChannel, minService, orderInfo, payResult);
    }
  }

  payResult(BaseData baseData) async {
    await queryDetails();
    Future.delayed(Duration(milliseconds: 800), () {
      EasyLoading.dismiss();
      SmartDialog.showToast(baseData?.msg == "ok" ? "订单支付成功" : baseData?.msg,
          alignment: Alignment.center);
    });
  }

  statusTitle() {
    if (isTakeOut == 0 || isTakeOut == 3 || isTakeOut == 4) {
      if (payStatus == 0 && orderStatus != -1) {
        title = S.of(context).dingdandaizhifu;
      } else {
        title = S.of(context).dingdanyizhifu;
        switch (orderStatus) {
          case -1:
            title = S.of(context).yiquxiao;
            center = S.of(context).yiquxiao;
            break;
          case 2:
            title = S.of(context).shangjiazhengzaipeican;
            break;
          case 3:
            title = S.of(context).dengdaiyonghuqucan;
            center = S.of(context).qudanhao(orderInfo.dayFlowCode);
            break;
          case 4:
            title = S.of(context).dingdanyiwancheng;
            center = S.of(context).dingdanyiwancheng;
            break;
          case 5:
            title = S.of(context).yiquxiao;
            center = S.of(context).yiquxiao;
            break;
        }
      }
    } else if (isTakeOut == 1) {
      if (payStatus == 0) {
        title = S.of(context).dingdandaizhifu;
      } else {
        title = S.of(context).dengdaishangjiaqueren;
        if (orderStatus < 4) {
          switch (sendStatus) {
            case 1:
              title = S.of(context).zhengzaihujiaoqishou;
              break;
            case 2:
              title = S.of(context).qishouyijiedanquhuozhong;
              break;
            case 3:
              title = S.of(context).qishoupeisongzhongyujisongdashijian;
              break;
            case 4:
              title = S.of(context).dingdanyisongda;
              center = S.of(context).dingdanyisongda;
              switch (orderStatus) {
                case 4:
                  title = S.of(context).dingdanyiwancheng;
                  center = S.of(context).dingdanyiwancheng;
                  break;
              }
              break;
          }
        } else if (orderStatus == 4) {
          title = S.of(context).dingdanyiwancheng;
          center = S.of(context).dingdanyiwancheng;
        }
      }
    } else if (isTakeOut == 2) {
      if (payStatus == 0) {
        title = S.of(context).dingdandaizhifu;
      } else {
        title = S.of(context).dingdandaifahuo;
        if (orderStatus < 4) {
          switch (sendStatus) {
            case 1:
              title = S.of(context).shangjiayifahuo;
              break;
            case 4:
              title = S.of(context).huopinyisongda;
              center = S.of(context).huopinyisongda;
              break;
          }
        } else if (orderStatus == 4) {
          title = S.of(context).dingdanyiwancheng;
          center = S.of(context).dingdanyiwancheng;
        }
      }
    }
    if (orderStatus == 5 || orderStatus == -1) {
      title = S.of(context).yiquxiao;
      center = S.of(context).yiquxiao;
    }
    if (refundStatus == 1) {
      title = S.of(context).dingdanyituikuan;
      center = S.of(context).dingdanyituikuan;
    }
  }

  Widget couponRemarks() {
    return Container(
      margin: EdgeInsets.only(left: 16.w, right: 16.w, top: 8.h, bottom: 2.h),
      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.circular(8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          orderInfoItem(S.of(context).youhuiquan, "暂无可用优惠券"),
          orderInfoItem(S.of(context).beizhu, "口味、面包硬度等"),
        ],
      ),
    );
  }

  Widget bottomPay() {
    return Container(
      height: 54.h,
      color: Colors.white,
      child: Row(
        children: [
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.baseline,
              textBaseline: TextBaseline.alphabetic,
              children: [
                Text(
                  S.of(context).heji,
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.black,
                  ),
                ),
                Text(
                  S
                      .of(context)
                      .yuan_(orderInfo != null ? orderInfo.finalPayPrice : "0"),
                  style: TextStyle(
                    fontSize: 20.sp,
                    color: Color(0xFF32A060),
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
            flex: 1,
          ),
          SizedBox(
            width: 16.w,
          ),
          InkWell(
            onTap: () {},
            child: Container(
              alignment: Alignment.center,
              color: Color(0xFF32A060),
              padding: EdgeInsets.symmetric(horizontal: 36.w),
              child: Text(
                S.of(context).jiesuan,
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget paySelector() {
    return Container(
      // margin: EdgeInsets.only(left: 16.w, right: 16.w, top: 14.h, bottom: 2.h),
      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.circular(8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            S.of(context).zhifufangshi,
            style: TextStyle(
              color: Color(0xFF727272),
              fontSize: 12.sp,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(
            height: 20.h,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              checkView(0),
              // Image.asset("assets/image/icon_alipay.webp"),
              Text(
                S.of(context).pingtaiyue,
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Color(0xff353535),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 20.h,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              checkView(1),
              // Image.asset("assets/image/icon_alipay.webp"),
              Text(
                S.of(context).dianpuyue,
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Color(0xff353535),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 20.h,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              checkView(2),
              IconText(
                S.of(context).weixinzhifu,
                leftImage: "assets/image/icon_we_chat.webp",
                iconSize: 14.w,
                space: 8.w,
                textStyle: TextStyle(
                  fontSize: 12.sp,
                  color: Color(0xFF353535),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }

  var checkIndex = 0;

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

  _orderCancel() async {
    BaseData baseData = await apiService
        .orderCancel(widget.arguments["id"])
        .catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      SmartDialog.showToast("订单取消成功");
      // Future.delayed(Duration(milliseconds:450), () {
      queryDetails();
      // });
    } else {
      SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
    }
  }

  ///评价弹窗
  assessShowBottomSheet() {
    showModalBottomSheet(
        builder: (BuildContext context) {
          return buildBottomSheetWidget(context);
        },
        backgroundColor: Colors.transparent,
        context: context);
  }

  Widget buildBottomSheetWidget(BuildContext context) {
    return Container(
        padding: EdgeInsets.only(top: 12),
        decoration: new BoxDecoration(
            color: Colors.white,
            borderRadius: new BorderRadius.only(
                topLeft: const Radius.circular(25.0),
                topRight: const Radius.circular(25.0))),
        child: Container(
          width: 299,
          height: 299,
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                      child: Align(
                    alignment: Alignment.center,
                    child: Text(
                      "订单评价",
                      style: TextStyle(
                        fontWeight: MyFontWeight.bold,
                        fontSize: 15.sp,
                        color: Color(0xFF000000),
                      ),
                    ),
                  )),
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        Navigator.of(context).pop();
                      });
                    },
                    child: Icon(
                      Icons.clear,
                      color: Colors.black,
                      size: 18,
                    ),
                  ),
                  SizedBox(width: 14),
                ],
              ),
              SizedBox(
                height: 12.h,
              ),
              Container(
                width: double.infinity,
                height: 1.h,
                color: Color(0xFFF2F2F2),
                margin: EdgeInsets.only(bottom: 43.h),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    width: 92,
                    height: 92,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(16),
                      border: Border.all(
                        color: Color(0xFFF2F2F2),
                        width: 1,
                      ),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Image.asset(
                          "assets/image/report_un.webp",
                          width: 45,
                          height: 45,
                        ),
                        SizedBox(
                          height: 4,
                        ),
                        Text(
                          "不满意",
                          style: TextStyle(
                            fontWeight: MyFontWeight.regular,
                            fontSize: 12.sp,
                            color: Color(0xFF262626),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    width: 92,
                    height: 92,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(16),
                      border: Border.all(
                        color: Color(0xFFFFD549),
                        width: 1,
                      ),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Image.asset(
                          "assets/image/report_h.webp",
                          width: 45,
                          height: 45,
                        ),
                        SizedBox(
                          height: 4,
                        ),
                        Text(
                          "很满意",
                          style: TextStyle(
                            fontWeight: MyFontWeight.regular,
                            fontSize: 12.sp,
                            color: Color(0xFF262626),
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ),
              Container(
                width: double.infinity,
                height: 36.h,
                alignment: Alignment.center,
                margin: EdgeInsets.only(left: 14.w, right: 14.w, top: 50.h),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(6),
                  color: Color(0xFF32A060),
                ),
                child: Text(
                  S.of(context).queding,
                  style: TextStyle(
                    fontWeight: MyFontWeight.medium,
                    fontSize: 15.sp,
                    color: Color(0xFFFFFFFF),
                  ),
                ),
              ),
            ],
          ),
        ));
  }

  Widget orderInfoItem(leftText, rightText) {
    return Container(
      margin: EdgeInsets.only(top: 8.h, bottom: 8.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            leftText,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 12.sp,
              color: Color(0xFF727272),
            ),
          ),
          Expanded(
            child: Text(
              rightText,
              textAlign: TextAlign.end,
              style: TextStyle(
                fontSize: 12.sp,
                color: Color(0xFF353535),
              ),
            ),
            flex: 1,
          ),
        ],
      ),
    );
  }
}