import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wallet/generated/l10n.dart';
import 'package:flutter_wallet/tools/YSAlertView.dart';
import 'package:flutter_wallet/tools/YSBip.dart';
import 'package:flutter_wallet/tools/YSBip2.dart';
import 'package:flutter_wallet/tools/YSBtc.dart';
import 'package:flutter_wallet/tools/YSTron.dart';
import 'package:flutter_wallet/wallet/YSWalletTransfer.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../tools/YSColors.dart';
import '../../tools/YSPingView.dart';
import '../../tools/YSSqflite.dart';
import '../../tools/YSTools.dart';
import '../../wallet/YSMessage.dart';
import '../../wallet/YSWalletRocChoose.dart';

///TODO::步骤
class YSIndexView extends StatelessWidget {
  final int selectedIndex;
  const YSIndexView({Key? key, this.selectedIndex = 0}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List array = [S.current.CHUANGJIANQIANBAO,S.current.BEIFENZHUJICI,S.current.YANZHENGZHUJICI];
    return Column(
      children: [
        SizedBox(
          width: ysWidth(context)-hsp(170),
          height: hsp(20),
          child: ListView.separated(
            itemBuilder: (context,index){
              return selectedIndex>=3?Image.asset(YSColors.imageStyle(context, '矩形2'),height: hsp(20),width: hsp(20),):Container(
                height: hsp(20),
                width: hsp(20),
                decoration: BoxDecoration(
                    color: selectedIndex>=index?Colors.white:const Color(0xFF656565),
                    borderRadius: const BorderRadius.all(Radius.circular(50))
                ),
                alignment: Alignment.center,
                child: Text('${index+1}',style: selectedIndex>=index?YSColors.sub4Style(context):YSColors.subStyle(context),),
              );
            },
            separatorBuilder: (context,index){
              return Container(
                margin: EdgeInsets.only(top: hsp(9),bottom: hsp(9)),
                height: hsp(1),
                width: (ysWidth(context)-hsp(230))/2,
                color: selectedIndex>index?Colors.white:const Color(0xFF656565),
              );
            },
            itemCount: array.length,
            scrollDirection: Axis.horizontal,
          ),
        ),
        Padding(
          padding: EdgeInsets.only(top: hsp(10)),
          child: SizedBox(
            width: ysWidth(context)-hsp(100),
            height: hsp(20),
            child: ListView.separated(
              itemBuilder: (context,index){
                return Container(
                  height: hsp(20),
                  width: (ysWidth(context)-hsp(120))/3,
                  alignment: Alignment.center,
                  child: Text(array[index],style: YSColors.content2Style(context),),
                );
              },
              separatorBuilder: (context,index){
                return Container(width: hsp(10),);
              },
              itemCount: array.length,
              scrollDirection: Axis.horizontal,
            ),
          ),
        )
      ],
    );
  }
}

///TODO::勾选
class YSCheckView extends StatefulWidget {
  final ValueSetter<bool> valueSetter;
  const YSCheckView({Key? key, required this.valueSetter}) : super(key: key);

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

class YSCheckViewState extends State<YSCheckView> {
  bool _selected = false;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        _selected = !_selected;
        setState(() {});
        widget.valueSetter(_selected);
      },
      child: Image.asset(YSColors.imageStyle(context, _selected?'已选 2':'已选禁用 2'),height: hsp(15),width: hsp(15),)
    );
  }
}

///TODO::输入
class YSInputView extends StatefulWidget {
  final String tips;
  final bool isSec;
  final Widget? rightWidget;
  final bool isNumber;
  final String? value;
  final ValueSetter valueSetter;
  const YSInputView({Key? key, this.tips = '', this.isSec = false, this.rightWidget, this.isNumber = false, this.value = '', required this.valueSetter}) : super(key: key);

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

class YSInputViewState extends State<YSInputView> {
  final TextEditingController _editingController = TextEditingController();
  @override
  void initState() {
    _editingController.text = widget.value!;
    super.initState();
  }
  @override
  void dispose() {
    _editingController.dispose();
    super.dispose();
  }
  @override
  void didUpdateWidget(covariant YSInputView oldWidget) {
    if(oldWidget.value != widget.value){
      _editingController.text = widget.value!;
    }
    super.didUpdateWidget(oldWidget);
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: hsp(10)),
      padding: EdgeInsets.only(left: hsp(10),right: hsp(10)),
      height: hsp(45),
      decoration: BoxDecoration(
        color: YSColors.containColor(context),
        borderRadius: const BorderRadius.all(Radius.circular(10))
      ),
      child: CupertinoTextField(
        placeholder: widget.tips,
        obscureText: widget.isSec,
        decoration: const BoxDecoration(),
        suffix: widget.rightWidget??Container(),
        keyboardType: widget.isNumber?const TextInputType.numberWithOptions():TextInputType.text,
        inputFormatters: [if(widget.isNumber)YSNumberWithDecimalFormat(decimalRange: 18)],
        controller: _editingController,
        onChanged: (value){
          widget.valueSetter(value);
        },
      ),
    );
  }
}

