package com.fs.qw.service.impl;

import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.company.domain.CompanyUser;
import com.fs.qw.domain.*;
import com.fs.common.utils.StringUtils;
import com.fs.company.service.ICompanyConfigService;
import com.fs.course.service.IFsCourseLinkService;
import com.fs.qw.domain.QwCompany;
import com.fs.qw.domain.QwGroupChat;
import com.fs.qw.domain.QwGroupChatUser;
import com.fs.qw.mapper.*;
import com.fs.qw.param.ChatParam;
import com.fs.qw.param.QwGroupChatParam;
import com.fs.qw.param.TransferChatParam;
import com.fs.qw.result.ResultMessage;
import com.fs.qw.service.*;
import com.fs.qw.vo.QwGroupChatOptionsVO;
import com.fs.qw.vo.QwGroupChatTransferVO;
import com.fs.qw.vo.QwGroupChatVO;
import com.fs.qwApi.Result.QwGroupChatDetailsResult;
import com.fs.qwApi.Result.QwGroupChatListResult;
import com.fs.qwApi.domain.QwGroupChatTransferResult;
import com.fs.qwApi.param.QwGroupChatTransferParam;
import com.fs.qwApi.service.QwApiService;
import com.fs.sop.domain.QwSop;
import com.fs.sop.mapper.QwSopMapper;
import com.fs.sop.mapper.SopUserLogsInfoMapper;
import com.fs.sop.service.IQwSopLogsService;
import com.fs.sop.service.IQwSopService;
import com.fs.sop.service.ISopUserLogsInfoService;
import com.fs.sop.service.ISopUserLogsService;
import com.fs.sop.service.impl.QwSopLogsServiceImpl;
import com.fs.sop.service.impl.QwSopServiceImpl;
import com.fs.voice.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客户群详情Service业务层处理
 *
 * @author fs
 * @date 2024-06-25
 */
@Service
public class QwGroupChatServiceImpl implements IQwGroupChatService
{
    @Autowired
    private QwGroupChatMapper qwGroupChatMapper;
    @Autowired
    private QwGroupChatUserMapper qwGroupChatUserMapper;
    @Autowired
    private QwSopMapper sopMapper;

    @Autowired
    private QwApiService qwApiService;
    @Autowired
    private QwCompanyMapper qwCompanyMapper;
    @Autowired
    private QwUserMapper qwUserMapper;
    @Autowired
    private IQwGroupChatTransferLogService qwGroupChatTransferLogService;

    /**
     * 查询客户群详情
     *
     * @param chatId 客户群详情主键
     * @return 客户群详情
     */
    @Override
    public QwGroupChat selectQwGroupChatByChatId(String chatId)
    {
        return qwGroupChatMapper.selectQwGroupChatByChatId(chatId);
    }

    /**
     * 查询客户群详情列表
     *
     * @param qwGroupChat 客户群详情
     * @return 客户群详情
     */
    @Override
    public List<QwGroupChatVO> selectQwGroupChatList(QwGroupChatParam qwGroupChat)
    {
        List<String> qwUserIds=null;
        if (!StringUtil.strIsNullOrEmpty(qwGroupChat.getQwUserList())){
            String[] split = qwGroupChat.getQwUserList().split(",");
            // 使用 Arrays.asList() 将数组转换为 List
            qwUserIds = Arrays.asList(split);
        }


        return qwGroupChatMapper.selectQwGroupChatListVO(qwGroupChat,qwUserIds);
    }

