import 'dart:convert';

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/generated/l10n.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/social_info.dart';
import 'package:huixiang/retrofit/data/user_info.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/activity_coupons.dart';
import 'package:huixiang/view_widget/custom_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:huixiang/view_widget/login_tips_dialog.dart';
import 'package:huixiang/view_widget/request_permission.dart';
import 'package:huixiang/view_widget/round_button.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../retrofit/data/rank.dart';
import '../../view_widget/mine_vip_entry.dart';
// import 'package:qrscan/qrscan.dart' as scanner;

class MineView extends StatefulWidget {
  final UserInfo userInfo;
  final GestureTapCallback toUserInfo;
  final GestureTapCallback toIntegralPage;
  final Function messageZero;
  final int totalMsg;
  final SocialInfo infoNumber;
  final List<Rank> ranks;

  MineView(this.userInfo, this.toUserInfo, this.toIntegralPage,
      this.messageZero, this.totalMsg, this.infoNumber,this.ranks);

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

class _MineView extends State<MineView> {
  ApiService apiService;
  String levelText = "普通用户";

  ///核销用户优惠券
  queryWiped(memberCouponId) async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString("token"),
      );
    }
    BaseData baseData = await apiService.wiped(memberCouponId);
    if (baseData != null && baseData.isSuccess) {
      SmartDialog.showToast("核销成功", alignment: Alignment.center);
    } else {
      SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          margin: EdgeInsets.only(top: 29.h),
          alignment: Alignment.centerRight,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Container(
                  height: 24.h,
                  alignment: Alignment.center,
                  margin: EdgeInsets.only(right: 12.w),
                  child: GestureDetector(
                      onTap: () {
                        Navigator.of(context)
                            .pushNamed('/router/system_msg_page')
                            .then((value) {
                          widget.messageZero();
                        });
                      },
                      child: Container(
                        height: 24.h,
                        alignment: Alignment.center,
                        child: Stack(
                          children: [
                            Image.asset(
                              "assets/image/icon_chat.webp",
                              width:24,
                              height: 24,
                            ),
                            if (widget.totalMsg != 0)
                              Container(
                                width: 36.w,
                                alignment: Alignment.topRight,
                                child: Container(
                                    width: 22.w,
                                    height: 14.h,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(100),
                                      border: Border.all(
                                        width: 1,
                                        color: Colors.white,
                                        style: BorderStyle.solid,
                                      ),
                                      color: Color(0xFFFF441A),
                                    ),
                                    child: RoundButton(
                                      text: widget.totalMsg.toString(),
                                      textColor: Colors.white,
                                      fontWeight: MyFontWeight.regular,
                                      backgroup: Color(0xFFFF441A),
                                      fontSize: 8.sp,
                                      radius: 100,
                                    )),
                              )
                          ],
                        ),
                      ))),
              InkWell(
                onTap: () {
                  toScan();
                },
                child: Container(
                  padding: EdgeInsets.only(left: 12.w,right:16.w,top:8.h,bottom:8.h),
                  child: Image.asset(
                    "assets/image/icon_scan_qr_code.webp",
                    width: 22,
                    height: 22,
                  ),
                ),
              ),
              // InkWell(
              //   onTap: () {
              //     Navigator.of(context).pushNamed('/router/setting_page');
              //   },
              //   child: Container(
              //     padding: EdgeInsets.all(8.h),
              //     margin: EdgeInsets.only(right: 12.w),
              //     child: Image.asset(
              //       "assets/image/icon_mine_setting.webp",
              //       width: 32,
              //       height: 32,
              //       color: Colors.white,
              //     ),
              //   ),
              // ),
            ],
          ),
        ),
        mineView(),
        SizedBox(
          height: 12.h,
        ),
      ],
    );
  }

  toScan() async {
    if (await Permission.camera.isPermanentlyDenied) {
      showCupertinoDialog(
          context: context,
          builder: (context) {
            return RequestPermission(
              "assets/image/icon_camera_permission_tips.webp",
              S.of(context).ninxiangjiquanxianweikaiqi,
              S.of(context).weilekaipaizhaoxuanzhetouxiang,
              S.of(context).kaiqiquanxian,
              (result) async {
                if (result) {
                  await openAppSettings();
                }
              },
              heightRatioWithWidth: 0.82,
            );
          });
    } else if (await Permission.camera.isGranted) {
      // http://pos.app.gznl.top/placeorder/?tableId=1315903669597634560&tenantCode=1166&shopId=1300372027722432512
      // 新版桌子码跳转
      // http://miniscan.lotus-wallet.com/placeorder?tenant_code=1194&table_id=1669609340031467520&store_id=1637659387134738432
      var result = await Navigator.of(context).pushNamed('/router/qr_scan');
      if (result.toString().contains("type\":\"coupon")) {
        ///活动优惠券赠送弹窗
        activityShowAlertDialog(result.toString());
        return;
      }
      if (result.toString().contains("type\":\"wiped")) {
        ///核销券
        queryWiped(jsonDecode(result.toString())["memberCouponId"]);
        return;
      }
      // String result = await scanner.scan();
      Uri uri = Uri.parse(result);
      String tableId = uri.queryParameters["tableId"] ?? uri.queryParameters["table_id"];
      String tenantCode = uri.queryParameters["tenantCode"] ?? uri.queryParameters["tenant_code"];
      String shopId = uri.queryParameters["shopId"] ?? uri.queryParameters["store_id"];
      if (tableId != null &&
          tableId != "" &&
          tenantCode != null &&
          tenantCode != "" &&
          shopId != null &&
          shopId != "") {
        Navigator.of(context).pushNamed(
          '/router/store_order',
          arguments: {
            "id": shopId,
            "tenant": tenantCode,
            "storeName": "",
            "tableId": int.tryParse(tableId),
          },
        );
        return;
      }
      String title = uri.queryParameters["title"];
      if (result.toString().contains("http:") ||
          result.toString().contains("https:")) {
        ///扫码跳转任意网页
        Navigator.of(context).pushNamed(
          '/router/scan_web',
          arguments: {
            "result": result,
            "title":title,
          },
        );
      }
    } else {
      await Permission.camera.request();
    }
  }

  activityShowAlertDialog(String result) {
    //显示对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return ActivityCoupons(result);
      },
    );
  }

  ///我的信息部分
  Widget mineView() {
    print("---" + widget.userInfo.toString());
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.only(left: 16.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          InkWell(
            onTap: () {
              widget.toUserInfo();
            },
            child: Stack(
              children: [
                MImage(
                  widget.userInfo == null ? "" : widget.userInfo.headimg,
                  isCircle: true,
                  width: 60,
                  height: 60,
                  fit: BoxFit.cover,
                  errorSrc: "assets/image/default_user.webp",
                  fadeSrc: "assets/image/default_user.webp",
                ),
                // Positioned(
                //   bottom: 0,
                //   right: 2.w,
                //   child: Image.asset(
                //     "assets/image/icon_mine_edit.webp",
                //     width: 17,
                //     height: 17,
                //   ),
                // ),
              ],
            ),
          ),
          SizedBox(
            width: 10.w,
          ),
          Expanded(
            flex: 1,
            child: Container(
              height: 53.h,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  widget.userInfo == null
                      ? InkWell(
                          child: Text(
                            S.of(context).denglu,
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: MyFontWeight.medium,
                              color: Color(0xFFFFFFFF),
                            ),
                          ),
                          onTap: widget.toUserInfo,
                        )
                      : Row(
                          children: [
                            InkWell(
                              onTap: () {
                                if (widget.userInfo == null) {
                                  LoginTipsDialog().show(context);
                                }
                              },
                              child: Text(
                                widget.userInfo == null
                                    ? S.of(context).denglu
                                    : "${widget.userInfo.nickname == "" ? "回乡" : widget.userInfo.nickname}",
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.bold,
                                  color: Color(0xFFFFFFFF),
                                ),
                              ),
                            ),
                            if (widget.userInfo.level != 1)
                              Image.asset(
                                "assets/image/icon_user.webp",
                                width: 18.w,
                                height: 18.h,
                              ),
                          ],
                        ),
                  widget.userInfo == null
                      ? Text(
                          S.of(context).weidengluxinxi,
                          style: TextStyle(
                            fontSize: 12.sp,
                            fontWeight: MyFontWeight.regular,
                            color: Color(0xFFFFFFFF),
                          ),
                        )
                      : mineVip(),
                  // Row(
                  //         children: [
                  //           Text(
                  //             "${S.of(context).guanzhu} ${widget?.infoNumber?.follow ?? "0"}",
                  //             style: TextStyle(
                  //               fontSize: 12.sp,
                  //               fontWeight: MyFontWeight.regular,
                  //               fontFamily: 'JDZhengHT',
                  //               color: Color(0xFFFFFFFF),
                  //             ),
                  //           ),
                  //           Container(
                  //             width: 1.w,
                  //             height: 12.h,
                  //             margin: EdgeInsets.symmetric(horizontal: 3.w),
                  //             color: Color(0xFFFFFFFF),
                  //           ),
                  //           Text(
                  //             "${S.of(context).fensi} ${widget?.infoNumber?.fans ?? "0"}",
                  //             style: TextStyle(
                  //               fontSize: 12.sp,
                  //               fontFamily: 'JDZhengHT',
                  //               fontWeight: MyFontWeight.regular,
                  //               color: Color(0xFFFFFFFF),
                  //             ),
                  //           ),
                  //         ],
                  //       ),
                ],
              ),
            ),
          ),
          widget.userInfo == null
              ? Container(
                  alignment: Alignment.center,
                  height: 50.h,
                  child: Icon(
                    Icons.keyboard_arrow_right,
                    size: 20,
                    color: Colors.black,
                  ),
                )
              : Container(
                  alignment: Alignment.bottomRight,
                  height: 50.h,
                  child: GestureDetector(
                      onTap: () {
                        widget.toIntegralPage();
                      },
                      child: Container(
                        padding: EdgeInsets.only(
                            top: 4.h, bottom: 4.h, right: 16.w, left: 7.w),
                        margin: EdgeInsets.only(right: 14.w),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(12),
                            color: Colors.white),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Image.asset(
                              "assets/image/icon_gold_coin.webp",
                              width: 16,
                              height: 16,
                            ),
                            Text(
                              S.of(context).tiantianlingjifen,
                              style: TextStyle(
                                color: Color(0xFF32A060),
                                fontSize: 12.sp,
                                fontWeight: MyFontWeight.regular,
                              ),
                            ),
                            // Icon(
                            //   Icons.keyboard_arrow_right,
                            //   size: 16,
                            //   color: Colors.black,
                            // )
                          ],
                        ),
                      )),
                ),
        ],
      ),
    );
  }

  Widget mineVip(){
    return Container(
      child: MineVipEntry(
        tag: "vip",
        ranks: widget.ranks,
        userInfo: widget.userInfo,
        rank: double.tryParse(widget.userInfo?.expendAmount ?? "0")
            .toInt(),
        rankMax: widget.userInfo?.memberRankVo?.nextOrigin ?? 0,
        createTime: widget.userInfo?.createTime ?? "",
      ),
    );

  }
}