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/tools/YSAlertView.dart';
import 'package:flutter_wallet/tools/YSColors.dart';
import 'package:flutter_wallet/tools/YSNetWork.dart';
import 'package:flutter_wallet/tools/YSRefrehLoad.dart';
import 'package:flutter_wallet/tools/YSTools.dart';

import 'YSTansDetail.dart';

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

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

class YSMessageState extends State<YSMessage> with SingleTickerProviderStateMixin{
  final List _titleArray = [
    {'title': S.current.ZHUANZHANGTONGZHI,'type':1},
    {'title': S.current.XITONGXIAOXI,'type':2}
  ];
  late TabController _tabController;
  @override
  void initState() {
    _tabController = TabController(
      vsync: this,
      length: _titleArray.length,
    );
    super.initState();
  }
  _postRead() async{
    Map request = {};
    request['address'] = YSData().wallet['public'];
    request['chain_id'] = YSData().typeId;
    // request['type'] = 1;
    Map dict = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.get, api: 'settransnotice', parameter: request);
    if(dict.isNotEmpty){
      refreshKey3.currentState!.refresh(request: {});
    }
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ysTitle: S.current.XIAOXIZHONGXIN,
      ysRightWidget: GestureDetector(
        onTap: (){
          ysShowCenterAlertView(context, YSTipsAlertView(valueSetter: (value){
            if(value){
              _postRead();
            }
          },tipsStr: '是否全部设为已读?',));

        },
        child: Text(S.current.QUANBUYIDU,style: YSColors.content2Style(context),),
      ),
      ysChild: SizedBox(
        width: ysWidth(context),
        height: ysHeight(context)-ysTOP(context)-60,
        child: DefaultTabController(
          length: _titleArray.length,
          child: Column(
            children: [
              SizedBox(
                height: hsp(50),
                child: TabBar(
                  controller: _tabController,
                  indicatorWeight: hsp(1),
                  labelColor: Colors.black,
                  tabs: _titleArray.map((f) {
                    return Tab(
                      child: Stack(
                        children: [
                          Text(f['title']),
                          // Container(
                          //   height: hsp(5),
                          //   width: hsp(5),
                          //   decoration: const BoxDecoration(
                          //     color: Colors.red,
                          //     borderRadius: BorderRadius.all(Radius.circular(50))
                          //   ),
                          //   margin: EdgeInsets.only(left: hsp(60),top: hsp(5)),
                          // )
                        ],
                      ),
                    );
                  }).toList(),
                ),
              ),
              Expanded(
                child: TabBarView(
                  controller: _tabController,
                  children: _titleArray.map((f) {
                    return f['type']==1?const YSMessageTransferDataView():const YSMessageSystemDataView();
                  }).toList(),
                )
              )
            ],
          ),
        ),
      ),
    );
  }
}


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

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

