import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'package:liftmanager/internal/bbs/model/brand_model.dart';
import 'package:liftmanager/internal/bbs/model/brand_model_type.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_search_bar.dart';
import 'package:liftmanager/widgets/load_image.dart';

class BrandPage extends StatefulWidget {
  BrandPage(this.index);

  final String index;

  @override
  State<StatefulWidget> createState() {
    return BrandPageState();
  }
}

class BrandPageState extends State<BrandPage> {
  @override
  void initState() {
    super.initState();
    getBrandList();
  }

  var brandList;
  List<dynamic> brandListPage;
  String title;

  Future getBrandList() async {
    await NewApiService().getBrandListType(title, onSuccess: (res) {
      brandList = res;
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  static bool isChinese(String value) {
    return RegExp(r"^[\u4e00-\u9fa5]+$").hasMatch(value);
  }

  // 文本编辑控制
  TextEditingController _textEditingController = new TextEditingController();

  // 焦点控制
  FocusNode _focusNode1 = new FocusNode();

  @override
  Widget build(BuildContext context) {
    // 监听FocusNode
    _focusNode1.addListener(() {
      // _focusNode1.hasFocus 是否聚焦
      print(_focusNode1.hasFocus);
    });

    return Scaffold(
      appBar: SearchAppBar2(
        backgroundColor: Colors.white,
        onPressed: (text) {
          title = text;
          getBrandList();
        },
      ),
      body: brandList != null
          ? Container(
              child: BrandSelectionPanel(
                  brandList: brandList, index: widget.index))
          : Center(
              child: Text("正在加载..."),
            ),
    );
  }

  Widget loadCircle() {
    return Container(
      padding: EdgeInsets.only(top: 10, bottom: 10),
      color: ThemeUtils.getTabsBg(context),
      child: Center(
        child: SpinKitFadingCircle(
          color: Colors.blueAccent,
          size: 30.0,
        ),
      ),
    );
  }
}

class Azlist extends StatelessWidget {
  Azlist(
      {Key key,
      this.initList,
      this.new_scrollController,
      this.indexNow,
      this.fun})
      : super(key: key);

  List<dynamic> initList;
  ScrollController new_scrollController;
  int indexNow;
  Function fun;

  static const word = [
    "热门",
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
    "#"
  ];

  List<Widget> list(context) => word.asMap().keys.map((i) {
        return GestureDetector(
          child: Container(
            width: 33,
            // padding: EdgeInsets.only(left:15,top:5,bottom:5),
            // color:Colors.red,
            child: Text(
              word[i],
              style: TextStyle(
                  // color:Color(0xffff0000),
                  color: Color(0xff0288FF),
                  // color:indexNow == i?Color(0xffff0000):Color(0xff0288FF),
                  fontSize: i == 0 ? 13 : 14),
              textAlign: TextAlign.center,
            ),
          ),
          onTap: () {
            fun(i);
            double nums = 0.0;

            for (var k = 0; k < initList.length; k++) {
              if (initList[k].name == word[i]) {
                double lastNums = nums + 30.0 * k;
                double numsFinal = ScreenUtil().setWidth(lastNums);
                new_scrollController.animateTo(numsFinal,
                    duration: Duration(milliseconds: 500),
                    curve: Curves.decelerate);
              }
              int a = ((initList[k].listBrand as List).length ~/ 4);
              int b;
              if ((initList[k].listBrand as List).length % 4 == 0) {
                b = 0;
              } else {
                b = 1;
              }
              nums += (a + b) * 100.0;
            }
          },
        );
      }).toList();

  @override
  Widget build(BuildContext context) {
    return Container(
      // padding: EdgeInsets.only(bottom: 5),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: list(context),
      ),
    );
  }
}

class BrandSelectionPanel extends StatefulWidget {
  final brandList;
  final index;
  final Function(ListBrand brand) onTapBrand;

  BrandSelectionPanel({this.brandList, this.index, this.onTapBrand});

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

class BrandSelectionPanelState extends State<BrandSelectionPanel> {
  final ScrollController _scrollController = new ScrollController();
  int indexNow;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Container(
          // padding: EdgeInsets.only(top:ScreenUtil().setWidth(48)),
          child: ListView(
            controller: _scrollController,
            children: <Widget>[
              Brand(
                initList: (widget.brandList.toList()),
                getIndex: widget.index,
                onTap: widget.onTapBrand,
              )
            ],
          ),
        ),
        Positioned.fill(
            right: 0,
            top: 0,
            child: Container(
              alignment: Alignment.centerRight,
              width: ScreenUtil().setWidth(40),
              child: Azlist(
                  initList: (widget.brandList.toList()),
                  new_scrollController: _scrollController,
                  indexNow: indexNow,
                  fun: (i) {
                    setState(() {
                      indexNow = i;
                    });
                  }),
            )),
      ],
    );
  }
}

class Brand extends StatelessWidget {
  Brand({Key key, this.initList, this.getIndex, this.onTap}) : super(key: key);

  final List<dynamic> initList;
  final String getIndex;
  final Function(ListBrand brand) onTap;

  List<Widget> brandList(context) => initList.map((i) {
        double width = MediaQuery.of(context).size.width;

        return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                  // width: width,
                  height: ScreenUtil().setWidth(30),
                  color: ThemeUtils.getDialogTextFieldColor(context),
                  child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          width: 2,
                          height: 13,
                          color: Color(0xFF568AFF),
                        ),
                        SizedBox(width: 10),
                        Text(
                          i.name,
                          style: TextStyle(fontSize: 15),
                          textAlign: TextAlign.start,
                        ),
                      ])),
              Wrap(
                  // spacing: 0,
                  alignment: WrapAlignment.start,
                  crossAxisAlignment: WrapCrossAlignment.center,
                  // runAlignment: WrapAlignment.center,
                  children: (i.listBrand as List).map((item) {
                    return GestureDetector(
                      child: Container(
                        width: (width - 30) / 4,
                        height: 100,
                        padding: EdgeInsets.all(10),
                        child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Container(
                                child: LoadNetworkImageAlt(item.logo,
                                    width: 50, height: 50, fit: BoxFit.contain),
                              ),
                              SizedBox(height: 5),
                              Container(
                                child: Text(
                                  item.name,
                                  style: TextStyle(
                                      color: Color(0xff666666), fontSize: 12),
                                  textAlign: TextAlign.start,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ]),
                      ),
                      onTap: () {
                        print(getIndex);
                        if (getIndex == "0") {
                          print(item.name);
                          print(item.id);
                          NavigatorUtils.push(context,
                              "${BbsRouter.interrogationPage}?brandName=${Uri.encodeComponent(item.name)}&brandId=${item.id.toString()}");
                        } else if (getIndex == "1") {
                          // NavigatorUtils.push(context, BbsRouter.visitPage);
                          NavigatorUtils.push(context,
                              "${BbsRouter.visitPage}?brandName=${Uri.encodeComponent(item.name)}&brandId=${item.id.toString()}");
                        } else {
                          if (onTap != null) {
                            onTap(item);
                          }
                        }
                      },
                    );
                  }).toList())
            ]);
      }).toList();

  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.only(top: ScreenUtil().setWidth(5)),
        child: Column(
          children: brandList(context),
        ));
  }
}
