import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wallet/base/YSBase.dart';
import 'package:flutter_wallet/find/YSLoadUrl.dart';
import 'package:flutter_wallet/find/view/YSBannerView.dart';
import 'package:flutter_wallet/generated/l10n.dart';
import 'package:flutter_wallet/tools/YSColors.dart';
import 'package:flutter_wallet/tools/YSNetWork.dart';
import 'package:flutter_wallet/tools/YSRefrehLoad.dart';
import 'package:provider/provider.dart';
import 'package:skeletons/skeletons.dart';
import '../tools/YSTools.dart';

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

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

class YSFindState extends State<YSFind> with SingleTickerProviderStateMixin,AutomaticKeepAliveClientMixin{
  List _titles = [];
  TabController? _tabController;
  _getTitleData() async{
    YSNetWork.ysRequestHttp(context, type: RequestType.get, api: 'dapptypes', parameter: {}, successSetter: (dict){
      _titles = dict['data']['list']??[];
      _tabController = TabController(
        vsync: this,
        length: _titles.length,
      );
      setState(() {});
    });
  }
  @override
  void initState() {
    networkDelay((){
      _getTitleData();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return YSBase(
      // backgroundColor: YSColors.containColor(context),
      isTab: true,
      ysTitle: S.current.FAXIAN,
      ysChild: SingleChildScrollView(
        padding: EdgeInsets.only(top: hsp(10),left: hsp(15),right: hsp(15)),
        child: Skeleton(
          isLoading: _tabController==null,
          skeleton: Column(
            children: [
              SkeletonAvatar(
                style: SkeletonAvatarStyle(
                    width: double.infinity,
                    height: hsp(40)
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: hsp(15),bottom: hsp(15)),
                child: SkeletonAvatar(
                  style: SkeletonAvatarStyle(
                      width: double.infinity,
                      height: ysWidth(context)/3
                  ),
                ),
              ),
              SkeletonAvatar(
                style: SkeletonAvatarStyle(
                    width: double.infinity,
                    height: hsp(50)
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: hsp(15)),
                child: Row(
                  children: [
                    SkeletonAvatar(
                      style: SkeletonAvatarStyle(
                        width: hsp(50),
                        height: hsp(50),
                        borderRadius: const BorderRadius.all(Radius.circular(50))
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
                      child: SkeletonAvatar(
                        style: SkeletonAvatarStyle(
                            width: hsp(50),
                            height: hsp(50),
                            borderRadius: const BorderRadius.all(Radius.circular(50))
                        ),
                      ),
                    ),
                    SkeletonAvatar(
                      style: SkeletonAvatarStyle(
                          width: hsp(50),
                          height: hsp(50),
                          borderRadius: const BorderRadius.all(Radius.circular(50))
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
          child: Column(
            children: [
              SizedBox(
                height: hsp(40),
                child: Row(
                  children: [
                    Container(
                      width: ysWidth(context)-hsp(60),
                      padding: EdgeInsets.only(left: hsp(10),right: hsp(10)),
                      decoration: BoxDecoration(
                        color: YSColors.contain2Color(context),
                        borderRadius: const BorderRadius.all(Radius.circular(5))
                      ),
                      child: CupertinoTextField(
                        placeholder: S.current.QINGSHURUWANGZHI,
                        style: YSColors.contentStyle(context),
                        decoration: const BoxDecoration(),
                        prefix: Image.asset(YSColors.imageStyle(context, '搜索 (6)'),height: hsp(15),width: hsp(15),),
                        textInputAction: TextInputAction.done,
                        onSubmitted: (value){
                          FocusScope.of(context).unfocus();
                          if(value.isNotEmpty){
                            intoPage(context,value);
                          }
                        },
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: hsp(10)),
                      child: GestureDetector(
                        onTap: () async{
                          String result = await YSCodeImage.scanCode();
                          if(result.isNotEmpty&&mounted){
                            intoPage(context,result);
                          }
                        },
                        child: Image.asset(YSColors.imageStyle(context, '扫码 (3)'),height: hsp(20),width: hsp(20),),
                      )
                    ),
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: hsp(15),bottom: hsp(15)),
                height: ysWidth(context)/3,
                child: Consumer(
                  builder: (BuildContext context, CurrentLocale value, Widget? child) {
                    return YSBannerView(key: Key(value.locale.languageCode),);
                  },
                ),
              ),
              SizedBox(
                height: ysHeight(context)-ysTOP(context)-hsp(200)-ysWidth(context)/3,
                width: ysWidth(context),
                child: _tabController!=null?DefaultTabController(
                  length: _titles.length,
                  child: Column(
                    children: [
                      SizedBox(
                        height: hsp(50),
                        child: TabBar(
                          controller: _tabController,
                          indicatorColor: YSColors.selectedColor(context),
                          isScrollable: true,
                          indicatorWeight: hsp(1),
                          tabs: _titles.map((f) {
                            return Tab(
                              child: Text(f['name'],style: YSColors.contentStyle(context),),
                            );
                          }).toList(),
                        ),
                      ),
                      SizedBox(
                        height: ysHeight(context)-ysTOP(context)-hsp(250)-ysWidth(context)/3,
                        child: TabBarView(
                          controller: _tabController,
                          children: _titles.map((f) {
                            return YSFindDataView(item: f,);
                          }).toList(),
                        ),
                      )
                    ],
                  ),
                ):Container(),
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

intoPage(BuildContext context,String url) {
  Navigator.of(context).push(
      CupertinoPageRoute(builder: (context){
        return YSLoadUrl(url: url);
      })
  );
}

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

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

class YSFindDataViewState extends State<YSFindDataView> {
  List _dataArray = [];
  @override
  Widget build(BuildContext context) {
    double width = (ysWidth(context)-hsp(90))/5;
    return YSRefreshLoad(
      url: 'dapps',
      request: {'type':widget.item['type']},
      postData: (value) {
        _dataArray = value;
        setState(() {});
      },
      child: SingleChildScrollView(
        padding: EdgeInsets.only(top: hsp(15)),
        child: GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 5,
              crossAxisSpacing: hsp(15),
              mainAxisSpacing: hsp(15),
              childAspectRatio: width/(width+hsp(20))
          ),
          itemBuilder: (context,index){
            Map item = _dataArray[index];
            return GestureDetector(
              onTap: (){
                intoPage(context,item['url']);
              },
              child: Column(
                children: [
                  Container(
                    height: width-hsp(10),
                    width: width-hsp(10),
                    margin: EdgeInsets.only(bottom: hsp(5)),
                    decoration: BoxDecoration(
                      borderRadius: const BorderRadius.all(Radius.circular(50)),
                      image: DecorationImage(image: NetworkImage(item['icon']))
                    ),
                  ),
                  Container(
                    width: width,
                    height: hsp(20),
                    alignment: Alignment.center,
                    child: SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: Text(item['name']??'',style: YSColors.subStyle(context),maxLines: 1,),
                    )
                  )
                ],
              ),
            );
          },
          itemCount: _dataArray.length,
          padding: const EdgeInsets.all(0),
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
        ),
      ),
    );
  }
}

