import 'package:dart_ping/dart_ping.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wallet/base/YSBase.dart';
import 'package:flutter_wallet/generated/l10n.dart';
import 'package:flutter_wallet/login/view/YSHelpView.dart';
import 'package:flutter_wallet/tools/YSAlertView.dart';
import 'package:flutter_wallet/tools/YSColors.dart';
import 'package:flutter_wallet/tools/YSTools.dart';
import 'package:flutter_wallet/wallet/view/YSWalletManagerListItemView.dart';
import 'package:provider/provider.dart';

import '../tools/YSPingView.dart';
import '../tools/YSSqflite.dart';
import 'YSWalletDetail.dart';
import 'YSWalletRocChoose.dart';

class YSWalletManager extends StatefulWidget {
  final bool isChoose;
  const YSWalletManager({Key? key,  this.isChoose = false}) : super(key: key);

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

class YSWalletManagerState extends State<YSWalletManager> {
  List _walletArray = [];
  bool _isDrag = false;
  @override
  void initState() {
    _getWalletData();
    super.initState();
  }
  _getWalletData() async{
    YSSqflite sqflite = YSSqflite().init();
    _walletArray = await sqflite.rawQuery();
    if(!mounted)return;
    YSSqflite.notifier(context, _walletArray);
  }
  @override
  Widget build(BuildContext context) {
    return YSBase2(
      titleType: 2,
      ysRightWidget: const YSCapsule(),
      ysChild: Padding(
        padding: EdgeInsets.only(left: hsp(20),right: hsp(20)),
        child: Column(
          children: [
            SizedBox(
              height: hsp(50),
              child: Row(
                children: [
                  Text('${S.current.QIANBAOGUANLI2}  ',style: YSColors.title2Style(context),),
                  GestureDetector(
                    onTap: (){
                      _isDrag = !_isDrag;
                      // _walletArray = _walletArray.reversed.toList();
                      setState(() {});
                    },
                    child: Transform.rotate(angle: _isDrag?3.14:0,child: Image.asset(YSColors.imageStyle(context, '排序'),height: hsp(17),width: hsp(17),),)
                  ),
                  const YSPingView(),
                  const Expanded(child: SizedBox()),
                  GestureDetector(
                    onTap: (){
                      YSData().isManager = true;
                      ysShowBottomAlertView(context, const YSChooseWalletType());
                    },
                    child: Image.asset(YSColors.imageStyle(context, '添 加'),height: hsp(17),width: hsp(17),),
                  )
                ],
              ),
            ),
            Consumer(
              builder: (context,YSWalletNotifier value,child) {
                _walletArray = value.walletArray;
                return ListView.separated(
                  itemBuilder: (context,index){
                    Map item = _walletArray[index];
                    return _isDrag==true?LongPressDraggable(
                      onDragEnd: (DraggableDetails detail) async{
                        int moveIndex = (detail.offset.dy-130)~/hsp(70);
                        if(moveIndex<_walletArray.length&&moveIndex!=index){
                          Map moveItem = _walletArray[moveIndex];
                          int itemSort = item['sort'];
                          int moveSort = moveItem['sort'];
                          YSSqflite sq = YSSqflite().init();
                          sq.rawUpdate(YSWalletDbData(moveItem['name'],moveItem['password'] , moveItem['word'], moveItem['private'],
                              moveItem['public'],moveItem['chooseType']), itemSort, '${moveItem['id']}');
                          sq.rawUpdate(YSWalletDbData(item['name'],item['password'] , item['word'], item['private'],
                              item['public'],item['chooseType']), moveSort, '${item['id']}');
                          List array2 = await sq.rawQuery();
                          if(!mounted)return;
                          YSSqflite.notifier(context, array2);
                        }
                      },
                      feedback: YSWalletManagerListItemView(item: item,isDetail: true),
                      child: YSWalletManagerListItemView(item: item,isDetail: true,),
                    ):GestureDetector(
                      onTap: () async{
                        if(widget.isChoose){
                          Navigator.of(context).pop(item);
                        }else{
                          YSSqflite sq = YSSqflite().init();
                          List array = await sq.rawQuery();
                          Map chooseItem = array.firstWhere((element) => element['chooseType']==1,orElse: ()=>{});
                          if(chooseItem.isNotEmpty){
                            sq.rawUpdate(YSWalletDbData(chooseItem['name'],chooseItem['password'] , chooseItem['word'], chooseItem['private'],
                                chooseItem['public'],0),chooseItem['sort'],'${chooseItem['id']}');
                          }
                          sq.rawUpdate(YSWalletDbData(item['name'],item['password'] , item['word'], item['private'], item['public'],1),item['sort'],'${item['id']}');
                          List array2 = await sq.rawQuery();
                          if(!mounted)return;
                          YSData().wallet = item;
                          YSSqflite.notifier(context, array2);
                          addToken(context);
                          Navigator.pop(context);
                        }
                      },
                      behavior: HitTestBehavior.opaque,
                      child: YSWalletManagerListItemView(item: item,isDetail: true,),
                    );
                  },
                  separatorBuilder: (context,index){
                    return Container(height: hsp(20),);
                  },
                  itemCount: _walletArray.length,
                  padding: EdgeInsets.only(top: hsp(5),bottom: hsp(10)),
                  physics: const NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                );
              }
            )
          ],
        ),
      ),
    );
  }
}



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

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

class YSWalletManager2State extends State<YSWalletManager2> {
  int _index = 0;
  List _walletArray = [];
  bool _isDrag = false;
  @override
  void initState() {
    _getWalletData();
    super.initState();
  }
  _getWalletData() async{
    YSSqflite sqflite = YSSqflite().init();
    String tabName = '${YSData().typeArray[_index]['name']}'.replaceAll('-', '').replaceAll(' ', '');
    _walletArray = await sqflite.rawQuery(name: tabName);
    if(!mounted)return;
    YSSqflite.notifier(context, _walletArray);
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ysTitle: S.current.QIANBAOGUANLI,
      ysRightWidget: GestureDetector(
        onTap: (){
          _isDrag = !_isDrag;
          setState(() {});
        },
        child: Text(_isDrag?S.current.WANCHENG:S.current.PAIXU),
      ),
      ysChild: SizedBox(
        width: ysWidth(context),
        height: ysHeight(context)-ysTOP(context)-60,
        child: Row(
          children: [
            Container(
              color: const Color(0xFFF1F3F7),
              height: ysHeight(context)-ysTOP(context)-60,
              width: hsp(60),
              child: ListView.builder(
                itemBuilder: (context,index){
                  Map item = YSData().typeArray[index];
                  // LogUtil.d(item);
                  return GestureDetector(
                    onTap: (){
                      _index = index;
                      _getWalletData();
                      setState(() {});
                    },
                    child: Container(
                      color: _index==index?Colors.white:Colors.transparent,
                      padding: EdgeInsets.only(left: hsp(15),right: hsp(15),bottom: hsp(15),top: hsp(15)),
                      child: YSImage.network(item['icon'],height: hsp(30),width: hsp(30),),
                    ),
                  );
                },
                itemCount: YSData().typeArray.length,
                padding: const EdgeInsets.all(0),
              ),
            ),
            Container(
              color: Colors.white,
              width: ysWidth(context)-hsp(60),
              child: Consumer(
                  builder: (context,YSWalletNotifier value,child) {
                    _walletArray = value.walletArray;
                    return ListView.builder(
                      itemBuilder: (context,index){
                        Map item = _walletArray[index];
                        return _isDrag==true?LongPressDraggable(
                          onDragEnd: (DraggableDetails detail) async{
                            int moveIndex = (detail.offset.dy-ysTOP(context)-60)~/hsp(70);
                            String tabName = '${YSData().typeArray[_index]['name']}'.replaceAll('-', '').replaceAll(' ', '');
                            if(moveIndex<_walletArray.length&&moveIndex!=index){
                              Map moveItem = _walletArray[moveIndex];
                              int itemSort = item['sort'];
                              int moveSort = moveItem['sort'];
                              YSSqflite sq = YSSqflite().init(name: tabName);
                              LogUtil.d('$moveItem======$itemSort $item======$moveSort');
                              sq.rawUpdate(YSWalletDbData(moveItem['name'],moveItem['password'] , moveItem['word'], moveItem['private'],
                                  moveItem['public'],moveItem['chooseType']), itemSort, '${moveItem['id']}',name: tabName);
                              sq.rawUpdate(YSWalletDbData(item['name'],item['password'] , item['word'], item['private'],
                                  item['public'],item['chooseType']), moveSort, '${item['id']}',name: tabName);
                              List array2 = await sq.rawQuery(name: tabName);
                              LogUtil.d('$array2');
                              if(!mounted)return;
                              YSSqflite.notifier(context, array2);
                            }
                          },
                          feedback: Padding(
                            padding: EdgeInsets.only(bottom: hsp(20)),
                            child: Row(
                              children: [
                                Padding(
                                  padding: EdgeInsets.only(right: hsp(10)),
                                  child: YSWalletManagerItem2View(item: item,width: ysWidth(context)-hsp(130)),
                                ),
                                Icon(Icons.menu,size: hsp(30),color: Colors.grey.withOpacity(0.5),)
                              ],
                            ),
                          ),
                          childWhenDragging: Container(height: hsp(90),),
                          child: Padding(
                            padding: EdgeInsets.only(bottom: hsp(20)),
                            child: Row(
                              children: [
                                Padding(
                                  padding: EdgeInsets.only(right: hsp(10)),
                                  child: YSWalletManagerItem2View(item: item,width: ysWidth(context)-hsp(130)),
                                ),
                                Icon(Icons.menu,size: hsp(30),color: Colors.grey.withOpacity(0.5),)
                              ],
                            ),
                          ),
                        ):GestureDetector(
                          onTap: () async{
                            Navigator.of(context).push(
                                CupertinoPageRoute(builder: (context){
                                  return YSWalletDetail(wallet: item,);
                                },)
                            );
                          },
                          behavior: HitTestBehavior.opaque,
                          child: Padding(
                            padding: EdgeInsets.only(bottom: hsp(20)),
                            child: YSWalletManagerItem2View(item: item,width: ysWidth(context)-hsp(90)),
                          )
                        );
                      },
                      itemCount: _walletArray.length,
                      padding: EdgeInsets.only(top: hsp(15),bottom: hsp(15),left: hsp(15),right: hsp(15)),
                    );
                  }
              )
              ,
            )
          ],
        ),
      ),
    );
  }
}

