package com.fs.qw.service.impl;

import com.fs.common.utils.StringUtils;
import com.fs.pay.pay.util.PayUtil;
import com.fs.qw.domain.*;
import com.fs.qw.dto.AddContactDTO;
import com.fs.qw.dto.ModifyDTO;
import com.fs.qw.event.EventMessageText;
import com.fs.qw.mapper.*;
import com.fs.qw.service.IQwContactService;
import com.fs.qw.utils.QwAllUtil;
import com.fs.qw.vo.QwContactListVO;
import com.fs.qw.vo.QwContactVO;
//import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.apache.commons.codec.digest.DigestUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.fs.qw.utils.QwAllUtil.*;

@Service
public class QwContactServiceImpl implements IQwContactService {
    @Autowired
    private QwContactMapper qwContactMapper;

    @Autowired
    private QwConversationMapper qwConversationMapper;

    @Autowired
    private QwMessageMapper qwMessageMapper;

    @Autowired
    private QwRoomMapper qwRoomMapper;

    @Autowired
    private QwRoomMemberMapper qwRoomMemberMapper;

    @Override
    public QwContactSearch search(String deviceId,Long phone) {
        Map<String,Object> map = new HashMap<>();
        map.put("phone",phone);
        return contactSearch(map,deviceId);
    }

    @Override
    public void add(AddContactDTO addContactDTO) {
        Map<String,Object> map = addContactDTO.toMap();
        contactAdd(map,addContactDTO.getDeviceId());
    }

    @Override
    public QwContactReturn list(Long seq,String deviceId) {
        return QwAllUtil.contactList(seq,deviceId);
    }

    @Override
    public void delete(String deviceId, Long userId) {
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        contactDel(map,deviceId);
    }

    @Override
    public void modify(ModifyDTO modifyDTO) {
        Map<String,Object> map = modifyDTO.toMap();
        contactAgreeFriend(map,modifyDTO.getDeviceId());
    }

    @Override
    public QwContactVO detail(String deviceId, Long userId) {
        return contactDetail(userId,deviceId);
    }

    @Override
    public void agreeFriend(String deviceId, Long userId, Long corpId) {
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("corpId",corpId);
        contactAgreeFriend(map,deviceId);
    }



    /**
     * 查询企微联系人
     *
     * @param id 企微联系人ID
     * @return 企微联系人
     */
    @Override
    public QwContact selectQwContactById(Long id)
    {
        return qwContactMapper.selectQwContactById(id);
    }

