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

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_wallet/tools/YSAlertView.dart';
import 'package:flutter_wallet/tools/YSNetWork.dart';
import 'package:flutter_wallet/tools/YSSqflite.dart';
import 'package:flutter_wallet/wallet/YSWalletListItemDetail.dart';
import 'package:provider/provider.dart';
import '../../login/view/YSHelpView.dart';
import '../../tools/YSColors.dart';
import '../../tools/YSTools.dart';

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

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

class YSWalletListItemViewState extends State<YSWalletListItemView> {
  double _amount = 0;
  Map _token = {};
  int _number = 0;
  @override
  void initState() {
    _amount = YSData().balanceMap['${widget.item['address']}${YSData().wallet['id']}token']??0;
    networkDelay((){
      _getToken();
    });
    super.initState();
  }
  _getToken() async{
    Map type = getWalletType(widget.item);
    List list = [];
    //ETH===========TRON-HD
    // LogUtil.d('_getToken=======${YSData().allTokenArray}');
    if(type.isNotEmpty&&widget.item['address']!='THb4CqiFdwNHsWsQCs4JhzwjMWys4aqCbF'){
      widget.item['name'] = type['token_name'];
      widget.item['address'] = YSData().wallet['public'];
      _token = widget.item;
      List list = YSData().priceArray.where((element) => element['symbol']==_token['name']).toList();
      if(list.isNotEmpty){
        _token = widget.item;
        _token['price_usd'] = double.parse(list.first['price']);
      }
      // String address = '';
      // if(type['token_name']=='BNB'){
      //   address = '0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c';
      // }else if(type['token_name']=='ETH'){
      //   address = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2';
      // }
      // list = YSData().allTokenArray.where((element) => element['address']==address).toList();
      // if(list.isNotEmpty){
      //   _token = widget.item;
      //   _token['price_usd'] = list.first['price_usd'];
      // }else{
      //   _token = widget.item;
      //   List list = YSData().priceArray.where((element) => element['symbol']==_token['name']).toList();
      //   if(list.isNotEmpty){
      //     _token['price_usd'] = double.parse(list.first['price']);
      //   }
      // }
    }else{
      list = YSData().allTokenArray.where((element) => element['address']==widget.item['address']).toList();
      if(list.isNotEmpty){
        _token = list.first;
      }else{
        _token = widget.item;
      }
    }
    _token['ysType'] = YSData().typeId;
    setState(() {});
  }

  @override
  void didUpdateWidget(covariant YSWalletListItemView oldWidget) {
    _number++;
    if(_number%50==0){
      _getToken();
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    // LogUtil.d('${_token['name']}===========${_token['address']}');
    return Slidable(
      key: const ValueKey(0),
      endActionPane: ActionPane(
        extentRatio: 0.3,
        motion: GestureDetector(
          onTap: (){
            ysShowCenterAlertView(context, YSTipsAlertView(valueSetter: (value) async{
              if(value){
                YSSqflite2 sqflite2 = YSSqflite2().init();
                sqflite2.rawDelete('${widget.item['hid']}');
                List array = await sqflite2.rawQuery();
                if(!mounted)return;
                YSSqflite2.notifier(YSData().context, array);
              }
            },tipsStr: '是否删除次资产?',));
          },
          child: Container(
            color: Colors.red,
            alignment: Alignment.center,
            child: Text('删除',style: YSColors.content2Style(context),),
          ),
        ),
        children:  const [],
      ),
      child: Consumer(
        builder: (context,YSUnitNotifier unit,child) {
          return GestureDetector(
            onTap: (){
              YSData().contAddress = _token['address'];
              YSData().contName = _token['name'];
              Navigator.of(context).push(
                CupertinoPageRoute(builder: (context){
                  return YSWalletListItemDetail(item: widget.item,);
                })
              );
            },
            behavior: HitTestBehavior.opaque,
            child: _token.isEmpty?Container():Container(
                padding: EdgeInsets.only(left: hsp(15),right: hsp(15),top: hsp(10),bottom: hsp(10)),
                alignment: Alignment.centerLeft,
                child: Row(
                  children: [
                    ClipRRect(
                      borderRadius: const BorderRadius.all(Radius.circular(50)),
                      key: Key('$_number'),
                      child: YSImage.network(_token['icon_url'],height: hsp(40),width: hsp(40),),
                    ),
                    Expanded(
                        child: Container(
                          padding: EdgeInsets.only(top: hsp(5),bottom: hsp(5),left: hsp(5),right: hsp(5)),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(_token['name']??'',style: YSColors.contentStyle(context),maxLines: 1,),
                              YSBalanceView(public: _token['address'],style: YSColors.subStyle(context),type: 1,walletAddress: YSData().wallet['public'],valueSetter: (value) {
                                _amount = double.parse(value)*(_token['price_usd']??1);
                                setState(() {});
                                YSData().balanceMap['${widget.item['address']}${YSData().wallet['id']}token'] = _amount;
                                if(_amount>0){
                                  Provider.of<YSBalanceTotalNotifier>(context, listen: false) .setValue({_token['symbol']:_amount,'ysType':_token['ysType']});
                                }else{
                                  Provider.of<YSBalanceTotalNotifier>(context, listen: false) .setValue({_token['symbol']:_amount,'ysType':_token['ysType']});
                                }
                              },key: Key('$_number'),)
                              // if(_info.isNotEmpty)Padding(
                              //     padding: EdgeInsets.only(top: hsp(5)),
                              //     child: RichText(text: TextSpan(
                              //         style: YSColors.subStyle(context),
                              //         children: [
                              //           TextSpan(
                              //             text: '\$${_info['lastPrice']} ',
                              //           ),
                              //           TextSpan(
                              //               text: ' ${(double.parse(_info['lastPrice']??'0')-double.parse(_info['openPrice']??'0')).toStringAsFixed(8)}',
                              //               style: const TextStyle(color: Color(0xFFFF0000))
                              //           )
                              //         ]
                              //     ),maxLines: 1,)
                              // )
                            ],
                          ),
                        )
                    ),
                    Container(
                      width: hsp(150),
                      padding: EdgeInsets.only(top: hsp(5),bottom: hsp(5),left: hsp(5),right: hsp(5)),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          Text('${YSUserRecord().unit=='RMB'?'¥':'\$'} ${(double.parse(toFlex(_amount,range: 2))*unitNumber()).toStringAsFixed(4)}'.fixAutoLines(),style: YSColors.contentStyle(context),),//${_info['count']}
                          // Padding(
                          //     padding: EdgeInsets.only(top: hsp(5)),
                          //     child: Text('\$ ${widget.item['gas']} ',style: YSColors.subStyle(context),)
                          // )
                        ],
                      ),
                    ),
                  ],
                )
            ),
          );
        }
      ),
    );
  }
}

