package com.fs.qw.service.impl;

import com.fs.common.core.domain.R;
import com.fs.qw.domain.QwGroupMsgUser;
import com.fs.qw.mapper.QwGroupMsgMapper;
import com.fs.qw.mapper.QwGroupMsgUserMapper;
import com.fs.qw.service.IQwGroupMsgUserService;
import com.fs.qw.vo.QwGroupMsgDetailsVO;
import com.fs.qwApi.Result.QwGetGroupmsgTaskResult;
import com.fs.qwApi.Result.QwGroupmsgSendResult;
import com.fs.qwApi.Result.SendItemResult;
import com.fs.qwApi.Result.TaskItemResult;
import com.fs.qwApi.param.QwGetGroupMsgTask;
import com.fs.qwApi.param.QwGetGroupmsgSendParam;
import com.fs.qwApi.service.QwApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 群发成员发送任务及执行结果反馈记录Service业务层处理
 *
 * @author fs
 * @date 2024-06-20
 */
@Service
public class QwGroupMsgUserServiceImpl implements IQwGroupMsgUserService
{
    @Autowired
    private QwGroupMsgUserMapper qwGroupMsgUserMapper;

    @Autowired
    private QwGroupMsgMapper qwGroupMsgMapper;

    @Autowired
    private QwApiService qwApiService;

    /**
     * 查询群发成员发送任务及执行结果反馈记录
     *
     * @param id 群发成员发送任务及执行结果反馈记录主键
     * @return 群发成员发送任务及执行结果反馈记录
     */
    @Override
    public QwGroupMsgUser selectQwGroupMsgUserById(Long id)
    {
        return qwGroupMsgUserMapper.selectQwGroupMsgUserById(id);
    }

    /**
     * 查询群发成员发送任务及执行结果反馈记录列表
     *
     * @param qwGroupMsgUser 群发成员发送任务及执行结果反馈记录
     * @return 群发成员发送任务及执行结果反馈记录
     */
    @Override
    public List<QwGroupMsgUser> selectQwGroupMsgUserList(QwGroupMsgUser qwGroupMsgUser)
    {
        return qwGroupMsgUserMapper.selectQwGroupMsgUserList(qwGroupMsgUser);
    }

    /**
     * 新增群发成员发送任务及执行结果反馈记录
     *
     * @param qwGroupMsgUser 群发成员发送任务及执行结果反馈记录
     * @return 结果
     */
    @Override
    public int insertQwGroupMsgUser(QwGroupMsgUser qwGroupMsgUser)
    {
        return qwGroupMsgUserMapper.insertQwGroupMsgUser(qwGroupMsgUser);
    }

    /**
     * 修改群发成员发送任务及执行结果反馈记录
     *
     * @param qwGroupMsgUser 群发成员发送任务及执行结果反馈记录
     * @return 结果
     */
    @Override
    public int updateQwGroupMsgUser(QwGroupMsgUser qwGroupMsgUser)
    {
        return qwGroupMsgUserMapper.updateQwGroupMsgUser(qwGroupMsgUser);
    }

    /**
     * 批量删除群发成员发送任务及执行结果反馈记录
     *
     * @param ids 需要删除的群发成员发送任务及执行结果反馈记录主键
     * @return 结果
     */
    @Override
    public int deleteQwGroupMsgUserByIds(Long[] ids)
    {
        return qwGroupMsgUserMapper.deleteQwGroupMsgUserByIds(ids);
    }

    /** 刷新/同步 客户群群发 结果 */
    @Override
    public R refreshResultsGroupMsgUser(List<QwGroupMsgDetailsVO> list) {

        QwGetGroupmsgSendParam param=new QwGetGroupmsgSendParam();


        // 过滤 群id 为 null 的数据
        List<QwGroupMsgDetailsVO> filteredList = list.stream()
                .filter(item -> item.getChatId() == null)
                .collect(Collectors.toList());

        for (QwGroupMsgDetailsVO vo: filteredList) {
            String userId = vo.getUserId();
            String msgId = vo.getMsgId();

            param.setMsgid(msgId);
            param.setUserid(userId);
            param.setLimit(1000);

            QwGroupmsgSendResult groupmsgSendResult = qwApiService.getGroupmsgSendResult(param, vo.getCorpId());
            if (groupmsgSendResult.getErrCode()!=0){
                if (groupmsgSendResult.getErrCode()==41063){
                    return R.ok("消息正在派发中,稍后再试");
                }else {
                    return R.error("结果同步失败userId:"+userId+"||msgId:"+msgId+"||"+groupmsgSendResult.getErrMsg());
                }

            }
            else {
                List<SendItemResult> sendList = groupmsgSendResult.getSendList();
                sendList.stream().forEach(it->{

                    QwGroupMsgUser qwGroupMsgUser=new QwGroupMsgUser();

                    qwGroupMsgUser.setUserId(userId);
                    qwGroupMsgUser.setMsgId(msgId);
                    qwGroupMsgUser.setGroupMsgId(vo.getGroupMsgId());
                    qwGroupMsgUser.setChatId(it.getChatId());

                    //根据上面的条件先查
                    List<QwGroupMsgUser> qwGroupMsgUsers = qwGroupMsgUserMapper.selectQwGroupMsgUserList(qwGroupMsgUser);


                    qwGroupMsgUser.setStatus(2);
                    qwGroupMsgUser.setSendTime(it.getSendTime());
                    qwGroupMsgUser.setChatType("group");
                    qwGroupMsgUser.setCorpId(vo.getCorpId());
                    qwGroupMsgUser.setCompanyId(vo.getCompanyId());
                    qwGroupMsgUser.setSendStatus(it.getStatus());

                    if (qwGroupMsgUsers.size()==0){
                        int i = qwGroupMsgUserMapper.insertQwGroupMsgUser(qwGroupMsgUser);
                        if (i>=0){
                            //删除掉第一次的主记录
                            qwGroupMsgUserMapper.deleteQwGroupMsgUserByStatus(vo);
                        }
                    }else {
                        qwGroupMsgUserMapper.updateQwGroupMsgUser(qwGroupMsgUser);
                    }

                });



            }



        }


        return R.ok("同步完成");
    }

