import 'dart:math';
import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wallet/generated/l10n.dart';
import 'package:flutter_wallet/shop/YSCrossRecord.dart';
import 'package:flutter_wallet/shop/view/YSExchangeRecordListItemView.dart';
import 'package:flutter_wallet/shop/view/YSShopListItemView.dart';
import 'package:flutter_wallet/tools/YSRefrehLoad.dart';
import 'package:skeletons/skeletons.dart';
import 'package:web3dart/crypto.dart';
import 'package:web3dart/web3dart.dart';

import '../login/view/YSHelpView.dart';
import '../tools/YSAes.dart';
import '../tools/YSAlertView.dart';
import '../tools/YSBip2.dart';
import '../tools/YSColors.dart';
import '../tools/YSNetWork.dart';
import '../tools/YSTools.dart';
import 'package:http/http.dart';

import '../tools/YSTron.dart';

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

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

class YSShopState extends State<YSShop> {//with AutomaticKeepAliveClientMixin
  final List _titleArray = [
    {'type':1,'title':S.current.DUIHUAN},
    {'type':2,'title':S.current.KUALIAN},
    {'type':3,'title':S.current.HANGQING}
  ];
  int _titleIndex = 1;
  @override
  Widget build(BuildContext context) {
    // super.build(context);
    int type = _titleArray[_titleIndex]['type'];
    return Scaffold(
      backgroundColor: YSColors.backgroundColor(context),
      body: SingleChildScrollView(
        child: SizedBox(
          width: ysWidth(context),
          height: ysHeight(context)-ystabBarHeight,
          child: Skeleton(
            isLoading: false,
            skeleton: Column(
              children: [
                SkeletonAvatar(
                  style: SkeletonAvatarStyle(
                      width: double.infinity,
                      height: hsp(90)
                  ),
                ),
                Padding(
                  padding: EdgeInsets.all(hsp(20)),
                  child: SkeletonAvatar(
                    style: SkeletonAvatarStyle(
                        width: double.infinity,
                        height: hsp(200)
                    ),
                  ),
                ),
                Container(
                  height: hsp(25),
                  margin: EdgeInsets.only(left: hsp(20),right: hsp(20)),
                  child: ListView.separated(
                    itemBuilder: (context,index){
                      return SkeletonAvatar( style: SkeletonAvatarStyle(width: (ysWidth(context)-hsp(130))/4, height: 25,borderRadius: const BorderRadius.all(Radius.circular(50))));
                    },
                    separatorBuilder: (context,index){
                      return Container(width: hsp(30),);
                    },
                    itemCount: 4,
                    scrollDirection: Axis.horizontal,
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(top: hsp(20)),
                  child: SkeletonAvatar( style: SkeletonAvatarStyle(width: ysWidth(context)-hsp(40), height: hsp(50)))
                )
              ],
            ),
            child: Stack(
              children: [
                // const YSHeadView(),
                Container(
                  height: hsp(90),
                  decoration: BoxDecoration(
                    color: YSColors.buttonColor(context),
                    borderRadius: const BorderRadius.only(bottomRight: Radius.circular(10),bottomLeft: Radius.circular(10))
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(top: ysTOP(context)+hsp(10),left: hsp(type==3?0:20),right: hsp(type==3?0:20)),
                  child: LayoutBuilder(
                    builder: (context,conSize){
                      return Column(
                        children: [
                          Container(
                            height: hsp(50),
                            margin: EdgeInsets.only(left: hsp(30),right: hsp(30)),
                            child: ListView.builder(
                              itemBuilder: (context,index){
                                Map item = _titleArray[index];
                                return GestureDetector(
                                  onTap: (){
                                    _titleIndex = index;
                                    setState(() {});
                                  },
                                  behavior: HitTestBehavior.opaque,
                                  child: Opacity(
                                    opacity: _titleIndex==index?1:0.6,
                                    child: Container(
                                      width: (conSize.maxWidth-hsp(60))/_titleArray.length,
                                      alignment: Alignment.center,
                                      child: Column(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          Text(item['title'],style: YSColors.title2Style(context),),
                                          Container(
                                            margin: EdgeInsets.only(top: hsp(5)),
                                            width: hsp(20),
                                            height: hsp(2),
                                            color: _titleIndex==index?Colors.white60:Colors.transparent,
                                          )
                                        ],
                                      )
                                    ),
                                  ),
                                );
                              },
                              padding: const EdgeInsets.all(0),
                              scrollDirection: Axis.horizontal,
                              itemCount: _titleArray.length,
                            ),
                          ),
                          Container(
                            height: conSize.maxHeight-hsp(50),
                            padding: EdgeInsets.only(top: hsp(20)),
                            child: type==1?const YSChangeView():
                            type==2? const YSCrossView():const YSPriceView(),
                          )
                        ],
                      );
                    },
                  ),
                ),
                if(type==1)Padding(
                  padding: EdgeInsets.only(top: ysTOP(context)+hsp(165),left: ysWidth(context)/2-hsp(25)),
                  child: Transform.rotate(angle: 1.55,child: Image.asset(YSColors.imageStyle(context, '交换  反向'),height: hsp(50),width: hsp(50),),)
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  // @override
  // // TODO: implement wantKeepAlive
  // bool get wantKeepAlive => false;
}

GlobalKey<YSChangeViewState> changeKey = GlobalKey();
class YSChangeView extends StatefulWidget {
  const YSChangeView({Key? key}) : super(key: key);

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

class YSChangeViewState extends State<YSChangeView> {
  final TextEditingController _amountField = TextEditingController();
  Map _wallet1 = {};
  Map _wallet2 = {};
  final TextEditingController _addressField = TextEditingController();
  int _changeIndex = 9999;
  List _array = [];
  @override
  void dispose() {
    _amountField.dispose();
    _addressField.dispose();
    super.dispose();
  }
  change() {

  }
  @override
  void initState() {
    networkDelay((){
      _getCrossListData();
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context,conSize) {
        return Column(
          children: [
            Container(
              width: conSize.maxWidth,
              decoration: BoxDecoration(
                  color: YSColors.containColor(context),
                  borderRadius: const BorderRadius.only(topLeft: Radius.circular(10),topRight: Radius.circular(10))
              ),
              height: hsp(110),
              alignment: Alignment.center,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  SizedBox(
                    width: conSize.maxWidth-hsp(180),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(S.of(context).NINJIANGZHIFU,style: YSColors.contentStyle(context),),
                        Padding(
                          padding: EdgeInsets.only(top: hsp(10),bottom: hsp(10)),
                          child: CupertinoTextField(
                            placeholder: S.current.QINGSHURUZHIFUJINE,
                            style: YSColors.contentStyle(context),
                            decoration: const BoxDecoration(),
                            padding: const EdgeInsets.all(0),
                            controller: _amountField,
                            inputFormatters: [YSNumberWithDecimalFormat(decimalRange: 18)],
                            keyboardType: TextInputType.number,
                          ),
                        ),
                        Row(
                          children: [
                            Text('${S.of(context).YUE}: ',style: YSColors.subStyle(context),),
                            // if(_wallet1.isNotEmpty)Expanded(child: YSBalanceView(public: _wallet1['address'],style: YSColors.subStyle(context),key: Key(_wallet1['address']),))
                            if(_wallet1.isNotEmpty)Expanded(child: YSBalanceView(
                              public: _wallet1['address'],
                              style: YSColors.subStyle(context),
                              key: Key(_wallet1['address']),
                              type: 1,
                              walletAddress: YSData().wallet['public'],
                            ))
                          ],
                        )
                      ],
                    ),
                  ),
                  GestureDetector(
                    onTap: (){
                      FocusScope.of(context).unfocus();
                      // ysShowBottomAlertView(context,  YSExchangeTypeChooseView1(valueSetter: (value){
                      //   _wallet1 = value;
                      //   _amountField.text = '';
                      //   _changeIndex = 9999;
                      //   setState(() {});
                      // },),isBarr: true);
                      ysShowBottomAlertView(context,  YSExchangeTypeChooseView2(valueSetter: (value){
                        _wallet1 = value;
                        if(value['address']==_wallet2['address']){
                          _wallet2.clear();
                        }
                        _amountField.text = '';
                        _changeIndex = 9999;
                        setState(() {});
                      },),isBarr: true);
                    },
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                      width: hsp(150),
                      alignment: Alignment.center,
                      child: _wallet1.isNotEmpty?Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          ClipRRect(
                            borderRadius: const BorderRadius.all(Radius.circular(50)),
                            child: YSImage.network(_wallet1['icon_url'],height: hsp(40),width: hsp(40),),
                          ),
                          Text(' ${_wallet1['bl_symbol']}',style: YSColors.contentStyle(context),),
                          Icon(Icons.arrow_drop_down,size: hsp(30),color: YSColors.sColor(context),)
                        ],
                      ):Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(S.current.QINGXUANZE,style: YSColors.contentStyle(context),),
                          Icon(Icons.arrow_drop_down,size: hsp(30),color: YSColors.sColor(context),)
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: hsp(1)),
              width: conSize.maxWidth,
              decoration: BoxDecoration(
                  color: YSColors.containColor(context),
                  borderRadius: const BorderRadius.only(bottomRight: Radius.circular(10),bottomLeft: Radius.circular(10))
              ),
              padding: EdgeInsets.all(hsp(15)),
              alignment: Alignment.center,
              child: Column(
                children: [
                  Row(
                    children: [
                      SizedBox(
                        width: conSize.maxWidth-hsp(180),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(S.of(context).NINJIANGDEDAO,style: YSColors.contentStyle(context),),
                            Padding(
                              padding: EdgeInsets.only(top: hsp(10),bottom: hsp(10)),
                              child: Text('0.00',style: YSColors.contentStyle(context),),
                            ),
                            Row(
                              children: [
                                Text('${S.of(context).YUE}: ',style: YSColors.subStyle(context),),
                                if(_wallet2.isNotEmpty)Expanded(child: YSBalanceView(
                                  public: _wallet2['address'],
                                  style: YSColors.subStyle(context),
                                  key: Key(_wallet2['address']),
                                  type: 1,
                                  walletAddress: _addressField.text,
                                ))
                              ],
                            )
                          ],
                        ),
                      ),
                      GestureDetector(
                        onTap: (){
                          FocusScope.of(context).unfocus();
                          ysShowBottomAlertView(context,  YSExchangeTypeChooseView2(valueSetter: (value){
                            _wallet2 = value;
                            if(value['address']==_wallet1['address']){
                              _wallet1.clear();
                            }
                            _addressField.text = '';
                            setState(() {});
                          },),isBarr: true);
                        },
                        behavior: HitTestBehavior.opaque,
                        child: Container(
                          width: hsp(150),
                          alignment: Alignment.center,
                          child: _wallet2.isNotEmpty?Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              ClipRRect(
                                borderRadius: const BorderRadius.all(Radius.circular(50)),
                                child: YSImage.network(_wallet2['icon_url'],height: hsp(40),width: hsp(40),),
                              ),
                              Text(' ${_wallet2['bl_symbol']}',style: YSColors.contentStyle(context),),
                              Icon(Icons.arrow_drop_down,size: hsp(30),color: YSColors.sColor(context),)
                            ],
                          ):Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text(S.current.QINGXUANZE,style: YSColors.contentStyle(context),),
                              Icon(Icons.arrow_drop_down,size: hsp(30),color: YSColors.sColor(context),)
                            ],
                          ),
                        ),
                      )],
                  ),
                  if(_wallet1.isNotEmpty&&_wallet2.isNotEmpty&&_wallet1['parentName']!=_wallet2['parentName'])Container(
                    margin: EdgeInsets.only(top: hsp(15)),
                    height: hsp(20),
                    decoration: BoxDecoration(
                        color: YSColors.contain2Color(context),
                        borderRadius: const BorderRadius.all(Radius.circular(4))
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          child: CupertinoTextField(
                            placeholder: S.of(context).QINGSHURUHUOXUANZENINDEMUBIAOQIANBAODIZHI,
                            style: YSColors.subStyle(context),
                            padding: EdgeInsets.only(left: hsp(10),right: hsp(10)),
                            decoration: const BoxDecoration(),
                            controller: _addressField,
                          )
                        ),
                        GestureDetector(
                          onTap: (){
                            // LogUtil.d(_wallet2);
                            // LogUtil.d(_wallet1);
                            // return;
                            ysShowBottomAlertView(context,  YSExchangeTypeChooseView1(valueSetter: (value){
                              _addressField.text = value['address']??'';
                            },item: _wallet2,),isBarr: true);
                          },
                          behavior: HitTestBehavior.opaque,
                          child: Container(
                            width: hsp(50),
                            height: hsp(10),
                            decoration: BoxDecoration(
                                border: Border(left: BorderSide(color: YSColors.lineColor(context),width: hsp(1)))
                            ),
                            child: Image.asset(YSColors.imageStyle(context, '钱包 (2)'),height: hsp(10),width: hsp(10),),
                          ),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
            Container(
              height: hsp(25),
              margin: EdgeInsets.only(top: hsp(25),bottom: hsp(25)),
              child: ListView.separated(
                itemBuilder: (context,index){
                  return GestureDetector(
                    onTap: () async{
                      String balanceStr = '0.0';
                      if(_wallet1.isNotEmpty){
                        if('${_wallet1['address']}'.substring(0,1)=='T'){
                          String public = YSTron.changeAddress(_wallet1['address']).replaceFirst('41', '0x');
                          String walletAddress = YSTron.changeAddress(YSData().wallet['public']).replaceFirst('41', '0x');
                          balanceStr = (await Wbe3Api().getTokenBalance(walletAddress,public));
                        }else{
                          balanceStr = await Wbe3Api().getTokenBalance(YSData().wallet['public'],_wallet1['address']);
                        }
                        // String balanceStr = await Wbe3Api.getBalance(_wallet1['address']);
                        double balance = double.parse(balanceStr);
                        _amountField.text = '${(balance*((index+1)*25)/100)}';
                        LogUtil.d(_amountField.text);
                      }
                      _changeIndex = index;
                      setState(() {});
                    },
                    child: Container(
                      height: hsp(25),
                      width: (conSize.maxWidth-hsp(90))/4,
                      decoration:  BoxDecoration(
                          color: _changeIndex==index?YSColors.selectedColor(context):const Color(0xFFE9EEFF),
                          borderRadius: const BorderRadius.all(Radius.circular(50)),
                          boxShadow: [
                            BoxShadow(color: YSColors.shadowColor(context),blurRadius: 3)
                          ]
                      ),
                      alignment: Alignment.center,
                      child: Text('${(index+1)*25}%',style: TextStyle(
                        fontSize: zsp(14),
                        color: _changeIndex==index?YSColors.content2Style(context).color:YSColors.selectedColor(context)),
                      ),
                    ),
                  );
                },
                separatorBuilder: (context,index){
                  return Container(width: hsp(30),);
                },
                itemCount: 4,
                scrollDirection: Axis.horizontal,
              ),
            ),
            GestureDetector(
              onTap: () async{
                // LogUtil.d(_wallet2);
                // LogUtil.d(_wallet1);
                // return;
                if(_wallet1.isEmpty){
                  ysFlutterToast(S.current.QINGXUANZEZHUANZHANGDIZHI);
                  return;
                }
                if(_wallet1['parentName']==_wallet2['parentName']){
                  _addressField.text = YSData().wallet['public'];
                }
                if(_addressField.text.isEmpty){
                  ysFlutterToast(S.current.QINGWANSHANJIESHOUDIZHI);
                  return;
                }
                if(_amountField.text.isEmpty){
                  ysFlutterToast(S.current.QINGTIANXIEZHUANZHANGSHULIANG);
                  return;
                }
                // List walletArray = await YSSqflite().init().rawQuery();
                // Map wallet = walletArray.firstWhere((element) => element['public']==_wallet1['address']);
                if(!mounted)return;
                if(YSData().typeId=='TRON-HD'){
                  ysShowCenterAlertView(context, YSLoadView(funAction: _exchangeData,wallet: YSData().wallet,successStr: S.current.SHOUQUANTIJIAOCHENGGONG,failStr: S.current.SHOUQUANTIJIAOSHIBAI,),isTrans: false);
                }else{
                  ysShowCenterAlertView(context, YSLoadView(funAction: _exchangeData,wallet: YSData().wallet,successStr: S.current.DUIHUANTIJIAOCHENGGONG,failStr: S.current.DUIHUANTIJIAOSHIBAI,),isTrans: false);
                }

                // if(!mounted)return;
                // Wbe3Api? web = await Wbe3Api().getInstances();//_wallet2['decimal']
                // bool? isCheck = await web?.setContaract(_wallet2['address']);//,decimal: _wallet2['decimal']
                // // LogUtil.d(isCheck);
                // // return;
                // if(isCheck==true&&mounted){
                //
                // }

              },
              behavior: HitTestBehavior.opaque,
              child: Container(
                height: hsp(50),
                decoration: BoxDecoration(
                    color: YSColors.buttonColor(context),
                    borderRadius: const BorderRadius.all(Radius.circular(10))
                ),
                alignment: Alignment.center,
                child: Text(S.of(context).DUIHUANYULAN,style: YSColors.buttonStyle(context),),
              ),
            ),
            // Expanded(child: Padding(
            //   padding: EdgeInsets.only(top: hsp(25)),
            //   child: SingleChildScrollView(
            //     padding: EdgeInsets.only(bottom: hsp(10)),
            //     child: Column(
            //       children: [
            //         Container(
            //           width: conSize.maxWidth,
            //           decoration: BoxDecoration(
            //               color: YSColors.containColor(context),
            //               borderRadius: const BorderRadius.all(Radius.circular(10))
            //           ),
            //           padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
            //           child: Column(
            //             children: [
            //               SizedBox(
            //                 height: hsp(45),
            //                 child: Row(
            //                   children: [
            //                     Expanded(child: Text(S.of(context).DUIHUANBAOJIA,style: YSColors.contentStyle(context),)),
            //                     Expanded(
            //                         child: Container(
            //                           alignment: Alignment.centerRight,
            //                           child: Text('1BTC≈15.966015ETH',style: YSColors.subStyle(context),),
            //                         )
            //                     )
            //                   ],
            //                 ),
            //               ),
            //               Divider(color: YSColors.lineColor(context),height: hsp(1),),
            //               Container(
            //                 alignment: Alignment.centerLeft,
            //                 height: hsp(30),
            //                 child: Row(
            //                   children: [
            //                     Expanded(child: Text(S.of(context).ZUIDAHUADONGCHAJIA,style: YSColors.contentStyle(context),)),
            //                     Expanded(
            //                         child: Container(
            //                           alignment: Alignment.centerRight,
            //                           child: Text('2.00%',style: YSColors.subStyle(context),),
            //                         )
            //                     )
            //                   ],
            //                 ),
            //               ),
            //               Container(
            //                 alignment: Alignment.centerLeft,
            //                 height: hsp(30),
            //                 child: Row(
            //                   children: [
            //                     Expanded(child: Text(S.of(context).SHOUXUFEI,style: YSColors.contentStyle(context),)),
            //                     Expanded(
            //                         child: Container(
            //                           alignment: Alignment.centerRight,
            //                           child: Text('2.00%',style: YSColors.subStyle(context),),
            //                         )
            //                     )
            //                   ],
            //                 ),
            //               ),
            //               Container(
            //                 alignment: Alignment.centerLeft,
            //                 height: hsp(30),
            //                 child: Row(
            //                   children: [
            //                     Expanded(child: Text(S.of(context).JIAGEYINGXIANG,style: YSColors.contentStyle(context),)),
            //                     Expanded(
            //                         child: Container(
            //                           alignment: Alignment.centerRight,
            //                           child: Text('2.00%',style: YSColors.subStyle(context),),
            //                         )
            //                     )
            //                   ],
            //                 ),
            //               )
            //             ],
            //           ),
            //         ),
            //         Container(
            //           margin: EdgeInsets.only(top: hsp(10)),
            //           width: conSize.maxWidth,
            //           decoration: BoxDecoration(
            //               color: YSColors.containColor(context),
            //               borderRadius: const BorderRadius.all(Radius.circular(10))
            //           ),
            //           padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
            //           child: Column(
            //             children: [
            //               SizedBox(
            //                 height: hsp(45),
            //                 child: Row(
            //                   children: [
            //                     Expanded(child: Text(S.of(context).ZUIJINDUIHUANJILU,style: YSColors.contentStyle(context),)),
            //                     Expanded(
            //                         child: Container(
            //                           alignment: Alignment.centerRight,
            //                           child: Text(S.of(context).GENGDUOJILU,style: YSColors.subStyle(context),),
            //                         )
            //                     )
            //                   ],
            //                 ),
            //               ),
            //               Divider(color: YSColors.lineColor(context),height: hsp(1),),
            //               const YSExchangeRecordListItemView(),
            //             ],
            //           ),
            //         )
            //       ],
            //     ),
            //   ),
            // ))
            if(_array.isNotEmpty)Container(
              margin: EdgeInsets.only(top: hsp(20)),
              width: conSize.maxWidth,
              decoration: BoxDecoration(
                  color: YSColors.containColor(context),
                  borderRadius: const BorderRadius.all(Radius.circular(10))
              ),
              padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
              child: Column(
                children: [
                  SizedBox(
                    height: hsp(45),
                    child: Row(
                      children: [
                        Expanded(child: Text(S.of(context).ZUIJINDUIHUANJILU,style: YSColors.contentStyle(context),)),
                        Expanded(
                            child: GestureDetector(
                              onTap: (){
                                Navigator.of(context).push(
                                    CupertinoPageRoute(builder: (context){
                                      return YSData().typeId=='TRON-HD'?const YSCrossRecord2():YSCrossRecord(item: _wallet1,);
                                    })
                                );
                              },
                              behavior: HitTestBehavior.opaque,
                              child: Container(
                                alignment: Alignment.centerRight,
                                child: Text(S.of(context).GENGDUOJILU,style: YSColors.subStyle(context),),
                              ),
                            )
                        )
                      ],
                    ),
                  ),
                  Divider(color: YSColors.lineColor(context),height: hsp(1),),
                  ListView.builder(
                    itemBuilder: (context,index){
                      Map item = _array[index];
                      return YSExchangeRecordListItemView2(item: item);
                    },
                    itemCount: _array.length>1?1:_array.length,
                    padding: const EdgeInsets.all(0),
                    physics: const NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                  ),
                ],
              ),
            )
          ],
        );
      }
    );
  }
  // _getCrossListData() async{
  //   YSNetWork.ysRequestHttp(context, type: RequestType.get, api: 'cross-txs', parameter: {'from_addr':_wallet1['address'],'page':1,'size':1}, successSetter: (dict){
  //     _array = dict['data']['list']??[];
  //     setState(() {});
  //   });
  // }
  _getCrossListData() async{
    YSNetWork.ysRequestHttp(context, type: RequestType.get, api: 'transactions',
        parameter: {'chain_id':YSData().typeId,'address':YSData().wallet['public'],'type':0,'page':1,'size':1},
      successSetter: (dict){
      _array = dict['data']['list']??[];
      setState(() {});
    });
  }

  _exchangeData() async{

    try{
      Wbe3Api? web = await Wbe3Api().getInstances();//_wallet2['decimal']
      // Map dataMap = _dict2['data'];
      Web3Client? client = Web3Client(_wallet1['parentRpc'], Client());
      String walletPublic = YSData().wallet['public'];
      String wall1Address = _wallet1['address'];
      String wall2Address = _wallet2['address'];
      String addressFileText = _addressField.text;
      if(!mounted)return;
      YSData().pancakeAddress = YSData().typeId=='ETH-HD'?'0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D':
      YSData().typeId=='TRON-HD'?'TKzxdSv2FZKQrEqkKVgp5DcwEXBEKMg2Ax':'0x10ED43C718714eb63d5aA57B78B54704E256024E';
      bool isTron = wall1Address.substring(0,1)=='T';
      if(isTron){
        double amountD = double.parse(_amountField.text);
        double number = amountD * pow(10, _wallet1['decimal']);
        String result = await YSTron.approveContractData(context, from: walletPublic, to: addressFileText, private: YSData().wallet['private'], amount: '$number', fromTokenAddress: wall1Address, toTokenAddress: wall2Address);
        if(result.isNotEmpty){
          _amountField.text = '';
          _changeIndex = 9999;
          _getCrossListData();
          return true;
          // setState(() {});
        }
        return false;
      }else{
        if(isTron){
          walletPublic = YSTron.changeAddress(walletPublic).replaceFirst('41', '0x');
          wall1Address = YSTron.changeAddress(wall1Address).replaceFirst('41', '0x');
          wall2Address = YSTron.changeAddress(wall2Address).replaceFirst('41', '0x');
          addressFileText = YSTron.changeAddress(addressFileText).replaceFirst('41', '0x');
          YSData().pancakeAddress = YSTron.changeAddress(YSData().pancakeAddress).replaceFirst('41', '0x');
        }
        DeployedContract? contract = await web!.fromAssets('asset/abi.json', wall1Address);
        LogUtil.d('allowance=============$walletPublic========$wall1Address========$wall2Address========$addressFileText');
        var allowance = await client.call(
          contract: contract,
          function: contract.function('allowance'),
          params: [
            EthereumAddress.fromHex(walletPublic),
            EthereumAddress.fromHex(YSData().pancakeAddress),
          ],
        );
        double amountD = double.parse(_amountField.text);
        // double number = amountD*pow(10, int.parse('18'));
        double number = amountD * pow(10, _wallet1['decimal']);
        // final gasprice = await client.getGasPrice();
        // number = number+gasprice.getValueInUnit(EtherUnit.wei);
        // return false;
        LogUtil.d('allowance=============${allowance.first}========$number');
        // return;
        if(double.parse('${allowance.first}')<number){
          BigInt amountValue = BigInt.from(number);
          LogUtil.d('approve=============$number ${_wallet1['decimal']} $amountValue');
          // BigInt amountValue = BigInt.from(number);
          var approve =  Transaction.callContract(
            contract: contract,
            function: contract.function('approve'),
            parameters: [
              EthereumAddress.fromHex(YSData().pancakeAddress),
              amountValue,
            ],
          );
          final networkId = await client.getNetworkId();
          LogUtil.d('allowance=============${approve.nonce}========$number');
          var txHash = '';
          if(isTron){
            Map request = {};
            request['tx'] = approve.data;
            String privateS = YSAes.aesEncode3('${YSData().wallet['private']}_${DateTime.now().microsecond}');
            request['prikey'] = privateS;
            // ignore: use_build_context_synchronously
            Map signDict = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'tronsign', parameter: request);
            if(signDict.isNotEmpty){

            }
          }else{
            final credentials = EthPrivateKey.fromHex(YSData().wallet['private']);
            txHash = await client.sendTransaction(
              credentials,
              approve,
              chainId: networkId,
            );
          }

          // return;
          TransactionReceipt? receipt = await client.getTransactionReceipt(txHash);
          LogUtil.d('approve=============$txHash');
          // return;
          double feeValue = double.parse(_amountField.text)*0.0001;
          var result = await web.tokenExchange(walletPublic, YSData().wallet['private'], feeValue.toStringAsFixed(8),_amountField.text,'${_wallet2['gas']}',
              wall2Address,_wallet1['parentRpc'],addressFileText,wall1Address);
          String resultStr = '$result';
          if(!mounted)return;
          if(resultStr.isNotEmpty){
            _amountField.text = '';
            _changeIndex = 9999;
            setState(() {});
            Map map = {};
            map['public'] = _wallet1['address'];
            map['balance'] = await Wbe3Api().getTokenBalance(walletPublic,wall1Address);
            if(!mounted)return;
            YSBalanceManager.notifier(context,map);
            return true;
          }
        }else{
          double feeValue = double.parse(_amountField.text)*0.0001;
          var result = await web.tokenExchange(walletPublic, YSData().wallet['private'], feeValue.toStringAsFixed(8),_amountField.text,'${_wallet2['gas']}',
              wall2Address,_wallet1['parentRpc'],addressFileText,wall1Address);
          String resultStr = '$result';
          if(!mounted)return;
          if(resultStr.isNotEmpty){
            _amountField.text = '';
            _changeIndex = 9999;
            setState(() {});
            Map map = {};
            map['public'] = _wallet1['address'];
            map['balance'] = await Wbe3Api().getTokenBalance(walletPublic,wall1Address);
            if(!mounted)return;
            YSBalanceManager.notifier(context,map);
            return true;
          }
        }
        return false;
      }
    }catch(e){
      LogUtil.d(e);
      ysFlutterToast('$e');
      return false;
    }
    // YSBip3().exchange(_wallet2['address']);
    // return false;
    // LogUtil.d(_wallet1);
    // return;
    // YSData().rpc = 'https://data-seed-prebsc-1-s1.binance.org:8545/';
    // Wbe3Api? web = await Wbe3Api().getInstances();//_wallet2['decimal']
    // double feeValue = double.parse(_amountField.text)*0.0001;
    // var result = await web.tokenExchange(_wallet1['address'], _wallet1['private'], feeValue.toStringAsFixed(8),_amountField.text,'${_wallet2['gas']}',
    //     _wallet2['address'],_wallet1['parentRpc'],_addressField.text,_wallet1['address']);
    // String resultStr = '$result';
    // if(!mounted)return;
    // if(resultStr.isNotEmpty){
    //   _amountField.text = '';
    //   _changeIndex = 9999;
    //   setState(() {});
    //   Map map = {};
    //   map['public'] = _wallet1['address'];
    //   map['balance'] = await Wbe3Api.getBalance(_wallet1['address']);
    //   if(!mounted)return;
    //   YSBalanceManager.notifier(context,map);
    //   return true;
    // }
    // return false;
  }
}

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

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

class YSCrossViewState extends State<YSCrossView> {
  final TextEditingController _amountField = TextEditingController();
  Map _coin = {};
  Map _wallet1 = {};
  Map _wallet2 = {};
  List _array = [];
  final TextEditingController _addressField = TextEditingController();
  int  _changeIndex = 9999;
  @override
  void initState() {
    _getWallet();
    super.initState();
  }
  _getWallet() async{
    Map item = YSData().typeArray.firstWhere((element) => element['id']==YSData().typeId);
    _wallet1 = {
      'icon_url':item['icon'],
      'bl_symbol':item['name'],
      'address':YSData().wallet['public'],
      'private':YSData().wallet['private'],
    };
    _getCoinData();
  }
  _getCoinData() async{
    YSNetWork.ysRequestHttp(context, type: RequestType.get, api: 'coins', parameter: {'page':'1','size':100,'symbol':_wallet1['bl_symbol']}, successSetter: (dict){
      YSData().coinArray = dict['data']['list']??[];
      _getCrossListData();
    });
  }
  @override
  void dispose() {
    _amountField.dispose();
    _addressField.dispose();
    super.dispose();
  }
  change() {
    Map temp = _wallet1;
    _wallet1 = _wallet2;
    _wallet2 = temp;
    setState(() {});
  }
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
        builder: (context,conSize) {
          return Column(
            children: [
              Container(
                width: conSize.maxWidth,
                decoration: BoxDecoration(
                    color: YSColors.containColor(context),
                    borderRadius: const BorderRadius.all(Radius.circular(10))
                ),
                padding: EdgeInsets.only(left: hsp(20),right: hsp(20),top: hsp(20),bottom: hsp(20)),
                alignment: Alignment.center,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      height: hsp(30),
                      alignment: Alignment.centerLeft,
                      child: Row(
                        children: [
                          Container(
                            constraints: BoxConstraints(
                                maxWidth: conSize.maxWidth-hsp(190)
                            ),
                            child: Text('${S.current.XUANZEXUYAOKUALIANDEZICHAN}  ',style: YSColors.subStyle(context),),
                          ),
                          GestureDetector(
                            onTap: (){
                              FocusScope.of(context).unfocus();
                              ysShowBottomAlertView(context,  YSCrossCoinChooseView(valueSetter: (value) async{
                                _coin = value;
                                // _coinbalance = double.parse(await Wbe3Api.getBalance(_coin['address']));
                                setState(() {});
                              },),isBarr: true);
                            },
                            behavior: HitTestBehavior.opaque,
                            child: Container(
                              width: hsp(150),
                              alignment: Alignment.centerLeft,
                              child: _coin.isNotEmpty?Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  ClipRRect(
                                    borderRadius: const BorderRadius.all(Radius.circular(50)),
                                    child: YSImage.network(_coin['icon_url'],height: hsp(30),width: hsp(30),),
                                  ),
                                  Text(' ${_coin['bl_symbol']}',style: YSColors.contentStyle(context),),
                                  Icon(Icons.arrow_drop_down,size: hsp(30),color: YSColors.sColor(context),)
                                ],
                              ):Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Text(S.current.QINGXUANZE,style: YSColors.contentStyle(context),),
                                  Icon(Icons.arrow_drop_down,size: hsp(30),color: YSColors.sColor(context),)
                                ],
                              ),
                            ),
                          )

                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(bottom: hsp(20)),
                      decoration: BoxDecoration(
                        border: Border(bottom: BorderSide(color: YSColors.lineColor(context),width: hsp(1)))
                      ),
                      child: Container(
                        margin: EdgeInsets.only(top: hsp(10),bottom: hsp(20)),
                        height: hsp(25),
                        child: Row(
                          children: [
                            Row(
                              children: [
                                SizedBox(
                                  width: hsp(40),
                                  child: Text('${S.current.YUE}:',style: YSColors.contentStyle(context),),
                                ),
                                SizedBox(
                                  width: hsp(100),
                                  // constraints: BoxConstraints(
                                  //     maxWidth: hsp(180)
                                  // ),
                                  child:_coin.isEmpty?const SizedBox():YSBalanceView(public: _coin['address'],style: YSColors.subStyle(context),key: Key(_coin['address']),type: 1,walletAddress: _wallet1['address'],dymic: 4,),
                                )
                              ],
                            ),
                            Container(
                              width: conSize.maxWidth-hsp(210),
                              alignment: Alignment.centerLeft,
                              decoration: BoxDecoration(
                                color: YSColors.contain2Color(context),
                                borderRadius: const BorderRadius.all(Radius.circular(5)),
                              ),
                              padding: EdgeInsets.only(left: hsp(10),right: hsp(10)),
                              child: CupertinoTextField(
                                placeholder: S.current.QINGSHURUKUALIANZICHANSHULIANG,
                                style: YSColors.subStyle(context),
                                padding: const EdgeInsets.all(0),
                                decoration: const BoxDecoration(),
                                inputFormatters: [YSNumberWithDecimalFormat()],
                                keyboardType: TextInputType.number,
                                controller: _amountField,
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: hsp(10),bottom: hsp(10)),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          GestureDetector(
                            onTap: (){
                              FocusScope.of(context).unfocus();
                              ysShowBottomAlertView(context,  YSExchangeTypeChooseView1(valueSetter: (value){
                                _wallet1 = value;
                                _coin.clear();
                                setState(() {});
                                _getCrossListData();
                              },),isBarr: true);
                            },
                            behavior: HitTestBehavior.opaque,
                            child: Container(
                              alignment: Alignment.centerRight,
                              child: _wallet1.isNotEmpty?Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  ClipRRect(
                                    borderRadius: const BorderRadius.all(Radius.circular(50)),
                                    child: YSImage.network(_wallet1['icon_url'],height: hsp(30),width: hsp(30),),
                                  ),
                                  Container(
                                    constraints: BoxConstraints(
                                      maxWidth: ((ysWidth(context)-hsp(200))/2)
                                    ),
                                    child: SingleChildScrollView(
                                      scrollDirection: Axis.horizontal,
                                      child: Text(' ${_wallet1['bl_symbol']}',style: YSColors.contentStyle(context),),
                                    )
                                  ),
                                  Icon(Icons.arrow_drop_down,size: hsp(30),color: YSColors.sColor(context),)
                                ],
                              ):Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Container(
                                    constraints: BoxConstraints(
                                      maxWidth: ((ysWidth(context)-hsp(150))/2)
                                    ),
                                    child: SingleChildScrollView(
                                      scrollDirection: Axis.horizontal,
                                      child: Text(S.current.QINGXUANZE,style: YSColors.contentStyle(context),),
                                    )
                                  ),
                                  Icon(Icons.arrow_drop_down,size: hsp(30),color: YSColors.sColor(context),)
                                ],
                              ),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: hsp(8),right: hsp(8)),
                            child: GestureDetector(
                              onTap: (){
                                // change();
                              },
                              child: Image.asset(YSColors.imageStyle(context, '交换  反向'),height: hsp(30),width: hsp(30),),
                            ),
                          ),
                          GestureDetector(
                            onTap: (){
                              FocusScope.of(context).unfocus();
                              ysShowBottomAlertView(context,  YSExchangeTypeChooseView1(valueSetter: (value){
                                _wallet2 = value;
                                _addressField.text = _wallet2['address']??'';
                                setState(() {});
                              },),isBarr: true);
                            },
                            behavior: HitTestBehavior.opaque,
                            child: Container(
                              alignment: Alignment.centerRight,
                              child: _wallet2.isNotEmpty?Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  ClipRRect(
                                    borderRadius: const BorderRadius.all(Radius.circular(50)),
                                    child: YSImage.network(_wallet2['icon_url'],height: hsp(30),width: hsp(30),),
                                  ),
                                  Container(
                                      constraints: BoxConstraints(
                                          maxWidth: ((ysWidth(context)-hsp(200))/2)
                                      ),
                                      child: SingleChildScrollView(
                                        scrollDirection: Axis.horizontal,
                                        child: Text(' ${_wallet2['bl_symbol']}',style: YSColors.contentStyle(context),),
                                      )
                                  ),
                                  Icon(Icons.arrow_drop_down,size: hsp(30),color: YSColors.sColor(context),)
                                ],
                              ):Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Container(
                                      constraints: BoxConstraints(
                                        maxWidth: ((ysWidth(context)-hsp(150))/2)
                                      ),
                                      child: SingleChildScrollView(
                                        scrollDirection: Axis.horizontal,
                                        child: Text(S.current.QINGXUANZE,style: YSColors.contentStyle(context),),
                                      )
                                  ),
                                  Icon(Icons.arrow_drop_down,size: hsp(30),color: YSColors.sColor(context),)
                                ],
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: hsp(15)),
                      height: hsp(20),
                      decoration: BoxDecoration(
                          color: YSColors.contain2Color(context),
                          borderRadius: const BorderRadius.all(Radius.circular(4))
                      ),
                      child: Row(
                        children: [
                          Expanded(
                              child: CupertinoTextField(
                                placeholder: S.of(context).QINGSHURUHUOXUANZENINDEMUBIAOQIANBAODIZHI,
                                style: YSColors.subStyle(context),
                                padding: EdgeInsets.only(left: hsp(10),right: hsp(10)),
                                decoration: const BoxDecoration(),
                                controller: _addressField,
                              )
                          ),
                          GestureDetector(
                            onTap: (){
                              ysShowBottomAlertView(context,  YSExchangeTypeChooseView1(valueSetter: (value){
                                _addressField.text = value['address']??'';
                              },item: _wallet2,),isBarr: true);
                            },
                            behavior: HitTestBehavior.opaque,
                            child: Container(
                              width: hsp(50),
                              height: hsp(10),
                              decoration: BoxDecoration(
                                  border: Border(left: BorderSide(color: YSColors.lineColor(context),width: hsp(1)))
                              ),
                              child: Image.asset(YSColors.imageStyle(context, '钱包 (2)'),height: hsp(10),width: hsp(10),),
                            ),
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ),
              Container(
                height: hsp(25),
                margin: EdgeInsets.only(top: hsp(25),bottom: hsp(25)),
                child: ListView.separated(
                  itemBuilder: (context,index){
                    return GestureDetector(
                      onTap: () async{
                        if(_coin.isNotEmpty){
                          Wbe3Api? web = await Wbe3Api().getInstances();
                          String balanceStr = '0.0';
                          if('${_wallet1['address']}'.substring(0,1)=='T'){
                            String public = YSTron.changeAddress(_wallet1['address']).replaceFirst('41', '0x');
                            String walletAddress = YSTron.changeAddress(YSData().wallet['public']).replaceFirst('41', '0x');
                            balanceStr = (await Wbe3Api().getTokenBalance(walletAddress,public));
                          }else{
                            balanceStr = await Wbe3Api().getTokenBalance(YSData().wallet['public'],_wallet1['address']);
                          }
                          // String? balanceStr = await web?.getTokenBalance(_wallet1['address'],_coin['address']);
                          double balance = double.parse(balanceStr);
                          _amountField.text = (balance/100*((index+1)*25)).toStringAsFixed(4);
                          _changeIndex = index;
                          setState(() {});
                        }
                      },
                      child: Container(
                        height: hsp(25),
                        width: (conSize.maxWidth-hsp(90))/4,
                        decoration:  BoxDecoration(
                            color: _changeIndex==index?YSColors.selectedColor(context):const Color(0xFFE9EEFF),
                            borderRadius: const BorderRadius.all(Radius.circular(50)),
                            boxShadow: [
                              BoxShadow(color: YSColors.shadowColor(context),blurRadius: 3)
                            ]
                        ),
                        alignment: Alignment.center,
                        child: Text('${(index+1)*25}%',style: TextStyle(fontSize: zsp(14),color: _changeIndex==index?YSColors.containColor(context):YSColors.selectedColor(context)),),
                      ),
                    );
                  },
                  separatorBuilder: (context,index){
                    return Container(width: hsp(30),);
                  },
                  itemCount: 4,
                  scrollDirection: Axis.horizontal,
                ),
              ),
              GestureDetector(
                onTap: () async{
                  _crossData();
                },
                behavior: HitTestBehavior.opaque,
                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.SHOUQUAN}${_coin['bl_symbol']??''}',style: YSColors.buttonStyle(context),),
                ),
              ),
              Expanded(child: Padding(
                padding: EdgeInsets.only(top: hsp(25)),
                child: SingleChildScrollView(
                  padding: EdgeInsets.only(bottom: hsp(10)),
                  child: Column(
                    children: [
                      // Container(
                      //   width: conSize.maxWidth,
                      //   decoration: BoxDecoration(
                      //       color: YSColors.containColor(context),
                      //       borderRadius: const BorderRadius.all(Radius.circular(10))
                      //   ),
                      //   padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
                      //   child: Column(
                      //     children: [
                      //       SizedBox(
                      //         height: hsp(45),
                      //         child: Row(
                      //           children: [
                      //             Expanded(child: Text(S.of(context).DUIHUANBAOJIA,style: YSColors.contentStyle(context),)),
                      //             Expanded(
                      //                 child: Container(
                      //                   alignment: Alignment.centerRight,
                      //                   child: Text('1BTC≈15.966015ETH',style: YSColors.subStyle(context),),
                      //                 )
                      //             )
                      //           ],
                      //         ),
                      //       ),
                      //       Divider(color: YSColors.lineColor(context),height: hsp(1),),
                      //       Container(
                      //         alignment: Alignment.centerLeft,
                      //         height: hsp(30),
                      //         child: Row(
                      //           children: [
                      //             Expanded(child: Text(S.of(context).ZUIDAHUADONGCHAJIA,style: YSColors.contentStyle(context),)),
                      //             Expanded(
                      //                 child: Container(
                      //                   alignment: Alignment.centerRight,
                      //                   child: Text('2.00%',style: YSColors.subStyle(context),),
                      //                 )
                      //             )
                      //           ],
                      //         ),
                      //       ),
                      //       Container(
                      //         alignment: Alignment.centerLeft,
                      //         height: hsp(30),
                      //         child: Row(
                      //           children: [
                      //             Expanded(child: Text(S.of(context).SHOUXUFEI,style: YSColors.contentStyle(context),)),
                      //             Expanded(
                      //                 child: Container(
                      //                   alignment: Alignment.centerRight,
                      //                   child: Text('2.00%',style: YSColors.subStyle(context),),
                      //                 )
                      //             )
                      //           ],
                      //         ),
                      //       ),
                      //       Container(
                      //         alignment: Alignment.centerLeft,
                      //         height: hsp(30),
                      //         child: Row(
                      //           children: [
                      //             Expanded(child: Text(S.of(context).JIAGEYINGXIANG,style: YSColors.contentStyle(context),)),
                      //             Expanded(
                      //                 child: Container(
                      //                   alignment: Alignment.centerRight,
                      //                   child: Text('2.00%',style: YSColors.subStyle(context),),
                      //                 )
                      //             )
                      //           ],
                      //         ),
                      //       )
                      //     ],
                      //   ),
                      // ),
                      if(_array.isNotEmpty)Container(
                        // margin: EdgeInsets.only(top: hsp(10)),
                        width: conSize.maxWidth,
                        decoration: BoxDecoration(
                            color: YSColors.containColor(context),
                            borderRadius: const BorderRadius.all(Radius.circular(10))
                        ),
                        padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
                        child: Column(
                          children: [
                            SizedBox(
                              height: hsp(45),
                              child: Row(
                                children: [
                                  Expanded(child: Text(S.of(context).ZUIJINDUIHUANJILU,style: YSColors.contentStyle(context),)),
                                  Expanded(
                                      child: GestureDetector(
                                        onTap: (){
                                          Navigator.of(context).push(
                                              CupertinoPageRoute(builder: (context){
                                                return YSCrossRecord(item: _wallet1,);
                                              })
                                          );
                                        },
                                        behavior: HitTestBehavior.opaque,
                                        child: Container(
                                          alignment: Alignment.centerRight,
                                          child: Text(S.of(context).GENGDUOJILU,style: YSColors.subStyle(context),),
                                        ),
                                      )
                                  )
                                ],
                              ),
                            ),
                            Divider(color: YSColors.lineColor(context),height: hsp(1),),
                            ListView.builder(
                              itemBuilder: (context,index){
                                Map item = _array[index];
                                return YSExchangeRecordListItemView(item: item);
                              },
                              itemCount: _array.length>1?1:_array.length,
                              padding: const EdgeInsets.all(0),
                              physics: const NeverScrollableScrollPhysics(),
                              shrinkWrap: true,
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
              ))
            ],
          );
        }
    );
  }
  _getCrossListData() async{
    YSNetWork.ysRequestHttp(context, type: RequestType.get, api: 'cross-txs', parameter: {'from_addr':_wallet1['address'],'page':1,'size':1}, successSetter: (dict){
      _array = dict['data']['list']??[];
      setState(() {});
    });
  }
  Map _dict2 = {};
  _crossData() async{
    FocusScope.of(context).unfocus();
    if(_coin.isEmpty){
      ysFlutterToast('请选择需要转出的资产');
      return;
    }
    if(_amountField.text.isEmpty){
      ysFlutterToast('请输入转出的资产金额');
      return;
    }
    if(_wallet1.isEmpty){
      ysFlutterToast('请选择转出链');
      return;
    }
    if(_wallet2.isEmpty){
      ysFlutterToast('请选择转入链');
      return;
    }
    if(_addressField.text.isEmpty){
      ysFlutterToast('请选择目标钱包的地址');
      return;
    }
    if(!mounted)return;
    // String? tokenBStr = await wbe3api?.getTokenBalance(_wallet1['address'], _coin['address']);
    Map code = {'Bnbchain':'bsc','Ethereum':'eth','Tron':'tron','Nova':'nova'};
    if(_wallet1['bl_symbol']==_wallet2['bl_symbol'])return;
    YSNetWork.ysRequestHttp(context, type: RequestType.get, api: 'cross-configs', parameter: {},isLoading: true, successSetter: (dict){
      List list = dict['data']['list']??[];
      for (var element in list) {
        String key1 = code['${_wallet1['bl_symbol']}'];
        String key2 = code['${_wallet2['bl_symbol']}'];
        if(element['from_chain']==key1&&element['to_chain']==key2){
          if(element['fee_type']==1){
            double navaAmount = double.parse(_amountField.text);
            double fee = double.parse('${element['fee_amount']}');
            if(navaAmount<=fee){
              ysFlutterToast('钱包余额不足');
              return;
            }
          }
          Map request = {};
          request['symbol'] = '${_coin['bl_symbol']}'.toLowerCase();
          request['amount'] = _amountField.text;
          request['from_chain'] = key1;
          request['from_addr'] = _wallet1['address'];
          request['to_chain'] = key2;
          request['to_addr'] = _wallet2['address'];
          YSNetWork.ysRequestHttp(context, type: RequestType.post, api: 'cross-txs', parameter: request,isLoading: true, successSetter: (dict2) async{
              // _postCrossData(dict2);
              _dict2 = dict2;
              ysShowCenterAlertView(context, YSLoadView(funAction: _postCrossData,wallet: YSData().wallet,),isTrans: false);
          });
        }
      }}
    );
  }
  Future<bool> _postCrossData() async{
    Wbe3Api? wbe3api = await Wbe3Api().getInstances();
    Map dataMap = _dict2['data'];
    Web3Client? client = Web3Client(YSData().rpc, Client());
    DeployedContract? contract = await wbe3api?.fromAssets('asset/abi.json', _coin['address']);
    var allowance = await client.call(
      contract: contract!,
      function: contract.function('allowance'),
      params: [
        EthereumAddress.fromHex(_wallet1['address']),
        EthereumAddress.fromHex(dataMap['contract']),
      ],
    );
    double amountD = double.parse('${dataMap['tx']['amount']}');
    double number = amountD*10*int.parse('${_coin['decimal']}');
    if(double.parse('${allowance.first}')<number){
      bool isCheck = await YSAuthCheck().check();
      if(isCheck){
        BigInt amountValue = BigInt.from(double.parse('${dataMap['tx']['amount']}') * pow(10, _coin['decimal']));
        var approve =  Transaction.callContract(
          contract: contract,
          function: contract.function('approve'),
          parameters: [
            EthereumAddress.fromHex(dataMap['contract']),
            amountValue,
          ],
        );
        final networkId = await client.getNetworkId();
        final credentials = EthPrivateKey.fromHex(_wallet1['private']);
        var txHash = await client.sendTransaction(
          credentials,
          approve,
          chainId: networkId,
        );
        TransactionReceipt? receipt = await client.getTransactionReceipt(txHash);
        Uint8List bytes = hexToBytes(dataMap['data']!);
        String from = dataMap['tx']['from_addr'];
        String to = dataMap['contract'];
        // String fee = dataMap['tx']['fee_amount'];
        String amount = '0';//dataMap['tx']['amount'];
        Wbe3Api? web = await Wbe3Api().getInstances();
        web?.adppContaractDecimals(to);
        var result = await web?.signETHTransaction(from,to, YSData().wallet['private'], amount,'100000',data: bytes);
        if('$result'.isNotEmpty){
          return true;
        }
      }else{
        return false;
      }
    }else{
      Uint8List bytes = hexToBytes(dataMap['data']!);
      String from = dataMap['tx']['from_addr'];
      String to = dataMap['contract'];
      // String fee = dataMap['tx']['fee_amount'];
      String amount = '0';//dataMap['tx']['amount'];
      Wbe3Api? web = await Wbe3Api().getInstances();
      web?.adppContaractDecimals(to);
      var result = await web?.signETHTransaction(from,to, YSData().wallet['private'], amount, '100000',data: bytes);
      if('$result'.isNotEmpty){
        return true;
      }
    }
    return false;
  }
}

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

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

class YSPriceViewState extends State<YSPriceView> with SingleTickerProviderStateMixin{
  List _titleArray = [];
  // final List _siftArray = [
  //   {'title':S.current.MINGCHENG,'tag':1,'status':0},
  //   {'title':S.current.HCHENGJIAOE,'tag':2,'status':0},
  //   {'title':S.current.ZUIXINJIA,'tag':3,'status':0},
  //   {'title':S.current.HZHANGDIE,'tag':4,'status':0}
  // ];
  TabController? _tabController;
  bool _isTips = false;
  @override
  void initState() {
    networkDelay((){
      _getTitleArray();
    });
    super.initState();
  }
  _getTitleArray() async{
    YSNetWork.ysRequestHttp(context, type: RequestType.get, api: 'marketclass', parameter: {}, successSetter: (dict){
      Map data = dict['data'];
      _titleArray = data['list']??[];
      _tabController = TabController(
        vsync: this,
        length: _titleArray.length,
      );
      setState(() {});
    });
  }
  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: const BorderRadius.only(topLeft: Radius.circular(10),topRight: Radius.circular(10)),
      child: Container(
        color: YSColors.backgroundColor(context),
        padding: EdgeInsets.only(left: hsp(20),right: hsp(20)),
        child: LayoutBuilder(
          builder: (context,conSize) {
            return _tabController==null?Container():DefaultTabController(
              length: _titleArray.length,
              child: Column(
                children: [
                  SizedBox(
                    height: hsp(45),
                    child: TabBar(
                      controller: _tabController,
                      indicatorColor: Colors.transparent,
                      isScrollable: true,
                      indicatorWeight: hsp(1),
                      labelColor: YSColors.contentStyle(context).color,
                      tabs: _titleArray.map((f) {
                        return Tab(
                          child: Text(f['title']),
                        );
                      }).toList(),
                    ),
                  ),
                  // SizedBox(
                  //   height: hsp(45),
                  //   child: Row(
                  //     children: [
                  //       Expanded(
                  //           child: ListView.builder(
                  //             itemBuilder: (context,index){
                  //               Map item = _siftArray[index];
                  //               return Container(
                  //                 width: conSize.maxWidth/4,
                  //                 alignment: Alignment.center,
                  //                 child: YSSiftView(siftMap: item,valueSetter: (value){
                  //                   for (Map element in _siftArray) {
                  //                     element.remove('status');
                  //                   }
                  //                   item['status'] = value;
                  //                   if(item['tag']==1){
                  //
                  //                   }else if(item['tag']==2){
                  //
                  //                   }else if(item['tag']==3){
                  //
                  //                   }else if(item['tag']==4){
                  //
                  //                   }
                  //                   setState(() {});
                  //                 },key: Key('${item['tag']}${item['status']}'),),
                  //               );
                  //             },
                  //             itemCount: _siftArray.length,
                  //             scrollDirection: Axis.horizontal,
                  //             padding: const EdgeInsets.all(0),
                  //           )
                  //       )
                  //     ],
                  //   ),
                  // ),
                  if(_isTips==true)YSShowTipsView(tipStr: S.current.GAIDIZHIJINZHICHIBSC,callback: (){
                    _isTips = false;
                    setState(() {});
                  },),
                  SizedBox(
                    height: conSize.maxHeight-hsp(_isTips==false?90:130)+hsp(45),//45
                    child: TabBarView(
                      controller: _tabController,
                      children: _titleArray.map((f) {
                        return YSShopPriceDataView(item: f,);
                      }).toList(),
                    ),
                  )
                ],
              ),
            );
          }
        ),
      ),
    );
  }
}

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

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

class YSShopPriceDataViewState extends State<YSShopPriceDataView> {
  List _dataArray = [];
  @override
  Widget build(BuildContext context) {
    return YSRefreshLoad(
      url: 'marketlist',
      request: {'class':widget.item['class']},
      postData: (value) {
        _dataArray = value;
        setState(() {});
      },
      child: SingleChildScrollView(
        child: ListView.builder(
          itemBuilder: (context, index) {
            Map item = _dataArray[index];
            return YSShopListItemView(item: item,);
          },
          itemCount: _dataArray.length,
          padding: const EdgeInsets.all(0),
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
        ),
      ),
    );
  }
}
