import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:zhiying_base_widget/pages/hot_ranking_page/hot_ranking_page_bloc.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/util/extension/color.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'model/hot_tabbar_model.dart';

class HotRankTableBar extends StatefulWidget {
  final Map<String, dynamic> data;

  const HotRankTableBar(this.data, {Key key}) : super(key: key);

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

class _HotRankTableBarState extends State<HotRankTableBar>
    with TickerProviderStateMixin {
  TabController _tabController;

  HotRankingTabBarModel _barModel;

  HotRankingPageBloc _pageBloc;

  @override
  void initState() {
    _barModel =
        HotRankingTabBarModel.fromJson(json.decode(widget.data['data']));
    _tabController =
        TabController(length: _barModel.tabList.length, vsync: this);
    _pageBloc = BlocProvider.of<HotRankingPageBloc>(context);

    ///待页面初始化后发送加载事件
    Timer(Duration(milliseconds: 100), () {
      if (_barModel != null &&
          _barModel.tabList != null &&
          _barModel.tabList.length > 0) {
        var params = {
          "type": "loadData",
          "type_id": _barModel.tabList[0].typeId
        };
        _pageBloc.sendEvent(params);
      }
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(bottom: 10),
      child: TabBar(
        indicatorPadding: EdgeInsets.only(bottom: 0),
        indicatorSize: TabBarIndicatorSize.label,
        controller: _tabController,
        indicatorColor: HexColor.fromHex(
            _barModel.tabList[_tabController.index].nameSelectColor),
        unselectedLabelColor: HexColor.fromHex(
            _barModel.tabList[_tabController.index].nameNoSelectColor),
        labelColor: HexColor.fromHex(
            _barModel.tabList[_tabController.index].nameSelectColor),
        isScrollable: true,
        tabs: _buildTabs(),
        onTap: (index) {
          var params = {
            "type": "loadData",
            "type_id": _barModel.tabList[_tabController.index].typeId
          };
          _pageBloc.sendEvent(params);
        },
      ),
    );
  }

  _buildTabs() {
    List<Widget> listWidget = List();
    for (int index = 0; index < _barModel.tabList.length; index++) {
      var item = _barModel.tabList[index];

      listWidget.add(Container(
        child: Padding(
          padding: const EdgeInsets.only(
            bottom: 2,
            top: 0,
          ),
          child: Text(
            item.name,
            style: TextStyle(fontSize: 26.sp),
          ),
        ),
      ));
    }
    return listWidget;
  }
}
