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:liftmanager/widgets/bbs_content.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/mvp/base_page_state.dart';
import 'package:liftmanager/internal/bbs/presenter/question_list_presenter.dart';
import 'package:liftmanager/internal/bbs/model/mix_model.dart';
import 'package:liftmanager/utils/time_format.dart';
import 'package:liftmanager/internal/search/presenter/base_list_provider.dart';
import 'package:liftmanager/widgets/state_layout.dart';
import 'package:provider/provider.dart';
import 'package:liftmanager/widgets/my_refresh_list.dart';
import 'package:liftmanager/utils/url.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'dart:convert';
import 'package:liftmanager/utils/theme_utils.dart';

class QuestionList extends StatefulWidget {
  // QuestionList(this.index);

  // final String index;

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

class QuestionListState
    extends BasePageState<QuestionList, QuestionListPresenterSeconds> {
  // NewsDetailItem item = NewsDetailItem();
  BaseListProvider<Records> provider = BaseListProvider<Records>();
  ScrollController _scrollController = new ScrollController();
  int _page = 1;
  int brandIdss;
  int exprtyIdss;
  String expertName;
  bool sortBool = true;
  String checkTypeName;
  String checkType;
  String brandName = "品牌";
  String masterName = "专家";
  String searchWord;
  @override
  void initState() {
    provider.setStateTypeNotNotify(StateType.loading);
    super.initState();
    _onRefresh();
    print(66666);
  }
  List<dynamic> typeList;
  List<dynamic> brandList;
  Future getBrandList() async {
    await NewApiService().getBrandListNoPage(
        onSuccess: (res) {
      if (res != null) {
        brandList = res;
        typeList = brandList;
        setState(() {});
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }
  List<dynamic> expertList;
  Future getExpertList() async {
    await NewApiService().getExpertListNoPage(
        onSuccess: (res) {
      if (res != null) {
        expertList = res;
        typeList = expertList;
        setState(() {});
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }


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

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    return ChangeNotifierProvider<BaseListProvider<Records>>(
        create: (_) => provider,
        child: Scaffold(
            appBar: SearchAppBar2(
              onPressed: (text) {
                searchWord = text;
                _onRefresh();
              },
            ),
            body: Container(
                child: Stack(
                  children: <Widget>[
                    Column(
              children: <Widget>[
                Container(
                    width: width,
                    height: ScreenUtil().setWidth(50),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(width: 0.5, color: Colours.line),
                      ),
                    ),
                    padding: EdgeInsets.only(
                        left: ScreenUtil().setWidth(15),
                        right: ScreenUtil().setWidth(15)),
                    // color: Color(0xFFF1F4FC),
                    child: Row(
                      children: <Widget>[
                        GestureDetector(
                          onTap: (){
                            typeList = [];
                            getBrandList();
                            setState(() {
                              sortBool = false;
                              checkTypeName = "品牌";
                              checkType = "brand";
                            });
                            
                          },
                          child: Row(
                          children: <Widget>[
                            Text(
                              brandName,
                              style: TextStyle(
                                  fontSize: ScreenUtil().setSp(16)),
                              textAlign: TextAlign.start,
                            ),
                            Container(
                              padding: EdgeInsets.only(top: 3),
                              child: Icon(
                                Icons.keyboard_arrow_down,
                                size: 26.0,
                              ),
                            )
                          ],
                        ),
                        ),
                        SizedBox(width: ScreenUtil().setWidth(30)),
                        GestureDetector(
                          onTap: (){
                            typeList = [];
                            getExpertList();
                            setState(() {
                              sortBool = false;
                              checkTypeName = "专家";
                              checkType = "master";
                            });
                          },
                          child: Row(
                          children: <Widget>[
                            Text(
                              masterName,
                              style: TextStyle(
                                  fontSize: ScreenUtil().setSp(16)),
                              textAlign: TextAlign.start,
                            ),
                            Container(
                              padding: EdgeInsets.only(top: 3),
                              child: Icon(
                                Icons.keyboard_arrow_down,
                                size: 26.0,
                              ),
                            )
                          ],
                        ),
                        ),
                      ],
                    )),
                Expanded(
                    flex: 1,
                    child: Consumer<BaseListProvider<Records>>(
                        builder: (_, provider, __) {
                      return MyListView(
                        key: Key('question_list'),
                        itemCount: provider.list.length,
                        stateType: provider.stateType,
                        onRefresh: _onRefresh,
                        pageSize: 10,
                        loadMore: _loadMore,
                        hasMore: provider.hasMore,
                        itemBuilder: (_, index) {
                          return GestureDetector(
                            child: Container(
                              padding: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(15),
                                  right: ScreenUtil().setWidth(10),
                                  top: ScreenUtil().setHeight(10),
                                  bottom: ScreenUtil().setHeight(10)),
                              decoration: BoxDecoration(
                                border: Border(
                                  bottom: BorderSide(
                                      width: 0.5, color: Colours.line),
                                ),
                              ),
                              child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(
                                      "[${provider.list[index].brandName??""}]${provider.list[index].title??""}",
                                      textAlign: TextAlign.left,
                                      style: TextStyle(
                                          fontSize: ScreenUtil().setSp(15)),
                                    ),
                                    Container(
                                      padding: EdgeInsets.only(
                                          top: ScreenUtil().setHeight(10),
                                          bottom: ScreenUtil().setHeight(10)),
                                      child: Row(
                                        children: <Widget>[
                                          ClipRRect(
                                              borderRadius:
                                                  BorderRadius.circular(
                                                      ScreenUtil()
                                                          .setWidth(18)),
                                              child: Container(
                                                child: LoadNetworkImage(
                                                  provider.list[index].avatarUrl,
                                                  // fit: BoxFit.fitWidth,
                                                  width:
                                                      ScreenUtil().setWidth(34),
                                                  height:
                                                      ScreenUtil().setWidth(34),
                                                      
                                                ),
                                              )),
                                          Container(
                                            padding: EdgeInsets.only(
                                                left:
                                                    ScreenUtil().setWidth(10)),
                                            child: Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: <Widget>[
                                                Text(
                                                  provider.list[index].userName??"",
                                                  style: TextStyle(
                                                      fontSize: ScreenUtil()
                                                          .setSp(14),
                                                      ),
                                                ),
                                                Text(
                                                  DateUtils.instance
                                                      .getFormartData(
                                                          timeSamp: provider
                                                              .list[index]
                                                              .createTime,
                                                          format: "yyyy-MM-dd"),
                                                  style: TextStyle(
                                                      fontSize: ScreenUtil()
                                                          .setSp(12),
                                                      color: Color(0xffaaaaaa)),
                                                ),
                                              ],
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                    Text(
                                      provider.list[index].expression,
                                      textAlign: TextAlign.left,
                                      style: TextStyle(
                                        color: Color(0xff666666),
                                        fontSize: ScreenUtil().setSp(14),
                                      ),
                                      maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                                    ),
                                    Container(
                                      padding: EdgeInsets.only(
                                          top: ScreenUtil().setHeight(5),
                                          bottom: ScreenUtil().setHeight(5)),
                                      child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.start,
                                          children: provider.list[index].imgs !=
                                                      null &&
                                                  provider.list[index].imgs
                                                      .isNotEmpty
                                              ? List<Widget>.from(provider
                                                  .list[index].imgs
                                                  .split(",")
                                                  .asMap().keys.map((subindex) {
                                                  // print(item);
                                                  return subindex<3?Container(
                                                    padding:subindex<provider
                                                  .list[index].imgs.split(",").length-1?EdgeInsets.only(right:6):EdgeInsets.only(right:0),
                                                    // color:Colors.red,
                                                    // decoration: BoxDecoration(
                                                    //   borderRadius: BorderRadius.circular(20.0),
                                                    // ),
                                                    child: ClipRRect(
                                                      borderRadius:
                                                          BorderRadius.circular(
                                                              10),
                                                      child: LoadNetworkImage(
                                                        provider
                                                  .list[index].imgs.split(",")[subindex],
                                                        // height: width/375*75,
                                                        height: ScreenUtil()
                                                            .setWidth(80),
                                                        width: ScreenUtil()
                                                            .setWidth(110),
                                                        isWater: true,
                                                      ),
                                                    ),
                                                  ):Container(child: null,);
                                                }).toList())
                                              : <Widget>[]),
                                    ),
                                    Row(
                                      children: <Widget>[
                                        Row(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Text(
                                              "${provider.list[index].likeNum??"0"}",
                                              style: TextStyle(
                                                  color: Color(0xff999999),
                                                  fontSize: ScreenUtil().setSp(14)),
                                              textAlign: TextAlign.start,
                                            ),
                                            SizedBox(
                                              width:3
                                            ),
                                            Icon(
                                              IconData(0xe7cd,
                                                  fontFamily: "myfont"),
                                              size: 14.0,
                                              color: Color(0xff999999),
                                            ),
                                          ],
                                        ),
                                        SizedBox(
                                          width:15
                                        ),
                                        Row(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Text(
                                              "${provider.list[index].browseNum??"0"}",
                                              style: TextStyle(
                                                  color: Color(0xff999999),
                                                  fontSize: ScreenUtil().setSp(14)),
                                              textAlign: TextAlign.start,
                                            ),
                                            SizedBox(
                                              width:3
                                            ),
                                            Icon(
                                              IconData(0xe610,
                                                  fontFamily: "myfont"),
                                              size: 14.0,
                                              color: Color(0xff999999),
                                            ),
                                          ],
                                        ),
                                      ],
                                    )
                                    
                                  ]),
                            ),
                            onTap: () {
                              // print(item);
                              NavigatorUtils.push(context,
                                  "${BbsRouter.questionDetail}?id=${provider.list[index].id.toString()}");
                            },
                          );
                        },
                      );
                    }))
              ],
            ),
            !sortBool?
            Positioned(
              top:0,
              left:0,
              child: GestureDetector(
                onTap: (){
                  setState(() {
                    sortBool = true;
                  });
                },
                child: Container(
                width:width,
                height:height,
                color: Color.fromRGBO(0, 0, 0, 0.5)
              ),
              )
            )
            :Container(
              child:null
            ),
            !sortBool?
            Positioned(
              top:0,
              left:0,
              child:Container(
                width: width,
                height:height/2,
                color: ThemeUtils.getDialogTextFieldColor(context),
                padding: EdgeInsets.all(10),
                child:ListView(
                  children:<Widget>[
                    GestureDetector(
                      onTap: (){
                        if(checkType=="brand"){
                          
                          setState(() {
                            brandIdss = null;
                            brandName = '品牌';
                            sortBool = true;
                            _onRefresh();
                          });
                        }else if (checkType=="master"){
                          
                          setState(() {
                            exprtyIdss = null;
                            masterName = '专家';
                            expertName = null;
                            sortBool = true;
                            _onRefresh();
                          });
                        }
                        
                        
                      },
                      child:Container(
                      padding: EdgeInsets.only(left:5,top:5,bottom:10),
                      child:Text(
                                  checkTypeName,
                                  style: TextStyle(
                                    color:Color(0xff666666),
                                    fontSize:ScreenUtil().setSp(16)
                                  ),
                                  textAlign:TextAlign.start,
                                ),
                    )
                    ),
                   typeList!=null&&typeList!=[]?Container(
                     child: Wrap(
                  alignment: WrapAlignment.start,
                  crossAxisAlignment: WrapCrossAlignment.center,
                  children: typeList.asMap().keys.map((index){
                    return InkWell(
                      onTap: (){
                            print("666");
                            
                            setState(() {
                              sortBool = true;
                              if(checkType=="brand"){
                                brandName = typeList[index].name??"";
                                brandIdss = typeList[index].id;
                                provider.setStateTypeNotNotify(StateType.loading);
                                _onRefresh();
                              }else if(checkType=="master"){
                                masterName= typeList[index].name??'';
                                exprtyIdss= int.parse(typeList[index].userId);
                                expertName= typeList[index].name;
                                provider.setStateTypeNotNotify(StateType.loading);
                                _onRefresh();
                              }
                            });
                            
                          },
                      child: Container(
                      width: width/4-15,
                      padding: EdgeInsets.only(bottom:ScreenUtil().setWidth(10),top:ScreenUtil().setWidth(10)),
                      margin: EdgeInsets.only(left:5,right:5,bottom:5,top:5),
                      decoration: BoxDecoration(
                        // border: Border(
                        //   bottom: BorderSide(width: 0.5, color: Colours.line),
                        // ),
                        color: Color(0xfff5f5f5)
                      ),
                      child:Text(
                                  typeList[index].name??"",
                                  style: TextStyle(
                                    color:checkThis(checkType=="brand"?typeList[index].id:typeList[index].userId)?Color(0xffff0000):Color(0xff666666),
                                    fontSize:ScreenUtil().setSp(15)
                                  ),
                                  textAlign:TextAlign.center,
                                  maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                ),
                    ),
                    );
                    
                  }).toList(),
                )
                   ):loadCircle()
                  ],
                  
                )
              )
            ):
            Container(
              child:null
            ),
                  ],
                )
            )
            ));
  }

  checkThis(id){
    bool isName = false;
    if((checkType == "brand" && brandIdss == id) || (checkType == "master" && exprtyIdss == int.parse(id))){
      isName = true;
    }
    return isName;
  }

  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,
        ),
      ),
    );
  }

  Future _onRefresh() async {
    _page = 1;
    await presenter.getQuestionList(_page,brandIdss,expertName,searchWord);
  }

  Future _loadMore() async {
    _page++;
    await presenter.getQuestionList(_page,brandIdss,expertName,searchWord);
  }

  @override
  QuestionListPresenterSeconds createPresenter() {
    return QuestionListPresenterSeconds();
  }
}