class YSWalletListChooseItemView extends StatefulWidget {
  final ValueSetter? valueSetter;
  final Map item;
  const YSWalletListChooseItemView({Key? key, required this.item, this.valueSetter}) : super(key: key);

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

class YSWalletListChooseItemViewState extends State<YSWalletListChooseItemView> {
  @override
  Widget build(BuildContext context) {
    bool isChoose = YSData().tokenArray.any((element) => element['hid']=='${widget.item['hid']}')&&widget.valueSetter==null;
    return GestureDetector(
      onTap: (){

      },
      behavior: HitTestBehavior.opaque,
      child: Container(
          padding: EdgeInsets.only(left: hsp(15),right: hsp(15),top: hsp(10),bottom: hsp(10)),
          alignment: Alignment.centerLeft,
          child: Row(
            children: [
              ClipRRect(
                borderRadius: const BorderRadius.all(Radius.circular(50)),
                child: YSImage.network(widget.item['icon_url'],height: hsp(40),width: hsp(40),),
              ),
              Expanded(
                  child: Container(
                    padding: EdgeInsets.only(top: hsp(5),bottom: hsp(5),left: hsp(5),right: hsp(5)),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(widget.item['name']??'',style: YSColors.contentStyle(context),maxLines: 1,),
                        Padding(
                          padding: EdgeInsets.only(top: hsp(5)),
                          child: Text(ysTextCut(widget.item['address']),style: YSColors.subStyle(context),)
                        )
                      ],
                    ),
                  )
              ),
              GestureDetector(
                onTap: () async{
                  if(widget.valueSetter!=null){
                    widget.valueSetter!(widget.item);
                  }else{
                    YSSqflite2 sq2 = YSSqflite2().init();
                    if(isChoose){
                      sq2.rawDelete('${widget.item['hid']}');
                    }else{
                      sq2.rawInsert(
                        hid: '${widget.item['hid']}',
                        name: '${widget.item['name']}',
                        gas: '${widget.item['gas']}',
                        decimal: '${widget.item['decimal']}',
                        rice_usd: '${widget.item['rice_usd']}',
                        percent_change_24h: '${widget.item['percent_change_24h']}',
                        address: '${widget.item['address']}',
                        total_supply: '${widget.item['total_supply']}',
                        icon_url: '${widget.item['icon_url']}',
                        symbol: '${widget.item['symbol']}'
                      );
                    }
                    List tokenArray = await sq2.rawQuery();
                    if(!mounted)return;
                    YSSqflite2.notifier(context, tokenArray);
                    setState(() {});
                  }
                },
                child: Icon(isChoose?Icons.remove_circle_outline:Icons.add_circle_outline,size: hsp(20),color: isChoose?Colors.grey:Colors.blue,),
              )
            ],
          )
      ),
    );
  }
}
