import 'dart:convert' as convert;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/goods_share_bloc.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/goods_share_image/goods_share_image.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/goods_share_link/goods_share_link.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/goods_share_miniprogram/goods_share_miniprogram.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/models/goods_share_temp_add_model.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class GoodsSharePage extends StatefulWidget {
  final Map<String, dynamic> model;

  const GoodsSharePage(this.model, {Key key}) : super(key: key);

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

class _GoodsSharePageState extends State<GoodsSharePage> {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<GoodsShareBloc>(
      bloc: GoodsShareBloc(),
      child: _GoodsShareContainer(widget.model),
    );
  }
}

class _GoodsShareContainer extends StatefulWidget {
  final Map<String, dynamic> model;

  const _GoodsShareContainer(this.model, {Key key}) : super(key: key);

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

class _GoodsShareContainerState extends State<_GoodsShareContainer>
    with TickerProviderStateMixin {
  GoodsShareBloc _bloc;
  TabController _tabController;
  List<Widget> _tabs = [];
  List<Widget> _contents = [];

  @override
  void initState() {
    String d = widget.model['data'];
    Map<String, dynamic> data =
        Map<String, dynamic>.from(convert.jsonDecode(d));
    Logger.debug(data['share_url_args'].toString());
    _bloc = BlocProvider.of<GoodsShareBloc>(context);
    _bloc.loadData('taobao', data['share_url_args']);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff8f8f8),
      appBar: _createNav(),
      body: StreamBuilder<GoodsShareData>(
        stream: _bloc.outData,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          GoodsShareData data = snapshot.data;
          List<Map<String, dynamic>> list = data?.tabs;
          List<GoodsShareTempDataModel> datas = data?.datas;
          if (list == null ||
              list.length == 0 ||
              datas == null ||
              datas.length == 0) {
            return Container();
          }

          _tabController = TabController(length: list.length, vsync: this);
          _tabs.clear();
          _contents.clear();
          for (int i = 0; i < list.length && i < datas.length; i++) {
            Map<String, dynamic> item = list[i];
            GoodsShareTempDataModel model = datas[i];
            _tabs.add(_createTabItem(item['title']));
            String mod_name = item['mod_name'];
            if (mod_name == 'share_goods_image.taobao') {
              _contents.add(GoodsShareImage(item, model));
            } else if (mod_name == 'share_goods_link.taobao') {
              _contents.add(GoodsShareLink(item, model));
            } else if (mod_name == 'share_goods_mini.taobao') {
              _contents.add(GoodsShareMiniprogram(item, model));
            } else {
              _contents.add(Container());
            }
          }

          return Column(
            children: <Widget>[
              _createCommission(),
              Expanded(child: SafeArea(child: _createContent())),
            ],
          );
        },
      ),
    );
  }

  // 导航栏
  Widget _createNav() {
    return CupertinoNavigationBar(
      border: Border(
        bottom: BorderSide(
          width: 0.0, // One physical pixel.
          style: BorderStyle.none,
        ),
      ),
      // backgroundColor: HexColor.fromHex('#ffffff'),
      leading: Navigator.canPop(context)
          ? GestureDetector(
              child: Container(
                padding: EdgeInsets.zero,
                child: Icon(
                  Icons.arrow_back_ios,
                  size: 20,
                ),
              ),
              onTap: () {
                if (Navigator.canPop(context)) {
                  Navigator.pop(context);
                }
              },
            )
          : Container(),
      middle: Text(
        '分享商品',
        style: TextStyle(
          fontSize: 15,
          color: HexColor.fromHex('#333333'),
        ),
      ),
    );
  }

  Widget _createCommission() {
    return Container(
      margin: EdgeInsets.only(left: 12.5, right: 12.5, top: 4, bottom: 4),
      padding: EdgeInsets.only(left: 10, right: 10),
      width: double.infinity,
      height: 32,
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(8)),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            width: 20,
            height: 20,
            margin: EdgeInsets.only(right: 10),
            decoration: BoxDecoration(
                color: Colors.redAccent,
                borderRadius: BorderRadius.circular(10)),
          ),
          Text(
            '奖励预估收益 ¥ 12.35 元',
            style: TextStyle(
                fontSize: 13,
                fontWeight: FontWeight.bold,
                color: Color(0xff333333)),
          ),
        ],
      ),
    );
  }

  Widget _createContent() {
    return Container(
      margin: EdgeInsets.only(left: 12.5, right: 12.5, top: 4, bottom: 4),
      width: double.infinity,
      height: double.infinity,
      // decoration: BoxDecoration(
      //     color: Colors.white, borderRadius: BorderRadius.circular(8)),
      child: Column(
        children: <Widget>[
          Container(
            height: 40,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(8), topRight: Radius.circular(8))),
            width: double.infinity,
            child: TabBar(
              controller: _tabController,
              tabs: _tabs,
              indicatorColor: Color(0xffff4242),
              indicatorSize: TabBarIndicatorSize.label,
            ),
          ),
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: _contents,
            ),
          )
        ],
      ),
    );
  }

  Widget _createTabItem(String title, {bool isSelected = false}) {
    return Text(
      title,
      style: TextStyle(
        fontSize: 13,
        color: isSelected ? Color(0xffff4242) : Color(0xff333333),
        fontWeight: FontWeight.bold,
      ),
    );
  }
}
