import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:tab_indicator_styler/tab_indicator_styler.dart';
import 'package:zhiying_base_widget/pages/favorites_page/bloc/favorites_bloc.dart';
import 'package:zhiying_base_widget/pages/favorites_page/bloc/favorites_repository.dart';
import 'package:zhiying_base_widget/widgets/favorites/goods_list/favorites_goods_list_widget.dart';
import 'package:zhiying_comm/util/empty_util.dart';
import 'package:zhiying_comm/util/extension/color.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:provider/provider.dart';
import 'package:zhiying_comm/util/log/let_log.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:zhiying_comm/util/router_util.dart';

import 'model/favorites_style_model.dart';
import 'notifier/favorites_page_notifier.dart';

///
/// 收藏夹
///
class FavoritesPage extends StatelessWidget {

  final Map<String, dynamic> data;
  FavoritesPage(this.data);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider.value(value: FavoritesPageNotifier()),
      ],
      child: BlocProvider<FavoritesBloc>(
        create: (_) => FavoritesBloc(FavoritesRepository())..add(FavoritesInitEvent(model: data)),
        child: _FavoritesPageContainer(),
      ),
    );
  }
}

class _FavoritesPageContainer extends StatefulWidget {
  @override
  _FavoritesPageContainerState createState() => _FavoritesPageContainerState();
}

class _FavoritesPageContainerState extends State<_FavoritesPageContainer> with TickerProviderStateMixin {
  TextEditingController _editingController;
  FocusNode _focusNode;
  TabController _tabController;
  bool _isNotEditing = true;

  /// 点击编辑
  void _onClickEditing() {
    RouterUtil.hideKeyboard(context);
    setState(() {
      _isNotEditing = !_isNotEditing;
    });
    Provider.of<FavoritesPageNotifier>(context, listen: false).editing();
  }

  /// 点击搜索
  void _onClickSearch() {}

  /// 执行搜索
  void _submitSearch() {
    String keyword = _editingController?.text?.toString()?.trim();
    // if (!EmptyUtil.isEmpty(keyword)) {
    _tabController.index = 0;
    Provider.of<FavoritesPageNotifier>(context, listen: false).search(keyword);
    // } else {
    //   Fluttertoast.showToast(msg: '请输入需要搜索的内容～');
    // }
  }

  /// tabBar的初始化
  void _tabControllerInit(FavoritesStyleModel model) {
    if ((null == _tabController && !EmptyUtil.isEmpty(model?.tabList)) ||
        (!EmptyUtil.isEmpty(model?.tabList) && null != _tabController && _tabController.length != model.tabList.length)) {
      _tabController = TabController(length: model.tabList.length, vsync: this)
        ..addListener(() {
          if (!_tabController.indexIsChanging) {
            RouterUtil.hideKeyboard(context);
            Logger.log('tab index = ${_tabController.index}');
            Provider.of<FavoritesPageNotifier>(context, listen: false).changeSelectIndex(_tabController.index);
          }
        });
    }
  }

  @override
  void initState() {
    _editingController = TextEditingController();
    _focusNode = FocusNode();
    super.initState();
  }

  @override
  void dispose() {
    _focusNode?.unfocus();
    _focusNode?.dispose();
    _editingController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<FavoritesBloc, FavoritesState>(
      listener: (context, state) {},
      buildWhen: (prev, current) {
        return true;
      },
      builder: (context, state) {
        if (state is FavoritesLoadedState) {
          _tabControllerInit(state?.model);
          return _buildMainWidget(state?.model);
        }
        return _buildSkeletonWidget();
      },
    );
  }

