/// 注册模板
library;

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:loopin/IM/im_service.dart';
import 'package:loopin/api/common_api.dart';
import 'package:loopin/controller/video_module_controller.dart';
import 'package:loopin/service/http.dart';
import 'package:loopin/utils/common.dart';
import 'package:shirne_dialog/shirne_dialog.dart';

import '../../utils/index.dart';

class Delete extends StatefulWidget {
  const Delete({super.key});

  @override
  State<Delete> createState() => _DeleteState();
}

class _DeleteState extends State<Delete> {
  final Map authObj = {'phonenumber': '', 'smsCode': '', 'clientId': '428a8310cd442757ae699df5d894f051', 'grantType': 'sms'};

  final fieldController = TextEditingController();
  Timer? timer;
  String vcodeText = '获取验证码';
  bool disabled = false;
  int time = 60;

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

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

  // 清空文本框
  void handleClear() {
    fieldController.clear();
    setState(() {
      authObj['phonenumber'] = '';
    });
  }

  //先退出，在注销
  void handleLogout() async {}

  // 提交表单
  void handleSubmit() async {
    FocusScope.of(context).unfocus(); // 收起键盘
    if (authObj['phonenumber'] == '') {
      MyDialog.toast('手机号不能为空', icon: Icon(Icons.warning), style: ToastStyle(backgroundColor: Colors.red.withAlpha(200)));
    } else if (!Utils.checkTel(authObj['phonenumber'])) {
      MyDialog.toast('手机号格式不正确', icon: Icon(Icons.warning), style: ToastStyle(backgroundColor: Colors.red.withAlpha(200)));
    } else if (authObj['smsCode'] == '') {
      MyDialog.toast('验证码不能为空', icon: Icon(Icons.warning), style: ToastStyle(backgroundColor: Colors.red.withAlpha(200)));
    } else {
      final dialogController = MyDialog.loading('注销中...');
      // 执行注销逻辑
      final del = await Http.post('${CommonApi.revoked}?smsCode=${authObj['smsCode']}');
      logger.w(del);
      // 执行退出登录逻辑
      final loginRes = await ImService.instance.logout();
      if (loginRes.success) {
        // 清除存储信息
        Common.logout();
        // 初始化视频
        final videoController = Get.find<VideoModuleController>();
        videoController.init();
        Get.offAllNamed(
          '/login',
          predicate: (route) {
            return route.settings.name == '/';
          },
        );
      }
    }
  }

  // 60s倒计时
  void handleVcode() {
    logger.i(authObj);
    FocusScope.of(context).unfocus(); // 收起键盘
    if (authObj['phonenumber'] == '') {
      MyDialog.toast('手机号不能为空', icon: Icon(Icons.warning), style: ToastStyle(backgroundColor: Colors.red.withAlpha(200)));
    } else if (!Utils.checkTel(authObj['phonenumber'])) {
      MyDialog.toast('手机号格式不正确', icon: Icon(Icons.warning), style: ToastStyle(backgroundColor: Colors.red.withAlpha(200)));
    } else {
      setState(() {
        disabled = true;
      });
      startTimer();
      getCode();
    }
  }

