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

import 'package:fluttertoast/fluttertoast.dart';
import 'package:path/path.dart';
import 'package:zhiying_base_widget/pages/mine_detail_page/models/mine_detail_model.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class MineDetailBloc extends BlocBase {
  MineDetailModel _user;

  StreamController<MineDetailModel> _userController =
      StreamController<MineDetailModel>();

  Stream<MineDetailModel> get outData => _userController.stream;

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

  void loadData() {
    NetUtil.request('/api/v1/user/info', method: NetMethod.GET,
        onCache: (data) {
      if (_user == null) _loadData(data);
    }, onSuccess: (data) {
      _loadData(data);
    });
  }

  void _loadData(dynamic data) {
    _user = MineDetailModel.fromJson(Map<String, dynamic>.from(data));

    _userController.add(_user);
  }

  /* 更新用户信息
  avatar 头像url
  nickname 昵称
  gender 性别(1女2男3未知)
  birthday 生日（时间戳）
  * */
  void updateUser(
      {String avatar, String nickname, String gender, String birthday}) {
    Map<String, dynamic> params = Map();
    if (avatar != null && avatar != '') {
      params['avatar'] = avatar;
    }
    if (nickname != null && nickname != '') {
      params['nickname'] = nickname;
    }
    if (gender != null && gender != '') {
      params['gender'] = gender;
    }
    if (birthday != null && birthday != '') {
      params['birthday'] = birthday;
    }
    NetUtil.request('/api/v1/user/info',
        method: NetMethod.POST,
        params: params,
        onCache: (data) {}, onSuccess: (data) {
      Fluttertoast.showToast(msg: '修改成功');
      loadData();
    });
  }

  void uploadAvatar(File file) async {
    List<int> originBytes = await file.readAsBytes();
    print('原图大小:' + originBytes.length.toString() + 'byte');
    print('原图大小:' + basename(file.path));

    Map<String, dynamic> params = Map();
    params['dir'] = 'avatar';
    params['file_size'] = originBytes.length;
    params['file_name'] = basename(file.path);
    NetUtil.request('/api/v1/img/upload',
        method: NetMethod.PUT,
        params: params,
        onCache: (data) {}, onSuccess: (data) async {
      String method = data['method'];
      String host = data['host'];
      String key = data['key'];
      String token = data['token'];

      var result = await NetUtil.uploadFile(host, file,
          params: {
            'key': key,
            'token': token,
          },
          method: method);
      print(result.toString());
      Map<String, dynamic> json = convert.jsonDecode(result.toString());

      String filename = json['fname'] ?? '';
      print(filename);
      String imageUrl =
          '${_user.fileBucketUrl.toString()}${filename.toString()}';
      if (_user.fileFormat != null && _user.fileFormat != '') {
        imageUrl += _user.fileFormat;
        imageUrl += '/${DateTime.now().millisecondsSinceEpoch.toString()}';
      } else {
        imageUrl += '?${DateTime.now().millisecondsSinceEpoch.toString()}';
      }
      updateUser(avatar: imageUrl);
    });
  }
}