    /** 刷新/同步 客户群发 结果 */
    @Override
    public R refreshResultsMsgUser(List<QwGroupMsgDetailsVO> list,String corpIdParam) {


    QwGetGroupmsgSendParam param=new QwGetGroupmsgSendParam();

    //群发成员发送任务及执行结果反馈记录
    QwGroupMsgUser qwGroupMsgUser=new QwGroupMsgUser();

    List<String> userIdList = list.stream().map(QwGroupMsgDetailsVO::getUserId).map(String::trim).distinct().collect(Collectors.toList());

    for (String userid:userIdList){
        if (userid==null&&!list.isEmpty()){
            Long id = list.get(0).getId();
            String msgId = list.get(0).getMsgId();
            String chatType = list.get(0).getChatType();
            Long companyId1 = list.get(0).getCompanyId();
            String corpId = list.get(0).getCorpId();

            if (chatType.equals("single")&&list.get(0).getTimerResultType()==1){

                QwGetGroupMsgTask qwGetGroupMsgTask=new QwGetGroupMsgTask();
                qwGetGroupMsgTask.setMsgid(msgId);
                qwGetGroupMsgTask.setLimit(1000);

                //获取群发成员发送任务列表结果
                QwGetGroupmsgTaskResult groupmsgTask = qwApiService.getGroupmsgTask(qwGetGroupMsgTask,corpIdParam );
                List<TaskItemResult> taskList = groupmsgTask.getTaskList();

                //根据群发成员发送任务列表获取到 循环获取到各个成员的执行结果（含客户列表）
                for (TaskItemResult talist:taskList){

                    String userId = talist.getUserId();

                    //获取企业群发成员执行结果
                    param.setUserid(userId);
                    param.setMsgid(msgId);
                    param.setLimit(1000);
                    QwGroupmsgSendResult groupmsgSendResult = qwApiService.getGroupmsgSendResult(param, corpIdParam);

                    if (groupmsgSendResult.getErrCode()!=0){
                        //啥也不干，可以从同步操作中再次获取
                    }else {
                        List<SendItemResult> sendList = groupmsgSendResult.getSendList();
                        for (SendItemResult itemResult: sendList ) {

                            qwGroupMsgUser.setUserId(userId);
                            qwGroupMsgUser.setStatus(talist.getStatus());
                            qwGroupMsgUser.setMsgId(msgId);
                            qwGroupMsgUser.setChatType(chatType);
                            qwGroupMsgUser.setCorpId(corpId);
                            qwGroupMsgUser.setCompanyId(companyId1);
                            qwGroupMsgUser.setGroupMsgId(id);
                            qwGroupMsgUser.setExternalUserid(itemResult.getExternalUserId());
                            qwGroupMsgUser.setSendStatus(itemResult.getStatus());
                            qwGroupMsgUser.setSendTime(itemResult.getSendTime());

                            qwGroupMsgUserMapper.insertQwGroupMsgUser(qwGroupMsgUser);

                        }
                    }


                }

            }
        }
        else if (userid!=null){
            param.setUserid(userid);
            param.setLimit(1000);
            param.setMsgid(list.get(0).getMsgId());

            QwGroupmsgSendResult groupmsgSendResult = qwApiService.getGroupmsgSendResult(param, corpIdParam);
            if (groupmsgSendResult.getErrCode()!=0){
                return R.error("结果同步失败userId:"+userid+"||msgId:"+list.get(0).getMsgId()+"||"+groupmsgSendResult.getErrMsg());
            }
            else {
                List<SendItemResult> sendList = groupmsgSendResult.getSendList();
                sendList.stream().forEach(it->{


                    qwGroupMsgUser.setUserId(userid);
                    qwGroupMsgUser.setMsgId(list.get(0).getMsgId());
                    qwGroupMsgUser.setGroupMsgId(list.get(0).getGroupMsgId());
                    qwGroupMsgUser.setExternalUserid(it.getExternalUserId());

                    qwGroupMsgUser.setStatus(2);
                    qwGroupMsgUser.setSendTime(it.getSendTime());
                    qwGroupMsgUser.setChatType("single");
                    qwGroupMsgUser.setCorpId(list.get(0).getCorpId());
                    qwGroupMsgUser.setCompanyId(list.get(0).getCompanyId());
                    qwGroupMsgUser.setSendStatus(it.getStatus());


                    qwGroupMsgUserMapper.updateQwGroupMsgUserResult(qwGroupMsgUser);


                });

            }

        }
    }


    return R.ok("同步完成");
}

    /**
     * 删除群发成员发送任务及执行结果反馈记录信息
     *
     * @param id 群发成员发送任务及执行结果反馈记录主键
     * @return 结果
     */
    @Override
    public int deleteQwGroupMsgUserById(Long id)
    {
        return qwGroupMsgUserMapper.deleteQwGroupMsgUserById(id);
    }
}