  startTimer() {
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (time > 0) {
          vcodeText = '获取验证码(${time--})';
        } else {
          vcodeText = '获取验证码';
          time = 60;
          disabled = false;
          timer.cancel();
        }
      });
    });
  }

  void getCode() async {
    //
    final res = await Http.get('${CommonApi.dictionaryApi}sms_template_id');
    final dictData = res['data'] as List;
    final templeId = dictData.first['dictValue'];
    logger.w(templeId);
    final resCode = await Http.get(CommonApi.getDelCode, params: {'templateId': templeId});
    logger.i('注销验证短信：$resCode');
  }

  @override
  Widget build(BuildContext context) {
    final phoneNum = authObj['phonenumber'] as String;
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () => FocusScope.of(context).unfocus(),
        child: Scaffold(
          appBar: AppBar(
            title: Text(
              '注销账号',
              style: TextStyle(color: Colors.black),
            ),
            forceMaterialTransparency: true,
          ),
          body: Container(
            alignment: Alignment.center,
            child: Column(
              children: [
                Container(
                  height: 40.0,
                  margin: const EdgeInsets.symmetric(vertical: 5.0, horizontal: 30.0),
                  decoration: BoxDecoration(
                    color: Color(0xFFFAF8F5),
                    borderRadius: BorderRadius.circular(15.0),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: TextField(
                          keyboardType: TextInputType.phone,
                          controller: fieldController,
                          inputFormatters: [
                            LengthLimitingTextInputFormatter(11), // 限制输入长度为 11
                            FilteringTextInputFormatter.digitsOnly, // 限制只能输入数字
                          ],
                          decoration: InputDecoration(
                            hintText: '输入手机号',
                            hintStyle: const TextStyle(color: Colors.black38),
                            suffixIcon: Visibility(
                              visible: phoneNum.isNotEmpty,
                              child: InkWell(
                                hoverColor: Colors.transparent,
                                highlightColor: Colors.transparent,
                                splashColor: Colors.transparent,
                                onTap: handleClear,
                                child: const Icon(
                                  Icons.clear,
                                  color: Colors.grey,
                                  size: 16.0,
                                ),
                              ),
                            ),
                            contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 12.0),
                            border: const OutlineInputBorder(borderSide: BorderSide.none),
                          ),
                          onChanged: (value) {
                            setState(() {
                              authObj['phonenumber'] = value;
                            });
                          },
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  height: 40.0,
                  margin: const EdgeInsets.symmetric(vertical: 5.0, horizontal: 30.0),
                  decoration: BoxDecoration(color: Color(0xFFFAF8F5), borderRadius: BorderRadius.circular(15.0)),
                  child: Row(
                    children: [
                      Expanded(
                        child: TextField(
                          keyboardType: TextInputType.phone,
                          inputFormatters: [
                            LengthLimitingTextInputFormatter(6),
                            FilteringTextInputFormatter.digitsOnly, // 限制只能输入数字
                          ],
                          decoration: const InputDecoration(
                            hintText: '验证码',
                            hintStyle: TextStyle(color: Colors.black38),
                            contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 12.0),
                            border: OutlineInputBorder(borderSide: BorderSide.none),
                          ),
                          onChanged: (value) {
                            setState(() {
                              authObj['smsCode'] = value;
                            });
                          },
                        ),
                      ),
                      SizedBox(
                        height: 25.0,
                        child: Container(
                          margin: const EdgeInsets.only(right: 8.0),
                          child: ElevatedButton(
                            style: ButtonStyle(
                                backgroundColor: WidgetStateProperty.all(Colors.white),
                                shape: WidgetStatePropertyAll(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0))),
                                padding: WidgetStateProperty.all(EdgeInsets.symmetric(horizontal: 15.0))),
                            onPressed: !disabled ? handleVcode : null,
                            child: Text(vcodeText, style: const TextStyle(fontSize: 13.0)),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Text(
                  '提示：\n'
                  '1. 账号注销后，平台会保留您的数据 7 天。\n'
                  '2. 若 7 天内未登录，平台将销毁所有保留数据。\n'
                  '3. 若在 7 天内重新登录，则视为放弃注销。\n'
                  '请谨慎操作。',
                  style: TextStyle(fontSize: 14, color: Colors.red[700]),
                ),
                Container(
                  margin: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 30.0),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(15.0),
                  ),
                  child: SizedBox(
                    width: double.infinity,
                    height: 45.0,
                    child: FilledButton(
                      style: ButtonStyle(shape: WidgetStatePropertyAll(RoundedRectangleBorder(borderRadius: BorderRadius.circular(30.0)))),
                      onPressed: handleSubmit,
                      child: const Text(
                        '确认注销',
                        style: TextStyle(fontSize: 16.0),
                      ),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 10.0,
                ),
              ],
            ),
          ),
        ));
  }
}
