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

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.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/min_api.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/border_text.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../login/captcha/block_puzzle_captcha.dart';
import '../main.dart';

class LogoutIng extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _LogoutIng();
  }
}

class _LogoutIng extends State<LogoutIng> {
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController provingController = TextEditingController();
  String money;
  String balance;
  String phone = "";
  MinApiService minService;
  ApiService apiService;
  var btnText = S.current.send_code;
  var _sendCodeStatus = 0;
  Timer _timer;
  UserInfo userInfo;
  String area = "+86";

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

  queryUserBalance() async {
    SharedPreferences value = await SharedPreferences.getInstance();
    apiService = ApiService(
      Dio(),
      context: context,
      token: value.getString("token"),
      showLoading: false,
    );
    BaseData<UserInfo> baseData =
    await apiService.queryInfo().catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      userInfo = baseData.data;
      balance = userInfo?.balance ?? "0.00";
      money = userInfo?.money ??"0.00";
      phone = userInfo?.phone ?? "";
      if (mounted) setState(() {});
    }
  }

  proving(mobile) async {
    if(phoneController.text != phone){
      SmartDialog.showToast("手机号码不正确",
          alignment: Alignment.center);
      return ;
    }
    if (_sendCodeStatus != 0)
      return;
    loadingBlockPuzzle(context);
  }

  sendProving(v) async{
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
          Dio(),
          context: context,
          token: value.getString("token"),
          showLoading: true
      );
    }
    BaseData baseData = await apiService.sendVerify({"areaCode": "+86", "mobile": phoneController.text, "verification": v}).catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      countdown();
      SmartDialog.showToast(baseData.data,
          alignment: Alignment.center);
    }else{
      SmartDialog.showToast(baseData.msg,
          alignment: Alignment.center);
    }
  }

  ///注销账户
  logout() async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
          Dio(),
          context: context,
          token: value.getString("token"),
          showLoading: true
      );
    }
    BaseData baseData = await apiService.deleteMine().catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      logOut();
      SmartDialog.showToast(baseData.data,
          alignment: Alignment.center);
    }else{
      SmartDialog.showToast(baseData.msg,
          alignment: Alignment.center);
      Navigator.of(context).pop();
    }
  }

  countdown() {
    if (_timer != null && _timer.isActive) return;
    int countdown = 60;
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      countdown--;
      if (countdown == 0) {
        setState(() {
          btnText = S.of(context).send_code;
        });
        _sendCodeStatus = 0;
        _timer.cancel();
      } else {
        setState(() {
          btnText = S.of(context).resend_in_seconds(countdown);
        });
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        title: "",
        titleColor: Colors.black,
        titleSize: 18.sp,
        background: Colors.transparent,
        leadingColor: Colors.black,
      ),
      body: GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
      FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Stack(
        children: [
          Container(
            width: double.infinity,
            height: double.infinity,
            margin: EdgeInsets.only(left: 16, right: 17),
            child: SingleChildScrollView(
              physics: BouncingScrollPhysics(),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: EdgeInsets.only(
                      top: 16,
                      bottom: 4,
                    ),
                    child: Text(
                      S.of(context).jinxingzhanghaozhuxiao,
                      style: TextStyle(
                        fontSize: 21.sp,
                        fontWeight: MyFontWeight.semi_bold,
                        color: Color(0xFF181818),
                      ),
                    ),
                  ),
                  Text(
                    S.of(context).zhuxiaotixing,
                    style: TextStyle(
                      fontSize: 14.sp,
                      height: 1.5,
                      fontWeight: MyFontWeight.regular,
                      color: Color(0xFF727272),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(
                      top: 24,
                      bottom: 16,
                    ),
                    child: Text(
                      S.of(context).shoujihao,
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: MyFontWeight.semi_bold,
                        color: Color(0xFF181818),
                      ),
                    ),
                  ),
                  Row(
                    children: [
                      GestureDetector(
                        onTap: (){
                          Navigator.of(context).pushNamed('/router/phone_address_page').then((value) {
                            if(value != null)
                              setState(() {
                                area = value;
                              });
                          });
                        },
                        child: Text(
                          area,
                          style: TextStyle(
                            fontWeight: MyFontWeight.regular,
                            fontSize: 16.sp,
                            color: Color(0xFF1A1A1A),
                          ),
                        )),
                      Icon(
                        Icons.keyboard_arrow_right,
                        size: 18,
                        color: Color(0xFF1A1A1A),
                      ),
                      Expanded(child:
                      Container(
                        margin: EdgeInsets.fromLTRB(0.w, 0, 20.w, 0),
                        // alignment: Alignment.topLeft,
                        height: 30.h,
                        // width: MediaQuery.of(context).size.width - 100.w,
                        child: TextField(
                          controller: phoneController,
                          keyboardType: TextInputType.phone,
                          inputFormatters: [LengthLimitingTextInputFormatter(11)],
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            hintText: S.of(context).qingshurushoujihao,
                            hintStyle: TextStyle(
                              fontSize: 14.sp,
                              fontWeight: MyFontWeight.regular,
                              color: Color(0xffA29E9E),
                            ),
                          ),
                        ),
                      )),
                    ],
                  ),
                  Container(
                    height: 1.h,
                    width: MediaQuery.of(context).size.width,
                    color: Color(0xFFF4F4F4),
                  ),
                  Padding(
                    padding: EdgeInsets.only(
                      top: 15,
                      bottom: 16,
                    ),
                    child: Text(
                      S.of(context).yanzhengma,
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: MyFontWeight.semi_bold,
                        color: Color(0xFF181818),
                      ),
                    ),
                  ),
                  Row(
                    children: [
                      Expanded(
                          child: Container(
                        margin: EdgeInsets.fromLTRB(0.w, 0, 20.w, 0),
                        alignment: Alignment.topLeft,
                        child: TextField(
                          controller: provingController,
                          keyboardType: TextInputType.phone,
                          inputFormatters: [
                            LengthLimitingTextInputFormatter(6)
                          ],
                          textInputAction: TextInputAction.next,
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            hintText: S.of(context).qingshuruyanzhengma,
                            hintStyle: TextStyle(
                              fontSize: 14.sp,
                              fontWeight: MyFontWeight.regular,
                              color: Color(0xffA29E9E),
                            ),
                          ),
                        ),
                      )),
                      GestureDetector(
                        onTap: (){
                          if(phoneController.text == ""){
                            SmartDialog.showToast("请输入手机号码",
                                alignment: Alignment.center);
                            return;
                          }
                          proving(phoneController.text);
                        },
                        child:
                        Text(
                          btnText,
                          style: TextStyle(
                            fontSize: 14.sp,
                            height: 1.5,
                            fontWeight: MyFontWeight.medium,
                            color:Color(0xFF32A060),
                          ),
                        ),
                      )

                    ],
                  ),
                  Container(
                    height: 1.h,
                    width: MediaQuery.of(context).size.width / 1.6,
                    color: Color(0xFFF4F4F4),
                  ),
                ],
              ),
            ),
          ),
          Align(
              alignment: Alignment.bottomCenter,
              child: GestureDetector(
                onTap: () {
                  if(phoneController.text == ""){
                    SmartDialog.showToast("请输入手机号码",
                        alignment: Alignment.center);
                  }else if(provingController.text == ""){
                    SmartDialog.showToast("请输入验证码",
                        alignment: Alignment.center);
                  }
                  if(phoneController.text != "" && provingController.text != ""){
                    showDeleteDialog();
                  }
                },

                child: Container(
                    width: double.infinity,
                    height: 54.h,
                    alignment: Alignment.center,
                    margin:EdgeInsets.symmetric(horizontal: 16.w,vertical:25.h),
                    decoration: BoxDecoration(
                      color: (phoneController.text == "" &&
                          provingController.text == "")
                          ? Color(0xFFD8D8D8)
                          : Color(0xFF32A060),
                      borderRadius: BorderRadius.circular(45),
                    ),
                    child: Text(
                      S.of(context).querenzhuxiao,
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: MyFontWeight.semi_bold,
                        color: Color(0xFFFFFFFF),
                      ),
                    )),
              ))
        ],
      )),
    );
  }

  ///确认注销账户弹窗
  showDeleteDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          content:Container(
            width: double.infinity,
            height: 400.h,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                GestureDetector(
                  onTap: (){
                    Navigator.of(context).pop();
                  },
                  child: Container(
                    alignment: Alignment.topRight,
                    child:Image.asset(
                      "assets/image/yq_qx.webp",
                      width: 20,
                      height: 20,
                      color: Color(0xFF353535),
                    ),
                  ),),
                (balance == "0.00" && money == "0.00")?
                Image.asset(
                  "assets/image/logout.webp",
                  width: 80,
                  height: 80,
                )
                :
                Image.asset(
                  "assets/image/logout_s.webp",
                  width: 80,
                  height: 80,
                ),
                Padding(
                  padding: EdgeInsets.only(top: 10, bottom: 6),
                  child: Text(
                    (balance == "0.00" && money == "0.00") ? "注销账号成功!" : "注销申请提交失败!",
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: MyFontWeight.semi_bold,
                      color: Color(0xFF353535),
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(bottom: 13),
                  child: Text(
                    (balance == "0.00" && money == "0.00") ? "由于当于帐号已注销,系统将自动退出登录":"您的海峡钱包余额及门店余额未使用完!",
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 16.sp,
                      height: 1.2,
                      fontWeight: MyFontWeight.regular,
                      color: Colors.black,
                    ),
                  ),
                ),
                if(balance != "0.00" && money != "0.00" || balance != "0.00" || money != "0.00")
                Text(
                  "${S.of(context).huixiangqianbao}:¥ $money",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: MyFontWeight.regular,
                    color: Color(0xFF353535),
                  ),
                ),
                if(balance != "0.00" && money != "0.00" || balance != "0.00" || money != "0.00")
                Text(
                  "${S.of(context).mendianyue}:¥ $balance",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: MyFontWeight.regular,
                    color: Color(0xFF353535),
                  ),
                ),
                SizedBox(
                  height:36.h,
                ),
                InkWell(
                  child: BorderText(
                    text: "我知道了",
                    textColor: Color(0xFF32A060),
                    fontSize: 16.sp,
                    fontWeight: FontWeight.bold,
                    borderColor: Color(0xFF32A060),
                    radius:25,
                    padding: EdgeInsets.all(12),
                    borderWidth: 1,
                  ),
                  onTap: () {
                    if(balance != "0.00" && money != "0.00" || balance != "0.00" || money != "0.00"){
                      Navigator.of(context).pop();
                      return;
                    }
                      logout();
                  },
                )
              ],
            ),
          ),
        );
      },
    );
  }

  logOut() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString("token", "");
    sharedPreferences.setString("user", "");
    sharedPreferences.setString("userJson", "");
    sharedPreferences.setString("userId", "");
    sharedPreferences.setString("mobile", "");
    sharedPreferences.setString("nick", "");

    Navigator.of(context)
        .pushNamedAndRemoveUntil('/router/new_login_page', (route) => false);
    // if (xgFlutterPlugin != null) {
    //   xgFlutterPlugin.stopXg();
    // }
  }

  //滑动拼图
  loadingBlockPuzzle(BuildContext context,
      {barrierDismissible = true}) {
    showDialog<Null>(
      context: context,
      barrierDismissible: barrierDismissible,
      builder: (BuildContext context) {
        return BlockPuzzleCaptchaPage(
          onSuccess: (v) {
            sendProving(v);
          },
          onFail: () {
            print("onFail");
          },
        );
      },
    );
  }
}