import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:tab_indicator_styler/tab_indicator_styler.dart';
import 'package:zhiying_base_widget/dialog/tip_dialog/tip_dialog.dart';
import 'package:zhiying_base_widget/widgets/wallet/wallet_detail/model/wallet_detail_model.dart';
import 'package:zhiying_base_widget/widgets/wallet/wallet_detail/wallet_detail_bloc.dart';
import 'package:zhiying_base_widget/widgets/wallet/wallet_detail/wallet_detail_sk.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:provider/provider.dart';

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

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

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

class _WalletDetailState extends State<WalletDetail>
    with TickerProviderStateMixin {
  WalletDetailModel _model;

  TabController _tabController;

  WalletDetailBloc _bloc;

  @override
  void initState() {
    if (widget.data != null) {
      _model = WalletDetailModel.fromJson(json.decode(widget.data['data']));
      _tabController =
          TabController(length: _model.providers.length, vsync: this);
    }
    _bloc = new WalletDetailBloc();
    _bloc.loadData(_model.providers[0].type);

    super.initState();
  }


  @override
  void didChangeDependencies() {
    RefreshListener.listen(context, (event) {
      if (event == "refresh") {
        if (_bloc.currentType == null) {
          _bloc.loadData(_model.providers[0].type);
        } else {
          _bloc.loadData(_bloc.currentType);
        }
      }
    });
    super.didChangeDependencies();
  }

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

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: _bloc.outData,
      builder: (context, asyn) {
        if (_bloc.listDataModel.length == 0) {
          ///骨架图
          return WalletDetailSkeleton();
        }
        return Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(8)),
          margin:
              EdgeInsets.only(left: 12.5, right: 12.5, top: 7.5, bottom: 7.5),
          padding: const EdgeInsets.only(bottom: 13),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(top: 12),
                child: TabBar(
                    indicatorWeight: 3,
                    indicator: MaterialIndicator(
                      height: 2,
                      bottomLeftRadius: 1,
                      bottomRightRadius: 1,
                      horizontalPadding: 0,
                      topLeftRadius: 1,
                      topRightRadius: 1,
                      color: HexColor.fromHex(_model.providers[0].selectColor),
                    ),
                    isScrollable: true,
                    unselectedLabelColor:
                        HexColor.fromHex(_model.providers[0].unselectColor),
                    labelColor:
                        HexColor.fromHex(_model.providers[0].selectColor),
                    controller: _tabController,
                    indicatorColor:
                        HexColor.fromHex(_model.providers[0].selectColor),
                    indicatorSize: TabBarIndicatorSize.label,
                    onTap: (index) {
                      ///变更平台
                      changeProvider(_model.providers[index].type);
                    },
                    tabs: _buildTabs()),
              ),

              ///日期选择
              Container(
                height: 50,
                alignment: Alignment.center,
                child: ListView.builder(
                  padding: EdgeInsets.only(left: 8),
                  itemCount: _model.dateList.length,
                  scrollDirection: Axis.horizontal,
                  itemBuilder: _buildTimeItem,
                ),
              ),

              /// 数据
              Container(
                height: 63,
                margin: EdgeInsets.only(top: 16, left: 15, right: 15),
                width: double.infinity,
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: CachedNetworkImageProvider(
                            _model.providerDashbord.finish.bgImg),
                        fit: BoxFit.fill)),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    _model.providerDashbord.finish.isShow == "1"
                        ? Container()
                        : Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              _model.providerDashbord.finish.text,
                              style: TextStyle(
                                  fontSize: 14,
                                  color: HexColor.fromHex(_model
                                      .providerDashbord.finish.textColor)),
                            ),
                          ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          _model.providerDashbord.finish.text ?? "",
                          style: TextStyle(color: Colors.black, fontSize: 11),
                        ),
                        InkWell(
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: CachedNetworkImage(
                                imageUrl:
                                    _model.providerDashbord.finish.tipIcon ??
                                        "",
                                width: 10,
                                height: 10,
                                fit: BoxFit.fill,
                              ),
                            ),
                            onTap: () {
                              ///显示弹窗
                              showTipDialog(
                                  null, _model.providerDashbord.finish.tipText);
                            })
                      ],
                    ),
                    Text(
                      _bloc.selectDateData.finish ?? "",
                      style: TextStyle(
                          color: Colors.red,
                          fontSize: 20,
                          fontFamily: 'Din',
                          package: 'zhiying_comm',
                          fontWeight: FontWeight.bold),
                    )
                  ],
                ),
              ),
              Container(
                child: ListView.builder(
                    padding: EdgeInsets.all(0),
                    itemCount: 3,
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    itemBuilder: (context, index) {
                      return _buildBottomItem(
                          context, index, _model.providerDashbord);
                    }),
              )
            ],
          ),
        );
      },
    );
  }

  ///平台选择
  _buildTabs() {
    List<Widget> listWidget = List();
    for (var item in _model.providers) {
      listWidget.add(Text(
        item.name,
        style: TextStyle(
          fontSize: 14,
        ),
      ));
    }
    return listWidget;
  }

  Widget _buildTimeItem(BuildContext context, int index) {
    var item = _model.dateList[index];
    return InkWell(
      child: Container(
        margin: EdgeInsets.only(top: 0, left: 8, right: 8),
        decoration: BoxDecoration(
          image: DecorationImage(
              image: CachedNetworkImageProvider(
                  item.type == _bloc.selectDateData.type
                      ? item.btnImg ?? ""
                      : item.btnNoColorImg ?? ""),
              fit: BoxFit.fitWidth),
        ),
        child: Padding(
          padding: const EdgeInsets.only(left: 16, right: 16),
          child: Center(
              child: Text(
            item.text,
            style: TextStyle(
                fontSize: 11,
                color: HexColor.fromHex(item.type == _bloc.selectDateData.type
                    ? item.textSelectColor
                    : item.textUnselectColor)),
          )),
        ),
      ),
      onTap: () {
        for (var select in _bloc.listDataModel) {
          if (select.type == item.type) {
            _bloc.selectDay = item.type;
            _bloc.refresh();
            return;
          }
        }
      },
    );
  }

  ///底部显示
  Widget _buildBottomItem(
      BuildContext context, int index, ProviderDashbord dashbord) {
    SelfBuy item;
    if (index == 0) {
      item = dashbord.selfBuy;
    } else if (index == 1) {
      item = dashbord.directPromote;
    } else {
      item = dashbord.indirectPromote;
    }

    var dataMap = _bloc.selectDateData.toJson();

    return Container(
      child: Column(
        children: <Widget>[
          SizedBox(
            height: 7.5,
          ),
          item.isShow == "0"
              ? Container()
              : Text(
                  item.title,
                  style: TextStyle(
                      color: HexColor.fromHex(item.titleColor), fontSize: 14),
                ),
          SizedBox(
            height: 7.5,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Expanded(
                child: Container(
                    height: 61.5,
                    margin: EdgeInsets.only(right: 8, left: 15),
                    padding: EdgeInsets.only(left: 10),
                    decoration: BoxDecoration(
                        image: DecorationImage(
                            image: CachedNetworkImageProvider(
                                item.itemList[0].bgImg ?? ""),
                            fit: BoxFit.fill)),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Text(
                              item.itemList[0].text ?? "",
                              style: TextStyle(
                                  fontSize: 11,
                                  color: HexColor.fromHex(
                                      item.itemList[0].textColor)),
                            ),
                            InkWell(
                              child: Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: CachedNetworkImage(
                                  imageUrl: item.itemList[0].tipIcon,
                                  width: 10,
                                  height: 10,
                                  fit: BoxFit.fill,
                                ),
                              ),
                              onTap: () {
                                //弹窗
                                showTipDialog(null, item.itemList[0].tipText);
                              },
                            )
                          ],
                        ),
                        Text(dataMap[item.itemList[0].vauleKey],
                            style: TextStyle(
                              fontFamily: 'Din',
                              package: 'zhiying_comm',
                              fontWeight: FontWeight.bold,
                              fontSize: 17,
                              color:
                                  HexColor.fromHex(item.itemList[1].valueColor),
                            ))
                      ],
                    )),
              ),
              Expanded(
                  child: Container(
                height: 61.5,
                margin: EdgeInsets.only(
                  left: 8,
                  right: 15,
                ),
                padding: EdgeInsets.only(left: 10),
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: CachedNetworkImageProvider(
                            item.itemList[1].bgImg ?? ""),
                        fit: BoxFit.fill)),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Text(
                          item.itemList[1].text ?? "",
                          style: TextStyle(
                              fontSize: 11,
                              color:
                                  HexColor.fromHex(item.itemList[1].textColor)),
                        ),
                        InkWell(
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: CachedNetworkImage(
                              imageUrl: item.itemList[1].tipIcon,
                              width: 10,
                              height: 10,
                              fit: BoxFit.fill,
                            ),
                          ),
                          onTap: () {
                            //弹窗
                            showTipDialog(null, item.itemList[1].tipText);
                          },
                        )
                      ],
                    ),
                    Text(
                      dataMap[item.itemList[1].vauleKey],
                      style: TextStyle(
                          fontSize: 17,
                          color: HexColor.fromHex(item.itemList[1].valueColor),
                          fontFamily: 'Din',
                          package: 'zhiying_comm',
                          fontWeight: FontWeight.bold),
                    )
                  ],
                ),
              ))
            ],
          )
        ],
      ),
    );
  }

  ///变更平台
  void changeProvider(String type) {
    _bloc.loadData(type);
  }

  ///显示提示框
  void showTipDialog(String title, String content) {
    showDialog(context: context, child: TipDialog(content: content));
  }
}
