package com.fs.qw.service.impl;

import com.fs.common.core.domain.R;
import com.fs.company.service.ICompanyConfigService;
import com.fs.qw.domain.QwGroupChat;
import com.fs.qw.domain.QwGroupChatUser;
import com.fs.qw.mapper.QwCompanyMapper;
import com.fs.qw.mapper.QwGroupChatMapper;
import com.fs.qw.mapper.QwGroupChatUserMapper;
import com.fs.qw.param.QwGroupChatUserDataType;
import com.fs.qw.service.IQwGroupChatUserService;
import com.fs.qw.vo.QwGroupChatUserVO;
import com.fs.qwApi.Result.QwGroupChatDetailsResult;
import com.fs.qwApi.service.QwApiService;
import com.fs.sop.domain.SopUserLogsInfo;
import com.fs.voice.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 客户群成员列Service业务层处理
 *
 * @author fs
 * @date 2024-06-20
 */
@Service
public class QwGroupChatUserServiceImpl implements IQwGroupChatUserService
{
    @Autowired
    private QwGroupChatUserMapper qwGroupChatUserMapper;

    @Autowired
    private ICompanyConfigService companyConfigService;

    @Autowired
    private QwApiService qwApiService;

    @Autowired
    private QwGroupChatMapper qwGroupChatMapper;

    @Autowired
    QwCompanyMapper qwCompanyMapper;


    /**
     * 查询客户群成员列
     *
     * @param id 客户群成员列主键
     * @return 客户群成员列
     */
    @Override
    public QwGroupChatUser selectQwGroupChatUserById(Long id)
    {
        return qwGroupChatUserMapper.selectQwGroupChatUserById(id);
    }


    /**
     * 查询客户群成员列列表
     *
     * @param qwGroupChatUser 客户群成员列
     * @return 客户群成员列
     */
    @Override
    public List<QwGroupChatUserVO> selectQwGroupChatUserList(QwGroupChatUser qwGroupChatUser)
    {
        return qwGroupChatUserMapper.selectQwGroupChatUserListVO(qwGroupChatUser);
    }

    /** 获取日星月的入群退群统计 */
    @Override
    public R getDataWeekMonthCount(QwGroupChatUserDataType qwGroupChatUserDataType) {
        List<HashMap<String, String>> dataWeekMonthCount=null;
        if (qwGroupChatUserDataType.getCountType()==3){
            dataWeekMonthCount = qwGroupChatUserMapper.getDataWeekMonthCountMonth(qwGroupChatUserDataType);

        }else {
            dataWeekMonthCount = qwGroupChatUserMapper.getDataWeekMonthCount(qwGroupChatUserDataType);

        }

        return R.ok().put("data",dataWeekMonthCount);
    }


    @Override
    public R cogradientGroupChatUser(String corpId,String chatIdParam) {


        QwGroupChatDetailsResult qwGroupChatDetailsResult = qwApiService.groupChatDetails(chatIdParam,corpId);

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

        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.setNotice(notice);
            qwGroupChat.setOwner(owner);
            qwGroupChat.setCreateAt(String.valueOf(createTime));
            qwGroupChat.setMemberVersion(groupChat.getMemberVersion());
            qwGroupChat.setCorpId(corpId);
//            qwGroupChat.setCompanyId(qwCompany.getId());
            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);

            qwGroupChatUserMapper.markActiveMembersOutByChatId(chatId, corpId);

            memberList.forEach(item -> {

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

                //邀请人id
                String nnvitorId = null;
                if (type == 1 && item != null && item.getInvitor() != null && !StringUtil.strIsNullOrEmpty(item.getInvitor().getUserId())) {
                    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.insertOrUpdateSyncGroupChatUser(qwGroupChatUser);

            });

        }
        else {
            return R.error(qwGroupChatDetailsResult.getErrMsg());
        }
        return R.ok();
    }

    @Override
    public int upDateDelGroupChatUser(QwGroupChatUser qwGroupChatUser) {

        return qwGroupChatUserMapper.upDateDelGroupChatUser(qwGroupChatUser);
    }

    @Override
    public int insertQwGroupChatUser(QwGroupChatUser qwGroupChatUser) {
        return qwGroupChatUserMapper.insertQwGroupChatUser(qwGroupChatUser);
    }

    @Override
    public int groupChatUserJoinAgain(QwGroupChatUser qwGroupChatUser) {

        return qwGroupChatUserMapper.groupChatUserJoinAgain(qwGroupChatUser);
    }

    @Override
    public QwGroupChatUser selectQwGroupChatUserByExternalUserId(QwGroupChatUser qwGroupChatUser) {

//        CompanyConfig companyConfig = companyConfigService.selectCompanyConfigByKey(companyId, "sys:qw:config");
//        QWCompanyConfig qwCompanyConfig = JSON.parseObject(companyConfig.getConfigValue(), QWCompanyConfig.class);
//        String corpId = qwCompanyConfig.getCorpId();
//        qwGroupChatUser.setCompanyId(companyId);
        return qwGroupChatUserMapper.selectQwGroupChatUserByExternalUserId(qwGroupChatUser);
    }

    @Override
    public List<QwGroupChatUser> selectQwGroupChatUserByChatIds(String[] array) {
        return qwGroupChatUserMapper.selectQwGroupChatUserByChatIds(array);
    }

    @Override
    public List<QwGroupChatUser> selectUserIsChat(String externalUserId) {
        return qwGroupChatUserMapper.selectUserIsChat(externalUserId);
    }

    @Override
    public List<QwGroupChatUser> selectByChatId(SopUserLogsInfo sopUserLogsInfo) {
        return qwGroupChatUserMapper.selectByChatId(sopUserLogsInfo);
    }

    @Override
    public List<String> selectChatNameByUserId(String userId) {
        return qwGroupChatUserMapper.selectChatNameByUserId(userId);
    }

}
