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

import 'YSWalletCollection.dart';
import 'YSWalletTransfer.dart';

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

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

class YSWalletListItemDetailState extends State<YSWalletListItemDetail> {
  List _dataArray = [];
  Map _token = {};
  @override
  void initState() {
    networkDelay((){
      _getToken();
    });
    super.initState();
  }
  _getToken() {
    List list = YSData().allTokenArray.where((element) => element['address']==widget.item['address']).toList();
    if(list.isNotEmpty){
      _token = list.first;
    }else{
      _token = widget.item;
    }
    setState(() {});
  }
  @override
  Widget build(BuildContext context) {
    return YSBase2(
      isScroll: false,
      ysTitle: _token['name']??'',
      // ysRightWidget: GestureDetector(
      //   onTap: (){},
      //   child: Text(S.current.DAIBIXIANGQING,style: YSColors.content2Style(context),),
      // ),
      ysChild: _token.isEmpty?Container():Padding(
        padding: EdgeInsets.only(left: hsp(20),right: hsp(20)),
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.only(top: hsp(20)),
              height: hsp(60),
              width: hsp(60),
              decoration: BoxDecoration(
                color: Colors.grey,
                borderRadius: const BorderRadius.all(Radius.circular(50)),
                border: Border.all(color: YSColors.containColor(context),width: hsp(2)),
                image: DecorationImage(image: NetworkImage(_token['icon_url']))
              ),
            ),
            Padding(
              padding: EdgeInsets.only(top: hsp(10)),
              child: Text('${_token['name']} ',style: YSColors.title2Style(context),),
            ),
            YSBalanceView(public: _token['address'],style: YSColors.sub2Style(context),walletAddress: YSData().wallet['public'],type: 1,),
            // Text('\$ 82.878',style: YSColors.sub2Style(context),),
            Container(
              height: hsp(45),
              decoration: BoxDecoration(
                color: YSColors.containColor(context),
                borderRadius: const BorderRadius.all(Radius.circular(10))
              ),
              margin: EdgeInsets.only(top: hsp(15)),
              padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
              child: Row(
                children: [
                  Text(S.current.JIAGE,style: YSColors.contentStyle(context),),
                  if(_token['price_usd']!=null)Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(toDecimalFlex(_token['price_usd'],range: 4),style: YSColors.subStyle(context),),
                        Text('\$ ${toDecimalFlex(_token['price_usd'],range: 4)}',style: YSColors.sub3Style(context),),
                      ],
                    )
                  )
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: hsp(40)),
              height: hsp(20),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(S.current.JIAOYIJILU,style: YSColors.contentStyle(context),),
                  PopupMenuButton(
                    itemBuilder: (BuildContext context) {
                      return [
                        PopupMenuItem(value: "0",child: Text("全部",style: YSColors.contentStyle(context),),),
                        PopupMenuItem(value: "1",child: Text("转入",style: YSColors.contentStyle(context),),),
                        PopupMenuItem(value: "2",child: Text("转出",style: YSColors.contentStyle(context),),),
                      ];
                    },
                    child: Image.asset(YSColors.imageStyle(context, '更多 (5)'),height: hsp(15),width: hsp(15),),
                    onSelected: (value){
                      Map request = YSData().wallet['public']!=_token['address']?{
                        'chain_id':YSData().typeId,'contract_address':_token['address'],'address':YSData().wallet['public'],'type':0
                      }:{
                        'chain_id':YSData().typeId,'address':YSData().wallet['public'],'type':0
                      };
                      request['type'] = value;
                      refreshKey.currentState?.refresh(request: request);
                    },
                  )
                ],
              ),
            ),
            Expanded(
              child: Container(
                margin: EdgeInsets.only(top: hsp(10),bottom: hsp(15)),
                decoration: BoxDecoration(
                  color: YSColors.containColor(context),
                  borderRadius: const BorderRadius.all(Radius.circular(10))
                ),
                padding: EdgeInsets.all(hsp(15)),
                child: LayoutBuilder(
                  builder: (context,conSize) {
                    return Column(
                      children: [
                        // Container(
                        //   height: hsp(40),
                        //   decoration: const BoxDecoration(
                        //     color: Color(0xFFEFF1F9),
                        //     borderRadius: BorderRadius.all(Radius.circular(10))
                        //   ),
                        //   padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
                        //   child: Row(
                        //     children: [
                        //       SizedBox(
                        //         width: conSize.maxWidth-hsp(50),
                        //         child: Text(S.current.NINYIKAIQIYINCANGXIAOEJIAOYI,style: TextStyle(fontSize: zsp(11),color: const Color(0xFF3D5AFF)),),
                        //       ),
                        //       Icon(Icons.chevron_right,size: hsp(20),color: const Color(0xFF3D5AFF),)
                        //     ],
                        //   ),
                        // ),
                        SizedBox(
                          height: conSize.maxHeight-hsp(0),
                          child: YSRefreshLoad(
                            key: refreshKey,
                            url: 'transactions',
                            request: YSData().wallet['public']!=_token['address']?{
                              'chain_id':YSData().typeId,'contract_address':_token['address'],'address':YSData().wallet['public'],'type':0
                            }:{
                              'chain_id':YSData().typeId,'address':YSData().wallet['public'],'type':0
                            },
                            postData: (value) async{
                              _dataArray = value;
                              YSTansTable table = YSTansTable().init();
                              List array = await table.rawQuery();
                              List temp  = [];
                              for (var element in _dataArray) {
                                for (var element2 in array) {
                                  if(element2['hash']==element['hash']){
                                    temp.add(element2);
                                    table.rawDelete('${element2['id']}');
                                  }
                                }
                              }
                              for (var element in temp) {
                                array.remove(element);
                              }
                              _dataArray.insertAll(0,array);
                              setState(() {});
                            },
                            child: SingleChildScrollView(
                              child: ListView.builder(
                                  itemBuilder: (context,index){
                                    Map item = _dataArray[index];
                                    return GestureDetector(
                                      onTap: (){
                                        LogUtil.d(item);
                                        Navigator.of(context).push(
                                          CupertinoPageRoute(builder: (context){
                                            return YSTansDetail(item: item,tokenAddress: _token['address'],);
                                          })
                                        );
                                      },
                                      behavior: HitTestBehavior.opaque,
                                      child: Container(
                                        padding: EdgeInsets.only(top: hsp(10),bottom: hsp(10)),
                                        decoration: BoxDecoration(
                                          border: Border(top: BorderSide(color: YSColors.lineColor(context),width: hsp(1)))
                                        ),
                                        child: Row(
                                          children: [
                                            Image.asset(YSColors.imageStyle(context, '编组 ${item['type']==1?'64':'54'}'),height: hsp(30),width: hsp(30),),
                                            Expanded(
                                              child: Padding(
                                                padding: EdgeInsets.only(left: hsp(10),right: hsp(10)),
                                                child: Column(
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                  children: [
                                                    Row(
                                                      children: [
                                                        Container(
                                                          constraints: BoxConstraints(
                                                            maxWidth: conSize.maxWidth-hsp(190),
                                                          ),
                                                          child: Text(ysTextCut(item['to_addr']),style: YSColors.contentStyle(context),maxLines: 1,),
                                                        ),
                                                        Padding(
                                                          padding: const EdgeInsets.only(left: 5),
                                                          child: GestureDetector(
                                                            onTap: (){
                                                              YSCopyPaste.copy(item['to_addr']);
                                                            },
                                                            child: Image.asset(YSColors.imageStyle(context, '复制备份'),height: hsp(10),width: hsp(10),),
                                                          ),
                                                        )
                                                      ],
                                                    ),
                                                    if(item['timestamp']!=null)Text('${toDateFlex(item['timestamp'])}',style: YSColors.subStyle(context),maxLines: 1,),
                                                  ],
                                                ),
                                              )
                                            ),
                                            Container(
                                              width: hsp(100),
                                              alignment: Alignment.centerRight,
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.end,
                                                children: [
                                                  Text(('${item['status']}'=='1'?S.current.JIAOYICHENGGONG:'${item['status']}'=='0'?S.current.JIAOYISHIBAI:S.current.JIAOYIZHONG).fixAutoLines(),
                                                    style: TextStyle(fontSize: zsp(10),color: '${item['status']}'=='1'?const Color(0xFF68AF64):const Color(0xFFDE5656)),maxLines: 1,),
                                                  if(item['symbol']!=null)Padding(
                                                    padding: EdgeInsets.only(top: hsp(5)),
                                                    child: Text(''
                                                        '${item['type']==2?'-':item['type']==1?'+':''}${toDecimalFlex((item['value']??double.parse(item['amount']??'0')),decimal: item['decimal']??0,range: 5)}${item['symbol']??''}',
                                                      style: TextStyle(fontSize: zsp(12),color: item['type']==1?const Color(0xFF68AF64):const Color(0xFFDE5656)),maxLines: 1,),
                                                  )
                                                ],
                                              ),
                                            )
                                          ],
                                        ),
                                      ),
                                    );
                                  },
                                itemCount: _dataArray.length,
                                padding: EdgeInsets.only(top: hsp(15)),
                                shrinkWrap: true,
                                physics: const NeverScrollableScrollPhysics(),
                              ),
                            ),
                          ),
                        )
                      ],
                    );
                  }
                ),
              )
            ),
            Container(
              margin: EdgeInsets.only(bottom: hsp(15)),
              height: hsp(45),
              child: Row(
                children: [
                  Expanded(
                    child: GestureDetector(
                      onTap: (){
                        Navigator.of(context).push(
                            CupertinoPageRoute(builder: (context){
                              return const YSWalletTransfer();
                            })
                        ).then((value) {
                          Map request = YSData().wallet['public']!=_token['address']?{
                            'chain_id':YSData().typeId,'contract_address':_token['address'],'address':YSData().wallet['public'],'type':0
                          }:{
                            'chain_id':YSData().typeId,'address':YSData().wallet['public'],'type':0
                          };
                          refreshKey.currentState?.refresh(request: request);
                        });
                      },
                      behavior: HitTestBehavior.opaque,
                      child: Container(
                        decoration: const BoxDecoration(
                          color: Color(0xFF68AF64),
                          borderRadius: BorderRadius.all(Radius.circular(10))
                        ),
                        alignment: Alignment.center,
                        child: SingleChildScrollView(
                          physics: const NeverScrollableScrollPhysics(),
                          scrollDirection: Axis.horizontal,
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Image.asset(YSColors.imageStyle(context, '形状3'),height: hsp(15),width: hsp(15),),
                              Text(' ${S.current.ZHUANZHANG}',style: YSColors.buttonStyle(context),)
                            ],
                          ),
                        ),
                      ),
                    )
                  ),
                  SizedBox(width: hsp(15),),
                  Expanded(
                      child: GestureDetector(
                        onTap: (){
                          Navigator.of(context).push(
                              CupertinoPageRoute(builder: (context){
                                return YSWalletCollection(wallet: YSData().wallet,);
                              })
                          );
                        },
                        behavior: HitTestBehavior.opaque,
                        child: Container(
                          decoration: const BoxDecoration(
                            color: Color(0xFF3D5AFF),
                            borderRadius: BorderRadius.all(Radius.circular(10))
                          ),
                          alignment: Alignment.center,
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Image.asset(YSColors.imageStyle(context, '形状 2'),height: hsp(15),width: hsp(15),),
                              Text(' ${S.current.SHOUKUAN}',style: YSColors.buttonStyle(context),)
                            ],
                          ),
                        ),
                      )
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