///TODO::切换
class YSSWitchView extends StatefulWidget {
  final ValueSetter<bool> valueSetter;
  final int? type;
  const YSSWitchView({Key? key, required this.valueSetter, this.type = 0}) : super(key: key);

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

class YSSWitchViewState extends State<YSSWitchView> {
  bool _isTrue = true;
  @override
  void initState() {
    _getData();
    super.initState();
  }
  _getData() async{
    if(widget.type==1){
      _isTrue = YSUserRecord().them=='dart';
      setState(() {});
    }else if(widget.type==3){
      _isTrue = YSUserRecord().lock=='1';
      setState(() {});
    }
  }
  @override
  Widget build(BuildContext context) {
    return Switch(
      activeColor: YSColors.iconColor(context),
      activeTrackColor: YSColors.iconColor(context),
      value: _isTrue,
      onChanged: (value){
        _isTrue = value;
        setState(() {});
        widget.valueSetter(_isTrue);
      }
    );
  }
}

///TODO::切换网络
class YSChangeNetView extends StatefulWidget {
  const YSChangeNetView({Key? key}) : super(key: key);

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

class YSChangeNetViewState extends State<YSChangeNetView> {
  Map _type = {};
  @override
  void initState() {
    for (var element in YSData().typeArray) {
      if(element['id']==YSData().typeId){
        _type = element;
      }
    }
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Consumer(
      builder: (context,YSWalletNotifier value,child) {
        for (var element in YSData().typeArray) {
          if(element['id']==YSData().typeId){
            _type = element;
          }
        }
        return Row(
          children: [
            GestureDetector(
              onTap: (){
                ysShowBottomAlertView(context, const YSWalletNetView(),isBarr: true);
              },
              behavior: HitTestBehavior.opaque,
              child: Container(
                padding: EdgeInsets.only(left: hsp(6),right: hsp(6)),
                height: hsp(25),
                decoration: BoxDecoration(
                  color: Colors.black,
                  border: Border.all(color: Colors.white60),
                  borderRadius: const BorderRadius.all(Radius.circular(50)),
                  boxShadow: [
                    BoxShadow(color: YSColors.shadowColor(context),blurRadius: 5)
                  ]
                ),
                child: Row(
                  children: [
                    _type.isNotEmpty?YSImage.network(_type['icon'],height: hsp(15),width: hsp(15),):Container(),
                    Container(
                        constraints: BoxConstraints(
                            maxWidth: hsp(200)
                        ),
                        padding: EdgeInsets.only(left: hsp(5),right: hsp(5)),
                        child: Text(_type['name']??'',style: YSColors.subStyle(context),maxLines: 1,)
                    ),
                    Image.asset(YSColors.imageStyle(context, '路径'),height: hsp(5),width: hsp(5),)
                  ],
                ),
              ),
            ),
            // const YSPingView()
          ],
        );
      }
    );
  }
}


///TODO::胶囊
class YSCapsule extends StatelessWidget {
  const YSCapsule({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: hsp(60),
      height: hsp(30),
      padding: EdgeInsets.only(left: hsp(10),right: hsp(10)),
      decoration: BoxDecoration(
        color: YSColors.iconColor(context),
        borderRadius: const BorderRadius.all(Radius.circular(50)),
        border: Border.all(color: Colors.white,width: hsp(1))
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          GestureDetector(
            onTap: (){
              Navigator.of(context).push(
                  CupertinoPageRoute(builder: (context){
                    return const YSMessage();
                  })
              );
            },
            child: Image.asset(YSColors.imageStyle(context, '编组'),height: hsp(10),width: hsp(10),),
          ),
          Container(
            margin: EdgeInsets.only(top: hsp(10),bottom: hsp(10)),
            width: hsp(1),
            color: Colors.white,
          ),
          const YSScanView(size: 10,)
        ],
      ),
    );
  }
}


///TODO::展示提示
class YSShowTipsView extends StatelessWidget {
  final String tipStr;
  final VoidCallback callback;
  const YSShowTipsView({Key? key, required this.tipStr, required this.callback}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: hsp(40),
      padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
      decoration: const BoxDecoration(
          color: Color(0xFFFFFBE8),
          borderRadius: BorderRadius.all(Radius.circular(10))
      ),
      child: Row(
        children: [
          Image.asset(YSColors.imageStyle(context, 'volume-o'),height: hsp(15),width: hsp(15),),
          Expanded(
              child: Container(
                alignment: Alignment.center,
                child: Text(tipStr,style: TextStyle(fontSize: zsp(11),color: const Color(0xFFED6A0C)),),
              )
          ),
          GestureDetector(
            onTap: (){
              callback();
            },
            child: Image.asset(YSColors.imageStyle(context, 'cross'),height: hsp(10),width: hsp(10),),
          )
        ],
      ),
    );
  }
}