    /**
     * 新增客户群
     *
     * @param chatId 客户群详情主键[可以事件触发]
     * @return 结果
     */
    @Override
    public R insertQwGroupChat(String chatId , String corpId)
    {
        QwCompany qwCompany = qwCompanyMapper.selectQwCompanyByCorpId(corpId);

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

        QwGroupChat qwGroupChat=new QwGroupChat();
        QwGroupChatUser qwGroupChatUser=new QwGroupChatUser();

        qwGroupChat.setStatus("0");

        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();
            //群创建时间戳
            long createTime = groupChat.getCreateTime();

            qwGroupChat.setName(name);
            qwGroupChat.setNotice(notice);
            qwGroupChat.setOwner(owner);
            qwGroupChat.setCreateAt(String.valueOf(createTime));
            qwGroupChat.setMemberVersion(groupChat.getMemberVersion());
            qwGroupChat.setCompanyId(qwCompany.getId());
            qwGroupChat.setChatId(chatId);
            qwGroupChat.setCorpId(corpId);
            Date date = new Date(createTime * 1000); // 乘以1000是因为时间戳是以秒为单位，而Date期望毫秒

            qwGroupChat.setCreateTime(date);

            qwGroupChatUser.setChatId(chatId);

            //群成员列表
            List<QwGroupChatDetailsResult.Member> memberList = groupChat.getMemberList();
            int size = memberList.size();
            qwGroupChat.setGroupSize((long) size);

            qwGroupChatMapper.insertQwGroupChat(qwGroupChat);

            memberList.stream().forEach(item->{

                //客户名称
                String name1 = item.getName();
                //客户id
                String userId = item.getUserId();
                //成员类型。
                //1 - 企业成员
                //2 - 外部联系人
                int type = item.getType();

                //邀请人id
                String nnvitorId=null;
                if (type==1){
                    nnvitorId = item.getInvitor().getUserId();
                }
                //微信unionid
                String unionid=null;
                if (type==2){
                    unionid  = item.getUnionid();
                }

                //加入时间
                long joinTime = item.getJoinTime();
                //入群方式
                int joinScene = item.getJoinScene();

                //群昵称
                String groupNickname = item.getGroupNickname();

                qwGroupChatUser.setName(name1);
                qwGroupChatUser.setUserId(userId);
                qwGroupChatUser.setType(String.valueOf(type));
                qwGroupChatUser.setInvitor(nnvitorId);
                qwGroupChatUser.setUnionid(unionid);

                Date date1 = new Date(createTime * 1000); // 乘以1000是因为时间戳是以秒为单位，而Date期望毫秒
                String formattedDate = sdf.format(date1);

                qwGroupChatUser.setJoinTime(formattedDate);

                qwGroupChatUser.setJoinScene(String.valueOf(joinScene));
                qwGroupChatUser.setGroupNickname(groupNickname);
                qwGroupChatUser.setCompanyId(qwCompany.getId());
                qwGroupChatUser.setCorpId(corpId);
                qwGroupChatUserMapper.insertQwGroupChatUser(qwGroupChatUser);

            });

        }else {
            return R.error("新增群失败:"+qwGroupChatDetailsResult.getErrMsg());
        }

