import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/view_widget/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_footer.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../retrofit/business_api.dart';
import '../../retrofit/data/base_data.dart';
import '../../retrofit/data/business_login_info.dart';
import '../../retrofit/data/business_store_list.dart';
import '../../utils/business_instance.dart';
import '../../utils/flutter_utils.dart';
import '../../utils/font_weight.dart';

class BusinessMinePage extends StatefulWidget {
  final BusinessLoginInfo businessLoginInfo;
  final String storeId;

  BusinessMinePage(this.businessLoginInfo, this.storeId);

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

class _BusinessMinePage extends State<BusinessMinePage>
    with AutomaticKeepAliveClientMixin {
  final RefreshController refreshController = RefreshController();
  BusinessApiService businessService;
  List<Records> records = [];
  double visiblePercentage;
  int networkStatus = 0;

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

  @override
  void dispose() {
    super.dispose();
    refreshController.dispose();
  }

  ///门店设置列表
  queryStoreList() async {
    // EasyLoading.show(
    //     status: S.current.zhengzaijiazai,
    //     maskType: EasyLoadingMaskType.black);
    if (businessService == null) {
      businessService = BusinessApiService(Dio(),
          context: context,
          token: BusinessInstance.instance.businessToken,
          tenant: BusinessInstance.instance.businessTenant,
          storeId: widget.storeId);
    }
    BaseData<BusinessStoreList> baseData = await businessService
        .getStoreList(BusinessInstance.instance.businessTenant, "1", "100")
        .catchError((error) {
      SmartDialog.showToast(AppUtils.dioErrorTypeToString(error.type),
          alignment: Alignment.center);
      networkStatus = -1;
      refreshController.refreshFailed();
      refreshController.loadFailed();
    });
    if (!mounted) return;
    if (baseData != null && baseData.isSuccess) {
      records = baseData.data.records ?? [];
      refreshController.refreshCompleted();
      networkStatus = 1;
      // EasyLoading.dismiss();
    } else {
      SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return VisibilityDetector(
        key: Key('my-widget-key'),
        onVisibilityChanged: (visibilityInfo) {
          visiblePercentage = visibilityInfo.visibleFraction;
          if (visiblePercentage == 1) queryStoreList();
        },
        child: Column(
          children: [
            Expanded(
              child: Container(
                child: SmartRefresher(
                  controller: refreshController,
                  enablePullDown: true,
                  enablePullUp: false,
                  header: MyHeader(color: Color(0xFF30415B)),
                  physics: BouncingScrollPhysics(),
                  footer: CustomFooter(
                    builder: (context, mode) {
                      return MyFooter(mode);
                    },
                  ),
                  onRefresh: () {
                    if (widget.businessLoginInfo != null) {
                      queryStoreList();
                    } else
                      refreshController.refreshFailed();
                  },
                  child: SingleChildScrollView(
                      physics: NeverScrollableScrollPhysics(),
                      child: Container(
                        child: Column(
                          children: [
                            mineInfo(),
                            commonFunctions(),
                            otherFunctions(),
                            SizedBox(
                              height: 54.h,
                            ),
                            Text(
                              "@回乡信息公司",
                              style: TextStyle(
                                  fontSize: 14.sp,
                                  color: Color(0xFF30415B),
                                  fontWeight: MyFontWeight.medium),
                            ),
                          ],
                        ),
                      )),
                ),
              ),
            ),
            SizedBox(
              height: 76.h,
            ),
          ],
        ));
  }

  Widget mineInfo() {
    return Container(
      child: Stack(
        children: [
          Container(
            width: double.infinity,
            height: 238.h,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(
                  "assets/image/bs_mine_bg.webp",
                ),
                fit: BoxFit.cover,
              ),
            ),
          ),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              Navigator.of(context)
                  .pushNamed('/router/account_information', arguments: {
                "businessLoginInfo": widget.businessLoginInfo,
              });
            },
            child: Container(
              padding: EdgeInsets.only(
                  top: MediaQuery.of(context).padding.top + 50, left: 16.w),
              child: Row(
                children: [
                  (widget?.businessLoginInfo?.avatar != "")
                      ? MImage(
                          widget?.businessLoginInfo?.avatar ?? "",
                          fit: BoxFit.cover,
                          width: 69.h,
                          height: 69.h,
                          radius: BorderRadius.circular(100),
                          errorSrc: "assets/image/default_2_1.webp",
                          fadeSrc: "assets/image/default_2_1.webp",
                        )
                      : Image.asset(
                          "assets/image/bs_mine_heading.webp",
                          width: 69,
                          height: 69,
                          fit: BoxFit.fill,
                        ),
                  SizedBox(
                    width: 10.w,
                  ),
                  Container(
                    height: 69.h,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Text(
                          widget?.businessLoginInfo?.name ?? "",
                          style: TextStyle(
                              fontSize: 18.sp,
                              color: Color(0xFF374C6C),
                              fontWeight: MyFontWeight.semi_bold),
                        ),
                        Text(
                          'ID:${widget?.businessLoginInfo?.account ?? ""}',
                          style: TextStyle(
                              fontSize: 16.sp,
                              color: Color(0xFF374C6C),
                              fontWeight: MyFontWeight.regular),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  ///常用功能
  Widget commonFunctions() {
    return Container(
      margin: EdgeInsets.only(top: 26.h, left: 16.w, right: 17.w, bottom: 23.h),
      child: Column(
        children: [
          Row(
            children: [
              Container(
                width: 4.w,
                height: 16.h,
                color: Color(0xFF30415B),
                margin: EdgeInsets.only(right: 12.w),
              ),
              Text(
                '常用功能',
                style: TextStyle(
                    fontSize: 16.sp,
                    color: Color(0xFF262626),
                    fontWeight: MyFontWeight.semi_bold),
              ),
            ],
          ),
          SizedBox(
            height: 20.h,
          ),
          // GestureDetector(
          //   behavior: HitTestBehavior.opaque,
          //   onTap: (){
          //     Navigator.of(context).pushNamed('/router/merchant_info',arguments:{
          //       "storeId":widget.storeId,
          //     });
          //   },
          //   child:
          //   commonFunctionsItem("assets/image/bs_store_info_logo.webp", "商户信息", widget?.businessLoginInfo?.name ?? ""),
          // ),
          Container(
            width: double.infinity,
            height: 1.h,
            color: Color(0xFFEBECEF),
            margin: EdgeInsets.only(left: 32.w, bottom: 12.h),
          ),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              if(networkStatus == -1){
                queryStoreList();
                return;
              }
              else if (widget.businessLoginInfo.storeList.length > 1) {
                Navigator.of(context).pushNamed('/router/select_shop',
                    arguments: {"routeSource": "门店设置", "records": records});
              } else {
                Navigator.of(context)
                    .pushNamed('/router/merchant_info', arguments: {
                  "storeId": widget.storeId,
                  "storeName": records[0].storeName,
                  "records": records[0],
                });
              }
            },
            child: commonFunctionsItem(
                "assets/image/bs_shop_logo.webp", "门店设置", ""),
          ),
          Container(
            width: double.infinity,
            height: 1.h,
            color: Color(0xFFEBECEF),
            margin: EdgeInsets.only(left: 32.w, bottom: 12.h),
          ),
          GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                Navigator.of(context)
                    .pushNamed('/router/security_setting', arguments: {
                  "storeId": widget.storeId,
                  "businessLoginInfo": widget.businessLoginInfo,
                });
              },
              child: commonFunctionsItem(
                  "assets/image/bs_secure.webp", "安全设置", "登录手机号/密码")),
        ],
      ),
    );
  }

  Widget commonFunctionsItem(icon, leftText, rightText) {
    return Container(
      margin: EdgeInsets.only(bottom: 14.h),
      child: Row(
        children: [
          Image.asset(
            icon,
            width: 24,
            height: 24,
            fit: BoxFit.fill,
          ),
          SizedBox(
            width: 8.w,
          ),
          Expanded(
              child: Text(
            leftText,
            style: TextStyle(
                fontSize: 14.sp,
                color: Color(0xFF30415B),
                fontWeight: MyFontWeight.medium),
          )),
          Text(
            rightText,
            style: TextStyle(
                fontSize: 14.sp,
                color: Color(0xFF353535),
                fontWeight: MyFontWeight.medium),
          ),
          Image.asset(
            "assets/image/icon_right_z.webp",
            width: 16,
            height: 16,
            color: Color(0xFF353535),
          ),
        ],
      ),
    );
  }

  Widget otherFunctions() {
    return Container(
      margin: EdgeInsets.only(
        left: 16.w,
        right: 17.w,
      ),
      child: Column(
        children: [
          Row(
            children: [
              Container(
                width: 4.w,
                height: 16.h,
                color: Color(0xFF30415B),
                margin: EdgeInsets.only(right: 12.w),
              ),
              Text(
                '其他功能',
                style: TextStyle(
                    fontSize: 16.sp,
                    color: Color(0xFF262626),
                    fontWeight: MyFontWeight.semi_bold),
              ),
            ],
          ),
          SizedBox(
            height: 20.h,
          ),
          GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                Navigator.of(context).pushNamed('/router/user_service_page');
              },
              child:
                  commonFunctionsItem("assets/image/bs_user.webp", "关于我们", ""))
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}