import 'package:flutter/material.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/internal/means/means_router.dart';
import 'package:liftmanager/widgets/bbs_content.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/internal/bbs/model/brand_model.dart';
import 'package:liftmanager/internal/bbs/model/error_model.dart';
import 'dart:async';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/utils/url.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:liftmanager/utils/theme_utils.dart';

class BrandDetail extends StatefulWidget {
  BrandDetail(this.id);
  final String id;
  String index = "1";
  int checkIndex = 1; // 1:直梯， 2：扶梯
  @override
  State<StatefulWidget> createState() {
    return BrandDetailState();
  }
}

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

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

  @override
  void initState() {
    super.initState();
    getBrandDetail();
    getFaultCodeList();
    getFileCategorysTree();
  }

  bool _hasData = false;
  Records detailObj;

  getBrandDetail() {
    NewApiService().getBrandDetail(widget.id, onSuccess: (res) {
      detailObj = res;
      print("获取详情成功");
      print(res);
      _hasData = true;
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  bool _hasCodeData = false;
  List<dynamic> codeList = [];

  getFaultCodeList() {
    _hasCodeData = false;
    NewApiService().getFaultCodeList(widget.id, 0, 12, topFlag: 1, onSuccess: (res) {
      codeList = res.records;
      _hasCodeData = true;
      setState(() {});
    }, onError: (code, msg) {
      _hasCodeData = true;
      toasts(msg);
      setState(() {});
    });
  }

  bool _hasTypeData = false;
  List<dynamic> typeList = [];

  getFileCategorysTree() {
    _hasTypeData = false;
    NewApiService().getFileCategorysTree(widget.id, onSuccess: (res) {
      print("获取分类信息");
      // print(res.toList());
      typeList = res;
      
      if(typeList.length > 0) {
        this.changeTypeIndex(0);
      }
      _hasTypeData = true;
      setState(() {});
    }, onError: (code, msg) {
      _hasTypeData = true;
      toasts(msg);
      setState(() {});
    });
  }

  int typeIndex;

  List<dynamic> brandFileList = [];

  changeTypeIndex(index) {
    typeIndex = index;
    brandFileList = typeList[index].chilList;
    print(brandFileList);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;

    return Scaffold(
        appBar: MyAppBar(
          centerTitle: "电梯资料库",
        ),
        body: _hasData
            ? Container(
                child: Stack(
                children: <Widget>[
                  typeList.length > 0
                      ? CategorysNav(
                          lists: typeList,
                          typeIndex: typeIndex,
                          fun: changeTypeIndex):Container(child: null,)
                      ,
                  Container(
                    padding: typeList.length > 0?EdgeInsets.only(top: ScreenUtil().setWidth(50)):EdgeInsets.only(top: ScreenUtil().setWidth(0)),
                    child: ListView(
                        controller: _scrollController,
                        children: <Widget>[
                          LableTitle(
                            title: "品牌简介",
                            isMore: false,
                          ),
                          Container(
                            height: 130,
                            padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(15),
                                right: ScreenUtil().setWidth(15),
                                bottom: ScreenUtil().setWidth(40)),
                            child: Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Container(
                                    width: ScreenUtil().setWidth(90),
                                    height: ScreenUtil().setWidth(80),
                                    // color: Colors.red,
                                    child: LoadNetworkImage(
                                      detailObj.logo,
                                      fit: BoxFit.cover,
                                    ),
                                  ),
                                  SizedBox(width: 10),
                                  Expanded(
                                    child: Text(
                                      detailObj.descr ?? '',
                                      overflow: TextOverflow.ellipsis,
                                      maxLines: 3,
                                      style: TextStyle(
                                          fontSize: ScreenUtil().setSp(15)),
                                      textAlign: TextAlign.start,
                                    ),
                                  )
                                ]),
                          ),
                          Container(
                            height: 5,
                            color: Color(0xffF8F8F8),
                          ),
                          LableTitle(
                            title: "品牌资料",
                            isMore: false,
                          ),
                          Container(
                            padding: EdgeInsets.only(
                                top: ScreenUtil().setWidth(10),
                                bottom: ScreenUtil().setWidth(30)),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                              // BrandFile(initList: brandFileList),
                              brandFileList.length > 0
                                  ? BrandFile(initList: brandFileList, brandId: widget.id)
                                  : Center(child:Text("暂无数据"))
                            ]),
                          ),
                          Container(
                            height: 5,
                            color: Color(0xffF8F8F8),
                          ),
                          LableTitle(
                            title: "错误代码库",
                            userTap: () {
                              NavigatorUtils.push(context,
                                  "${MeansRouter.errorList}?id=${widget.id.toString()}");
                            },
                          ),
                          _hasCodeData
                              ? ErrorCode(
                                  lists: codeList,
                                )
                              : loadCircle(),
                          SizedBox(
                            height: 10,
                          )
                        ]),
                  )
                ],
              ))
            : 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,
        ),
      ),
    );
  }

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

class CategorysNav extends StatelessWidget {
  CategorysNav({Key key, this.lists, this.typeIndex, this.fun})
      : super(key: key);

