package tasks

import (
	"gitee.ltd/lxh/wechat-robot/internal/model"
	"gitee.ltd/lxh/xybot"
	"gitee.ltd/lxh/xybot/friend"
	"github.com/gofiber/fiber/v2/log"
	"slices"
	"strings"
)

// syncContact
// @description: 同步联系人
// @param containerHost 容器接口地址
// @param robotWxId 机器人微信号
// @param robotId 机器人ID
func syncContact(containerHost, robotWxId string, robotId uint) {
	robotCli, err := xybot.NewClient(robotWxId, containerHost, false)
	if err != nil {
		log.Errorf("创建微信客户端失败: %v", err)
	}

	// 先获取全部id
	ids, err := robotCli.Friend.GetContractList(true)
	if err != nil {
		// 处理错误
		log.Errorf("[%s]获取联系人列表失败: %v", robotWxId, err)
		return
	}

	// 将ids拆分成二十个一个的数组之后再获取详情
	var contacts = make([]friend.ContactListItem, 0)
	chunker := slices.Chunk(ids, 20)
	processChunk := func(chunk []string) bool {
		// 获取昵称等详细信息
		var c = make([]friend.ContactListItem, 0)
		c, err = robotCli.Friend.GetContractDetail(chunk)
		if err != nil {
			// 处理错误
			log.Errorf("[%s]获取联系人详情失败: %v", robotWxId, err)
			return false
		}
		contacts = append(contacts, c...)
		return true
	}
	chunker(processChunk)

	// 循环联系人信息，打印一下
	db := model.GetDB()
	nowIds := make([]string, 0)
	for _, contact := range contacts {
		//log.Infof("[%s]联系人信息: %+v", robotWxId, contact)

		if strings.TrimSpace(contact.UserName.String) == "" {
			// 微信号为空，跳过
			continue
		}
		nowIds = append(nowIds, contact.UserName.String)

		// 判断数据库是否存在当前数据，不存在就新建，存在就更新
		var existId uint
		db.Model(&model.Contact{}).Where("robot_id = ?", robotId).Where("wechat_id = ?", contact.UserName.String).Pluck("id", &existId)
		if existId > 0 {
			// 存在，修改
			pm := map[string]any{
				"alias":          contact.Alias,
				"nickname":       contact.NickName.String,
				"avatar":         contact.BigHeadImgUrl,
				"pyinitial":      contact.Pyinitial.String,
				"quan_pin":       contact.QuanPin.String,
				"sex":            contact.Sex,
				"country":        contact.Country,
				"province":       contact.Province,
				"city":           contact.City,
				"signature":      contact.Signature,
				"sns_background": contact.SnsUserInfo.SnsBgImgId,
			}
			if contact.BigHeadImgUrl == "" {
				pm["avatar"] = contact.SmallHeadImgUrl
			}
			err = db.Model(&model.Contact{}).Where("id = ?", existId).Updates(pm).Error
		} else {
			// 组装联系人信息，然后存入数据库
			var c model.Contact
			c.RobotID = robotId
			c.WechatID = contact.UserName.String
			c.Alias = contact.Alias
			c.Nickname = contact.NickName.String
			c.Avatar = contact.BigHeadImgUrl
			if contact.BigHeadImgUrl == "" {
				c.Avatar = contact.SmallHeadImgUrl
			}
			c.Type = "friend"
			if strings.HasSuffix(contact.UserName.String, "@chatroom") {
				// 群聊
				c.Type = "group"
			}
			c.Pyinitial = contact.Pyinitial.String
			c.QuanPin = contact.QuanPin.String
			c.Sex = contact.Sex
			c.Country = contact.Country
			c.Province = contact.Province
			c.City = contact.City
			c.Signature = contact.Signature
			c.SnsBackground = contact.SnsUserInfo.SnsBgImgId

			err = db.Create(&c).Error
		}
		if err != nil {
			log.Debugf("[%s]保存联系人失败: %v", robotWxId, err)
		}

	}

	// 清理掉不存在的联系人
	db.Model(&model.Contact{}).Where("robot_id = ?", robotId).Where("wechat_id NOT IN ?", nowIds).Delete(&model.Contact{})
}
