import 'dart:async';
import 'dart:convert' as convert;

import 'package:zhiying_base_widget/pages/security_page/models/security_style_model.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class SecurityPageBloc extends BlocBase {
  SecurityStyleModel _style;
  Map<String, dynamic> securityStatus;

  StreamController<SecurityStyleModel> _styleController =
      StreamController<SecurityStyleModel>();

  Stream<SecurityStyleModel> get outData => _styleController.stream;

  @override
  void dispose() {
    _styleController.close();
    _styleController = null;
  }

  void loadData(String skipIdentifier) async {
    NetUtil.request('/api/v1/mod/${skipIdentifier.toString()}',
        method: NetMethod.GET, onCache: (data) {
      _loadData(data);
    }, onSuccess: (data) async {
      securityStatus = Map<String, dynamic>.from(await _getStatus());
      _loadData(data);
    });
  }

  // 获取授权状态等信息
  Future<Map> _getStatus() async {
    var result = await NetUtil.post(
      '/api/v1/settings/account/security',
      method: NetMethod.GET,
    );
    return result['data'];
  }

  void _loadData(dynamic data) {
    try {
      Map<String, dynamic> json = Map<String, dynamic>.from(data);
      if (json == null || json.length == 0) {
        return;
      }
      List mods = json['mod_list'];
      if (mods.first != null) {
        json = Map<String, dynamic>.from(mods.first);
        String d = json['data'];
        Map<String, dynamic> da =
            Map<String, dynamic>.from(convert.jsonDecode(d));
        _style = SecurityStyleModel.fromJson(da);

        if (securityStatus != null) {
          _style.settings.forEach((item) {
            List<String> keys = item.dataKeys;
            if (keys.length > 0) {
              item.desc = securityStatus[keys.first] ?? '';
            }
          });
        }

        _styleController.add(_style);
      }
    } catch (err) {
      Logger.error(err);
    }
  }
}
