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

import 'package:fluttertoast/fluttertoast.dart';
import 'package:zhiying_base_widget/pages/security_page/security_bind_alipay/models/security_bind_alipay_model.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class SecurityBindAlipayBloc extends BlocBase {
  SecurityBindAlipayModel _model;

  StreamController<SecurityBindAlipayModel> _dataController =
      StreamController<SecurityBindAlipayModel>();

  Stream<SecurityBindAlipayModel> get outData => _dataController.stream;

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

  void loadData(String skipIdentifier) async {
    NetUtil.request('/api/v1/mod/${skipIdentifier.toString()}',
        method: NetMethod.GET, onCache: (data) {
      _loadData(data);
    }, onSuccess: (data) {
      _loadData(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));
        _model = SecurityBindAlipayModel.fromJson(da);
        _dataController.add(_model);
      }
    } catch (err) {
      Logger.error(err);
    }
  }

  Future<bool> bindAlipay(String name, String account, String code) {
    return NetUtil.post('/api/v1/settings/account/security/alipay',
        method: NetMethod.POST,
        params: Map<String, dynamic>.from({
          'alipay_real_name': name,
          'alipay_account': account,
          'valid_code': code,
        })).then((result) {
      if (result['code'] == 1) return true;
      return false;
    }).catchError((error) {
      Fluttertoast.showToast(msg: error);
      return false;
    });
  }
}
