import 'package:chat/data/UserData.dart';
import 'package:chat/models/UserInfo.dart';
import 'package:chat/models/ref_name_provider.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/utils/sql_model.dart';
import 'package:flutter/material.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:provider/provider.dart';

class FriendModel {
  @required
  int friendId;
  @required
  String avatar;
  @required
  String name;
  String refName;
  String nameTag;
  int state;
  String creatTime;
  int applyId;

  FriendModel(
      {this.avatar,
      this.name,
      this.friendId,
      this.refName,
      this.state = 0,
      this.applyId = 0,
      this.creatTime = ''})
      : assert(avatar != null),
        assert(name != null),
        assert(friendId != null) {
    nameTag = getNameTag();
  }

  getTitle() {
    return refName ?? name;
  }

  updataRefName() {
    refName = Provider.of<RefNameProvider>(Constants.getCurrentContext(), listen: false)
        .getRefName(friendId, name);
    nameTag = getNameTag();
  }

  FriendModel.fromJson(Map<String, dynamic> json) {
    friendId = json['friendId'];
    avatar = json['avatar'];
    name = json['name'];
    updataRefName();
  }

  FriendModel.fromServerJson(Map<String, dynamic> json) {
    friendId = json['UserId'];
    avatar = json['ImgUrl'];
    name = json['UserName'];
    state = json['ApplyStatus'];
    updataRefName();
  }

  FriendModel.fromApplyServerJson(Map<String, dynamic> json) {
    friendId = json['ApplyUserId'];
    avatar = json['ApplyUrl'];
    name = json['ApplyName'];
    state = json['Status'];
    creatTime = json['CreatTime'];
    applyId = json['Id'];
    updataRefName();
  }

  getNameTag() {
    var origin = refName;
    if (origin == null || origin.length == 0) {
      origin = name;
    }
    String pinyin = PinyinHelper.getPinyinE(origin);
    if (pinyin == null || pinyin.length == 0) {
      return '#';
    }
    var tag = pinyin.substring(0, 1).toUpperCase();
    if (tag == 'Ẩ') {
      return 'A';
    } else if (tag == 'Đ') {
      return 'D';
    } else if (tag.compareTo("A") < 0 || tag.compareTo("Z") > 0) {
      return '#';
    }
    return tag;
  }
}

class FriendTableModel {
  final String table = 'friend';
  Sql sql;

  FriendTableModel() {
    sql = Sql.setTable(table);
  }

  createTable() async {
    print('创建表$table');
    await sql.createTable(
        table, 'friendId INTEGER, userId INTEGER, avatar TEXT,name TEXT');
  }

  Future clear() {
    return sql.clearTable(table);
  }

  Future insert(FriendModel friendModel) async {
    var myId = UserData().basicInfo.userId;
    var response = await sql.insert({
      'avatar': friendModel.avatar,
      'userId': myId,
      'name': friendModel.name,
      'friendId': friendModel.friendId
    });
    return response;
  }

  Future insertWithUserInfo(UserInfo friendInfo) async {
    var response = await sql.insert({
      'avatar': friendInfo.headimgurl,
      'name': friendInfo.nickName,
      'userId': UserData().basicInfo.userId,
      'friendId': friendInfo.userId
    });
    return response;
  }

  deleteFriend(int friendId) async {
    var curUserId = UserData().basicInfo.userId;
    var res = await sql.db.delete(table,
        where: 'userId=? and friendId = ?', whereArgs: [curUserId, friendId]);
    print('删除好友结果$res');
    return res;
  }

  Future<List<FriendModel>> getAllConversation() async {
    List<FriendModel> resultList = [];

    var curUserId = UserData().basicInfo.userId;
    var list = await sql.query(table, where: 'userId = $curUserId');

    for (var i = 0; i < list.length; i++) {
      Map row = list[i];

      resultList.add(FriendModel.fromJson(row));
    }

    return resultList;
  }
}
