import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:zhiying_base_widget/pages/vip_center_page/bloc/vip_center_bloc.dart';
import 'package:zhiying_base_widget/pages/vip_center_page/bloc/vip_center_repository.dart';
import 'package:zhiying_base_widget/pages/vip_center_page/model/vip_center_style_model.dart';
import 'package:zhiying_base_widget/pages/vip_center_page/vip_center_tip_dialog_widget.dart';
import 'package:zhiying_base_widget/pages/vip_center_page/vip_center_upgrade_dialog_page.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'dart:ui';
import 'package:flutter_bloc/flutter_bloc.dart';

///
/// 会员中心
///
class VipCenterPage extends StatelessWidget {
  final Map<String, dynamic> data;

  VipCenterPage(this.data);

  @override
  Widget build(BuildContext context) {
    return BlocProvider<VipCenterBloc>(
      create: (_) => VipCenterBloc(VipCenterRepository())..add(VipCenterInitEvent()),
      child: _VipCenterPageContainer(),
    );
  }
}

class _VipCenterPageContainer extends StatefulWidget {
  @override
  __VipCenterPageContainerState createState() => __VipCenterPageContainerState();
}

class __VipCenterPageContainerState extends State<_VipCenterPageContainer> {


  SwiperController _swiperController;

  /// 分享
  void _onShareClick() {}

  /// 点击子item任务
  void _onClickItemTask() {
    // showDialog(context: context, child: VipCenterTipDialog());
    showModalBottomSheet(
        backgroundColor: Colors.transparent,
        isScrollControlled: true,
        context: context,
        builder: (context) {
          return VipCenterUpgradeDialogPage();
        });
  }

  @override
  void initState() {
    _swiperController = SwiperController();
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<VipCenterBloc, VipCenterState>(
      listener: (context, state) {},
      buildWhen: (prov, current) {
        if (current is VipCenterErrorState) {
          return false;
        }
        return true;
      },
      builder: (context, state) {
        /// 数据加载成功
        if (state is VipCenterLoadedState) {
          return _buildMainWidget(state?.styleMode);
        }

        /// 初始化出错
        if (state is VipCenterInitErrorState) {}

        /// 加载骨架图
        return _buildSkeletonWidget();
      },
    );
  }

  /// 骨架图
  Widget _buildSkeletonWidget(){
    return Scaffold(
      appBar: _buildAppBarWidget(null),
      body: Container(),
    );
  }

  /// 主视图
  Widget _buildMainWidget(VipCenterStyleModel styleModel) {
    return MediaQuery.removePadding(
      context: context,
      removeBottom: true,
      child: Container(
        color: HexColor.fromHex(styleModel?.bgColor ?? '#F9F9F9'),
        child: Stack(
          children: <Widget>[
            /// 背景图
            Align(
                alignment: Alignment.topCenter,
                child: Container(
                  width: double.infinity,
                  height: 244 + MediaQueryData.fromWindow(window).padding.top,
                  // color: HexColor.fromHex('#2A2A2A'),
                  child: CachedNetworkImage(
                    imageUrl: styleModel?.bgImg ?? '',
                    fit: BoxFit.cover,
                  ),
                )),

            /// 内容
            Scaffold(
              backgroundColor: Colors.transparent,
              appBar: _buildAppBarWidget(styleModel),
              body: ListView(
                children: <Widget>[
                  const SizedBox(height: 20),

                  /// 会员中心
                  _buildVipInifoWidget(styleModel),
                  const SizedBox(height: 30),

                  /// 会员卡片
                  _buildVipCardWidget(),
                  // const SizedBox(height: 12),

                  /// 快速导航
                  _buildQuickWidget(),

                  /// 任务
                  _buildTaskWidget(),
                ],
              ),
            ),

            /// 升级按钮
            Align(alignment: Alignment.bottomCenter, child: _buildUpgradeButtonWidget(styleModel)),
          ],
        ),
      ),
    );
  }

  /// 头部Widget
  Widget _buildHeadWidget() {
    return Container(
      child: Stack(
        children: <Widget>[],
      ),
    );
  }

  int _indexSelect = 0;

  /// 会员卡片
  Widget _buildVipCardWidget() {
    return Container(
      width: double.infinity,
      height: 123,
      // color: HexColor.fromHex('#eeF0D199'),
      child: Swiper(
        controller: _swiperController,
        itemCount: 4,
        itemBuilder: (context, index) {
          return Container(
            height: double.infinity,
            width: double.infinity,
            color: HexColor.fromHex('#eeF0D199'),
          );
        },
        onIndexChanged: (index) => _indexSelect = index,
        scale: 0.85,
        viewportFraction: 0.81,
        loop: false,
        onTap: (index) => _onClickItemTask(),
      ),
    );
  }