        return R.ok();
    }

    /**
     * 修改客户群
     *
     * @param qwGroupChat 客户群详情[可以事件触发]
     * @return 结果
     */
    @Override
    public int updateQwGroupChat(QwGroupChat qwGroupChat,String corpId)
    {
        qwGroupChat.setUpdateTime(DateUtils.getNowDate());
        return qwGroupChatMapper.updateQwGroupChat(qwGroupChat);
    }

    /**
     * 删除客户群
     *
     * @param chatId 客户群详情主键[解散客户群]
     * @return 结果
     */
    @Override
    public int deleteQwGroupChatByChatIdAndCompanyId(String chatId,String corpId)
    {
        qwGroupChatUserMapper.deleteQwGroupChatUserByIdAndCompanyId(chatId,corpId);
        return qwGroupChatMapper.deleteQwGroupChatByChatIdAndCompanyId(chatId,corpId);
    }

    @Override
    public List<QwGroupChatOptionsVO> selectGroupChatOptionsVOList(String corpId) {

        return qwGroupChatMapper.selectGroupChatOptionsVOList(corpId);
    }

    /**
     *  同步客户群列表
     */
    @Override
    public R cogradientGroupChat(String corpId,List<String> qwUserIdList) throws Exception {

//        过滤群主的id集合
        ArrayList<String> ownerFilterList = new ArrayList<>(qwUserIdList);
        try {
            QwGroupChatListResult qwGroupChatListResult = qwApiService.groupChatList(ownerFilterList, null, corpId);

            if (qwGroupChatListResult.getErrcode()!=0){
                return R.error(qwGroupChatListResult.getErrmsg());
            }
            insertGroupChatList(qwGroupChatListResult,corpId,ownerFilterList);

        }catch (Exception e){
            e.printStackTrace();
            System.out.println("同步客户群列表失败");
            return R.error(e.getMessage());
        }

        System.out.println("同步客户群列表成功");
        return R.ok();

    }


    /**
    * 递归 入库
    */
    public R insertGroupChatList(QwGroupChatListResult qwGroupChatListResult, String corpId, ArrayList<String> ownerFilterList) {

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

        QwGroupChat qwGroupChat = new QwGroupChat();
        QwGroupChatUser qwGroupChatUser = new QwGroupChatUser();

        if (qwGroupChatListResult.getErrcode() == 0) {
            List<QwGroupChatListResult.GroupChat> group_chat_list = qwGroupChatListResult.getGroup_chat_list();
            for (QwGroupChatListResult.GroupChat list : group_chat_list) {

//                qwGroupChat.setChatId(list.getChat_id());
                qwGroupChat.setStatus(String.valueOf(list.getStatus()));

                QwGroupChatDetailsResult qwGroupChatDetailsResult = qwApiService.groupChatDetails(list.getChat_id(), corpId);
                if (qwGroupChatDetailsResult.getErrCode() == 0) {
                    QwGroupChatDetailsResult.GroupChats groupChat = qwGroupChatDetailsResult.getGroupChat();
                    //群id
                    String chatId = groupChat.getChatId();
                    //群名
                    String name = groupChat.getName();
                    //群公告
                    String notice = groupChat.getNotice();
                    //群主id
                    String owner = groupChat.getOwner();
                    //群创建时间
                    long createTime = groupChat.getCreateTime();

                    qwGroupChat.setName(name);
                    qwGroupChat.setCorpId(corpId);
                    qwGroupChat.setNotice(notice);
                    qwGroupChat.setOwner(owner);
                    qwGroupChat.setCreateAt(String.valueOf(createTime));
                    qwGroupChat.setMemberVersion(groupChat.getMemberVersion());
                    qwGroupChat.setChatId(chatId);

                    Date date = new Date(createTime * 1000); // 乘以1000是因为时间戳是以秒为单位，而Date期望毫秒

                    qwGroupChat.setCreateTime(date);

                    qwGroupChatUser.setChatId(chatId);

                    //群成员列表
                    List<QwGroupChatDetailsResult.Member> memberList = groupChat.getMemberList();
                    int size = memberList.size();
                    qwGroupChat.setGroupSize((long) size);

                    qwGroupChatMapper.insertOrUpdateQwGroupChat(qwGroupChat);

                    memberList.stream().forEach(item -> {

                        //客户名称
                        String name1 = item.getName();
                        //客户id
                        String userId = item.getUserId();
                        //成员类型。
                        //1 - 企业成员
                        //2 - 外部联系人
                        int type = item.getType();

                        //邀请人id
                        String nnvitorId = null;
                        if (type == 1) {
                            nnvitorId = item.getInvitor().getUserId();
                        }
                        //微信unionid
                        String unionid = null;
                        if (type == 2) {
                            unionid = item.getUnionid();
                        }

                        //加入时间
                        long joinTime = item.getJoinTime();
                        //入群方式
                        int joinScene = item.getJoinScene();

                        //群昵称
                        String groupNickname = item.getGroupNickname();

                        qwGroupChatUser.setName(name1);
                        qwGroupChatUser.setUserId(userId);
                        qwGroupChatUser.setType(String.valueOf(type));
                        qwGroupChatUser.setInvitor(nnvitorId);
                        qwGroupChatUser.setUnionid(unionid);

                        Date date1 = new Date(createTime * 1000); // 乘以1000是因为时间戳是以秒为单位，而Date期望毫秒

                        String formattedDate = sdf.format(date1);

                        qwGroupChatUser.setJoinTime(formattedDate);

                        qwGroupChatUser.setJoinScene(String.valueOf(joinScene));
                        qwGroupChatUser.setGroupNickname(groupNickname);
                        qwGroupChatUser.setCorpId(corpId);
                        qwGroupChatUserMapper.insertOrUpdateQwGroupChatUser(qwGroupChatUser);

                    });

                }
                // 处理离职查询不到详情的情况
                else {
                    if (list.getStatus() == 1) {
                        QwGroupChat qwGroupChatResigned = qwGroupChatMapper.selectQwGroupChatByChatId(list.getChat_id());
                        qwGroupChatResigned.setUpdateTime(new Date());
                        qwGroupChatResigned.setStatus(String.valueOf(list.getStatus()));
                        qwGroupChatMapper.updateQwGroupChat(qwGroupChatResigned);
                    }
                }
            }

            if (!StringUtil.strIsNullOrEmpty(qwGroupChatListResult.getNext_cursor())){
                QwGroupChatListResult qwGroupChatListResultOrder = qwApiService.groupChatList(ownerFilterList, qwGroupChatListResult.getNext_cursor(), corpId);
                insertGroupChatList(qwGroupChatListResultOrder,corpId,ownerFilterList);
            }
        } else {
            return R.error("获取客户列表失败:" + qwGroupChatListResult.getErrmsg());
        }
        return R.ok();
    }



    @Override
    public List<QwGroupChatOptionsVO> listAllByQwUserList(String qwUserIds, String corpId, String sopId) {
        List<QwGroupChatOptionsVO> list = qwGroupChatMapper.listAllByQwUserList(qwUserIds, corpId);
        if(StringUtils.isNotEmpty(sopId)){
            QwSop qwSop = sopMapper.selectQwSopById(sopId);
            List<String> chatIds;
            if(StringUtils.isEmpty(qwSop.getChatId())){
                chatIds = new ArrayList<>();
            }else{
                chatIds = Arrays.asList(qwSop.getChatId().split(","));
            }
            list = list.stream().filter(e -> !chatIds.contains(e.getChatId())).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public List<QwGroupChat> selectQwGroupChatByChatIds(String[] ids) {
        return qwGroupChatMapper.selectQwGroupChatByChatIds(ids);
    }

    /**
     * 查询客户群列表
     * @param qwGroupChat 参数
     * @return  list
     */
    @Override
    public List<QwGroupChatTransferVO> selectQwGroupChatTransferList(QwGroupChatParam qwGroupChat) {
        return qwGroupChatMapper.selectQwGroupChatTransferList(qwGroupChat);
    }

    /**
     * 客户群转移
     * @param param         参数
     * @param user          当前销售
     * @param isResigned    是否转移离职员工客户群
     * @return  message
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultMessage processTransfer(TransferChatParam param, CompanyUser user, boolean isResigned) {
        ResultMessage resultMessage = new ResultMessage();

        QwUser qwUser = qwUserMapper.selectQwUserById(param.getQwId());
        if (Objects.isNull(qwUser)) {
            throw new CustomException("接替群主不存在");
        }

        // 准备转移参数
        QwGroupChatTransferParam transferParam = new QwGroupChatTransferParam();
        transferParam.setChat_id_list(param.getChatIds().stream()
                .map(ChatParam::getChatId)
                .collect(Collectors.toList()));
        transferParam.setNew_owner(qwUser.getQwUserId());

        // 调用不同的API
        QwGroupChatTransferResult result = isResigned ?
                qwApiService.resignedGroupChatTransfer(transferParam, param.getCorpId()) :
                qwApiService.groupChatTransfer(transferParam, param.getCorpId());

        if (result.getErrcode() != 0) {
            throw new CustomException(result.getErrmsg());
        }

        // 处理失败结果
        result.getFailed_chat_list().forEach(failed -> resultMessage.addFailure(failed.getChat_id(), failed.getErrmsg()));

        // 过滤掉转移失败的群聊
        List<ChatParam> successChatParams = filterSuccessChats(param.getChatIds(), result.getFailed_chat_list());

        // 处理成功的转移记录
        processSuccessTransfers(successChatParams, user, qwUser, resultMessage, isResigned);

        return resultMessage;
    }

    /**
     * 过滤转移失败客户群
     * @param chatParams    入参
     * @param failedChats   失败列表
     * @return  客户群
     */
    private List<ChatParam> filterSuccessChats(List<ChatParam> chatParams, List<QwGroupChatTransferResult.FailedChat> failedChats) {
        Set<String> failedChatIds = failedChats.stream()
                .map(QwGroupChatTransferResult.FailedChat::getChat_id)
                .collect(Collectors.toSet());

        return chatParams.stream()
                .filter(c -> !failedChatIds.contains(c.getChatId()))
                .collect(Collectors.toList());
    }

    /**
     * 处理转移成功客户群
     *
     * @param successChatParams 转移成功客户群
     * @param user              当前销售账户
     * @param newOwner          新群主
     * @param resultMessage     消息
     * @param isResigned        是否转移离职员工客户群
     */
    private void processSuccessTransfers(List<ChatParam> successChatParams, CompanyUser user, QwUser newOwner, ResultMessage resultMessage, boolean isResigned) {
        List<QwGroupChatTransferLog> transferLogs = successChatParams.stream()
                .map(chatParam -> createTransferLog(chatParam, user, newOwner, isResigned))
                .collect(Collectors.toList());

        if (!transferLogs.isEmpty()) {
            qwGroupChatTransferLogService.saveBatch(transferLogs);
            transferLogs.forEach(log -> resultMessage.addSuccess());
        }
    }

    /**
     * 保存转移记录修改群主
     * @param chatParam  客户群
     * @param user       当前销售
     * @param newOwner   新群主
     * @param isResigned 是否转移离职员工客户群
     * @return  log
     */
    private QwGroupChatTransferLog createTransferLog(ChatParam chatParam, CompanyUser user, QwUser newOwner, boolean isResigned) {
        QwGroupChat qwGroupChat = qwGroupChatMapper.selectQwGroupChatByChatId(chatParam.getChatId());
        QwUser oldOwner = qwUserMapper.selectQwUserById(chatParam.getQwId());

        // 更新群主信息
        qwGroupChat.setOwner(newOwner.getQwUserId());
        qwGroupChat.setUpdateTime(new Date());
        if (isResigned) {
            qwGroupChat.setStatus("3");
        }
        qwGroupChatMapper.updateQwGroupChat(qwGroupChat);

        // 创建转移日志
        QwGroupChatTransferLog transferLog = new QwGroupChatTransferLog();
        transferLog.setChatName(qwGroupChat.getName());
        transferLog.setCorpId(qwGroupChat.getCorpId());
        transferLog.setTransferType(isResigned ? 1 : 0);
        transferLog.setCompanyId(user.getCompanyId());
        transferLog.setCompanyUserId(user.getUserId());
        transferLog.setOldOwner(oldOwner.getQwUserId());
        transferLog.setOldCompanyUserId(oldOwner.getCompanyUserId());
        transferLog.setOldQwUserName(oldOwner.getQwUserName());
        transferLog.setOldQwUserId(oldOwner.getId());
        transferLog.setNewOwner(newOwner.getQwUserId());
        transferLog.setNewCompanyUserId(newOwner.getCompanyUserId());
        transferLog.setNewQwUserName(newOwner.getQwUserName());
        transferLog.setNewQwUserId(newOwner.getId());
        transferLog.setChatId(chatParam.getChatId());
        transferLog.setCreateTime(LocalDateTime.now());

        return transferLog;
    }

}