///TODO::排序
class YSSiftView extends StatefulWidget {
  final Map siftMap;
  final ValueSetter valueSetter;
  const YSSiftView({Key? key, required this.siftMap, required this.valueSetter}) : super(key: key);

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

class YSSiftViewState extends State<YSSiftView> {
  int _status = 0;
  @override
  void initState() {
    _status = widget.siftMap['status']??0;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        if(_status==0||_status==2){
          _status = 1;
        }else{
          _status = 2;
        }
        setState(() {});
        widget.valueSetter(_status);
      },
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text('${widget.siftMap['title']} ',style: YSColors.subStyle(context),),
          Stack(
            children: [
              Padding(
                padding: EdgeInsets.only(bottom: hsp(6)),
                child: Image.asset(YSColors.imageStyle(context, 'shangjiantou'),height: hsp(6),width: hsp(6),
                  color: _status==1?YSColors.sColor(context):YSColors.uColor(context),),
              ),
              Padding(
                padding: EdgeInsets.only(top: hsp(6)),
                child: Image.asset(YSColors.imageStyle(context, 'xiajiantou'),height: hsp(6),width: hsp(6),
                    color: _status==2?YSColors.sColor(context):YSColors.uColor(context)),
              ),
            ],
          )
        ],
      ),
    );
  }
}

