import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wallet/base/YSTabBar.dart';
import 'package:flutter_wallet/login/view/YSHelpView.dart';
import 'package:flutter_wallet/tools/YSAlertView.dart';
import 'package:flutter_wallet/tools/YSNetWork.dart';
import '../base/YSBase.dart';
import '../generated/l10n.dart';
import '../tools/YSBip.dart';
import '../tools/YSColors.dart';
import '../tools/YSSqflite.dart';
import '../tools/YSTools.dart';

class YSWalletWordCheck extends StatefulWidget {
  final List wordsArray;
  const YSWalletWordCheck({Key? key, required this.wordsArray}) : super(key: key);

  @override
  YSWalletWordCheckState createState() => YSWalletWordCheckState();
}

class YSWalletWordCheckState extends State<YSWalletWordCheck> {
  int _stateIndex = 0;
  @override
  Widget build(BuildContext context) {
    return YSBase2(
      topHeight: 335,
      isScroll: false,
      titleType: 1,
      ysChild: Padding(
        padding: EdgeInsets.only(top: hsp(20)),
        child: _stateIndex==0?YSWordCheckView1(valueSetter: (value){
          setState(() {
            _stateIndex = value;
          });
        },wordsArray: widget.wordsArray,):const YSWordCheckView2(),
      ),
    );
  }
}

class YSWordCheckView1 extends StatefulWidget {
  final List wordsArray;
  final ValueSetter<int> valueSetter;
  const YSWordCheckView1({Key? key, required this.valueSetter, required this.wordsArray}) : super(key: key);

  @override
  YSWordCheckView1State createState() => YSWordCheckView1State();
}