class YSMessageTransferDataViewState extends State<YSMessageTransferDataView> {
  List _dataArray = [];
  @override
  void initState() {
    networkDelay((){
      _postSyntransnotice();
    });
    super.initState();
  }
  _postSyntransnotice() async{
    Map request = {};
    request['page'] = 1;
    request['count'] = 10;
    request['address'] = YSData().wallet['public'];
    request['chain_id'] = YSData().typeId;
    Map dict = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'gettransnotice', parameter: request);
    if(dict.isNotEmpty){
      // Map dict = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'gettransnotice', parameter: request);
    }
  }
  @override
  Widget build(BuildContext context) {
    return YSRefreshLoad(
      key: refreshKey3,
      url: 'gettransnotice',
      request: {'address':YSData().wallet['public'],'chain_id':YSData().typeId},
      postData: (value) {
        _dataArray = value;
        setState(() {});
      },
      child: SingleChildScrollView(
        child: ListView.separated(
          itemBuilder: (context,index){
            Map item = _dataArray[index];
            String value = '${item['value']??''}';
            if(value.isEmpty){
              value = '0';
            }
            return GestureDetector(
              onTap: (){
                Navigator.of(context).push(
                    CupertinoPageRoute(builder: (context){
                      return YSTansDetail2(item: item,);
                    })
                ).then((value) {
                  refreshKey3.currentState!.refresh(request: {});
                });
              },
              behavior: HitTestBehavior.opaque,
              child: Container(
                padding: EdgeInsets.only(top: hsp(10),bottom: hsp(10),left: hsp(15),right: hsp(15)),
                child: Row(
                  children: [
                    if(item['Status']==0)Container(
                      height: hsp(5),
                      width: hsp(5),
                      decoration: const BoxDecoration(
                        color: Colors.red,
                        borderRadius: BorderRadius.all(Radius.circular(50))
                      ),
                      margin: EdgeInsets.only(right: hsp(5)),
                    ),
                    item['TxStatus']==1?Icon(Icons.check_circle,size: hsp(30),color: Colors.green,):Icon(Icons.error,size: hsp(30),color: Colors.red,),
                    Container(
                        padding: EdgeInsets.only(left: hsp(10),right: hsp(10)),
                        width: (ysWidth(context)-hsp(70))*0.7,
                        child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: [
                          Padding(
                            padding: EdgeInsets.only(bottom: hsp(5)),
                            child: Text('${item['Symbol']??''}:${toDecimalFlex(item['Amount'],decimal: item['Decimal'],range: 6)}',style: YSColors.contentStyle(context),),
                          ),
                          Text('发送地址：${ysTextCut(item['ToAddress'])}',style: YSColors.subStyle(context),)
                        ],)),
                    Container(
                        padding: EdgeInsets.only(left: hsp(10),right: hsp(10)),
                        width: (ysWidth(context)-hsp(70))*0.3,
                        child: Column(crossAxisAlignment: CrossAxisAlignment.end,children: [
                          Padding(
                            padding: EdgeInsets.only(bottom: hsp(5)),
                            child: Text(item['CreateTime'],style: YSColors.subStyle(context),),
                          ),
                          Text(item['Symbol']??'',style: YSColors.subStyle(context),)
                        ],))
                  ],
                ),
              ),
            );
          },
          separatorBuilder: (context,index){
            return Divider(height: hsp(1),thickness: hsp(1),color: YSColors.lineColor(context),);
          },
          itemCount: _dataArray.length,
          padding: const EdgeInsets.all(0),
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
        ),
      ),
    );
  }
}

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

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

class YSMessageSystemDataViewState extends State<YSMessageSystemDataView> {
  List _dataArray = [];
  @override
  Widget build(BuildContext context) {
    return YSRefreshLoad(
        url: 'notices',
        request: const {'type':'0'},
        postData: (value){
          _dataArray = value;
          setState(() {});
        },
        child: SingleChildScrollView(
          child: ListView.separated(
            itemBuilder: (context,index){
              Map item = _dataArray[index];
              return Container(
                padding: EdgeInsets.only(top: hsp(10),bottom: hsp(10),left: hsp(15),right: hsp(15)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                        padding: EdgeInsets.only(bottom: hsp(5)),
                        child: Row(
                          children: [
                            Expanded(child: Text(item['title']??'',style: YSColors.contentStyle(context),),),
                            Container(
                              width: hsp(150),
                              alignment: Alignment.centerRight,
                              child: Text(item['CreateTime']??'',style: YSColors.subStyle(context),),
                            )
                          ],
                        )
                    ),
                    Text(item['txt']??''.fixAutoLines(),style: YSColors.subStyle(context),)
                  ],
                ),
              );
            },
            separatorBuilder: (context,index){
              return Divider(height: hsp(1),thickness: hsp(1),color: YSColors.lineColor(context),);
            },
            itemCount: _dataArray.length,
            padding: const EdgeInsets.all(0),
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
          ),
        )
    );;
  }
}