  List<dynamic> lists = [];

  int typeIndex;

  Function fun;

  @override
  Widget build(BuildContext context) {
    return Positioned(
      child: Container(
          color: Color(0xffFAF7FA),
          child: Row(
            children: typeList(context),
          )),
    );
  }

  List<Widget> typeList(context) => lists.asMap().keys.map((index) {
        double width = MediaQuery.of(context).size.width;

        return Container(
            width: width / (lists.length),
            padding: EdgeInsets.only(top: ScreenUtil().setWidth(10)),
            child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  GestureDetector(
                      onTap: () {
                        fun(index);
                      },
                      child: Container(
                        padding:
                            EdgeInsets.only(bottom: ScreenUtil().setWidth(10)),
                        decoration: BoxDecoration(
                          border: Border(
                            bottom: BorderSide(
                                width: 3,
                                color: typeIndex == index
                                    ? Color(0xff02A0FD)
                                    : Color(0xffFAF7FA)),
                          ),
                        ),
                        child: Text(
                          lists[index].name,
                          style: TextStyle(
                              color: Color(0xfff333333),
                              fontSize: ScreenUtil().setSp(16)),
                          textAlign: TextAlign.center,
                        ),
                      ))
                ]));
      }).toList();
}

class ErrorCode extends StatelessWidget {
  ErrorCode({Key key, this.lists}) : super(key: key);

  List<dynamic> lists = [];

  @override
  Widget build(BuildContext context) {
    return Container(
        // margin: EdgeInsets.symmetric(vertical: 5, horizontal: 5),
        padding: EdgeInsets.only(
            top: ScreenUtil().setWidth(5),
            left: ScreenUtil().setWidth(15),
            right: ScreenUtil().setWidth(15)),
        child: Wrap(
          spacing: 13,
          runSpacing : 10,
          alignment: WrapAlignment.start,
          crossAxisAlignment: WrapCrossAlignment.center,
          children: errorList(context),
          // children: (lists != null && lists.length > 0)
          //     ? errorList(context)
          //     : loadCircle(),
        ));
  }

  List<Widget> errorList(context) => lists.map((item) {
        double width = MediaQuery.of(context).size.width;

        return Container(
          // color:Colors.yellow,
          height: 30,
          width: width*0.28,
          padding: EdgeInsets.all(0),
          decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(2.0),
                color: Color(0xff9FD1FE),
              ),
          child: 
          GestureDetector(
            onTap: () {
              NavigatorUtils.push(context,
                  "${MeansRouter.errorDetail}?id=${item.id.toString()}");
            },
            child: Container(
              // width: 90,
              
              padding: EdgeInsets.only(
                  left: ScreenUtil().setWidth(10),
                  right: ScreenUtil().setWidth(10),
                  top: ScreenUtil().setWidth(5),
                  // bottom: ScreenUtil().setWidth(5)
                  ),
              
              child: Text(
                item.code,
                style: TextStyle(
                    color: Color(0xffffffff), fontSize: ScreenUtil().setSp(15)),
                textAlign: TextAlign.center,
                maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
              ),
            ),
          )
          // GestureDetector(
          //   child: Container(
          //     // width: 90,
              
          //     margin: EdgeInsets.all(4),
          //     // padding: EdgeInsets.only(
          //     //     left: ScreenUtil().setWidth(10),
          //     //     right: ScreenUtil().setWidth(10),
          //     //     top: ScreenUtil().setWidth(5),
          //     //     // bottom: ScreenUtil().setWidth(5)
          //     //     ),
              
          //     child: Text(
          //       item.code,
          //       style: TextStyle(
          //           color: Color(0xffffffff), fontSize: ScreenUtil().setSp(15)),
          //       textAlign: TextAlign.center,
          //     ),
          //   ),
          //   onTap: () {
          //     NavigatorUtils.push(context,
          //         "${MeansRouter.errorDetail}?id=${item.id.toString()}");
          //   },
          // ),
        );
      }).toList();

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

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

  List<dynamic> initList;
  String brandId;

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

        return Container(
          width: width / 3,
          child: FlatButton(
            padding: EdgeInsets.all(0),
            highlightColor: Colors.white,
            splashColor: Colors.white,
            child: Container(
              // width: 90,
              height: ScreenUtil().setWidth(80),
              // 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(
                      child: LoadNetworkImage(
                        item.icon,
                        width: ScreenUtil().setWidth(50),
                        height: ScreenUtil().setWidth(30),
                        // alignment: Alignment.centerLeft,
                      ),
                    ),
                    SizedBox(height: 10),
                    Container(
                      child: Text(
                        item.name ?? '',
                        style: TextStyle(
                            color: Color(0xff666666),
                            fontSize: ScreenUtil().setSp(14)),
                        textAlign: TextAlign.center,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ]),
            ),
            onPressed: () {
              NavigatorUtils.push(context, "${MeansRouter.meansList}?catagoryId=${item.id.toString()}&dataTable=2&brandId=${brandId}");
            },
          ),
        );
      }).toList();

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