class YSWordCheckView1State extends State<YSWordCheckView1> {
  final List _checkArray = [];
  final List _wordArray = [];
  List _showArray = [];
  @override
  void initState() {
    _getWordsArray();
    super.initState();
  }
  _getWordsArray() {
    for (var element in widget.wordsArray) {
      _wordArray.add({'word':element,'isChoose':false});
    }
    _showArray = shuffle(_wordArray);
  }
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Image.asset('images/沙漏黑白.gif',height: hsp(80),width: hsp(80),),
        const YSIndexView(selectedIndex: 2,),
        Expanded(
            child: Padding(
              padding: EdgeInsets.only(top: hsp(20),left: hsp(20),right: hsp(20)),
              child: ClipRRect(
                  borderRadius: const BorderRadius.only(topLeft: Radius.circular(10),topRight: Radius.circular(10)),
                  child: Container(
                    width: ysWidth(context),
                    padding: EdgeInsets.only(top: hsp(20),bottom: hsp(15),left: 15,right: 15),
                    color: YSColors.containColor(context),
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            alignment: Alignment.center,
                            child: Text(S.current.YANZHENGZHUJICI2,style: YSColors.titleStyle(context),),
                          ),
                          Padding(
                            padding: EdgeInsets.only(top: hsp(10)),
                            child: Text(S.current.QINGANZHAOBEIFENZHUJICISHUNXUTIANCHONG,style: TextStyle(fontSize: zsp(14),color: const Color(0xFFED260C)),),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: hsp(5)),
                            decoration: BoxDecoration(
                                color: YSColors.contain2Color(context)
                            ),
                            child: GridView.builder(
                              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: 3,
                                  childAspectRatio: 71/22,
                                  mainAxisSpacing: hsp(10),
                                  crossAxisSpacing: hsp(10)
                              ),
                              itemBuilder: (context,index){
                                Map item = {};
                                Map word = {};
                                if(index<_checkArray.length){
                                  item = _checkArray[index];
                                  word = _wordArray[index];
                                }
                                return Stack(
                                  children: [
                                    Container(
                                      decoration: const BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.all(Radius.circular(5))
                                      ),
                                      alignment: Alignment.center,
                                      margin: EdgeInsets.only(right: hsp(2),top: hsp(2)),
                                      child: Text(item['word']??'',style: YSColors.subStyle(context),),
                                    ),
                                    if(item.isNotEmpty&&word['word']!=item['word'])Positioned(
                                      right: 0,
                                      top: 0,
                                      child: GestureDetector(
                                        onTap: (){
                                          item['isChoose'] = false;
                                          _checkArray.remove(item);
                                          setState(() {});
                                        },
                                        child: Image.asset(YSColors.imageStyle(context, '错误 (1) 2'),height: hsp(10),width: hsp(10),),
                                      )
                                    ),
                                  ],
                                );
                              },
                              padding: EdgeInsets.all(hsp(15)),
                              itemCount: 12,
                              shrinkWrap: true,
                              physics: const NeverScrollableScrollPhysics(),
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: hsp(10),bottom: hsp(10)),
                            padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
                            height: hsp(40),
                            decoration: const BoxDecoration(
                              color: Color(0xFFFFFBE8),
                              borderRadius: BorderRadius.all(Radius.circular(5))
                            ),
                            alignment: Alignment.centerLeft,
                            child: Text(S.current.ZHUJICISHUNXUCUOWUQINGJIANCHAHOU,style: TextStyle(fontSize: zsp(11),color: const Color(0xFFED6A0C)),),
                          ),
                          GridView.builder(
                            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 3,
                                childAspectRatio: 71/22,
                                mainAxisSpacing: hsp(10),
                                crossAxisSpacing: hsp(10)
                            ),
                            itemBuilder: (context,index){
                              Map item = _showArray[index];
                              bool isChoose = item['isChoose'];
                              return GestureDetector(
                                onTap: (){
                                  if(isChoose){
                                    item['isChoose'] = false;
                                    _checkArray.remove(item);
                                  }else{
                                    item['isChoose'] = true;
                                    _checkArray.add(item);
                                  }

                                  setState(() {});
                                },
                                child: Container(
                                  decoration: BoxDecoration(
                                    border: Border.all(color: YSColors.lineColor(context),width: hsp(1)),
                                    borderRadius: const BorderRadius.all(Radius.circular(5)),
                                    color: isChoose?const Color(0xFFF6F6F6):Colors.transparent
                                  ),
                                  alignment: Alignment.center,
                                  child: Text(item['word'],style: YSColors.subStyle(context),),
                                ),
                              );
                            },
                            itemCount: _showArray.length,
                            padding: const EdgeInsets.all(0),
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                          )
                        ],
                      ),
                    ),
                  )
              ),
            )
        ),
        Padding(
          padding: EdgeInsets.only(left: hsp(20),right: hsp(20)),
          child: Container(
            padding: EdgeInsets.only(top: hsp(20),bottom: hsp(20),left: hsp(20),right: hsp(20)),
            color: YSColors.containColor(context),
            child: GestureDetector(
              onTap: (){
                _checkWords();
              },
              child: Container(
                height: hsp(50),
                decoration: BoxDecoration(
                  color: YSColors.buttonColor(context),
                  borderRadius: const BorderRadius.all(Radius.circular(10)),
                ),
                alignment: Alignment.center,
                child: Text(S.current.QUERENDAORU,style: YSColors.buttonStyle(context),),
              ),
            ),
          ),
        )
      ],
    );
  }
  _checkWords() async{
    LogUtil.d(widget.wordsArray);
    if(_checkArray.length!=_wordArray.length){
      ysFlutterToast('助记词验证错误');
      return;
    }
    for(int i=0;i<_wordArray.length;i++){
      Map word = _wordArray[i];
      Map check = _checkArray[i];
      if(word['word']!=check['word']){
        ysFlutterToast('助记词验证错误');
        return;
      }
    }
    ysShowCenterAlertView(context, YSLoadView2(funAction: () async{
      return await YSBipManager.setMnemonic(widget.wordsArray.join(' '));
    },valueSetter: (isDone) async{
      if(isDone&&mounted){
        if(YSData().isManager){
          List array = await YSSqflite().rawQuery();
          if(!mounted)return;
          YSSqflite.notifier(context, array);
          Navigator.popUntil(context, ModalRoute.withName("YSWalletManager"));
        }else{
          widget.valueSetter(1);
          // Navigator.of(context).pushAndRemoveUntil(CupertinoPageRoute(builder: (context){
          //   return const YSTabBar();
          // }), (route) => false);
        }
      }

    },));
    // bool isDone = await YSBipManager.setMnemonic(widget.wordsArray.join(' '));
    // List array = await YSSqflite().rawQuery(name: 'Tron');
    // LogUtil.d(array);
    // return;

  }
}
class YSWordCheckView2 extends StatefulWidget {
  const YSWordCheckView2({Key? key}) : super(key: key);

  @override
  YSWordCheckView2State createState() => YSWordCheckView2State();
}

class YSWordCheckView2State extends State<YSWordCheckView2> {
  final List _logoArray = ['编组 32','编组 42','编组 52','编组 62','编组 72','编组 82','编组 92'];
  @override
  void initState() {
    Future.delayed(const Duration(seconds: 0)).then((value) {
      _intoHome();
    });
    super.initState();
  }
  _intoHome() {
    ysShowCenterAlertView(context, YSAlertMessage(callback: (){
      Navigator.of(context).pushAndRemoveUntil(CupertinoPageRoute(builder: (context){
        return const YSTabBar();
      }), (route) => false);
    },),isTrans: true);
  }
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Image.asset('images/沙漏黑白.gif',height: hsp(80),width: hsp(80),),
        const YSIndexView(selectedIndex: 3,),
        Container(
          margin: EdgeInsets.only(top: hsp(25)),
          height: hsp(50),
          width: ysWidth(context)-hsp(30),
          child: GridView.builder(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 7
            ),
            itemBuilder: (context,index){
              return Image.asset(YSColors.imageStyle(context, _logoArray[index]));
            },
            itemCount: _logoArray.length,
            padding: const EdgeInsets.all(0),
          ),
        )
      ],
    );
  }
}

