import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wallet/base/YSBase.dart';
import 'package:flutter_wallet/login/view/YSHelpView.dart';
import 'package:flutter_wallet/tools/YSNetWork.dart';
import 'package:flutter_wallet/tools/YSSqflite.dart';
import 'package:flutter_wallet/tools/YSTools.dart';

import '../generated/l10n.dart';
import '../tools/YSColors.dart';
import '../tools/YSRefrehLoad.dart';

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

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

class YSAlwayAddressAddState extends State<YSAlwayAddressAdd> {
  final List _array = [
    {'title':'钱包地址','tips':'请输入地址','index':1,'key':'address'},
    {'title':'设置名称','tips':'请输入名称','index':2,'key':'name'},
    {'title':'设置备注','tips':'备注仅做补充信息，不参与链上交易','index':3,'key':'remark'}
  ];
  TextEditingController _addressField = TextEditingController();
  TextEditingController _nameField = TextEditingController();
  TextEditingController _remarkField = TextEditingController();
  List _chooseArray = [];
  @override
  void dispose() {
    _addressField.dispose();
    _nameField.dispose();
    _remarkField.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ysTitle: S.current.XINJIANLIANXIREN,
      ysChild: Column(
        children: [
          Container(
            width: ysWidth(context),
            color: Colors.white,
            child: Column(
              children: [
                Container(
                  height: hsp(45),
                  color: YSColors.containColor(context),
                  padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
                  alignment: Alignment.centerLeft,
                  child: Text(S.current.QUANBUWANGLUO,style: YSColors.contentStyle(context),),
                ),
                Divider(height: hsp(1),color: YSColors.lineColor(context),),
                GestureDetector(
                  onTap: (){
                    ysShowBottomAlertView(context, YSAlwayAddressAlertView(valueSetter: (value){
                      _chooseArray.clear();
                      _chooseArray = value;
                      setState(() {});
                    },),isBarr: true);
                  },
                  behavior: HitTestBehavior.opaque,
                  child: Container(
                    height: hsp(60),
                    padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
                    child: Row(
                      children: [
                        Expanded(child: SingleChildScrollView(
                          scrollDirection: Axis.horizontal,
                          padding: const EdgeInsets.all(0),
                          child: Stack(
                            children: [
                              for(int i = 0;i<_chooseArray.length;i++)Container(
                                height: hsp(30),
                                width: hsp(30),
                                margin: EdgeInsets.only(left: hsp(i*20)),
                                decoration: BoxDecoration(
                                    borderRadius: const BorderRadius.all(Radius.circular(50)),
                                    color: Colors.white,
                                    image: DecorationImage(image: NetworkImage(_chooseArray[i]['icon'],),),
                                    boxShadow: [
                                      BoxShadow(color: YSColors.shadowColor(context),blurRadius: 3)
                                    ]
                                ),
                              )
                            ],
                          ),
                        )),
                        Icon(Icons.chevron_right,size: hsp(25),color: YSColors.shadowColor(context),)
                      ],
                    ),
                  ),
                ),
                Divider(height: hsp(1),color: YSColors.lineColor(context),),
                ListView.separated(
                  itemBuilder: (context,index){
                    Map item = _array[index];
                    return Container(
                      padding: EdgeInsets.only(top: hsp(15),bottom: hsp(15),left: hsp(15),right: hsp(15)),
                      color: Colors.white,
                      child: Row(
                        children: [
                          SizedBox(
                            width: hsp(60),
                            child: Text(item['title'],style: YSColors.contentStyle(context),),
                          ),
                          Expanded(child: CupertinoTextField(
                            placeholder: item['tips'],
                            style: YSColors.contentStyle(context),
                            decoration: const BoxDecoration(),
                            controller: item['index']==1?_addressField:item['index']==2?_nameField:_remarkField,
                            suffix: item['index']==1?GestureDetector(
                              onTap: () async{
                                String result = await YSCodeImage.scanCode();
                                if(result.isNotEmpty&&mounted){
                                  _addressField.text = result;
                                }
                              },
                              child: Image.asset(YSColors.imageStyle(context, '扫码 (3)'),height: hsp(20),width: hsp(20),),
                            ):Container(),
                          ))
                        ],
                      ),
                    );
                  },
                  separatorBuilder: (context,index){
                    return Divider(height: hsp(1),color: YSColors.lineColor(context),);
                  },
                  itemCount: _array.length,
                  padding: const EdgeInsets.all(0),
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                ),
              ],
            ),
          ),
          GestureDetector(
            onTap: (){
              FocusScope.of(context).unfocus();
              if(_chooseArray.isEmpty){
                ysFlutterToast('请选择网络');
                return;
              }
              if(_addressField.text.isEmpty){
                ysFlutterToast('请完善钱包地址');
                return;
              }
              if(_nameField.text.isEmpty){
                ysFlutterToast('请设置名称');
                return;
              }
              for (var element in _chooseArray) {
                YSAlwayAddressTable table = YSAlwayAddressTable().init();
                table.rawInsert(_addressField.text, _nameField.text, _remarkField.text, element['icon'], element['id']);
                Navigator.of(context).pop('');
              }
            },
            child: Container(
              width: ysWidth(context)-hsp(150),
              height: hsp(50),
              margin: EdgeInsets.only(top: hsp(50)),
              decoration: BoxDecoration(
                color: YSColors.buttonColor(context),
                borderRadius: const BorderRadius.all(Radius.circular(5))
              ),
              alignment: Alignment.center,
              child: Text('添加',style: YSColors.buttonStyle(context),),
            ),
          )
        ],
      ),
    );
  }
}

