import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:tab_indicator_styler/tab_indicator_styler.dart';
import 'package:zhiying_base_widget/pages/search_think_page/bloc/search_think_bloc.dart';
import 'package:zhiying_base_widget/pages/search_think_page/model/search_think_model.dart';
import 'package:zhiying_base_widget/widgets/home/home_quick_entry/cached_network_image_util.dart';
import 'package:zhiying_base_widget/widgets/search/tabbar/search_tab_sk.dart';
import 'package:zhiying_base_widget/widgets/search/widget/my_tab.dart';
import 'package:zhiying_base_widget/widgets/search_result/sort/search_result_sort_widget.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'package:zhiying_comm/zhiying_comm.dart';

import 'model/search_result_tab_model.dart';

class SearchResultTabWidget extends StatefulWidget {
  final Map<String, dynamic> data;
  SearchResultTabModel model;

  SearchResultTabWidget(this.data, {Key key}) : super(key: key) {
    try {
      Logger.log('SearchResultTabWidget data = ${data.toString()}');
      model = SearchResultTabModel.fromJson(jsonDecode(data['data']));
    } catch (e) {
      Logger.error(e.toString());
    }
  }

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

class _SearchResultTabWidgetState extends State<SearchResultTabWidget> {
  TabController _tabController;


  /// 联想点击事件
  _onThinkItemClick(SearchThinkModel model){

  }

  @override
  void initState() {
    int length = widget?.model?.search_icon_list?.length ?? 0;
    int initIndex = 0;
    try{
      for(int i = 0; i<length; i++){
        SearchResultTabItemModel  item = widget.model.search_icon_list[i];
        if(item.type == widget.model.type.toString()){
          initIndex = i;
          break;
        }
      }
    }catch(_){}
    _tabController = TabController(length: length, vsync: ScrollableState(), initialIndex: initIndex);
    //   ..addListener((){
    //   String type = '';
    //   try{
    //     type = widget.model.search_icon_list[_tabController.index].type;
    //   }catch(_){}
    //   if(!EmptyUtil.isEmpty(type)) {
    //     BlocProvider.of<SearchThinkBloc>(context).add(SearchThinkChangeTypeEvent(type));
    //   }
    // });
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return _getMainWidget(widget?.model);
  }

  /// 获取主视图
  Widget _getMainWidget(SearchResultTabModel model) {
    return Visibility(
      replacement: SearchTabSkeleton(),
      visible: !EmptyUtil.isEmpty(model),
      child: _getTabar(model),
    );
  }

  /// 获取TabBar
  Widget _getTabar(SearchResultTabModel model) {
    return Container(
      margin: const EdgeInsets.only(/*left: 12.5, right: 12.5,*/ top: 5),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          TabBar(
            controller: _tabController,
            isScrollable: true,
            labelStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
            unselectedLabelColor: HexColor.fromHex('#999999'),
            labelColor: HexColor.fromHex('#FF4242'),
            // indicatorSize: TabBarIndicatorSize.label,
            indicator: MaterialIndicator(
              height: 2.5,
              topLeftRadius: 8,
              topRightRadius: 8,
              bottomLeftRadius: 8,
              bottomRightRadius: 8,
              color: HexColor.fromHex('#FF4242'),
              horizontalPadding: 25,
            ),
            tabs: model.search_icon_list.map((item) {
              return MyTab(
                icon: CachedNetworkImage(
                  imageUrl: item?.with_icon_color ?? '',
                  width: 14,
                ),
                text: item.name,
              );
            }).toList(),
          ),

          // SearchResultSortWidget(null),

          Expanded(
            child: _getStackWidget(model),
          ),
        ],
      ),
    );
  }


  Widget _getStackWidget(SearchResultTabModel model){
    return Stack(
      children: <Widget>[

        /// tabBraviwe
        _getTabBarViewWidget(model),

        // BlocConsumer<SearchThinkBloc, SearchThinkState>(
        //   listener: (context, state){},
        //   buildWhen: (prev, current){
        //     if(current is SearchThinkErrorState){
        //       return false;
        //     }
        //     return true;
        //   },
        //   builder: (context, state){
        //     if(state is SearchThinkLoadedState){
        //       return _getThinkListWidget(state.model);
        //     }
        //     return Container();
        //   },
        // ),

      ],
    );
  }


  /// 联想列表
  Widget _getThinkListWidget(List<SearchThinkModel> model){
    return Container(
      height: double.infinity,
      color: Colors.white,
      child: ListView.builder(itemBuilder: (context, index){
        SearchThinkModel item  = model[index];
        return GestureDetector(
          onTap: ()=> _onThinkItemClick(item),
          child: Container(
            decoration: BoxDecoration(
                border: Border(bottom: BorderSide(width: 0.5, color:  HexColor.fromHex('#EEEEEE')))
            ),
            padding: const EdgeInsets.only(top: 13, bottom: 13),
            child: Text('${item?.keywords}', style: TextStyle( color:  HexColor.fromHex('#333333'), fontSize: 14),),
          ),
        );
      },
        itemCount: model?.length ?? 0,
        padding: const EdgeInsets.only(left: 12.5, right: 12.5),
        shrinkWrap: true,
      ),
    );
  }

  /// tabBraviwe
  Widget _getTabBarViewWidget(SearchResultTabModel model){
    return TabBarView(
      physics: NeverScrollableScrollPhysics(),
      controller: _tabController,
      children: model.search_icon_list.map((item) {
        // TODO 这里需要和后台沟通改成页面的唯一标示
        return PageFactory.create('search_result_item', item.toJson()..['keywords']= widget?.model?.keywords ?? '');
      }).toList(),
    );
  }

}