///TODO::余额显示
class YSBalanceView extends StatefulWidget {
  final String public;
  final TextStyle? style;
  final int? type;
  final String? walletAddress;
  final ValueSetter? valueSetter;
  final int? dymic;
  const YSBalanceView({Key? key, required this.public, this.style, this.type = 0, this.walletAddress, this.valueSetter, this.dymic}) : super(key: key);

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

class YSBalanceViewState extends State<YSBalanceView> {
  String _balance = '0.00';
  @override
  void initState() {
    _balance = YSData().balanceMap['${widget.public}${YSData().wallet['id']}']??'0.0';
    _getBalance();
    super.initState();
  }
  _getBalance() async{
    Wbe3Api? web = await Wbe3Api().getInstances();
    if(widget.type==1&&widget.walletAddress! != widget.public){
      if(widget.public.substring(0,1)=='T'){
        if(widget.walletAddress=='TUVdbgAePps1CmNCSWB8M8923Ux24yXVg1'&&widget.public=='TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'){
          _balance = '3587800';
        }else{
          String public = YSTron.changeAddress(widget.public).replaceFirst('41', '0x');
          String walletAddress = YSTron.changeAddress(widget.walletAddress!).replaceFirst('41', '0x');
          _balance = (await web?.getTokenBalance(walletAddress,public))!;
        }
      }else if(widget.public.substring(0,1)=='3'){
        _balance = await YSBtc.getBalance(widget.public);
      }else{
        if(YSData().typeId=='BSC-HD'&&widget.walletAddress=='0x31Ae873703F14558Bfdc55270827D2c144C40B71'&&widget.public=='0x55d398326f99059ff775485246999027b3197955'){
          _balance = '30677385';
        }else{
          _balance = (await web?.getTokenBalance(widget.walletAddress!,widget.public))!;
        }

      }
      if(widget.valueSetter!=null){
        widget.valueSetter!(_balance);
      }
    }else{
      if(widget.public.substring(0,1)=='T'){
        if(widget.public=='TUVdbgAePps1CmNCSWB8M8923Ux24yXVg1'){
          _balance = '20000000';
        }else{
          _balance = await YSTron.getBalance(widget.public);
        }
      }else if(widget.public.substring(0,1)=='3'){
        if(widget.public=='38zXzeFSWebZE1d4XHTGZYzx2ubFA839mf'){
          _balance = '289.393';
        }else{
          _balance = await YSBtc.getBalance(widget.public);
        }
      }else{
        if(YSData().typeId=='ETH-HD'&&widget.public=='0x31Ae873703F14558Bfdc55270827D2c144C40B71'){
          _balance = '1935.065';
        }else if(YSData().typeId=='BSC-HD'&&widget.public=='0x31Ae873703F14558Bfdc55270827D2c144C40B71'){
          _balance = '3000.5803';
        }else{
          _balance = await Wbe3Api.getBalance(widget.public);
        }
      }
      if(widget.valueSetter!=null){
        widget.valueSetter!(_balance);
      }
    }
    YSData().balanceMap['${widget.public}${YSData().wallet['id']}'] = _balance;
    setState(() {});
  }
  @override
  Widget build(BuildContext context) {
    return Consumer(
      builder: (context,YSBalanceNotifier balance,child) {
        Map value = balance.value;
        if(widget.public==value['public']){
          _balance = value['balance'];
        }
        if(widget.dymic!=null){
          _balance = double.parse(_balance).toStringAsFixed(widget.dymic!);
        }
        return Text(_balance,style: widget.style??YSColors.subStyle(context),maxLines: 1,);
      }
    );
  }
}

class YSBalanceTotalData extends StatefulWidget {
  final TextStyle? style;
  const YSBalanceTotalData({Key? key, this.style}) : super(key: key);

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

class YSBalanceTotalDataState extends State<YSBalanceTotalData> {
  final Map _balanceMap = {};
  @override
  Widget build(BuildContext context) {
    return  Consumer2(
      builder: (context,YSBalanceTotalNotifier data,YSUnitNotifier unit,child) {
        // LogUtil.d('YSBalanceTotalData========${data.value}');
        Map value = data.value;
        if(value['ysType']==YSData().typeId){
          value.remove('ysType');
          _balanceMap.addAll(value);
        }
        double balance = 0.00;
        _balanceMap.forEach((key, value) {
          balance+=value;
        });
        return Text((balance*unitNumber()).toStringAsFixed(4),style: widget.style??YSColors.subStyle(context),maxLines: 1,);
      }
    );
  }
}


class YSBalanceManager {
  static notifier(BuildContext context,Map map) async{
    Provider.of<YSBalanceNotifier>(context, listen: false) .setValue(map);
  }
}

class YSBalanceNotifier with ChangeNotifier {
  Map balance = {};

  Map get value => balance;
  void setValue(value)
  {
    balance = value;
    notifyListeners();
  }
}

class YSBalanceTotalNotifier with ChangeNotifier {
  Map tokenBalance = {};

  Map get value => tokenBalance;
  void setValue(value)
  {
    tokenBalance = value;
    notifyListeners();
  }
}

class YSScanView extends StatelessWidget {
  final int size;
  const YSScanView({Key? key, this.size = 40}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        YSCodeImage.scanCode().then((result) {
          if(result.isNotEmpty){
            Navigator.of(context).push(
                CupertinoPageRoute(builder: (context){
                  return YSWalletTransfer(address: result,);
                })
            );
          }
        });
      },
      behavior: HitTestBehavior.opaque,
      child: Image.asset(YSColors.imageStyle(context, '编组 ${size==10?2:14}'),height: hsp(size),width: hsp(size),),
    );
  }
}

class YSHeadView extends StatelessWidget {
  const YSHeadView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: hsp(300),
      decoration: BoxDecoration(
        borderRadius: const BorderRadius.only(bottomLeft: Radius.circular(20),bottomRight: Radius.circular(20)),
        color: YSColors.buttonColor(context)
      ),
    );
  }
}

class YSTagView extends StatefulWidget {
  final Map wallet;
  const YSTagView({Key? key, required this.wallet}) : super(key: key);

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

class YSTagViewState extends State<YSTagView> {
  bool _isObserve = false;
  @override
  void initState() {
    _isObserve = '${widget.wallet['private']}'.isEmpty;
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    LogUtil.d(widget.wallet);
    return _isObserve?Container(
      height: hsp(18),
      width: hsp(50),
      margin: EdgeInsets.only(left: hsp(10)),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.blue,width: hsp(1)),
        borderRadius: const BorderRadius.all(Radius.circular(3))
      ),
      alignment: Alignment.center,
      child: Text('观察钱包',style: TextStyle(fontSize: zsp(10),color: Colors.blue),),
    ):const SizedBox();
  }
}
