import 'package:ff_stars/ff_stars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:tobias/tobias.dart' as tobias;
import 'package:farmer_client/services/pay.dart';
import 'package:farmer_client/services/orderAPI.dart';
import 'package:farmer_client/utils/processStatus.dart';
import 'package:farmer_client/widgets/DefaultButton.dart';
import 'package:farmer_client/widgets/Bold.dart';
import 'package:farmer_client/widgets/OrderInfoCard.dart';
import 'package:farmer_client/widgets/layout/BasicPage.dart';
import 'package:farmer_client/widgets/Modal.dart' as modal;
import 'package:farmer_client/models/entities/OrderInfoModel.dart';

import './widgets/PayItem.dart';

class OrderPageInfo extends BasicPage {
  final id = Rx<String>('');
  final orderStateText = Rx<String>('待支付');
  final orderStateColor = Rx<Color>(Colors.black);
  final orderInfoContent = Rx<OrderInfoModel>(OrderInfoModel.fromJson(
      {'status': 6, 'dispatchStatus': 6, 'workStatus': 6}));

  final evalText = Rx<String>('');
  final evalStars = Rx<num>(-1);

  // orderStates
  @override
  void beforeShow() {
    // TODO: implement beforeShow
    super.beforeShow();
    if (Get.arguments != null && Get.arguments['orderId'] != null) {
      id(Get.arguments['orderId']);

      orderInfo(Get.arguments['orderId']).then((value) {
        EasyLoading.show(status: '数据加载中...');
        OrderInfoModel orderInfo = OrderInfoModel.fromJson(value);
        ProcessSign processSign = getProcessSign(getProcessStatus(orderInfo));
        orderStateText(processSign.label);
        orderStateColor(processSign.color);
        orderInfoContent(orderInfo);
        EasyLoading.dismiss();
      });
    }
  }

  Widget _action(BuildContext context, String orderId) {
    bool mustAction = false;
    var btnLabel;
    var btnFunction;

    switch (getProcessStatus(orderInfoContent.value)) {
      case 1:
      case 2:
        mustAction = true;
        btnLabel = '取消';
        btnFunction = () {
          _cancelOrder(orderId);
        };
        break;
      case 4:
        mustAction = true;
        btnLabel = '支付';
        btnFunction = () {
          _bottomSheet(context);
        };
        break;
      case 5:
        mustAction = true;
        btnLabel = '评价';
        btnFunction = () {
          _fnEvaluate(orderId);
        };
        break;
      case 3:
      case 6:
      default:
        break;
    }

    if (mustAction) {
      return DefaultButton(
        color: const Color(0xffffffff),
        backColor: const Color(0xFFFF703B),
        width: 300.w,
        height: 49.h,
        text: btnLabel,
        margin: const EdgeInsets.all(0),
        fontSize: 20.sp,
        radius: 24.5.w,
        onPressed: btnFunction,
      );
    } else {
      return const Text('');
    }
  }

  @override
  Widget builder(BuildContext context) {
    naviTitle = '订单详情';

    return Column(
      children: [
        Obx(
          () => OrderInfoCard(
              item: orderInfoContent(),
              orderStateText: orderStateText(),
              orderStateColor: orderStateColor()),
        ),
        Obx(
          () => Container(
              padding: EdgeInsets.fromLTRB(15, 50.w, 15, 0),
              child: _action(context, id.value)),
        ),
      ],
    );
  }

  // 取消订单
  _cancelOrder(String orderId) {
    modal.showDialog(
        title: '提示',
        content: Container(
          alignment: Alignment.center,
          child: const Text('确定要取消此订单吗？'),
        ),
        onCancel: () => true,
        onConfirm: () => {
              orderDelete(orderId).then((value) {
                Fluttertoast.showToast(msg: '订单取消成功！');
                Get.offAllNamed('/order');
              })
            });
  }

