import 'package:flutter/material.dart';
import 'package:flutter_wallet/tools/YSNetWork.dart';
import 'package:flutter_wallet/tools/YSSqflite.dart';

import '../../generated/l10n.dart';
import '../../login/view/YSHelpView.dart';
import '../../tools/YSAes.dart';
import '../../tools/YSAlertView.dart';
import '../../tools/YSBip2.dart';
import '../../tools/YSColors.dart';
import '../../tools/YSTools.dart';
import '../../tools/YSTron.dart';

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

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

class YSExchangeRecordListItemViewState extends State<YSExchangeRecordListItemView> {
  @override
  void initState() {
    networkDelay((){
      _getCoinData();
    });
    super.initState();
  }
  _getCoinData() async{
    YSNetWork.ysRequestHttp(context, type: RequestType.get, api: 'coins', parameter: {'symbol':widget.item['from_chain']}, successSetter: (dict1){
      List list1 = dict1['data']['list']??[];
      if(list1.isNotEmpty){
        widget.item['from_icon'] = list1.first['icon'];
      }
      YSNetWork.ysRequestHttp(context, type: RequestType.get, api: 'coins', parameter: {'symbol':widget.item['to_chain']}, successSetter: (dict2){
        List list2 = dict2['data']['list']??[];
        if(list2.isNotEmpty){
          widget.item['to_icon'] = list2.first['icon'];
        }
        setState(() {});
      });
    });

  }
  @override
  Widget build(BuildContext context) {
    String stateStr = widget.item['state']==1?'创建成功':widget.item['state']==2?'发起成功':widget.item['state']==4?'已发送夸链交易':widget.item['state']==6?'完成':'';
    return GestureDetector(
      onTap: (){
        ysShowBottomAlertView(context, YSCrossDetailAlertView(item: widget.item,),isBarr: true);
      },
      behavior: HitTestBehavior.opaque,
      child: Container(
        alignment: Alignment.centerLeft,
        child: Column(
          children: [
            SizedBox(
              height: hsp(45),
              child: Row(
                children: [
                  Expanded(child: Text(widget.item['create_time'],style: YSColors.contentStyle(context),)),
                  Expanded(
                      child: Container(
                        alignment: Alignment.centerRight,
                        child: Text(stateStr,style: YSColors.subStyle(context),),
                      )
                  )
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(bottom: hsp(15)),
              height: hsp(50),
              color: YSColors.contain2Color(context),
              padding: EdgeInsets.only(left: hsp(30),right: hsp(30)),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      if(widget.item['from_icon']!=null)ClipRRect(
                        borderRadius: const BorderRadius.all(Radius.circular(50)),
                        child: YSImage.network(widget.item['from_icon'],height: hsp(25),width: hsp(25),),
                      ),
                      Text(' ${widget.item['from_chain']}'.toUpperCase(),style: YSColors.contentStyle(context),)
                    ],
                  ),
                  Container(
                    height: hsp(20),
                    width: hsp(50),
                    // decoration: BoxDecoration(
                    //   color: YSColors.lineColor(context)
                    // ),
                    alignment: Alignment.center,
                    child: Icon(Icons.arrow_right_alt,size: hsp(20),color: YSColors.iconColor(context),),
                  ),
                  Row(
                    children: [
                      if(widget.item['to_icon']!=null)ClipRRect(
                        borderRadius: const BorderRadius.all(Radius.circular(50)),
                        child: YSImage.network(widget.item['to_icon'],height: hsp(25),width: hsp(25),),
                      ),
                      Text(' ${widget.item['to_chain']}'.toUpperCase(),style: YSColors.contentStyle(context),)
                    ],
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

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

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

class YSExchangeRecordListItemView2State extends State<YSExchangeRecordListItemView2> {
  @override
  void initState() {
    networkDelay((){
      _getCoinData();
    });
    super.initState();
  }
  _getCoinData() async{
    YSNetWork.ysRequestHttp(context, type: RequestType.get, api: 'coins', parameter: {'symbol':widget.item['symbol']}, successSetter: (dict1){
      List list1 = dict1['data']['list']??[];
      if(list1.isNotEmpty){
        widget.item['from_icon'] = list1.first['icon'];
      }
      YSNetWork.ysRequestHttp(context, type: RequestType.get, api: 'coins', parameter: {'symbol':widget.item['symbol']}, successSetter: (dict2){
        List list2 = dict2['data']['list']??[];
        if(list2.isNotEmpty){
          widget.item['to_icon'] = list2.first['icon'];
        }
        setState(() {});
      });
    });

  }
  @override
  Widget build(BuildContext context) {
    String stateStr = widget.item['state']==1?'创建成功':widget.item['state']==2?'发起成功':widget.item['state']==4?'已发送夸链交易':widget.item['state']==6?'完成':'';
    return GestureDetector(
      onTap: (){
        ysShowBottomAlertView(context, YSCrossDetailAlertView2(item: widget.item,),isBarr: true);
      },
      behavior: HitTestBehavior.opaque,
      child: Container(
        alignment: Alignment.centerLeft,
        child: Column(
          children: [
            SizedBox(
              height: hsp(45),
              child: Row(
                children: [
                  Expanded(child: Text(toDateFlex(widget.item['timestamp']),style: YSColors.contentStyle(context),)),
                  Expanded(
                      child: Container(
                        alignment: Alignment.centerRight,
                        child: Text(stateStr,style: YSColors.subStyle(context),),
                      )
                  )
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(bottom: hsp(15)),
              height: hsp(50),
              color: YSColors.containColor(context),
              padding: EdgeInsets.only(left: hsp(30),right: hsp(30)),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      if(widget.item['from_icon']!=null)ClipRRect(
                        borderRadius: const BorderRadius.all(Radius.circular(50)),
                        child: YSImage.network(widget.item['from_icon'],height: hsp(25),width: hsp(25),),
                      ),
                      Text(' ${widget.item['symbol']}'.toUpperCase(),style: YSColors.contentStyle(context),)
                    ],
                  ),
                  Container(
                    height: hsp(20),
                    width: hsp(50),
                    // decoration: BoxDecoration(
                    //   color: YSColors.lineColor(context)
                    // ),
                    alignment: Alignment.center,
                    child: Icon(Icons.arrow_right_alt,size: hsp(20),color: YSColors.iconColor(context),),
                  ),
                  Row(
                    children: [
                      if(widget.item['to_icon']!=null)ClipRRect(
                        borderRadius: const BorderRadius.all(Radius.circular(50)),
                        child: YSImage.network(widget.item['to_icon'],height: hsp(25),width: hsp(25),),
                      ),
                      Text(' ${widget.item['symbol']}'.toUpperCase(),style: YSColors.contentStyle(context),)
                    ],
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}




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

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

class YSCrossDetailAlertViewState extends State<YSCrossDetailAlertView> {
  List _list = [];
  Map _tx = {};
  @override
  void initState() {
   networkDelay((){_getCrossDetail();});
    super.initState();
  }
  _getCrossDetail() async{
    YSNetWork.ysRequestHttp(context, type: RequestType.get, api: 'cross-txs/${widget.item['id']}', parameter: {}, successSetter: (dict){
      _tx = dict['data']['tx'];
      _list = [
        {'title':'付款地址','value':_tx['from_addr'],'type':1},
        {'title':'授权地址','value':_tx['to_addr'],'type':1},
        {'title':'跨链资产','value':'${_tx['symbol']}'.toUpperCase(),'type':2},
        {'title':'授权数量','value':_tx['amount'],'type':3},
        {'title':'网络费','value':_tx['fee_amount'],'type':3}
      ];
      setState(() {});
      // if(_tx['symbol']!=null)_getTokenIcon(_tx['symbol']);
    });
  }
  _getTokenIcon(String symbol) {
    YSNetWork.ysRequestHttp(context, type: RequestType.get, api: 'coins', parameter: {'symbol':symbol}, successSetter: (dict){
      List list = dict['data']['list']??[];
      if(list.isNotEmpty){
        _tx['icon'] = list.first['icon'];
      }
      setState(() {});
    });
  }
  @override
  Widget build(BuildContext context) {
    String stateStr = _tx['state']==1?'创建成功':_tx['state']==2?'发起成功':_tx['state']==4?'已发送夸链交易':_tx['state']==6?'完成':'';
    LogUtil.d(widget.item);
    return Container(
      padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
      height: hsp(500),
      width: ysWidth(context),
      decoration: BoxDecoration(
        color: YSColors.containColor(context),
        borderRadius: const BorderRadius.only(topRight: Radius.circular(10),topLeft: Radius.circular(10))
      ),
      child: Column(
        children: [
          SizedBox(
            height: hsp(50),
            child: Row(
              children: [
                Container(width: hsp(30),),
                Expanded(child: Align(
                  alignment: Alignment.center,
                  child: Text('交易详情',style: YSColors.contentStyle(context),))
                ),
                GestureDetector(
                  onTap: (){
                    Navigator.pop(context);
                  },
                  child: Icon(Icons.close,size: hsp(20),color: YSColors.iconColor(context),),
                )
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: hsp(10),bottom: hsp(5)),
            height: hsp(60),
            width: hsp(60),
            decoration: widget.item['from_icon']!=null?BoxDecoration(
              color: Colors.white,
              image: DecorationImage(image: NetworkImage(widget.item['from_icon']),fit: BoxFit.fill),
              borderRadius: const BorderRadius.all(Radius.circular(50))
            ):const BoxDecoration(),
          ),
          Text('bakewallet.org',style: YSColors.subStyle(context),),
          Container(
            padding: EdgeInsets.only(top: hsp(15),bottom: hsp(10)),
            child: Text(stateStr,style: YSColors.titleStyle(context),)
          ),
          // Container(
          //   padding: EdgeInsets.all(hsp(15)),
          //   margin: EdgeInsets.only(left: hsp(20),right: hsp(20)),
          //   decoration: const BoxDecoration(
          //     color: Color(0xFFFBE7E7),
          //     borderRadius: BorderRadius.all(Radius.circular(5))
          //   ),
          //   child: Row(
          //     children: [
          //       Expanded(
          //         child: Text('注意！授权此权限后，改合约将会获得您的USDT的转账权限，'
          //             '如果该合约为恶意合约，会有被盗的风险，请务必确认当前链接是可信赖的！',style: TextStyle(fontSize: zsp(11),color: const Color(0xFFD26967)),),
          //       ),
          //       Container(
          //         alignment: Alignment.center,
          //         width: hsp(20),
          //         child: Icon(Icons.chevron_right,size: hsp(20),color: const Color(0xFFD26967),),
          //       )
          //     ],
          //   ),
          // ),
          ListView.separated(
            itemBuilder: (context,index){
              Map item = _list[index];
              int type = item['type'];
              return GestureDetector(
                onTap: (){
                  if(type==1){
                    YSCopyPaste.copy(item['value']);
                  }
                },
                behavior: HitTestBehavior.opaque,
                child: Padding(
                  padding: EdgeInsets.only(top: hsp(10),bottom: hsp(10)),
                  child: Row(
                    children: [
                      Container(
                        width: hsp(100),
                        alignment: Alignment.center,
                        child: Text(item['title'],style: YSColors.contentStyle(context),),
                      ),
                      Expanded(
                        child: Text(item['value'],style: type==1?TextStyle(fontSize: zsp(14),color: Colors.blue):YSColors.subStyle(context))
                      ),
                    ],
                  ),
                ),
              );
            }, 
            separatorBuilder: (context,index){
              return Divider(height: hsp(1),color: YSColors.lineColor(context),);
            }, 
            itemCount: _list.length,
            shrinkWrap: true,
            padding: EdgeInsets.only(top: hsp(10)),
            physics: const NeverScrollableScrollPhysics(),
          )
        ],
      ),
    );
  }
}

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

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

class YSCrossDetailAlertView2State extends State<YSCrossDetailAlertView2> {
  List _list = [];
  String _statusStr = '';
  @override
  void initState() {
    networkDelay((){_getCrossDetail();});
    super.initState();
  }
  _getCrossDetail() async{
    // LogUtil.d(widget.item);
    // return;
    _list = [
      {'title':'付款地址','value':widget.item['from_addr'],'type':1},
      {'title':'授权地址','value':widget.item['to_addr'],'type':1},
      {'title':'授权资产','value':'${widget.item['symbol']}'.toUpperCase(),'type':2},
      {'title':'授权哈希','value':widget.item['hash'],'type':3},
    ];
    _getTokenStatus();
  }
  _getTokenStatus() async{
    Map dict = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'tron/approve/check', parameter: {'hash':widget.item['hash']});
    if(dict.isNotEmpty){
      Map data = dict['data']??{};
      _statusStr = data.isNotEmpty?'授权已确认':'授权未确认';
      setState(() {});
    }
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      height: hsp(500),
      width: ysWidth(context),
      decoration: BoxDecoration(
          color: YSColors.containColor(context),
          borderRadius: const BorderRadius.only(topRight: Radius.circular(10),topLeft: Radius.circular(10))
      ),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
            height: hsp(450),
            child: Column(
              children: [
                SizedBox(
                  height: hsp(50),
                  child: Row(
                    children: [
                      Container(width: hsp(30),),
                      Expanded(child: Align(
                          alignment: Alignment.center,
                          child: Text('交易详情',style: YSColors.contentStyle(context),))
                      ),
                      GestureDetector(
                        onTap: (){
                          Navigator.pop(context);
                        },
                        child: Icon(Icons.close,size: hsp(20),color: YSColors.iconColor(context),),
                      )
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: hsp(10),bottom: hsp(5)),
                  height: hsp(60),
                  width: hsp(60),
                  decoration: widget.item['from_icon']!=null?BoxDecoration(
                      color: Colors.white,
                      image: DecorationImage(image: NetworkImage(widget.item['from_icon']),fit: BoxFit.fill),
                      borderRadius: const BorderRadius.all(Radius.circular(50))
                  ):const BoxDecoration(),
                ),
                Text('bakewallet.org',style: YSColors.subStyle(context),),
                Container(
                    padding: EdgeInsets.only(top: hsp(15),bottom: hsp(10)),
                    child: Text(_statusStr,style: YSColors.titleStyle(context),)
                ),
                // Container(
                //   padding: EdgeInsets.all(hsp(15)),
                //   margin: EdgeInsets.only(left: hsp(20),right: hsp(20)),
                //   decoration: const BoxDecoration(
                //     color: Color(0xFFFBE7E7),
                //     borderRadius: BorderRadius.all(Radius.circular(5))
                //   ),
                //   child: Row(
                //     children: [
                //       Expanded(
                //         child: Text('注意！授权此权限后，改合约将会获得您的USDT的转账权限，'
                //             '如果该合约为恶意合约，会有被盗的风险，请务必确认当前链接是可信赖的！',style: TextStyle(fontSize: zsp(11),color: const Color(0xFFD26967)),),
                //       ),
                //       Container(
                //         alignment: Alignment.center,
                //         width: hsp(20),
                //         child: Icon(Icons.chevron_right,size: hsp(20),color: const Color(0xFFD26967),),
                //       )
                //     ],
                //   ),
                // ),
                ListView.separated(
                  itemBuilder: (context,index){
                    Map item = _list[index];
                    int type = item['type'];
                    return GestureDetector(
                      onTap: (){
                        if(type==1){
                          YSCopyPaste.copy(item['value']);
                        }
                      },
                      behavior: HitTestBehavior.opaque,
                      child: Padding(
                        padding: EdgeInsets.only(top: hsp(10),bottom: hsp(10)),
                        child: Row(
                          children: [
                            Container(
                              width: hsp(100),
                              alignment: Alignment.center,
                              child: Text(item['title'],style: YSColors.contentStyle(context),),
                            ),
                            Expanded(
                                child: Text(item['value'],style: type==1?TextStyle(fontSize: zsp(14),color: Colors.blue):YSColors.subStyle(context))
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                  separatorBuilder: (context,index){
                    return Divider(height: hsp(1),color: YSColors.lineColor(context),);
                  },
                  itemCount: _list.length,
                  shrinkWrap: true,
                  padding: EdgeInsets.only(top: hsp(10)),
                  physics: const NeverScrollableScrollPhysics(),
                )
              ],
            ),
          ),
          if(_statusStr=='授权已确认')GestureDetector(
            onTap: () async{
              ysShowCenterAlertView(context, YSLoadView(funAction: _exchangeData,wallet: YSData().wallet,successStr: S.current.DUIHUANTIJIAOCHENGGONG,
                failStr: S.current.DUIHUANTIJIAOSHIBAI,),isTrans: false);


            },
            child: Container(
              height: hsp(50),
              decoration: BoxDecoration(
                  color: YSColors.buttonColor(context),
              ),
              alignment: Alignment.center,
              child: Text(S.of(context).DUIHUAN,style: YSColors.buttonStyle(context),),
            ),
          )
        ],
      ),
    );
  }

  _exchangeData() async{
    List list = await YSTronTable().rawQuery();
    // LogUtil.d(widget.item);
    // LogUtil.d(list);
    List array = list.where((element) => element['hash']==widget.item['hash']).toList();
    if(array.isNotEmpty){
      Map arrayMap = array.first;
      String fromAddress = arrayMap['from_addr'];
      String toAddress = arrayMap['to_addr'];
      String fromTokenAddress = arrayMap['from_token_addr'];
      String toTokenAddress = arrayMap['to_token_addr'];
      int amount = int.parse(arrayMap['amount']);
      String hash = arrayMap['hash'];
      // ignore: use_build_context_synchronously
      Map result1 = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'tron/query/swap', parameter: {
        "amount":amount                                       //转账金额 要和授权的保持一致
        ,"from_token":fromTokenAddress      //转出token
        ,"to_token":toTokenAddress        //转入token
        ,"owner_address":fromAddress   //钱包地址
      });
      if(result1.isNotEmpty){
        int result1Data = result1['data'];
        // ignore: use_build_context_synchronously
        Map result2 = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'tron/myres', parameter: {
          'owner_address': fromAddress,
        });
        if(result2.isNotEmpty){
          Map result2Data = result2['data'];
          int network_rate = result2Data['network_rate'];
          int rest_energy = result2Data['rest_energy'];
          int limit = (result1Data*network_rate*1.1)~/1;
          String privateS = YSAes.aesEncode3('${YSData().wallet['private']}_${DateTime.now().microsecond}');
          //ignore: use_build_context_synchronously
          Map result3 = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'tron/doswap', parameter: {
            "prikey":privateS,                                            //私钥，要进行aes加密
            "amount":amount                                      //转出金额
            ,"from_token":fromTokenAddress     //转出token
            ,"to_token":toTokenAddress        //转入token
            ,"owner_address":fromAddress   //钱包地址
            ,"limit":limit                                     //最大费用
          });
          if(result3.isNotEmpty){
            String result3Data = result3['data']??'';
            if(result3Data.isNotEmpty){
              Map map = {};
              fromAddress = YSTron.changeAddress(fromAddress).replaceFirst('41', '0x');
              fromTokenAddress = YSTron.changeAddress(fromTokenAddress).replaceFirst('41', '0x');
              map['public'] = fromAddress;
              map['balance'] = await Wbe3Api().getTokenBalance(fromAddress,fromTokenAddress);
              // ignore: use_build_context_synchronously
              YSBalanceManager.notifier(context,map);
              return true;
              return result3Data;
            }
          }
        }
      }
    }
    return false;
  }
}

