package com.fs.qw.service.impl;

import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
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.QwGroupChatParam;
import com.fs.qw.service.*;
import com.fs.qw.vo.QwGroupChatOptionsVO;
import com.fs.qw.vo.QwGroupChatVO;
import com.fs.qwApi.Result.QwGroupChatDetailsResult;
import com.fs.qwApi.Result.QwGroupChatListResult;
import com.fs.qwApi.service.QwApiService;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 客户群详情Service业务层处理
 *
 * @author fs
 * @date 2024-06-25
 */
@Service
public class QwGroupChatServiceImpl implements IQwGroupChatService
{
    private static final Logger log = LoggerFactory.getLogger(QwGroupChatServiceImpl.class);
    @Autowired
    private QwGroupChatMapper qwGroupChatMapper;

    @Autowired
    private QwGroupChatUserMapper qwGroupChatUserMapper;

    @Autowired
    private QwApiService qwApiService;

    @Autowired
    private ICompanyConfigService companyConfigService;

    @Autowired
    private IFsCourseLinkService iFsCourseLinkService;

    @Autowired
    IQwExternalContactService qwExternalContactService;

    @Autowired
    IQwCompanyService iQwCompanyService;

    @Autowired
    private ISopUserLogsInfoService sopUserLogsInfoService;

    @Autowired
    private IQwSopService iQwSopService;

    @Autowired
    private IQwSopLogsService iQwSopLogsService;

    @Autowired
    private IQwGroupMsgService iQwGroupMsgService;

    @Autowired
    private QwSopLogsServiceImpl qwSopLogsService;

    @Autowired
    private QwSopServiceImpl qwSopService;

    @Autowired
    QwAutoTagsMapper qwAutoTagsMapper;

    @Autowired
    QwCompanyMapper qwCompanyMapper;

    @Autowired
    private QwSopMapper qwSopMapper;

    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private QwExternalContactMapper qwExternalContactMapper;
    @Autowired
    private ISopUserLogsService sopUserLogsService;

    @Autowired
    private ISopUserLogsInfoService iSopUserLogsInfoService;

    @Autowired
    private QwAppContactWayMapper  qwAppContactWayMapper;

    @Autowired
    private QwAppContactWayLogsMapper qwAppContactWayLogsMapper;

    @Autowired
    private IQwExternalErrRetryService errRetryService;

    @Autowired
    private SopUserLogsInfoMapper sopUserLogsInfoMapper;

//    @Autowired
//    private IQwGetJsapiTicketService qwGetJsapiTicketService;

    /**
     * 查询客户群详情
     *
     * @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 List<QwGroupChatOptionsVO> listAllByQwUserList(String qwUserIds) {
        return qwGroupChatMapper.listAllByQwUserList(qwUserIds);
    }

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

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

//        过滤群主的id集合
        ArrayList<String> ownerFilterList=new ArrayList<>();

        try {
            QwGroupChatListResult qwGroupChatListResult = qwApiService.groupChatList(ownerFilterList, null, corpId);

            insertGroupChatList(qwGroupChatListResult,corpId,ownerFilterList);

        }catch (Exception e){
            return R.error(e.getMessage());
        }


        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);

                    });

                }
            }

            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();
    }



}