  // 满意度表单
  Widget _evaluateWidget(Function onEvaluate) {
    double star = -1;
    String desc = '';

    return Container(
        alignment: Alignment.center,
        child: Container(
          margin: const EdgeInsets.fromLTRB(15, 20, 15, 20),
          child: Column(
            children: [
              Container(
                padding: const EdgeInsets.fromLTRB(0, 0, 0, 10),
                decoration: const BoxDecoration(
                    border: Border(
                        bottom: BorderSide(width: 0.8, color: Color(0x20000000)
                            // 0x17000000
                            ))),
                child: Row(
                  children: [
                    Text(
                      '满意度：',
                      style: TextStyle(
                          fontSize: 17.sp, fontWeight: FontWeight.bold),
                    ),
                    FFStars(
                      //https://pub.dev/packages/ff_stars
                      normalStar: Image.asset('images/icons/starOff.png'),
                      selectedStar: Image.asset('images/icons/starOn.png'),
                      starsChanged: (realStars, selectedStars) {
                        star = realStars;
                        onEvaluate(star, desc);
                      },
                      step: 1,
                      defaultStars: 0,
                    ),
                  ],
                ),
              ),
              Container(
                margin: const EdgeInsets.fromLTRB(0, 20, 0, 0),
                width: 300.w,
                height: 100.w,
                decoration: BoxDecoration(
                  border: Border.all(
                    color: const Color(0x20000000),
                    width: 0.8,
                  ),
                ),
                child: TextField(
                  minLines: 6,
                  maxLines: 6,
                  style: TextStyle(fontSize: 17.sp, height: 1.5),
                  decoration: const InputDecoration(
                    isCollapsed: true,
                    border: InputBorder.none,
                    counterText: '',
                    hintText: '请输入评价内容',
                    floatingLabelBehavior: FloatingLabelBehavior.never,
                  ),
                  onChanged: (e) {
                    desc = e;
                    onEvaluate(star, desc);
                  },
                ),
              )
            ],
          ),
        ));
  }

  // 评价
  _fnEvaluate(String orderId) {
    int evalStars = -1;
    String evalText = '';

    onEvaluate(int val1, String val2) {
      evalStars = val1;
      evalText = val2;
    }

    modal.showDialog(
      title: '评价此订单',
      content: _evaluateWidget(onEvaluate),
      onCancel: () => true,
      onConfirm: () {
        if (evalStars != -1 && evalText != '') {
          orderEvaluation(orderId, evalStars, evalText).then((value) {
            Fluttertoast.showToast(msg: '评价成功！');
            Get.offAllNamed('/order');
          });
        } else {
          Fluttertoast.showToast(msg: '请完整选择评分或输入评价内容');
          return false;
        }
      },
    );
  }

  // 调用支付接口
  Future<void> payMoney(String payType) async {
    if (payType == 'wxPay') {
      final isInstall = await fluwx.isWeChatInstalled;
      if (!isInstall) {
        EasyLoading.showError('请先安装微信');
        return;
      }
      createOrder(id.value, "wx").then((value) {
        fluwx
            .payWithWeChat(
          appId: value['appid'].toString(),
          partnerId: value['partnerId'].toString(),
          prepayId: value['prepayId'].toString(),
          packageValue: value['packageValue'].toString(),
          nonceStr: value['noncestr'].toString(),
          timeStamp: int.parse(value['timestamp'].toString()),
          sign: value['sign'].toString(),
        )
            .then((res) {
          print("payWithWeChat--------${res}");
        }).catchError((onError) {
          print("payWithWeChat错误--------${onError}");
        });
      });

      // 监听支付结果
      fluwx.weChatResponseEventHandler.listen((event) async {
        print(event.errCode);
        // 支付成功
        if (event.errCode == 0) {
          // EasyLoading.showSuccess('支付成功');
          Get.snackbar('提示', "支付成功");
          Get.offAllNamed('/order');
        } else {
          EasyLoading.showError('支付失败');
        }
        // 关闭弹窗
      });
      return;
    } else if (payType == 'aliPay') {
      final isInstall = await tobias.isAliPayInstalled();
      if (!isInstall) {
        EasyLoading.showError('请先安装支付宝');
        return;
      }
      // map["paySign"]
      createOrder(id.value, "aliPay").then((value) {
        tobias.aliPay(value).then((payResult) {
          print("支付宝:" + payResult.toString());

          if (payResult['resultStatus'] == '9000') {
            Get.snackbar('提示', "支付成功");
            Get.offAllNamed('/order');
          } else {
            EasyLoading.showError('支付失败');
          }
        });
      });
    }
  }

  // 支付 sheet
  _bottomSheet(BuildContext context) {
    //用于在底部打开弹框的效果
    showModalBottomSheet(
        context: context,
        isScrollControlled: false,
        backgroundColor: Colors.white,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(10))),
        builder: (BuildContext context) {
          return SizedBox(
            height: 200.w, //对话框高度就是此高度
            child: Center(
                child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.fromLTRB(0, 25.w, 0, 34.w),
                  child: Bold(text: "支付方式", fontSize: 17.sp),
                ),
                PayItem(
                  label: "支付宝",
                  icon: const AssetImage('images/alipay.png'),
                  onPress: () {
                    payMoney('aliPay');
                  },
                ),
                PayItem(
                  label: "微信",
                  icon: const AssetImage('images/weChatPay.png'),
                  onPress: () {
                    payMoney('wxPay');
                  },
                ),
              ],
            )),
          );
        });
  }
}
