import 'dart:async';

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/user_info.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:huixiang/view_widget/pay_selected_dialog.dart';
import 'package:pin_input_text_field/pin_input_text_field.dart';
import 'package:shared_preferences/shared_preferences.dart';

class PlatformCodePage extends StatefulWidget {
  final Map<String, dynamic> arguments;

  PlatformCodePage({this.arguments});

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

class _PlatformCodePage extends State<PlatformCodePage> {
  ApiService apiService;
  int codeType = 0;
  UserInfo userInfo;
  String inputText = "";
  Timer _timer;
  int sendCodeStatus = 0;
  var codeText = "重新发送";

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

  @override
  void dispose() {
    if (_timer != null && _timer.isActive) _timer.cancel();
    super.dispose();
  }

  ///发送修改支付密码的短信验证
  sendCode() async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(Dio(),
          context: context,
          token: value.getString("token"),
          showLoading: false);
    }
    BaseData baseData =
        await apiService.sendVerifyByUpdatePayPwd().catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      countdown();
      codeType = 1;
      SmartDialog.showToast(baseData.data, alignment: Alignment.center);
    } else {
      SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
    }
  }

  ///验证验证码
  verificationCode(String smsCode) async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(Dio(),
          context: context, token: value.getString("token"), showLoading: false);
    }
    BaseData baseData = await apiService.verifyByUpdatePayPwd({
      "smsCode": smsCode,
    }).catchError((error) {});
    if (baseData != null && baseData.isSuccess) {
      Navigator.of(context).popAndPushNamed(
          '/router/platform_pay_code',
          arguments: {
            "inputText": inputText,
          });
      SmartDialog.showToast(baseData.data ?? false, alignment: Alignment.center);
    } else {
      SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
    }
  }

  countdown() {
    if (_timer != null && _timer.isActive) return;
    int countdown = 60;
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      countdown--;
      if (countdown == 0) {
        codeText = "重新发送";
        sendCodeStatus = 0;
        _timer.cancel();
      } else {
        codeText = S.of(context).resend_in_seconds(countdown);
      }
      refresh();
    });
  }

  void refresh() {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          appBar: AppBar(
            backgroundColor: Colors.white,
            leading: GestureDetector(
                child: Icon(
                  Icons.arrow_back_ios,
                  color: Colors.black,
                ),
                onTap: () {
                  Navigator.of(context).pop();
                }),
            title: Text(
              S.of(context).pingtaizhifumima,
              style: TextStyle(
                fontWeight: MyFontWeight.regular,
                fontSize: 17.sp,
                color: Color(0xFF0D0D0D),
              ),
            ),
            centerTitle: true,
            elevation: 0.0,
          ),
          body: Column(
            children: [
              if (codeType == 0) verification(),
              if (codeType == 1) verificationIssued(),
            ],
          ),
        ));
  }

  ///忘记密码-验证
  Widget verification() {
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.only(top: 28.h),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            "为了确认身份,我们需要验证您的手机号",
            style: TextStyle(
              fontWeight: MyFontWeight.semi_bold,
              fontSize: 18.sp,
              color: Color(0xFF353535),
            ),
          ),
          SizedBox(
            height: 14.h,
          ),
          Text(
            "点击发送短信,将会发送验证码至手机",
            style: TextStyle(
              fontWeight: MyFontWeight.semi_bold,
              fontSize: 14.sp,
              color: Color(0xFFA29E9E),
            ),
          ),
          SizedBox(
            height: 14.h,
          ),
          Text(
            AppUtils.phoneEncode(widget.arguments["userInfo"]?.phone ?? ""),
            style: TextStyle(
              fontWeight: MyFontWeight.medium,
              fontSize: 14.sp,
              color: Color(0xFF353535),
            ),
          ),
          GestureDetector(
            onTap: () {
              setState(() {
                sendCode();
              });
            },
            child: Container(
              width: 163.w,
              height: 46.h,
              alignment: Alignment.center,
              margin: EdgeInsets.only(top: 34.h),
              decoration: BoxDecoration(
                color: Color(0xFF32A060),
                borderRadius: BorderRadius.circular(23.r),
              ),
              child: Text(
                S.of(context).fasongduanxin,
                style: TextStyle(
                  fontWeight: MyFontWeight.semi_bold,
                  fontSize: 18.sp,
                  color: Color(0xFFFFFFFF),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  ///验证码已发状态
  Widget verificationIssued() {
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.only(top: 28.h),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            "验证码已发至 ${AppUtils.phoneEncode(widget.arguments["userInfo"]?.phone ?? "")}",
            style: TextStyle(
              fontWeight: MyFontWeight.semi_bold,
              fontSize: 18.sp,
              color: Color(0xFF353535),
            ),
          ),
          SizedBox(
            height: 14.h,
          ),
          GestureDetector(
            onTap: () {
              sendCode();
            },
            child: Text(
              codeText,
              style: TextStyle(
                fontWeight: MyFontWeight.semi_bold,
                fontSize: 14.sp,
                color: Color(0xFF32A060),
              ),
            ),
          ),
          SizedBox(
            height: 14.h,
          ),
          Container(
            margin: EdgeInsets.only(top: 24.h, bottom: 31.h,right: 55.w,left: 55.w),
            height: 58.h,
            child: PinInputTextField(
              pinLength: 4,
              onChanged: (txt) {
                print(txt);
                setState(() {
                  inputText = txt;
                });
              },
              decoration: BoxLooseDecoration(
                strokeColorBuilder: FixedColorBuilder(Color(0xFFEBEAEA)),
                textStyle: TextStyle(
                  fontWeight: MyFontWeight.medium,
                  fontSize: 20.sp,
                  color: Color(0xFF353535),
                ),
                radius: Radius.circular(4.r),
              ),
            ),
          ),
          GestureDetector(
              onTap: () {
                setState(() {
                  if (inputText.length == 4) {
                    verificationCode(inputText);
                  } else {
                    SmartDialog.showToast("请输入验证码",
                        alignment: Alignment.center);
                  }
                });
              },
              child: Container(
                width: 163.w,
                height: 46.h,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: inputText.length == 4
                      ? Color(0xFF32A060)
                      : Color(0xFFBBE7CC),
                  borderRadius: BorderRadius.circular(23.r),
                ),
                child: Text(
                  "下一步",
                  style: TextStyle(
                    fontWeight: MyFontWeight.semi_bold,
                    fontSize: 18.sp,
                    color: Color(0xFFFFFFFF),
                  ),
                ),
              ))
        ],
      ),
    );
  }
}