import 'dart:async';
import 'dart:convert';

import 'package:barcode_widget/barcode_widget.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/product.dart';
import 'package:huixiang/retrofit/data/vip_card.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/store/scan.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/utils/location.dart';
import 'package:huixiang/utils/painter_bg.dart';
import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:huixiang/view_widget/my_footer.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../retrofit/data/user_info.dart';
import '../view_widget/classic_header.dart';

class VipPayCode extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _VipPayCode();
  }
}

class _VipPayCode extends State<VipPayCode> {
  ApiService apiService;

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

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

  UserInfo userInfo;
  final RefreshController refreshController = RefreshController();
  bool vipCodeText = false;
  Timer _timer;
  bool isDispose = false;

  ///查询用户信息
  queryUser() async {
    try{
      SharedPreferences value = await SharedPreferences.getInstance();
      if (apiService == null)
        apiService = ApiService(
          Dio(),
          context: context,
          token: value.getString("token"),
        );
      BaseData<UserInfo> baseData =
      await apiService.queryInfo().catchError((onError) {
        refreshController.refreshFailed();});
      if (baseData != null && baseData.isSuccess) {
        userInfo = baseData.data;
      SharedPreferences.getInstance().then((value) => {
        value.setString('user', jsonEncode(baseData.data)),
      });
        setState(() {});
        refreshController.refreshCompleted();
      }else{
        refreshController.refreshFailed();
      }
    }finally{
      refreshCode();
    }
  }

  refreshCode(){
    if (_timer != null) return;
    const oneSec = const Duration(minutes: 2);
    var callback = ((timer) {
      if (isDispose) return;
      queryUser();
    });
    _timer = Timer.periodic(oneSec, callback);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        title: "会员码",
        background: Color(0xFF32A060),
        titleColor: Colors.white,
        brightness: Brightness.dark,
        leadingColor: Colors.white,
      ),
      body: Container(
        color: Color(0xFF32A060),
        height: double.infinity,
        padding: EdgeInsets.only(top: 45.h),
        child: Stack(
          alignment: Alignment.topCenter,
          children: [
            Container(
              color: Color(0xFF32A060),
              // height: 485.h,
              padding: EdgeInsets.only(top: 47.h),
              child: Container(
                height: 438.h,
                width: double.infinity,
                decoration: BoxDecoration(
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withAlpha(12),
                      offset: Offset(0, 2),
                      blurRadius: 14,
                      spreadRadius: 0,
                    ),
                  ],
                  borderRadius: BorderRadius.circular(6),
                ),
                margin: EdgeInsets.symmetric(horizontal: 16.w,),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    SizedBox(height: 46.h,),
                    Text(
                      "请保持屏幕常亮,并对准扫码盒或枪口",
                      style: TextStyle(
                        fontWeight: MyFontWeight.regular,
                        fontSize: 12.sp,
                        color: Color(0xFF4D4D4D),
                      ),
                    ),
                    SizedBox(height: 30.h,),
                    QrImage(
                      data: userInfo != null
                          ? (userInfo?.vipScanNo ?? "")
                          : "",
                      version: QrVersions.auto,
                      size: 200.w,
                      gapless: true,
                    ),
                  ],
                ),
              ),
            ),
            Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(56),
                color: Color(0xFF32A060),
                border: Border.all(
                  color: Color(0xFF32A060),
                  width: 8.w,
                ),
              ),
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(56),
                  color: Colors.white,
                  border: Border.all(
                    color: Colors.white,
                    width: 2.w,
                  ),
                ),
                child: MImage(
                  userInfo?.headimg ?? "",
                  width: 80,
                  height: 80,
                  radius: BorderRadius.circular(56),
                  fit: BoxFit.cover,
                  errorSrc: "assets/image/default_1.webp",
                  fadeSrc: "assets/image/default_1.webp",
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}