class YSAlwayAddressAlertView extends StatefulWidget {
  final ValueSetter valueSetter;
  const YSAlwayAddressAlertView({Key? key, required this.valueSetter}) : super(key: key);

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

class YSAlwayAddressAlertViewState extends State<YSAlwayAddressAlertView> {
  final List _chooseArray = [];
  @override
  Widget build(BuildContext context) {
    return Container(
      height: hsp(400),
      decoration: BoxDecoration(
        color: YSColors.containColor(context),
        borderRadius: const BorderRadius.only(topRight: Radius.circular(10),topLeft: Radius.circular(10))
      ),
      child: Column(
        children: [
          Container(
            height: hsp(49),
            alignment: Alignment.center,
            padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(
                  width: hsp(50),
                ),
                Text(S.current.XUANZEWANGLUO,style: YSColors.titleStyle(context),),
                GestureDetector(
                  onTap: (){
                    if(_chooseArray.isEmpty)return;
                    widget.valueSetter(_chooseArray);
                    Navigator.pop(context);
                  },
                  child: Container(
                    width: hsp(50),
                    alignment: Alignment.centerRight,
                    child: Text('选择',style: YSColors.contentStyle(context),),
                  ),
                )
              ],
            )
          ),
          Divider(height: hsp(1),color: YSColors.lineColor(context),),
          SizedBox(
            height: hsp(350),
            child: YSRefreshLoad(
              url: 'chains',
              request: const {},
              postData: (value) {
                YSData().typeArray = value;
                setState(() {});
              },
              child: ListView.separated(
                  itemBuilder: (context,index){
                    Map item = YSData().typeArray[index];
                    bool isChoose = _chooseArray.contains(item);
                    return GestureDetector(
                      onTap: () async{
                        if(isChoose){
                          _chooseArray.remove(item);
                        }else{
                          _chooseArray.add(item);
                        }
                        setState(() {});
                        // if(!mounted)return;
                        // Navigator.pop(context);
                      },
                      behavior: HitTestBehavior.opaque,
                      child: Container(
                        height: hsp(49),
                        padding: EdgeInsets.only(left: hsp(15),right: hsp(15)),
                        child: Row(
                          children: [
                            SizedBox(
                              height: hsp(40),
                              width: hsp(40),
                              child: YSImage.network(item['icon'],),
                            ),
                            Expanded(
                                child: Text(' ${item['name']}',style: YSColors.contentStyle(context),)
                            ),
                            if(isChoose)Image.asset(YSColors.imageStyle(context, '矩形2'),height: hsp(15),width: hsp(15),),
                          ],
                        ),
                      ),
                    );
                  },
                  separatorBuilder: (context,index){
                    return Divider(height: hsp(1),color: YSColors.lineColor(context),);
                  },
                  itemCount: YSData().typeArray.length
              ),
            ),
          )
        ],
      ),
    );
  }
}