  /// 快速导航
  Widget _buildQuickWidget() {
    return Container(
      margin: const EdgeInsets.only(left: 12.5, right: 12.5, top: 12),
      padding: const EdgeInsets.only(top: 12),
      width: double.infinity,
      decoration: BoxDecoration(
          color: HexColor.fromHex('#FFFFFF'),
          // borderRadius: BorderRadius.only(bottomLeft: Radius.circular(10), bottomRight: Radius.circular(10))
          borderRadius: BorderRadius.circular(10)),
      child: GridView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
        ),
        itemBuilder: (context, index) {
          return _QuickItemWidget();
        },
        itemCount: 12,
      ),
    );
  }

  /// 任务视图
  Widget _buildTaskWidget() {
    return Container(
      margin: const EdgeInsets.only(left: 12.5, right: 12.5, top: 10),
      padding: const EdgeInsets.only(left: 15.5, right: 13.5, top: 15, bottom: 100),
      decoration: BoxDecoration(
        color: HexColor.fromHex('#FFFFFF'),
        borderRadius: BorderRadius.only(topLeft: Radius.circular(10), topRight: Radius.circular(10)),
      ),
      child: Column(
        children: <Widget>[
          _TaskItemWidget(),
          _TaskItemWidget(),
        ],
      ),
    );
  }

  /// 会员信息
  Widget _buildVipInifoWidget(VipCenterStyleModel styleModel) {
    return Column(
      children: <Widget>[
        /// 会员头像
        Container(
          width: 45,
          height: 45,
          // color: Colors.red,
          child: Stack(
            children: <Widget>[
              Center(
                child: Container(height: double.infinity, width: double.infinity, decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(45/2)
                ),),
              ),
              Align(
                alignment: Alignment.bottomRight,
                child: Transform.translate(
                  offset: Offset(36/2, 18/2),
                    child: CachedNetworkImage(imageUrl: styleModel?.avatarLvIcon, width: 36,)),
              ),
            ],
          ),
        ),
        const SizedBox(height: 13),

        /// 会员昵称
        Text('我不猜', style: TextStyle(color: HexColor.fromHex(styleModel?.avatarUsernameColor ?? '#FFFFFF'), fontSize: 16)),
      ],
    );
  }

  /// 升级按钮
  Widget _buildUpgradeButtonWidget(VipCenterStyleModel styleModel) {
    return Container(
      height: 50,
      margin: const EdgeInsets.only(left: 15.5 + 12.5, right: 15.5 + 12.5, bottom: 24),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(50 / 2),
          image: DecorationImage(
              fit: BoxFit.fitWidth,
              image: CachedNetworkImageProvider(
                styleModel?.bottomBtn?.img ?? '',
              ))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          /// vip 图标
          CachedNetworkImage(
            imageUrl: styleModel?.bottomBtn?.icon,
            width: 18,
          ),
          const SizedBox(width: 18),
          Text(
            styleModel?.bottomBtn?.name ?? '',
            style: TextStyle(color: HexColor.fromHex('#303030'), fontSize: 18, fontWeight: FontWeight.bold, decoration: TextDecoration.none),
          )
        ],
      ),
    );
  }

  /// appBar
  Widget _buildAppBarWidget(VipCenterStyleModel styleModel) {
    return AppBar(
      backgroundColor: Colors.transparent,
      leading: IconButton(
        icon: Icon(
          Icons.arrow_back_ios,
          size: 22,
          color: HexColor.fromHex('#FFFFFF'),
        ),
        onPressed: () => Navigator.maybePop(context),
      ),
      centerTitle: true,
      elevation: 0,
      title: Text(styleModel?.appBarName ?? '会员中心', style: TextStyle(fontSize: 18, color: HexColor.fromHex(styleModel?.appBarNameColor ?? '#FFFFFF'))),
      actions: <Widget>[
        GestureDetector(
          onTap: () => _onShareClick(),
          behavior: HitTestBehavior.opaque,
          child: Center(
            child: Container(
              margin: const EdgeInsets.only(right: 12.5),
              width: 20,
              height: 20,
              child: CachedNetworkImage(
                imageUrl: styleModel?.appBarRightShareIcon ?? '',
              ),
            ),
          ),
        )
      ],
    );
  }
}

class _QuickItemWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          width: 41,
          height: 40,
          color: Colors.yellowAccent,
          child: Stack(
            children: <Widget>[
              /// icon
              Align(
                alignment: Alignment.topRight,
                child: Container(
                  width: 11,
                  height: 11,
                  color: Colors.red,
                ),
              )
            ],
          ),
        ),
        const SizedBox(height: 5),
        Text(
          '自购分佣',
          style: TextStyle(color: HexColor.fromHex('#999990'), fontSize: 12),
        )
      ],
    );
  }
}

class _TaskItemWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        /// title
        _buildTitleWidget(),
        const SizedBox(height: 15),

        /// data
        Column(
          children: <Widget>[
            _buildDataWidget(),
            const SizedBox(height: 15.5),
            _buildDataWidget(),
            const SizedBox(height: 15.5),
            _buildDataWidget(),
            const SizedBox(height: 15.5),
          ],
        ),
        const SizedBox(height: 6)
      ],
    );
  }

  /// 标题
  Widget _buildTitleWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Container(
          width: 18,
          height: 18,
          color: Colors.red,
        ),
        const SizedBox(width: 10),
        Text(
          '必做任务',
          style: TextStyle(fontSize: 16, color: HexColor.fromHex('#333333'), fontWeight: FontWeight.bold),
        )
      ],
    );
  }

  /// 元素
  Widget _buildDataWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.end,
      children: <Widget>[
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              '邀请好友10人',
              style: TextStyle(color: HexColor.fromHex('#333333'), fontSize: 14),
            ),
            const SizedBox(height: 4.5),

            /// 进度条
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Container(
                  height: 10,
                  width: 140,
                  color: Colors.red,
                ),
                const SizedBox(width: 10),
                Text(
                  '3/10',
                  style: TextStyle(color: HexColor.fromHex('#666660'), fontSize: 14),
                )
              ],
            )
          ],
        ),

        /// 完成的图片
        Container(
          width: 65,
          height: 24,
          color: Colors.red,
        )
      ],
    );
  }
}
