import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/data/address.dart';
import 'package:huixiang/retrofit/data/store_info.dart';
import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/utils/location.dart';
import 'package:huixiang/view_widget/round_button.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class DistributionMode extends StatefulWidget {
  final Function(
    String addressId,
    int isTake,
    String memberCouponId,
    int orderId,
    String promotionId,
  ) queryOrderInfo;
  final Function(int selectedBtn) queryAddress;
  final Function(String addId) selectedNewAddress;
  final StoreInfo storeInfo;
  final Address address;
  final String pageType;
  final double distance;

  DistributionMode(this.queryOrderInfo, this.queryAddress, this.storeInfo,
      this.address, this.selectedNewAddress, this.pageType, this.distance);

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

class _DistributionMode extends State<DistributionMode> {
  List<String> addressBgs = [
    "assets/svg/dingdan_ziqu.svg",
    "assets/svg/dingdan_waimai.svg",
    "assets/svg/dingdan_wuliu.svg",
  ];

  BMFCoordinate myLatLng;
  String distance = "0";
  int selectedBtn = 0;

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

    startLocation();
  }

  ///定位获取当前的位置
  void startLocation() async {
    Location.getInstance().startLocation(context, (BaiduLocation result) {
      if (result != null &&
          result.latitude != null &&
          result.longitude != null) {
        print("location: $result");
        myLatLng = BMFCoordinate(result.latitude, result.longitude);
        calculate();
        Location.getInstance().stopLocation();
      }
    });
  }

  calculate() async {
    BMFCoordinate bmfCoordinate = BMFCoordinate(
      double.tryParse(widget.storeInfo.latitude),
      double.tryParse(widget.storeInfo.longitude),
    );
    distance = await AppUtils.calculateDistance(bmfCoordinate, myLatLng);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 165.h,
      margin: EdgeInsets.only(
        left: 16.w,
        right: 16.w,
        top: 10.h,
      ),
      child: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
              color: Color(0x80FFFFFF),
              boxShadow: [
                BoxShadow(
                  color: Color(0x0D000000),
                  offset: Offset(0, 3),
                  blurRadius: 14,
                  spreadRadius: 0,
                ),
              ],
              borderRadius: BorderRadius.circular(8),
            ),
            child: SvgPicture.asset(
              addressBgs[selectedBtn],
              width: double.infinity,
              height: double.infinity,
              fit: BoxFit.fill,
            ),
          ),
          Column(
            children: [
              Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Expanded(
                      flex: 1,
                      child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          setState(() {
                            selectedBtn = 0;
                            widget.queryOrderInfo(
                                null, selectedBtn, null, 0, null);
                          });
                        },
                        child: Container(
                          height: 50.h,
                          alignment: Alignment.center,
                          child: Text(
                            S.of(context).daodianziqu,
                            style: TextStyle(
                              fontSize: 14.sp,
                              fontWeight: MyFontWeight.semi_bold,
                              color: Colors.black,
                            ),
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: GestureDetector(
                        onTap: () {
                          // if (widget.storeInfo.storeName == "一心回乡商城") {
                          //   SmartDialog.showToast("该功能暂未开放!",
                          //       alignment: Alignment.center);
                          //   return;
                          // }
                          selectedBtn = 1;
                          widget.queryAddress(selectedBtn);
                          // SmartDialog.showToast("该功能暂未开放!",
                          //     alignment: Alignment.center);
                        },
                        child: Container(
                          height: 50.h,
                          alignment: Alignment.center,
                          child: Text(
                            (widget?.storeInfo?.pickupType?.takeawayStatus ?? false) == false ? "" :S.of(context).waimaipeisong,
                            style: TextStyle(
                              fontSize: 14.sp,
                              fontWeight: MyFontWeight.regular,
                              color: Colors.black,
                            ),
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: GestureDetector(
                        onTap: () {
                          // if (widget.storeInfo.storeName == "一心回乡商城"){
                          //   SmartDialog.showToast("该功能暂未开放!",
                          //       alignment: Alignment.center);
                          //   return;
                          // }
                          selectedBtn = 2;
                          widget.queryAddress(selectedBtn);
                          // SmartDialog.showToast("该功能暂未开放!",
                          //     alignment: Alignment.center);
                        },
                        child: Container(
                          height: 50.h,
                          alignment: Alignment.center,
                          child: Text(
                            (widget?.storeInfo?.pickupType?.expressDeliveryStatus ?? false) == false ? "" :S.of(context).kuaidiwuliu,
                            style: TextStyle(
                              fontSize: 14.sp,
                              fontWeight: MyFontWeight.regular,
                              color: Colors.black,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              selectedBtn == 0
                  ? Container(
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 15.h),
                      child: Column(
                        children: [
                          Row(
                            children: [
                              Expanded(
                                child: Column(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceEvenly,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisSize: MainAxisSize.max,
                                  children: [
                                    Text(
                                      widget.storeInfo != null
                                          ? (widget.storeInfo.storeName ?? "")
                                          : "",
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontSize: 14.sp,
                                        fontWeight: MyFontWeight.semi_bold,
                                        color: Color(0xFF4C4C4C),
                                      ),
                                    ),
                                    SizedBox(
                                      height: 6,
                                    ),
                                    Text(
                                      widget.storeInfo != null
                                          ? widget.storeInfo.address
                                          : "",
                                      overflow: TextOverflow.ellipsis,
                                      maxLines: 2,
                                      style: TextStyle(
                                        fontSize: 12.sp,
                                        fontWeight: MyFontWeight.regular,
                                        color: Color(0xFF727272),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              SizedBox(
                                width: 18,
                              ),
                              Stack(
                                alignment: Alignment.center,
                                children: [
                                  Column(
                                    children: [
                                      Image.asset(
                                        "assets/image/map.webp",
                                        height: 61.h,
                                        width: 61.w,
                                      ),
                                    ],
                                  ),
                                  Column(
                                    children: [
                                      RoundButton(
                                        height: 13,
                                        text: distance.length > 3
                                            ? ((widget.distance ?? 0) > 1000
                                                ? "${((widget.distance ?? 0) / 1000 * 100).toInt() / 100.0}km"
                                                : S.of(context).mi(
                                                    ((widget.distance ?? 0) *
                                                                100)
                                                            .toInt() /
                                                        100.0))
                                            : "距离您${(widget.distance ?? 0) > 1000 ?
                                        "${((widget.distance ?? 0) / 1000 * 100).toInt() / 100.0}km"
                                            : S.of(context).mi(((widget.distance ?? 0) * 100).toInt() / 100.0)}",
                                        // distance.length > 3
                                        //     ? "${distance}km"
                                        //     : "距离您${distance}km",
                                        textColor: Color(0xFF34A262),
                                        fontWeight: MyFontWeight.semi_bold,
                                        radius: 7.5,
                                        backgroup: Colors.white,
                                        fontSize: 7.sp,
                                      ),
                                      Image.asset(
                                        "assets/image/landmark.webp",
                                        height: 24.h,
                                        width: 24.w,
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ],
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisSize: MainAxisSize.max,
                          ),
                        ],
                      ),
                    )
                  : GestureDetector(
                      onTap: () {
                        setState(() {
                          Navigator.of(context).pushNamed(
                              '/router/manage_address_page',
                              arguments: {"isSelector": true}).then((value) {
                            widget.selectedNewAddress((value as Map)["id"]);
                          });
                        });
                      },
                      child: Container(
                        width: double.infinity,
                        padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 15.h),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Image.asset(
                                  (widget.storeInfo?.pickupType?.expressDeliveryStatus ?? false == true) ? "assets/image/order_wl.webp":"assets/image/icon_permission_location.webp",
                                        height: 24.h,
                                        width: 24.w,
                                      ),
                                SizedBox(width: 5),
                                Text(
                                  widget?.address?.username ?? "",
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                    fontSize: 15.sp,
                                    fontWeight: MyFontWeight.medium,
                                    color: Color(0xFF4C4C4C),
                                  ),
                                ),
                                SizedBox(
                                  width: 13.w,
                                ),
                                Expanded(
                                  child: Text(
                                    widget?.address?.phone ?? "",
                                    overflow: TextOverflow.ellipsis,
                                    maxLines: 2,
                                    style: TextStyle(
                                      fontSize: 15.sp,
                                      fontWeight: MyFontWeight.medium,
                                      color: Color(0xFF4C4C4C),
                                    ),
                                  ),
                                ),
                                InkWell(
                                    onTap: () {
                                      setState(() {
                                        Navigator.of(context).pushNamed(
                                            '/router/manage_address_page',
                                            arguments: {
                                              "isSelector": true
                                            }).then((value) {
                                          widget.selectedNewAddress(
                                              (value as Map)["id"]);
                                        });
                                      });
                                    },
                                    child: Container(
                                      padding: EdgeInsets.symmetric(
                                          horizontal: 15.w, vertical: 5.h),
                                      child: Icon(
                                        Icons.keyboard_arrow_right,
                                        size: 24,
                                      ),
                                    )),
                              ],
                            ),
                            Padding(
                              padding: EdgeInsets.only(top: 4.h, left: 25.w),
                              child: Text(
                                (widget?.address?.city ?? "") +
                                    (widget?.address?.area ?? "") +
                                    (widget?.address?.address ?? ""),
                                overflow: TextOverflow.ellipsis,
                                maxLines: 2,
                                style: TextStyle(
                                  fontSize: 12.sp,
                                  fontWeight: MyFontWeight.regular,
                                  color: Color(0xFF727272),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    )
            ],
          ),
        ],
      ),
    );
  }
}