import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:zhiying_base_widget/pages/security_page/models/security_style_model.dart';
import 'package:zhiying_base_widget/pages/security_page/security_page_bloc.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:provider/provider.dart';

///
/// 账号安全
///
class SecurityPage extends StatefulWidget {
  final Map<String, dynamic> data;

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

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

class _SecurityPageState extends State<SecurityPage> {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<SecurityPageBloc>(
      bloc: SecurityPageBloc(),
      child: _SecurityContainer(widget.data),
    );
  }
}

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

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

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

class _SecurityContainerState extends State<_SecurityContainer> {
  SecurityPageBloc _bloc;
  UserInfoModel _user;

  @override
  void didChangeDependencies() {
    _user = Provider
        .of<UserInfoNotifier>(context)
        .userInfo;
    super.didChangeDependencies();
  }


  @override
  void initState() {
    _bloc = BlocProvider.of<SecurityPageBloc>(context);
    _bloc.loadData(widget.data['skip_identifier']);

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<SecurityStyleModel>(
        stream: _bloc.outData,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          SecurityStyleModel style = snapshot.data;

          List<Widget> widgets = List();
          widgets.addAll(style?.settings?.map((item) {
            return _createItem(item);
          })?.toList() ??
              []);
          if((style?.accountDelete?.isShow??"0")=="1"){
            widgets.add(_createLogout(style));
          }


          return Scaffold(
              backgroundColor: Color(0xfff9f9f9),
              appBar: _createNav(style),
              body: SingleChildScrollView(
                child: Column(
                  children: widgets,
                ),
              ));
        });
  }

  // 导航栏
  Widget _createNav(SecurityStyleModel style) {
    return CupertinoNavigationBar(
      border: Border(
        bottom: BorderSide(
          width: 0.0, // One physical pixel.
          style: BorderStyle.none,
        ),
      ),
      backgroundColor: HexColor.fromHex(style?.appBarBgColor ?? '#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?.appBarName ?? '账号安全',
        style: TextStyle(
          fontSize: 15,
          color: HexColor.fromHex(style?.appBarNameColor ?? '#333333'),
        ),
      ),
    );
  }

  Widget _createItem(SecurityStyleItemModel item) {
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.only(left: 12.5, right: 12.5),
        width: double.infinity,
        height: 50,
        color: Colors.white,
        child: Row(
          children: <Widget>[
            Expanded(
              child: Text(
                item.name,
                style: TextStyle(
                  fontSize: 13,
                  color: HexColor.fromHex(item?.nameColor ?? '#333333'),
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            Expanded(
              child: Text(
                item.desc ?? '',
                textAlign: TextAlign.right,
                style: TextStyle(
                  fontSize: 13,
                  color: HexColor.fromHex(item?.descColor ?? '#333333'),
                ),
              ),
            ),
            Icon(
              Icons.arrow_forward_ios,
              size: 14,
              color: Color(0xff999999),
            )
          ],
        ),
      ),
      onTap: () async {
        // 淘宝授权不跳转
        if (item.skipIdentifier == 'pub.flutter.account_security_toabao_auth') {
          if (_user == null || EmptyUtil.isEmpty(_user.token)) {
            RouterUtil.goLogin(context);
            return;
          }
          if (!(_user?.isTBAuth ?? false)) {
            // 淘宝授权
            await TaobaoAuth.auth(context);
          }
          return;
        }
        await RouterUtil.route(
            item,
            Map<String, dynamic>.from(
                {'status': _bloc.securityStatus, 'data': item.toJson()}),
            context);
        _bloc.loadData(widget.data['skip_identifier']);
      },
    );
  }

  Widget _createLogout([SecurityStyleModel style]) {
    return GestureDetector(
      child: Container(
        color: HexColor.fromHex("#FFFFFF"),
        width: double.infinity,
        height: 50,
        margin: EdgeInsets.only(top: 10),
        child: Center(
          child: Text(
            style?.accountDelete?.text ?? "",
            style: TextStyle(
              fontSize: 13,
              color: HexColor.fromHex(style?.accountDelete?.textColor ?? ""),
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
      onTap: () {
        Logger.debug('账号注销');
        RouterUtil.route(SkipModel(skipIdentifier: style?.accountDelete?.skipIdentifier ?? ""), style?.accountDelete?.toJson(), context).then((value) {
          if(value!=null&&value){
            Navigator.pop(context,true);
          }
        } );
      },
    );
  }
}