package com.fs.app.service;

import com.alibaba.fastjson.JSON;
import com.fs.common.utils.DateUtils;
import com.fs.company.service.ICompanyConfigService;
import com.fs.qw.domain.*;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.param.QwAutoRulesTagsParams;
import com.fs.qw.service.*;
import com.fs.qwApi.Result.QwGroupChatDetailsResult;
import com.fs.qwApi.Result.QwOpenidResult;
import com.fs.qwApi.domain.QwResult;
import com.fs.qwApi.param.QwEditUserTagParam;
import com.fs.qwApi.param.QwOpenidByUserParams;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class QwDataCallbackService {

    org.slf4j.Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    ICompanyConfigService companyConfigService;
    @Autowired
    IQwExternalContactService qwExternalContactService;
    @Autowired
    IQwTagGroupService qwTagGroupService;
    @Autowired

    QwUserMapper qwUserMapper;

    @Autowired
    com.fs.qwApi.service.QwApiService qwApiService;

    @Autowired
    IQwGroupChatService qwGroupChatService;

    @Autowired
    IQwGroupChatUserService qwGroupChatUserService;

    @Autowired
    IQwAutoTagsService qwAutoTagsService;

    @Autowired
    IQwAutoTagsLogsService qwAutoTagsLogsService;


    @Autowired
    private IQwDeptService qwDeptService;




    @Async
    public void dataCallback( Document document,String corpId,QwCompany qwCompany) throws Exception {


        Element root = document.getDocumentElement();
        NodeList msgTypeNode = root.getElementsByTagName("MsgType");
        String msgType = msgTypeNode.item(0).getTextContent();
        if(msgType.equals("event")){
            NodeList eventNode = root.getElementsByTagName("Event");
            String event = eventNode.item(0).getTextContent();
            String changeType ="";
            NodeList changeTypeList = root.getElementsByTagName("ChangeType");
            if(changeTypeList.getLength() > 0) {
                changeType = changeTypeList.item(0).getTextContent();
            }

            switch (event){
                //调用api接口删除员工
                case "unsubscribe" :
                    String fromUserName = root.getElementsByTagName("FromUserName").item(0).getTextContent();
                    QwUser delQwUser = qwUserMapper.selectQwUserByCorpIdAndUserId(corpId, fromUserName);
                    if (delQwUser!=null){
                        delQwUser.setIsDel(2);
                        delQwUser.setStatus(0);
                        qwUserMapper.updateQwUser(delQwUser);
                        QwExternalContact qwExternalContact = new QwExternalContact();
                        qwExternalContact.setUserId(fromUserName);
                        qwExternalContact.setStatus(0);
                        qwExternalContact.setCorpId(corpId);
                        List<QwExternalContact> qwExternalContacts = qwExternalContactService.selectQwExternalContactList(qwExternalContact);
                        for (QwExternalContact externalContact : qwExternalContacts) {
                            QwExternalContact lz = new QwExternalContact();
                            lz.setId(externalContact.getId());
                            lz.setStatus(1);
                            qwExternalContactService.updateQwExternalContact(lz);
                        }

                    }
                    break;
                case "subscribe":
                    String fromUserNameUserId = root.getElementsByTagName("FromUserName").item(0).getTextContent();
                    QwUser updateOrInsertQwUser = qwUserMapper.selectQwUserByCorpIdAndUserId(corpId, fromUserNameUserId);
                    //userid转openid
                    QwOpenidByUserParams param=new QwOpenidByUserParams();
                    param.setUserid(fromUserNameUserId);
                    QwOpenidResult qwOpenidResult = qwApiService.useridToOpenid(param, corpId);
                    if (updateOrInsertQwUser!=null&&qwOpenidResult.getErrCode()==0){
                        updateOrInsertQwUser.setOpenid(qwOpenidResult.getOpenid());
                        qwUserMapper.updateQwUser(updateOrInsertQwUser);
                    }

                    break;
                case "change_contact" :
                    if (changeType.equals("create_user")){
                        String userID = root.getElementsByTagName("UserID").item(0).getTextContent();
                        QwUser qw = qwUserMapper.selectQwUserByCorpIdAndUserId(corpId, userID);
                        QwUser qwUser = new QwUser();
                        qwUser.setQwUserId(userID);
                        qwUser.setCreateTime(new Date());
                        qwUser.setCorpId(corpId);

                        if (qw==null){
                            String serverQwUserName = qwApiService.getServerQwUserName(corpId, qwCompany.getOpenSecret(), userID);
                            qwUser.setQwUserId(userID);
                            qwUser.setDepartment(root.getElementsByTagName("Department").item(0).getTextContent().toString());
                            qwUser.setQwUserName(serverQwUserName);
                            QwOpenidByUserParams param1=new QwOpenidByUserParams();
                            param1.setUserid(userID);
                            QwOpenidResult qwOpenid = qwApiService.useridToOpenid(param1, corpId);
                            qwUser.setOpenid(qwOpenid.getOpenid());
                            qwUserMapper.insertQwUser(qwUser);
                        }else {
                            qw.setIsDel(0);
                            qw.setUpdateTime(new Date());
                            qwUserMapper.updateQwUser(qw);
                        }
                    }
                    else if (changeType.equals("delete_user")){
                        String userID = root.getElementsByTagName("UserID").item(0).getTextContent();
                        QwUser qwUser = qwUserMapper.selectQwUserByCorpIdAndUserId(corpId, userID);
                        if (qwUser!=null){
                            qwUser.setIsDel(2);
                            qwUser.setStatus(0);
                            qwUserMapper.updateQwUser(qwUser);
                            QwExternalContact qwExternalContact = new QwExternalContact();
                            qwExternalContact.setUserId(userID);
                            qwExternalContact.setStatus(0);
                            qwExternalContact.setCorpId(corpId);
                            List<QwExternalContact> qwExternalContacts = qwExternalContactService.selectQwExternalContactList(qwExternalContact);
                            for (QwExternalContact externalContact : qwExternalContacts) {
                                QwExternalContact lz = new QwExternalContact();
                                lz.setId(externalContact.getId());
                                lz.setStatus(1);
                                qwExternalContactService.updateQwExternalContact(lz);
                            }
                        }
                    }
                    else if (changeType.equals("create_party")){

                        qwDeptService.insertOrUpdateQwDept(corpId);
                    }
                    else if (changeType.equals("update_party")){

                        qwDeptService.insertOrUpdateQwDept(corpId);

                    }else if (changeType.equals("delete_party")){
                        QwDept qwDept=new QwDept();
                        qwDept.setDeptId(Long.valueOf(root.getElementsByTagName("Id").item(0).getTextContent()));
                        qwDeptService.deleteQwDeptByDeptId(qwDept);
                    }

                    break;
                case "change_external_contact" :
                    switch (changeType){
                        case "add_external_contact":
                            String State =null;
                            NodeList StateList = root.getElementsByTagName("State");
                            if(StateList.getLength() > 0) {
                                State = StateList.item(0).getTextContent();
                            }
                            String WelcomeCode =null;
                            NodeList WelcomeCodeList = root.getElementsByTagName("WelcomeCode");
                            if(WelcomeCodeList.getLength() > 0) {
                                WelcomeCode = WelcomeCodeList.item(0).getTextContent();
                            }
                            qwExternalContactService.insertQwExternalContactByExternalUserId(root.getElementsByTagName("ExternalUserID").item(0).getTextContent(),root.getElementsByTagName("UserID").item(0).getTextContent(),null,corpId,State,WelcomeCode);
                            break;
                        case "edit_external_contact":
                            qwExternalContactService.updateQwExternalContactByExternalUserId(root.getElementsByTagName("ExternalUserID").item(0).getTextContent(),root.getElementsByTagName("UserID").item(0).getTextContent(),corpId);
                            break;
                        case "del_external_contact":
                            qwExternalContactService.deleteQwExternalContactByExternalUserId(root.getElementsByTagName("ExternalUserID").item(0).getTextContent(),root.getElementsByTagName("UserID").item(0).getTextContent(),corpId);
                            break;
                        case "del_follow_user":
                            qwExternalContactService.deletefollowUserByExternalUserId(root.getElementsByTagName("ExternalUserID").item(0).getTextContent(),root.getElementsByTagName("UserID").item(0).getTextContent(),corpId);
                            break;
                        case "transfer_fail":
                            qwExternalContactService.transferFailByExternalUserId(root.getElementsByTagName("ExternalUserID").item(0).getTextContent(),root.getElementsByTagName("UserID").item(0).getTextContent(),corpId,root.getElementsByTagName("FailReason").item(0).getTextContent());
                            break;
                    }
                    break;
                case "change_external_tag":

                    switch (changeType){
                        case "create":
                            qwTagGroupService.addTagByTagId(root.getElementsByTagName("TagType").item(0).getTextContent(),root.getElementsByTagName("Id").item(0).getTextContent(),corpId);
                            break;
                        case "update":
                            qwTagGroupService.updateTagByTagId(root.getElementsByTagName("TagType").item(0).getTextContent(),root.getElementsByTagName("Id").item(0).getTextContent(),corpId);
                            break;
                        case "delete":
                            qwTagGroupService.deleteTagByTagId(root.getElementsByTagName("TagType").item(0).getTextContent(),root.getElementsByTagName("Id").item(0).getTextContent(),corpId);
                            break;
                        case "shuffle":
                            qwTagGroupService.shuffleTagByTagId(root.getElementsByTagName("Id").item(0).getTextContent(),corpId);
                            break;

                    }

                    break;
                case "change_external_chat":

                    switch (changeType){
                        case "create":
                            //新建的客户群
                            qwGroupChatService.insertQwGroupChat(root.getElementsByTagName("ChatId").item(0).getTextContent(),corpId);
                            break;
                        case "update":

                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                            //群id
                            String chatId = root.getElementsByTagName("ChatId").item(0).getTextContent();
                            //变更详情
                            String updateDetail = root.getElementsByTagName("UpdateDetail").item(0).getTextContent();

                            //群信息
                            QwGroupChat qwGroupChat=new QwGroupChat();

                            //成员详细信息
                            QwGroupChatUser qwGroupChatUser=new QwGroupChatUser();
                            qwGroupChatUser.setCorpId(corpId);
                            //成员入群
                            if (updateDetail.equals("add_member")){

                                //入群方式
                                String joinScene = root.getElementsByTagName("JoinScene").item(0).getTextContent();

                                //消息创建时间
//                                    String CreateTime = root.getElementsByTagName("CreateTime").item(0).getTextContent();
//                                    Date date1 = new Date(Long.valueOf(CreateTime) * 1000); // 乘以1000是因为时间戳是以秒为单位，而Date期望毫秒
//                                    String formattedDate = sdf.format(date1);
                                String formattedDate = sdf.format(new Date());

                                //入群数量
                                String MemChangeCnt = root.getElementsByTagName("MemChangeCnt").item(0).getTextContent();

                                // 获取MemChangeList中的Item元素,当是成员入群或退群时有值。变更的成员列表
                                NodeList items = document.getElementsByTagName("Item");

                                QwAutoTags qwAutoTags = qwAutoTagsService.selectQwAutoTagsByChatIdJSON(corpId, chatId);
                                logger.info("成员入群:qwAutoTags:"+qwAutoTags);
                                //存分时段里符合条件的标签
                                Set<String> combinedTagsItem = new HashSet<>();

                                //添加标签的日志记录
                                QwAutoTagsLogs qwAutoTagsLogs=new QwAutoTagsLogs();

                                //添加的标签
                                QwEditUserTagParam qwEditUserTagParam = new QwEditUserTagParam();

                                boolean isMatch = false;

                                //查出 符合的标签
                                if (qwAutoTags != null) {
                                    List<QwAutoRulesTagsParams> qwAutoRulesTagsParams = JSON.parseArray(qwAutoTags.getRulesTags(), QwAutoRulesTagsParams.class);
                                    for (QwAutoRulesTagsParams qrtp : qwAutoRulesTagsParams) {
                                        if (qrtp.getRules().contains(chatId));{
                                            combinedTagsItem.addAll(qrtp.getTags());
                                            isMatch=true;
                                            break;
                                        }

                                    }

                                }

                                logger.info("成员入群items:"+items.getLength());
                                //成员列表
                                for (int i = 0; i < items.getLength(); i++) {

                                    String userid = items.item(i).getTextContent();
                                    qwGroupChatUser.setChatId(chatId);
                                    qwGroupChatUser.setUserId(userid);
                                    qwGroupChatUser.setJoinScene(joinScene);
                                    qwGroupChatUser.setJoinTime(formattedDate);

                                    //这个群有符合条件的标签
                                    if (isMatch){

                                        //根据客户id获取 该客户属于哪个成员
                                        List<QwExternalContact> qwExternalContacts = qwExternalContactService.selectQwExternalContactByExternalUserId(userid, corpId);
                                        qwExternalContacts.stream().forEach(item->{

                                            qwEditUserTagParam.setUserid(item.getUserId());
                                            qwEditUserTagParam.setExternal_userid(userid);
                                            //总标签 转换回列表
                                            List<String> combinedTagsList = new ArrayList<>(combinedTagsItem);
                                            // 设置标签
                                            qwEditUserTagParam.setAdd_tag(combinedTagsList);


                                            qwAutoTagsLogs.setAutoTagId(qwAutoTags.getId());
                                            qwAutoTagsLogs.setType(2L);
                                            qwAutoTagsLogs.setQwUserid(item.getQwUserId());
                                            qwAutoTagsLogs.setExternalUserId(userid);
                                            qwAutoTagsLogs.setEffectiveRules(JSON.toJSONString(combinedTagsList));
                                            qwAutoTagsLogs.setAddTime(new Date());
                                            qwAutoTagsLogs.setChatId(chatId);
                                            qwAutoTagsLogs.setJoinScene(joinScene);
                                            qwAutoTagsLogs.setCorpId(corpId);
                                            //  qwAutoTagsLogs.setCompanyId(companyId);
                                            // 企微加标签
                                            QwResult qwResult = qwApiService.editUserTag(qwEditUserTagParam, corpId);
                                            logger.info("自动添加标签-入群行为：符合条件 " + qwResult);
                                            qwAutoTagsLogsService.insertQwAutoTagsLogs(qwAutoTagsLogs);
                                        });

                                    }


                                    //查一遍有没有这个人-有的话 更新一下（退群后再入群的人）
                                    QwGroupChatUser qwGroupChatUserOld = qwGroupChatUserService.selectQwGroupChatUserByExternalUserId(qwGroupChatUser);

                                    if (qwGroupChatUserOld==null) {
                                        qwGroupChatUserService.insertQwGroupChatUser(qwGroupChatUser);
                                    }else {
                                        qwGroupChatUserOld.setIsOut(1L);
                                        qwGroupChatUserOld.setCorpId(corpId);
                                        qwGroupChatUserOld.setJoinScene(joinScene);
                                        qwGroupChatUserOld.setJoinTime(formattedDate);
                                        qwGroupChatUserOld.setQuitScene(null);
                                        qwGroupChatUserOld.setOutTime(null);
                                        qwGroupChatUserService.groupChatUserJoinAgain(qwGroupChatUserOld);
                                    }

                                }
                                //先查一遍（后期可直接改sql,不查）
                                QwGroupChat qwGroupChatOld = qwGroupChatService.selectQwGroupChatByChatId(chatId);
                                if (qwGroupChatOld != null) {
                                    qwGroupChatOld.setCorpId(corpId);
                                    //当日入群数
                                    qwGroupChatOld.setTodayJoin(qwGroupChatOld.getTodayJoin()+Integer.valueOf(MemChangeCnt));
                                    //当前群人总数
                                    qwGroupChatOld.setGroupSize(qwGroupChatOld.getGroupSize()+Integer.valueOf(MemChangeCnt));

                                    qwGroupChatService.updateQwGroupChat(qwGroupChatOld,corpId);
                                }
                            }
                            //成员退群
                            if (updateDetail.equals("del_member")){

                                //退群数量
                                String MemChangeCnt = root.getElementsByTagName("MemChangeCnt").item(0).getTextContent();
                                //退群方式
                                String QuitScene = root.getElementsByTagName("QuitScene").item(0).getTextContent();

                                String CreateTime = root.getElementsByTagName("CreateTime").item(0).getTextContent();
                                Date date1 = new Date(Long.valueOf(CreateTime) * 1000); // 乘以1000是因为时间戳是以秒为单位，而Date期望毫秒
                                String formattedDate = sdf.format(date1);

                                // 获取MemChangeList中的Item元素,当是成员入群或退群时有值。变更的成员列表
                                NodeList items = document.getElementsByTagName("Item");

                                //成员列表
                                for (int i = 0; i < items.getLength(); i++) {
                                    String userid = items.item(i).getTextContent();
                                    //是否退群
                                    qwGroupChatUser.setIsOut(2L);
                                    //退群时间
                                    qwGroupChatUser.setOutTime(formattedDate);

                                    qwGroupChatUser.setChatId(chatId);
                                    qwGroupChatUser.setUserId(userid);
                                    //退群方式
                                    qwGroupChatUser.setQuitScene(Integer.parseInt(QuitScene));
                                    qwGroupChatUser.setCorpId(corpId);
                                    //更新
                                    qwGroupChatUserService.upDateDelGroupChatUser(qwGroupChatUser);
                                }

                                //先查一遍（后期可直接改sql,不查）
                                QwGroupChat qwGroupChatOld = qwGroupChatService.selectQwGroupChatByChatId(chatId);
                                if (qwGroupChatOld != null) {
                                    int memChangeCount;

                                    if (MemChangeCnt == null || MemChangeCnt.isEmpty()) {
                                        memChangeCount = 1;
                                    } else {
                                        try {
                                            memChangeCount = Integer.parseInt(MemChangeCnt);
                                        } catch (NumberFormatException e) {
                                            memChangeCount = 1;
                                        }
                                    }

                                    // 确保qwGroupChatOld不是null
                                    if (qwGroupChatOld != null) {
                                        //当日退群数
                                        Long todayOut = qwGroupChatOld.getTodayOut();
                                        if (todayOut != null) {

                                            qwGroupChatOld.setTodayJoin(todayOut + (long) memChangeCount);
                                        } else {

                                            qwGroupChatOld.setTodayJoin((long) memChangeCount); // 或者根据实际情况决定如何处理
                                        }

                                        //总退群数
                                        qwGroupChatOld.setAllOutGroup(qwGroupChatOld.getAllOutGroup()+memChangeCount);

                                        long newGroupSize = (qwGroupChatOld.getGroupSize() - memChangeCount) < 0 ? 0 : qwGroupChatOld.getGroupSize() - memChangeCount;

                                        //当前群人总数
                                        qwGroupChatOld.setGroupSize(newGroupSize);
                                        qwGroupChatOld.setCorpId(corpId);

                                        qwGroupChatService.updateQwGroupChat(qwGroupChatOld,corpId);

                                    }
                                }

                            }
                            //群主变更/群名变更/群公告变更
                            if (updateDetail.equals("change_owner")||updateDetail.equals("change_name")||updateDetail.equals("change_notice")){


                                //获取群聊详情
                                QwGroupChatDetailsResult qwGroupChatDetailsResult = qwApiService.groupChatDetails(chatId, corpId);

                                if (qwGroupChatDetailsResult.getErrCode()==0){
                                    QwGroupChatDetailsResult.GroupChats groupChat = qwGroupChatDetailsResult.getGroupChat();

                                    //群名
                                    String name = groupChat.getName();
                                    //群公告
                                    String notice = groupChat.getNotice();
                                    //群主id
                                    String owner = groupChat.getOwner();

                                    qwGroupChat.setName(name);
                                    qwGroupChat.setNotice(notice);
                                    qwGroupChat.setOwner(owner);
                                    qwGroupChat.setMemberVersion(groupChat.getMemberVersion());
                                    qwGroupChat.setCorpId(corpId);
                                    qwGroupChat.setChatId(chatId);
                                    qwGroupChat.setUpdateTime(DateUtils.getNowDate());
                                    //更新
                                    qwGroupChatService.updateQwGroupChat(qwGroupChat,corpId);

                                }
                            }

                            break;
                        case "dismiss":
                            //解散客户群（删掉!）
                            qwGroupChatService.deleteQwGroupChatByChatIdAndCompanyId(root.getElementsByTagName("ChatId").item(0).getTextContent(),corpId);
                            break;
                    }

                    break;
                default:
                    logger.info("默认："+event);
            }
        }
    }



}
