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

import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/res/colors.dart';
import 'package:account_center/common/utils/format_check.dart';
import 'package:account_center/style/style_params.dart';
import 'package:account_center/widget/verify_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

typedef PhoneNumProvider = String Function();

// 发送验证码控件
class SendVCode extends StatefulWidget {
  final PhoneNumProvider phoneProvider;
  final String code;
  final Future<bool> Function()? onSend;
  const SendVCode(
    this.code,
    this.phoneProvider, {
    super.key,
    this.onSend,
  });

  @override
  State<SendVCode> createState() => _SendVCodeState();
}

class _SendVCodeState extends State<SendVCode> {
  static const codeTime = 59; //倒计时时间

  Timer? _countdownTimer;
  String _codeCountdownStr = '获取验证码';
  int _countdownNum = codeTime;
  var defaultColor = RColors.appMain;

  late bool isClickable = true;

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: isClickable ? _onTap : null,
      child: Text(
        _codeCountdownStr,
        style: TextStyle(color: StyleParams.themeColor, fontSize: 14.0),
      ),
    );
  }

  _onTap() {
    isClickable = FormatCheck.isChinaPhoneLegal(widget.phoneProvider.call());
    if (!isClickable) {
      ToastUtil.showToast("请输入正确的手机号");
      isClickable = true;
      return;
    }
    _setState();
    if (isClickable && (_countdownNum == codeTime)) {
      if (widget.onSend != null) {
        widget.onSend?.call().then((value) {
          if (value) {
            _action();
          }
        });
      } else {
        _send();
      }
    }
  }

  void _send() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (BuildContext context) => VerifyPage(
          url:
              'https://mslapp-download.oss-cn-beijing.aliyuncs.com/driver/captchaReg.html',
        ),
      ),
    ).then(
      (result) {
        var data = json.decode(result);
        print(data);
        if (data != null) {
          fetch(
            Method.post,
            url: HttpApi.sendMessageMachineCheck,
            params: {
              'code': widget.code,
              'mobile': widget.phoneProvider.call(),
              'scene': 'nc_message_h5',
              'sessionId': data['sessionid'],
              'sig': data['sig'],
              'token': data['nc_token'],
            },
            onSuccess: (data) {
              ToastUtil.showToast('获取验证码成功');
              _action();
            },
            onError: (code, msg) {},
          );
        }
      },
    );
  }

  void _action() {
    // widget.onClick();
    isClickable = false;
    _setState();
    defaultColor = Color(0xFF9B9B9B);
    _codeCountdownStr = '${_countdownNum--}s';
    _countdownTimer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_countdownNum > 0) {
        _codeCountdownStr = '${_countdownNum--}s';
      } else {
        _codeCountdownStr = '获取验证码';
        isClickable = true;
        defaultColor = RColors.appMain;
        _countdownNum = codeTime;
        _countdownTimer?.cancel();
      }
      _setState();
    });
  }

  _setState() {
    setState(() {});
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    super.dispose();
  }
}