class YSWalletManagerItem2View extends StatelessWidget {
  final Map item;
  final double width;
  const YSWalletManagerItem2View({Key? key, required this.item, required this.width}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      height: hsp(70),
      padding: EdgeInsets.all(hsp(10)),
      decoration: BoxDecoration(
          color: Colors.black,
          borderRadius: const BorderRadius.all(Radius.circular(10)),
          boxShadow: [
            BoxShadow(color: YSColors.shadowColor(context),blurRadius: 5)
          ]
      ),
      child: Row(
        children: [
          Expanded(child: Padding(
            padding: EdgeInsets.only(right: hsp(10),left: hsp(10)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    RichText(text: TextSpan(
                      text: '${item['name']}',
                      style: YSColors.contentStyle(context),
                      children: [
                        WidgetSpan(child: YSTagView(wallet: item,),alignment: PlaceholderAlignment.middle)
                      ]
                    )),
                    if(item['chooseType']==1)Icon(Icons.check_circle,size: hsp(20),color: YSColors.iconColor(context),)
                  ],
                ),
                Padding(
                  padding: EdgeInsets.only(top: hsp(5)),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Container(
                            constraints: BoxConstraints(
                                maxWidth: ysWidth(context)/2
                            ),
                            child: Text(ysTextCut(item['public']),style: YSColors.subStyle(context),maxLines: 1,),
                          ),
                          GestureDetector(
                            onTap: (){
                              YSCopyPaste.copy(item['public']);
                            },
                            child: Image.asset(YSColors.imageStyle(context, '复制'),height: hsp(15),width: hsp(15),),
                          )
                        ],
                      ),
                      // Text('10.1 Layer3',style: TextStyle(fontSize: zsp(8),color: const Color(0xFF3D5AFF)),),
                    ],
                  ),
                )
              ],
            ),
          )),
        ],
      ),
    );
  }
}

