import 'dart:convert';

import 'package:chat/data/UserData.dart';
import 'package:chat/data/group_data_mgr.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/TokenMgr.dart';
import 'package:chat/utils/friend_list_mgr.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:shared_preferences/shared_preferences.dart';

class RefNameProvider with ChangeNotifier {
  int curSelectIndex = 0;
  Map<int, String> refMap = {};

  init() async {
    print('初始化别名');
    var sp = await SharedPreferences.getInstance();
    List refList =
        sp.getStringList('Ref_Name' + UserData().basicInfo.userId.toString());
    refMap.clear();
    if (refList != null) {
      for (var i = 0; i < refList.length; i++) {
        Map ref = json.decode(refList[i]);
        refMap[ref['userId']] = ref['refName'];
      }
      notifyListeners();
    } else {
      sysnRefListFromServer();
    }
  }

  sysnRefListFromServer() async {
    Map data = {"userId": UserData().basicInfo.userId};
    data['sign'] = TokenMgr().getSign(data);
    try {
      Response res = await HttpUtil().post('alias/user/list', data: data);
      if (res == null) {
        return;
      }
      var resData = res.data;
      if (resData['code'] == 0) {
        List jsonList = resData['data'];
        if (jsonList == null || jsonList.length == 0) {
          return;
        }

        for (var i = 0; i < jsonList.length; i++) {
          var ref = jsonList[i];
          refMap[ref['userId']] = Uri.decodeComponent(ref['aliasName']);
        }
      }
    } catch (e) {}
  }

  getRefName(int userId, String name) {
    return refMap[userId] == null ? name : refMap[userId];
  }

  String getGroupRefName(int sessionId, int userId) {
    if (refMap[userId] != null) {
      return refMap[userId];
    }

    var groupRefName = GroupInfoMgr().getGroupFdName(sessionId, userId);
    if (groupRefName != null) {
      return groupRefName;
    }

    return '';
  }

  changeRefName(int userId, String refName, callback) {
    if (refName == null || refName == '') {
      refMap.remove(userId);
    } else {
      refMap[userId] = refName;
    }

    notifyListeners();

    saveRefName();
    FriendListMgr().updateRefNmae(userId);
    commitChangeToServer(userId, refName, callback);
  }

  commitChangeToServer(int userId, String refName, callback) async {
    Map data = {"userId": UserData().basicInfo.userId, "aliasUserId": userId};
    data['sign'] = TokenMgr().getSign(data);
    data["aliasName"] = Uri.encodeComponent(refName);

    try {
      Response res = await HttpUtil()
          .post('alias/set/up', data: data, isShowLoading: true);
      if (res == null) {
        return;
      }
      var resData = res.data;
      showToast(resData['msg']);
      if (resData['code'] == 0) {
        print('设置别名成功');
        if (callback != null) callback();
      } else {
        print(resData.msg);
      }
    } catch (e) {}
  }

  saveRefName() async {
    List<String> refList = [];
    refMap.keys.forEach((userId) {
      var refStr = json.encode({"userId": userId, "refName": refMap[userId]});
      refList.add(refStr);
    });

    var sp = await SharedPreferences.getInstance();
    sp.setStringList(
        'Ref_Name' + UserData().basicInfo.userId.toString(), refList);
  }
}