    /**
     * 查询企微联系人列表
     *
     */
    @Override
    public List<QwContactListVO> selectQwContactList(String homeUserId)
    {
        List<QwContact> list =  qwContactMapper.selectQwContactsByHomeUserId(homeUserId);
        List<QwContactListVO> listVOS = new ArrayList<>();
        for (QwContact qwContact : list) {
            if (!qwContact.getDeleted()) {
                QwContactListVO listVO = new QwContactListVO();
                listVO.setId(qwContact.getUserId());
                listVO.setAvatar(qwContact.getAvatar());
                if (qwContact.getRemark()!= null && !qwContact.getRemark().equals("")){
                    listVO.setDisplayName(qwContact.getRemark());
                }else {
                    listVO.setDisplayName(qwContact.getNickName());
                }
                listVO.setIndex(getFormattedNickname(listVO.getDisplayName()));
                listVO.setUnread(0);
                String combinedString = sortAndCombine(qwContact.getUserId().toString(), homeUserId);
                String conversationId = DigestUtils.md5Hex(combinedString);
                QwConversation qwConversation = qwConversationMapper.selectByConversationId(conversationId);
                if (qwConversation != null) {
                    QwMessage qwMessage = qwMessageMapper.selectQwMessageById(qwConversation.getLastMessageId());
                    if (qwMessage.getMessageType() == 1) {
                        listVO.setLastContent(qwMessage.getContent());
                    } else if (qwMessage.getMessageType() == 2) {
                        listVO.setLastContent("[图片]");
                    } else if (qwMessage.getMessageType() == 3) {
                        listVO.setLastContent("[视频]");
                    } else if (qwMessage.getMessageType() == 4) {
                        listVO.setLastContent("[文件]");
                    } else if (qwMessage.getMessageType() == 5) {
                        listVO.setLastContent("[语音]" + qwMessage.getDuration() + "\"");
                    } else if (qwMessage.getMessageType() == 7) {
                        listVO.setLastContent("[动画表情]");
                    } else {
                        listVO.setLastContent("");
                    }
                    listVO.setLastSendTime(qwMessage.getSendTime());
                } else {
                    listVO.setLastSendTime(0L);
                    listVO.setLastContent("");
                }
                listVOS.add(listVO);
            }
        }
        List<QwRoom> qwRoomList = qwRoomMapper.selectByHome(homeUserId);
        for (QwRoom qwRoom : qwRoomList){
            QwContactListVO listVO = new QwContactListVO();
            listVO.setId(qwRoom.getRoomId());
            listVO.setUnread(0);
            listVO.setAvatar("https://hos-1309931967.cos.ap-chongqing.myqcloud.com/fs/20231025/faf2cbc41c9a4921b8218dec0a610a38.jpeg");
            listVO.setIsGroup(true);
            if (StringUtils.isEmpty(qwRoom.getRoomName())){
                listVO.setDisplayName("群聊");
            }else {
                listVO.setDisplayName(qwRoom.getRoomName());
            }
            listVO.setIndex(getFormattedNickname(qwRoom.getRoomName()));
            listVO.setLastSendTime(0L);
            listVO.setLastContent("");
            listVOS.add(listVO);
        }
        return listVOS;
    }
    public String sortAndCombine(String senderId, String receiverId) {
        // 将 senderId 和 receiverId 放入数组，进行排序
        String[] ids = {senderId, receiverId};
        Arrays.sort(ids);
        // 组合排序后的值为一个字符串，并返回
        return ids[0] + ids[1];
    }

    //获取昵称的首字母大写
    public static String getFormattedNickname(String nickname) {
        if (nickname == null || nickname.isEmpty()) {
            return "";
        }
        char firstChar = nickname.charAt(0);

        if (isChineseChar(firstChar)) {
            String pinyin = PinyinHelper.toHanyuPinyinStringArray(firstChar)[0];
            return pinyin.substring(0, 1).toUpperCase();
        } else if (Character.isLetter(firstChar)) {
            return String.valueOf(Character.toUpperCase(firstChar));
        } else {
            return "#";
        }
    }
    // 判断是否为中文字符
    private static boolean isChineseChar(char c) {
        return Character.UnicodeScript.of(c) == Character.UnicodeScript.HAN;
    }

    /**
     * 新增企微联系人
     *
     * @param qwContact 企微联系人
     * @return 结果
     */
    @Override
    public int insertQwContact(QwContact qwContact)
    {
        return qwContactMapper.insertQwContact(qwContact);
    }

    /**
     * 修改企微联系人
     *
     * @param qwContact 企微联系人
     * @return 结果
     */
    @Override
    public int updateQwContact(QwContact qwContact)
    {
        return qwContactMapper.updateQwContact(qwContact);
    }

    /**
     * 批量删除企微联系人
     *
     * @param ids 需要删除的企微联系人ID
     * @return 结果
     */
    @Override
    public int deleteQwContactByIds(Long[] ids)
    {
        return qwContactMapper.deleteQwContactByIds(ids);
    }

    /**
     * 删除企微联系人信息
     *
     * @param id 企微联系人ID
     * @return 结果
     */
    @Override
    public int deleteQwContactById(Long id)
    {
        return qwContactMapper.deleteQwContactById(id);
    }


    @Override
    public QwContact selectQwContactByUserId(Long UserId) {
        return qwContactMapper.selectQwContactByUserId(UserId);
    }


}