  /// mainWidget
  Widget _buildMainWidget(FavoritesStyleModel model) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      resizeToAvoidBottomPadding: false,
      backgroundColor: HexColor.fromHex('#FFFFFF'),
      appBar: _buildAppBarWidget(model),
      body: Column(
        children: <Widget>[
          /// 搜索框
          Padding(padding: const EdgeInsets.only(left: 12.5, right: 12.5, top: 4), child: _buildSearchWidget(model)),

          /// tabBar
          Padding(padding: const EdgeInsets.only(top: 4), child: _buildTabBarWidget(model)),

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

  /// TabBar
  Widget _buildTabBarWidget(FavoritesStyleModel model) {
    return Container(
      padding: const EdgeInsets.only(top: 12.5, bottom: 14.5),
      width: double.infinity,
      child: TabBar(
        isScrollable: true,
        labelStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
        unselectedLabelStyle: TextStyle(fontWeight: FontWeight.w400, fontSize: 14),
        labelColor: HexColor.fromHex(model?.tabNameSelectedColor ?? '#FF0100'),
        unselectedLabelColor: HexColor.fromHex(model?.tabNameColor ?? '#333333'),
        indicatorSize: TabBarIndicatorSize.label,
        controller: _tabController,
        indicatorWeight: 5,
        indicator: MaterialIndicator(
          topLeftRadius: 1,
          topRightRadius: 1,
          bottomLeftRadius: 1,
          bottomRightRadius: 1,
          height: 2,
          color: HexColor.fromHex(model?.tabLineColor ?? '#FF0100'),
          horizontalPadding: 5,
        ),
        tabs: model.tabList.map((e) => Text(e?.name ?? '')).toList(),
      ),
    );
  }

  /// tabBarView
  Widget _buildTabBarViewWidget(FavoritesStyleModel model) {
    int length = model?.tabList?.length ?? 0;
    if (length > 0) {
      int index = -1;
      return TabBarView(
        physics: NeverScrollableScrollPhysics(),
        controller: _tabController,
        children: model.tabList.map((e) {
          ++index;
         return FavoritesGoodsListWidget(
            model: model,
            type: e?.type,
            currentIndex: index,
          );
        }).toList(),
      );
    }
    return Container(color: HexColor.fromHex('#F9F9F9'));
  }

  /// 搜索框
  Widget _buildSearchWidget(FavoritesStyleModel model) {
    return Container(
      alignment: Alignment.center,
      width: double.infinity,
      height: 35,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(35 / 2),
        color: HexColor.fromHex(model?.searchBarBgColor ?? '#F9F9F9'),
      ),
      child: TextField(
        controller: _editingController,
        focusNode: _focusNode,
        onSubmitted: (text) => _submitSearch(),
        textInputAction: TextInputAction.search,
        style: TextStyle(color: HexColor.fromHex('#333333'), fontSize: 14, textBaseline: TextBaseline.alphabetic),
        textAlign: TextAlign.center,
        decoration: InputDecoration(
          fillColor: Colors.transparent,
          filled: true,
          isDense: true,
          contentPadding: EdgeInsets.zero,
          hintText: model?.searchBarText ?? '搜索商品',
          hintStyle: TextStyle(color: HexColor.fromHex(model?.searchBarTextColor ?? '#999999'), fontSize: 14, textBaseline: TextBaseline.alphabetic),
          border: InputBorder.none,
          enabledBorder: InputBorder.none,
          disabledBorder: InputBorder.none,
          errorBorder: InputBorder.none,
          focusedErrorBorder: InputBorder.none,
          focusedBorder: InputBorder.none,
        ),
      ),
    );
  }

  /// appbar
  Widget _buildAppBarWidget(FavoritesStyleModel model) {
    return AppBar(
      backgroundColor: HexColor.fromHex(model?.appBarBgColor ?? '#FFFFFF'),
      brightness: Brightness.light,
      leading: IconButton(
        icon: Icon(
          Icons.arrow_back_ios,
          size: 22,
          color: HexColor.fromHex('#333333'),
        ),
        onPressed: () => Navigator.maybePop(context),
      ),
      title: Text(
        model?.appBarName ?? '我的收藏',
        style: TextStyle(color: HexColor.fromHex(model?.appBarNameColor ?? '#333333'), fontSize: 15, fontWeight: FontWeight.bold),
      ),
      centerTitle: true,
      elevation: 0,
      actions: <Widget>[
        GestureDetector(
          onTap: () => _onClickEditing(),
          behavior: HitTestBehavior.opaque,
          child: Center(
            child: Padding(
              padding: const EdgeInsets.only(right: 12.5),
              child: Text(
                _isNotEditing ? model?.appBarRightText ?? '编辑' : model?.appBarRightEditingText ?? '完成',
                style: TextStyle(
                    color: HexColor.fromHex(_isNotEditing ? model?.appBarRightTextColor ?? '#333333' : model?.appBarRightEditingColor ?? '#FF4242'),
                    fontSize: 14,
                    fontWeight: FontWeight.bold),
              ),
            ),
          ),
        )
      ],
    );
  }

  /// 骨架图
  Widget _buildSkeletonWidget() {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Container(),
    );
  }
}
