import 'package:flutter/material.dart';
import 'package:liftmanager/res/gaps.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/internal/search/search_router.dart';
import 'package:liftmanager/widgets/app_search_bar.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'dart:math';
import 'dart:convert';
import 'package:liftmanager/utils/url.dart';
import 'package:liftmanager/utils/theme_utils.dart';

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

  final String index;
  

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

class BrandPageState extends State<BrandPage> {
  // NewsDetailItem item = NewsDetailItem();
  ScrollController _scrollController = new ScrollController();

  @override
  void initState() {
    super.initState();
    getBrandList();
  }
  var changeList;
  List<dynamic> brandListPage;
  String title;
  int indexNow;
  Future getBrandList() async {
    await NewApiService().getBrandListType(title,onSuccess: (res) {
      // brandListPage = res.records;
      print(jsonEncode(res));
      changeList = res;
      print(456);
      // changeList = res.where((item)=>(item["listBrand"] as List).length>0);
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }
  
  @override
  void dispose() {
    _scrollController.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) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;

    

    // 监听FocusNode
    _focusNode1.addListener((){
      // _focusNode1.hasFocus 是否聚焦
      print(_focusNode1.hasFocus);
    });

    return Scaffold(
      appBar: SearchAppBar2(
        onPressed: (text) {
                title = text;
                getBrandList();
              },
      ),
      body:changeList!=null?Container(
        child: Stack(
          children: <Widget>[
            // Positioned(
            //       left: 0,
            //       top: 0,
            //       child:  FlatButton(
            //         padding: EdgeInsets.symmetric(horizontal: 0),
            //         child: Container(
            //           width: width,
            //           height: ScreenUtil().setWidth(48),
            //           padding: EdgeInsets.only(top:ScreenUtil().setWidth(10),bottom:ScreenUtil().setWidth(10),left:ScreenUtil().setWidth(15),right:ScreenUtil().setWidth(15)),
            //           // color: Color(0xFFF1F4FC),
            //           color: ThemeUtils.getDialogTextFieldColor(context),
            //           child:Row(
            //             children: <Widget>[
            //               Container(
            //                 padding: EdgeInsets.only(right:ScreenUtil().setWidth(10)),
            //                 child: Icon(
            //                   IconData(
            //                     0xe6dd,
            //                     fontFamily:"myfont"
            //                   ),
            //                   size: 24.0,
            //                   color:Color(0xffcccccc),
            //                 ),
            //               ),
            //             Text(
            //               "自定义品牌",
            //               style: TextStyle(
            //                 fontSize:ScreenUtil().setSp(16)
            //               ),
            //               textAlign:TextAlign.start,
            //             ),
            //             ],
            //           )
            //         ),
            //         onPressed: (){
            //           showDialog(
            //             context: context,
            //             barrierDismissible: true,  // 是否可以点击底部遮罩层取消dialog
            //             // child: Text('data')
            //             builder: (context) {
            //               return Container(
            //                 child: AlertDialog(
            //                   backgroundColor:ThemeUtils.getDialogTextFieldColor(context),
            //                   title: Text('品牌名称:'),
            //                   titlePadding: EdgeInsets.fromLTRB(24.0, 24.0, 0.0, 0.0),
            //                   titleTextStyle: TextStyle( fontSize: ScreenUtil().setSp(16)),
            //                   content: Container(
            //                     height: ScreenUtil().setWidth(30),
            //                     child: TextField(
            //                     /*
            //                     *  _textEditingController.text是当前文本
            //                     *  initialValue + onChanged 也可以实现获取当前文本
            //                     * 
            //                     *  onChanged是专门用于监听文本变化
            //                     *  而controller 除了能监听文本变化外，它还可以设置默认值、选择文本
            //                     */
            //                     controller: _textEditingController,
            //                     // textInputAction: TextInputAction.go, // 输入框的确定按钮
            //                     focusNode: _focusNode1,
            //                     decoration: InputDecoration(
            //                       contentPadding: EdgeInsets.only(left:ScreenUtil().setWidth(10),right:ScreenUtil().setWidth(5),),
            //                       border: OutlineInputBorder(
            //                           borderRadius: BorderRadius.circular(2.0),
            //             //            borderSide: BorderSide(color: Colors.red, width: 3.0, style: BorderStyle.solid)//没什么卵效果
            //                       ),
            //                       // labelText: 'TextField', // 上标
            //                       // icon: Icon(Icons.ac_unit), // Field外部
            //                       hintText: '请输入', // hint 暗示
            //                       // helperText: '左下角', // helper 帮手
            //                       hasFloatingPlaceholder: false, // labelText是否漂浮
            //                       // errorText: '错误文本',
            //                       errorBorder: InputBorder.none, // 当error时的border
            //                       // prefixIcon: Icon(Icons.phone_iphone), // Field前边
            //                       // 后缀和前缀在focus时显示
            //                       // prefixText: '前缀',  // 前缀
            //                       // prefix: Text('prefix'),
            //                       // suffixText: '后缀', // 后缀
            //                       // counterText: '右下角', // 计数器
            //                       filled: false, // 背景色
            //                       // fillColor: Colors.cyan.withAlpha(35),
            //                       focusedBorder: OutlineInputBorder(), // 当focus时的border
            //                       // semanticCounterText: '222'
            //                     ),
            //                     // keyboardType: TextInputType.numberWithOptions(),
            //                     cursorColor: Color(0xFF999999),
            //                     obscureText: false, // 输入变成**
            //                     onChanged: (val) {
            //                       // xxx
            //                     },
            //                   ),
            //                   ),
            //                   contentPadding: EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0),
            //                   contentTextStyle: TextStyle(fontSize: ScreenUtil().setSp(14)),
            //                   actions: <Widget>[
            //                     Container(
            //                       height:36,
            //                       decoration: BoxDecoration(
            //                         gradient: const LinearGradient(
            //                             colors: [Color(0xFF00D9FF), Color(0xFF0287FF)]),
            //                       ),
            //                       child: FlatButton(
            //                         child: Text('确认',style: TextStyle(color:Colors.white),),
            //                         onPressed: (){
            //                           print(_textEditingController.text);
            //                           if(_textEditingController.text.trim()== null){
            //                             toasts("请输入");
            //                             return;
            //                           }
            //                           if(!isChinese(_textEditingController.text)){
            //                             toasts("请输入中文");
            //                             return;
            //                           }
            //                           NewApiService().addBrand(_textEditingController.text, onSuccess: (res) {
            //                             toasts("自定义品牌成功");
            //                             getBrandList();
            //                             setState(() {});
            //                             _textEditingController.text = "";
            //                             Navigator.maybePop(context);
            //                           }, onError: (code, msg) {
            //                             toasts(msg);
            //                             _textEditingController.text = "";
            //                             Navigator.maybePop(context);
            //                           });
                                      
            //                         },
            //                       ),
            //                     ),
                                
            //                     FlatButton(
            //                       color: Color(0xffcccccc),
            //                       child: Text('取消',style: TextStyle(color:Colors.white),),
            //                       onPressed: (){
            //                         Navigator.maybePop(context);
            //                         _textEditingController.text = "";
            //                       },
            //                     ),
            //                   ],
            //                   semanticLabel: 'semanticLabel',
            //                   shape: Border.all(color: Colors.white),
            //                   elevation: 22
            //                 ),
            //               );
            //             }
            //           );
                      
            //         },
            //       )
                  
            //     ),
                 
            Container(
              // padding: EdgeInsets.only(top:ScreenUtil().setWidth(48)),
              child:ListView(
                controller:_scrollController,
                children:<Widget>[
                  
                  Brand(initList:(changeList.toList()),getIndex:widget.index)
                ]
              ),
            ),
            Positioned(
                  right: 0,
                  top: ScreenUtil().setWidth(50),
                  child: Container(
                    width:ScreenUtil().setWidth(40),
                    // color: Colors.grey,
                    height: height*0.8,
                    child:Azlist(initList:(changeList.toList()),new_scrollController:_scrollController,indexNow: indexNow,fun:(i){
                      setState(() {
                        indexNow = i;
                      });
                    }),
                  )
            ), 
          ],
        )
      ):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){
    double width = MediaQuery.of(context).size.width;

    return Expanded(
      // height: 16,
      child: GestureDetector(
        child: Container(
              width: ScreenUtil().setWidth(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?ScreenUtil().setSp(13):ScreenUtil().setSp(14)
                    ),
                    textAlign:TextAlign.center,
                  ),
            ),
            onTap: (){
              print(i);
              
              fun(i);
              print(1 ~/ 2);
              double nums = 0.0;

              for(var k = 0; k< initList.length; k++){
                if(initList[k].name == word[i]){
                  double lastNums = nums + 30.0*k;
                  print(lastNums);
                  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(
        crossAxisAlignment: CrossAxisAlignment.center,
        children:list(context),
      ),
    );
  }
}

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

  List<dynamic> initList;
  String getIndex;

  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),
            padding: EdgeInsets.only(left:ScreenUtil().setWidth(15)),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children:<Widget>[
                Text(
                  i.name,
                  style: TextStyle(
                    fontSize:ScreenUtil().setSp(16)
                  ),
                  textAlign:TextAlign.start,
                ),
              ]
            )
          ),
          Container(
            // color: Colors.yellow,
            // height: ScreenUtil().setWidth(200),
            child:Wrap(
              // spacing: 16,
              alignment: WrapAlignment.start,
              crossAxisAlignment: WrapCrossAlignment.center,
              children: (i.listBrand as List).map((item){
                return Container(
                  // color:Colors.yellow,
                  height: ScreenUtil().setWidth(100),
                  child: FlatButton(
                    padding: EdgeInsets.all(0),
                  highlightColor:Colors.white,
                  splashColor: Colors.white,
                  child:Container(
                          width: width/4,
                          height: ScreenUtil().setWidth(100),
                          // color: Colors.red,
                          padding: EdgeInsets.only(left:ScreenUtil().setWidth(10),right:ScreenUtil().setWidth(10),top:ScreenUtil().setWidth(10)),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children:<Widget>[
                              Container(
                                // height: 70,
                                // color: Colors.red,
                                child: LoadNetworkImage(
                                    item.logo,
                                    width: ScreenUtil().setWidth(60),
                                    height:ScreenUtil().setWidth(50),
                                    fit:BoxFit.contain
                                    // alignment: Alignment.centerLeft,
                                  )
                              ),
                              Container(
                                child: Text(
                                          item.name,
                                          style: TextStyle(
                                            color:Color(0xff666666),
                                            fontSize:ScreenUtil().setSp(15)
                                          ),
                                          textAlign:TextAlign.start,
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                              ),
                            ]
                          ),
                        ),
                  onPressed: (){
                    print(999);
                    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()}");
                    }
                  },  
                ),
                );
              }).toList() 
            )
          )
        ]
      );
  }).toList();

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


