package com.fs.qw.service.impl;


import com.alibaba.fastjson.JSON;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.company.service.ICompanyConfigService;
import com.fs.qw.domain.QwCompany;
import com.fs.qw.domain.QwGroupMsg;
import com.fs.qw.domain.QwGroupMsgItem;
import com.fs.qw.domain.QwGroupMsgUser;
import com.fs.qw.mapper.QwCompanyMapper;
import com.fs.qw.mapper.QwGroupMsgItemMapper;
import com.fs.qw.mapper.QwGroupMsgMapper;
import com.fs.qw.mapper.QwGroupMsgUserMapper;
import com.fs.qw.param.QwCountCustomerParam;
import com.fs.qw.param.QwGroupMsgDetailsParam;
import com.fs.qw.param.QwGroupMsgParam;
import com.fs.qw.service.IQwExternalContactService;
import com.fs.qw.service.IQwGroupMsgService;
import com.fs.qw.service.IQwGroupchatStatisticService;
import com.fs.qw.service.IQwUserbehaviorDataService;
import com.fs.qw.vo.QwGroupMsgDetailsVO;
import com.fs.qw.vo.QwGroupMsgVO;
import com.fs.qwApi.Result.*;
import com.fs.qwApi.domain.QwResult;
import com.fs.qwApi.param.QwGetGroupMsgTask;
import com.fs.qwApi.param.QwGetGroupmsgSendParam;
import com.fs.qwApi.param.QwMsgTemplate;
import com.fs.qwApi.service.QwApiService;
import com.fs.sop.service.IQwSopService;
import com.fs.voice.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 客户群发记录主Service业务层处理
 *
 * @author fs
 * @date 2024-06-20
 */
@Service
public class QwGroupMsgServiceImpl implements IQwGroupMsgService
{
    @Autowired
    private QwGroupMsgMapper qwGroupMsgMapper;

    @Autowired
    private QwGroupMsgItemMapper qwGroupMsgItemMapper;

    @Autowired
    private QwGroupMsgUserMapper qwGroupMsgUserMapper;

    @Autowired
    private QwCompanyMapper qwCompanyMapper;

    @Autowired
    private QwApiService qwApiService;

    @Autowired
    private IQwExternalContactService qwExternalContactService;


    @Autowired
    private QwWelcomeServiceImpl qwWelcomeService;

    @Autowired
    private ICompanyConfigService companyConfigService;

    @Autowired
    private IQwSopService iQwSopService;
    ;
    @Autowired
    private IQwUserbehaviorDataService qwUserbehaviorDataService;

    @Autowired
    private IQwGroupchatStatisticService qwGroupchatStatisticService;
    /**
     * 查询客户群发记录主
     *
     * @param id 客户群发记录主主键
     * @return 客户群发记录主
     */
    @Override
    public QwGroupMsgVO selectQwGroupMsgByIdVO(Long id)
    {
        return qwGroupMsgMapper.selectQwGroupMsgByIdVO(id);
    }

    /**
     * 查询客户群发记录主列表
     *
     * @param qwGroupMsg 客户群发记录主
     * @return 客户群发记录主
     */
    @Override
    public List<QwGroupMsgVO> selectQwGroupMsgListVO(QwGroupMsg qwGroupMsg)
    {
        return qwGroupMsgMapper.selectQwGroupMsgListVO(qwGroupMsg);
    }

    @Override
    public List<QwGroupMsgVO> selectQwGroupMsgListMyVO(QwGroupMsg qwGroupMsg) {
        return qwGroupMsgMapper.selectQwGroupMsgListMyVO(qwGroupMsg);
    }

    /**
     * 新增客户群发/客户群群发记录
     *
     * @param qwGroupMsgParam 客户群发记录参数
     * @return 结果
     */
    @Override
    public R insertQwGroupMsg(QwGroupMsgParam qwGroupMsgParam) throws Exception {

        QwCompany qwCompany = qwCompanyMapper.selectQwCompanyByCorpId(qwGroupMsgParam.getCorpId());

        if (qwGroupMsgParam.getUserIdsSelectList().isEmpty()){
            return R.error("请选择发送对象");
        }
        ArrayList<String> userIdsSelectList = qwGroupMsgParam.getUserIdsSelectList();

        //发送消息组件表
        QwMsgTemplate msgTemplate=new QwMsgTemplate();

        //客户群发消息的附件记录表
        QwGroupMsgItem qwGroupMsgItem=new QwGroupMsgItem();

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

        //客户群发记录主表
        QwGroupMsg qwGroupMsg=new QwGroupMsg();

        //文字+图片
        switch (qwGroupMsgParam.getMsgType()){
            case 1:
                if(!StringUtil.strIsNullOrEmpty(qwGroupMsgParam.getImagePicUrl())){
                    QwUploadImgResult uploadimg = qwApiService.uploadimgs(qwGroupMsgParam.getImagePicUrl(), qwGroupMsgParam.getCorpId());
                    if (uploadimg.getErrcode()!=0){
                        return R.error("图片上传失败:"+uploadimg.getErrMsg());
                    }

                    msgTemplate.setImagePicUrl(uploadimg.getUrl());

                    //附件表
                    qwGroupMsgItem.setMediaPicUrl(uploadimg.getUrl());
                }

                qwGroupMsgItem.setMsgType(1);

                break;
            case 2:
                //图文
                if(!StringUtil.strIsNullOrEmpty(qwGroupMsgParam.getLinkUrl())){
                    QwUploadImgResult uploadimgOne=new QwUploadImgResult();
                    if (!StringUtil.strIsNullOrEmpty(qwGroupMsgParam.getLinkPicurl())){
                        uploadimgOne = qwApiService.uploadimgs(qwGroupMsgParam.getLinkPicurl(), qwGroupMsgParam.getCorpId());
                        if (uploadimgOne.getErrcode()!=0){
                            return R.error("图片上传失败:"+uploadimgOne.getErrMsg());
                        }
                    }

                    msgTemplate.setLinkTitle(qwGroupMsgParam.getLinkTitle());
                    msgTemplate.setLinkPicurl(uploadimgOne.getUrl());
                    msgTemplate.setLinkDesc(qwGroupMsgParam.getLinkDesc());
                    msgTemplate.setLinkUrl(qwGroupMsgParam.getLinkUrl());

                    qwGroupMsgItem.setMsgType(2);
                    qwGroupMsgItem.setTitle(qwGroupMsgParam.getLinkTitle());
                    qwGroupMsgItem.setPicurl(uploadimgOne.getUrl());
                    qwGroupMsgItem.setDescription(qwGroupMsgParam.getLinkDesc());
                    qwGroupMsgItem.setUrl(qwGroupMsgParam.getLinkUrl());


                }
                break;
            case 3:
                break;
            //文件
            case 4:
                if(!StringUtil.strIsNullOrEmpty(qwGroupMsgParam.getFileUrl())){
                    File fileOne = urlToFile(qwGroupMsgParam.getFileUrl());
                    QwUploadResult file = qwApiService.upload(fileOne, "file", qwGroupMsgParam.getCorpId());

                    if (file.getErrCode()!=0){
                        return R.error("文件临时文件上传失败:"+file.getErrMsg());
                    }

                    msgTemplate.setFileMediaId(file.getMediaId());

                    qwGroupMsgItem.setFileMediaId(file.getMediaId());
                    qwGroupMsgItem.setFileUrl(qwGroupMsgParam.getFileUrl());
                    qwGroupMsgItem.setMsgType(4);
                    qwGroupMsgItem.setCreatedAt(file.getCreatedAt());

                    fileOne.delete();
                }
                break;
            case 5:
                if ( !StringUtil.strIsNullOrEmpty(qwGroupMsgParam.getVideoUrl())){
                    File fileOne = urlToFile(qwGroupMsgParam.getVideoUrl());
                    QwUploadResult file = qwApiService.upload(fileOne, "video",qwGroupMsgParam.getCorpId());
                    if (file.getErrCode()!=0){
                        return R.error("视频临时文件上传失败:"+file.getErrMsg());
                    }

                    msgTemplate.setVideoMediaId(file.getMediaId());

                    qwGroupMsgItem.setVideoMediaId(file.getMediaId());
                    qwGroupMsgItem.setVideoUrl(qwGroupMsgParam.getVideoUrl());
                    qwGroupMsgItem.setMsgType(5);
                    qwGroupMsgItem.setCreatedAt(file.getCreatedAt());
                    fileOne.delete();
                }
                break;
        }


//        if (qwGroupMsgParam.getMsgType()==3){
//            return R.error("暂时无法上传小程序");
//        }


        qwGroupMsg.setCorpId(qwGroupMsgParam.getCorpId());

        //主表存/任务类型
        qwGroupMsg.setChatType(qwGroupMsgParam.getChatType());

        //发送这条消息文本的成员集合
        qwGroupMsg.setSender(userIdsSelectList.toString());
        qwGroupMsg.setAllowSelect(qwGroupMsgParam.getAllowSelect());
        qwGroupMsg.setTextContent(qwGroupMsgParam.getTextContent());
        qwGroupMsg.setCreateName(qwGroupMsgParam.getCreateName());
        qwGroupMsg.setGroupChatNames(qwGroupMsgParam.getGroupChatNames());

        //如果发送给客户群
        if (qwGroupMsgParam.getChatType().equals("group")){

            qwGroupMsg.setFilterCustomers(JSON.toJSONString(qwGroupMsgParam.getGroupChatNamesMap()));

            //定时发送时,就只存记录
            if (qwGroupMsgParam.getIsTimerSend()==1){

                qwGroupMsg.setIsSend(3);
                qwGroupMsg.setIsTimerSend(1);
                qwGroupMsg.setTimerSend(qwGroupMsgParam.getTimerSend());
                qwGroupMsg.setCreateTime(DateUtils.getNowDate());

                //主表做记录
                insertRecordsGroup(qwGroupMsg,qwGroupMsgItem,qwGroupMsgParam.getCorpId(),qwCompany.getId());

                return R.ok();
            }else {

                qwGroupMsg.setIsSend(1);
                qwGroupMsg.setCreateTime(DateUtils.getNowDate());
                //主表做记录
                insertRecordsGroup(qwGroupMsg,qwGroupMsgItem,qwGroupMsgParam.getCorpId(),qwCompany.getId());

            }


            //因为群发群,群主只能选择一个一个发
            for (String qwUserid: qwGroupMsgParam.getUserIdsSelectList()) {
                HashMap<String, ArrayList<String>> groupChatNamesMap = qwGroupMsgParam.getGroupChatNamesMap();
                if (groupChatNamesMap.containsKey(qwUserid)){
                    ArrayList<String> arrayList = groupChatNamesMap.get(qwUserid);
                    if (!arrayList.isEmpty()){

                        msgTemplate.setChatType(qwGroupMsgParam.getChatType());
                        msgTemplate.setSender(qwUserid);
                        msgTemplate.setAllowSelect(qwGroupMsgParam.getAllowSelect()==1?true:false);
                        msgTemplate.setTextContent(qwGroupMsgParam.getTextContent());
                        msgTemplate.setType(qwGroupMsgParam.getMsgType());
                        msgTemplate.setChatIdList(arrayList);

                        QwAddMsgTemplateResult qwAddMsgTemplateResult = qwApiService.addMsgTemplate(msgTemplate,qwGroupMsgParam.getCorpId());

                        if (qwAddMsgTemplateResult.getErrCode()!=0){
                            qwGroupMsg.setIsSend(0);
                            qwGroupMsg.setCreateTime(DateUtils.getNowDate());
                            //主表做记录
                            insertRecordsGroup(qwGroupMsg,qwGroupMsgItem,qwGroupMsgParam.getCorpId(),qwCompany.getId());
                            return R.error("成员:"+qwUserid+"/群群发消息失败"+":"+qwAddMsgTemplateResult.getErrMsg());
                        }
                        else {

                            //记录一条
                            qwGroupMsgUser.setChatType(qwGroupMsgParam.getChatType());
                            qwGroupMsgUser.setCorpId(qwGroupMsgParam.getCorpId());
                            qwGroupMsgUser.setCompanyId(null);
                            qwGroupMsgUser.setGroupMsgId(qwGroupMsg.getId());
                            qwGroupMsgUser.setMsgId(qwAddMsgTemplateResult.getMsgId());
                            qwGroupMsgUser.setUserId(qwUserid);

                            //群发成员发送任务及执行结果反馈记录
                            qwGroupMsgUserMapper.insertQwGroupMsgUser(qwGroupMsgUser);

                            QwGetGroupMsgTask qwGetGroupMsgTask=new QwGetGroupMsgTask();
                            qwGetGroupMsgTask.setMsgid(qwAddMsgTemplateResult.getMsgId());
                            qwGetGroupMsgTask.setLimit(1000);

                            //延迟4秒
                            Thread.sleep(4000);

                            //获取群发成员发送任务列表 （只有状态为2,即成员选择发送了群聊后，才能看见 有哪些群聊（群聊列表））
                            QwGetGroupmsgTaskResult groupmsgTask = qwApiService.getGroupmsgTask(qwGetGroupMsgTask, qwGroupMsgParam.getCorpId());

                            if (groupmsgTask.getErrCode()==2){

                                QwGetGroupmsgSendParam qwGetGroupmsgSendParam=new QwGetGroupmsgSendParam();
                                //获取企业群发成员执行结果（发送给客户群的话，要成员选择发送了之后，才会有列表）
                                qwGetGroupmsgSendParam.setUserid(qwUserid);
                                qwGetGroupmsgSendParam.setMsgid(qwAddMsgTemplateResult.getMsgId());
                                qwGetGroupmsgSendParam.setLimit(1000);

                                QwGroupmsgSendResult groupmsgSendResult = qwApiService.getGroupmsgSendResult(qwGetGroupmsgSendParam, qwGroupMsgParam.getCorpId());
                                if (groupmsgSendResult.getErrCode()!=0){
                                    return R.error("获取企业群发成员执行结果失败:"+groupmsgSendResult.getErrMsg());
                                }else {
                                    List<SendItemResult> sendList = groupmsgSendResult.getSendList();

                                    for (SendItemResult send: sendList) {

                                        qwGroupMsgUser.setChatType(qwGroupMsgParam.getChatType());
                                        qwGroupMsgUser.setCorpId(qwGroupMsgParam.getCorpId());
                                        qwGroupMsgUser.setCompanyId(qwCompany.getId());
                                        qwGroupMsgUser.setGroupMsgId(qwGroupMsg.getId());
                                        qwGroupMsgUser.setUserId(send.getUserId());
                                        qwGroupMsgUser.setMsgId(qwAddMsgTemplateResult.getMsgId());
                                        //群聊id
                                        qwGroupMsgUser.setChatId(send.getChatId());
                                        //发送时间
                                        qwGroupMsgUser.setSendTime(send.getSendTime());
                                        //发送状态
                                        qwGroupMsgUser.setSendStatus(send.getStatus());

                                        //群发成员发送任务及执行结果反馈记录
                                        qwGroupMsgUserMapper.insertQwGroupMsgUser(qwGroupMsgUser);
                                    }
                                }
                            }

                        }
                    }
                }


            }


        }
        else if (qwGroupMsgParam.getChatType().equals("single")){

            qwGroupMsg.setSelectType(qwGroupMsgParam.getSelectType());
            //筛选出客户
            QwCountCustomerParam qwCountCustomerParam=new QwCountCustomerParam();
            qwCountCustomerParam.setUserIdsSelectList(qwGroupMsgParam.getUserIdsSelectList());
            qwCountCustomerParam.setSelectType(qwGroupMsgParam.getSelectType());
            qwCountCustomerParam.setGender(qwGroupMsgParam.getGender());
            qwCountCustomerParam.setGroupChatSelectList(qwGroupMsgParam.getGroupChatSelectList());
            qwCountCustomerParam.setTimeScreenCharge(qwGroupMsgParam.getTimeScreenCharge());
            qwCountCustomerParam.setTagsIdsSelectList(qwGroupMsgParam.getTagsIdsSelectList());
            qwCountCustomerParam.setOutTagsIdsSelectList(qwGroupMsgParam.getOutTagsIdsSelectList());

            //根据 条件 筛选出预计发送的客户id列表
            ArrayList<String> customerList= qwExternalContactService.selectQwGroupMsgExpectCustomerList(qwCountCustomerParam, qwCompany.getCorpId());

            qwGroupMsg.setToUserNum(customerList.size());
            qwGroupMsg.setFilterCustomers(JSON.toJSONString(qwCountCustomerParam));

            //客户列表
            msgTemplate.setExternalUseridList(customerList);

            //发送消息文本组装
            //群发任务类型()
            msgTemplate.setChatType(qwGroupMsgParam.getChatType());

            msgTemplate.setAllowSelect(qwGroupMsgParam.getAllowSelect()==1?true:false);
            msgTemplate.setTextContent(qwGroupMsgParam.getTextContent());
            msgTemplate.setType(qwGroupMsgParam.getMsgType());

            //开启定时发送时 就制作记录
            if (qwGroupMsgParam.getIsTimerSend()==1){
                //发送失败 主表做记录
                qwGroupMsg.setIsSend(3);
                qwGroupMsg.setIsTimerSend(1);
                qwGroupMsg.setTimerSend(qwGroupMsgParam.getTimerSend());
                qwGroupMsg.setCreateTime(DateUtils.getNowDate());

                //主表做记录
                insertRecordsGroup(qwGroupMsg,qwGroupMsgItem,qwGroupMsgParam.getCorpId(),qwCompany.getId());
                return R.ok();
            }


            QwAddMsgTemplateResult qwAddMsgTemplateResult = qwApiService.addMsgTemplate(msgTemplate, qwGroupMsgParam.getCorpId());

            qwGroupMsg.setMsgid(qwAddMsgTemplateResult.getMsgId() == null ? null : qwAddMsgTemplateResult.getMsgId());

            //延迟三秒
            Thread.sleep(4000);

        if (qwAddMsgTemplateResult.getErrCode()!=0){

            //发送失败 主表做记录
            qwGroupMsg.setIsSend(0);
            qwGroupMsg.setCreateTime(DateUtils.getNowDate());
            //主表做记录
            insertQwGroupMsgSinger(qwGroupMsg,qwGroupMsgItem,qwGroupMsgParam.getCorpId(),qwCompany.getId(),qwAddMsgTemplateResult);

            return R.error("消息发送失败:"+qwAddMsgTemplateResult.getErrMsg());
        }
        else if (qwAddMsgTemplateResult.getErrCode()==41063){

            qwGroupMsg.setIsSend(2);
            qwGroupMsg.setCreateTime(DateUtils.getNowDate());
            //主表做记录
            insertQwGroupMsgSinger(qwGroupMsg,qwGroupMsgItem,qwGroupMsgParam.getCorpId(),qwCompany.getId(),qwAddMsgTemplateResult);
            return  R.ok("消息发送成功-待更新");
        }
        else {

            QwGetGroupMsgTask qwGetGroupMsgTask=new QwGetGroupMsgTask();
            qwGetGroupMsgTask.setMsgid(qwAddMsgTemplateResult.getMsgId());
            qwGetGroupMsgTask.setLimit(1000);

            //获取群发成员发送任务列表
            QwGetGroupmsgTaskResult groupmsgTask = qwApiService.getGroupmsgTask(qwGetGroupMsgTask, qwGroupMsgParam.getCorpId());

            if (groupmsgTask.getErrCode()!=0){

                if (groupmsgTask.getErrCode()==41063){
                    //正在发送 主表做记录
                    qwGroupMsg.setIsSend(2);
                    qwGroupMsg.setIsTimerSend(2);
                    qwGroupMsg.setCreateTime(DateUtils.getNowDate());

                    //主表做记录
                    insertRecordsGroup(qwGroupMsg,qwGroupMsgItem,qwGroupMsgParam.getCorpId(),qwCompany.getId());
                    return R.ok("消息发送成功-待更新");
                }else {
                    //失败了 主表做记录
                    qwGroupMsg.setIsSend(0);
                    qwGroupMsg.setIsTimerSend(2);
                    qwGroupMsg.setCreateTime(DateUtils.getNowDate());

                    //主表做记录
                    insertRecordsGroup(qwGroupMsg,qwGroupMsgItem,qwGroupMsgParam.getCorpId(),qwCompany.getId());
                    return R.error("获取群发成员发送任务列表失败:"+qwAddMsgTemplateResult.getErrMsg());
                }

            }
            else{
                List<TaskItemResult> taskList = groupmsgTask.getTaskList();
                //发送成员总数
                int size = taskList.size();

                qwGroupMsg.setFromUserNum(size);
                qwGroupMsg.setIsSend(1);
                qwGroupMsg.setCreateTime(DateUtils.getNowDate());

                //主表做记录
                int i = qwGroupMsgMapper.insertQwGroupMsg(qwGroupMsg);
                if (i>0){

                    qwGroupMsgItem.setGroupMsgId(qwGroupMsg.getId());
                    qwGroupMsgItem.setMsgId(qwAddMsgTemplateResult.getMsgId());
                    qwGroupMsgItem.setCorpId(qwGroupMsgParam.getCorpId());
                    qwGroupMsgItem.setCompanyId(qwCompany.getId());
                    //附件做记录
                    int i1 = qwGroupMsgItemMapper.insertQwGroupMsgItem(qwGroupMsgItem);

                    if (i1<=0){
                        return R.error("录入入群发消息附件表失败");
                    }

                    QwGetGroupmsgSendParam qwGetGroupmsgSendParam=new QwGetGroupmsgSendParam();

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

                        //获取企业群发成员执行结果
                        qwGetGroupmsgSendParam.setUserid(userId);
                        qwGetGroupmsgSendParam.setMsgid(qwAddMsgTemplateResult.getMsgId());
                        qwGetGroupmsgSendParam.setLimit(1000);
                        QwGroupmsgSendResult groupmsgSendResult = qwApiService.getGroupmsgSendResult(qwGetGroupmsgSendParam, qwGroupMsgParam.getCorpId());

                        if (groupmsgSendResult.getErrCode()!=0){
                            return R.error("获取成员执行结果失败");
                        }else {
                            List<SendItemResult> sendList = groupmsgSendResult.getSendList();
                            for (SendItemResult itemResult: sendList ) {

                                qwGroupMsgUser.setUserId(userId);
                                qwGroupMsgUser.setStatus(list.getStatus());
                                qwGroupMsgUser.setMsgId(qwAddMsgTemplateResult.getMsgId());
                                qwGroupMsgUser.setChatType(qwGroupMsgParam.getChatType());
                                qwGroupMsgUser.setCorpId(qwGroupMsgParam.getCorpId());
                                qwGroupMsgUser.setCompanyId(qwCompany.getId());
                                qwGroupMsgUser.setGroupMsgId(qwGroupMsg.getId());
                                qwGroupMsgUser.setExternalUserid(itemResult.getExternalUserId());
                                qwGroupMsgUser.setSendStatus(itemResult.getStatus());
                                qwGroupMsgUser.setSendTime(itemResult.getSendTime());

                                int i2 = qwGroupMsgUserMapper.insertQwGroupMsgUser(qwGroupMsgUser);
                                if (i2<=0) {
                                    return R.error("录入群发成员发送任务及执行结果反馈记录表失败");
                                }

                            }
                        }


                    }


                }
                else {
                    // 插入失败的处理逻辑
                    return R.error("录入入群发消息主表失败");
                }
            }


        }

        }

        return R.ok();
    }

    /** 统计数据详情，已发送，未发送，已接收，未接收等 */
    @Override
    public R getCountGroupMsgUser(Long groupMsgId) {
        return R.ok().put("data",qwGroupMsgMapper.getCountGroupMsgUser(groupMsgId));
    }

    @Override
    public R getCountGroupMsgBaseUser(Long groupMsgId) {

        return R.ok().put("data",qwGroupMsgMapper.getCountGroupMsgBaseUser(groupMsgId));
    }


    /**
     *  客户群发 发送/接收的数据详情
     */
    @Override
    public List<QwGroupMsgDetailsVO> getCountGroupMsgUserDetails(QwGroupMsgDetailsParam qwGroupMsgDetailsParam) {


     return qwGroupMsgMapper.getCountGroupMsgUserDetails(qwGroupMsgDetailsParam);


    }

    @Override
    public R remindGroupMsg(QwGroupMsgDetailsParam qwGroupMsgDetailsParam) {

        QwResult qwResult = qwApiService.remindGroupmsgSend(qwGroupMsgDetailsParam.getQwMsgId(),qwGroupMsgDetailsParam.getCorpId());
//        qwUserbehaviorDataService.updateQwUserbehaviorDataByTimer();
//        qwGroupchatStatisticService.updateQwGroupchatStatisticByTimer();
//        qwGroupchatStatisticService.updateQwGroupchatStatisticByTimerOwner();
//         iQwSopService.selectQwSopByUserId("wmotXidAAAT6hYfrrbXMPRxeG09Gtw7A", 7L,"HaoMingZiKeYiRangNiDePengYouGengRongYiJiZhuNi",100L,1);
//        qwSopTimerService.checkQwSopTimer();
//        return R.ok().put("data","qwResult");
        return R.ok().put("data",qwResult);

    }

    /**
     * 修改客户群发记录主
     *
     * @param qwGroupMsg 客户群发记录主
     * @return 结果
     */
    @Override
    public int updateQwGroupMsg(QwGroupMsg qwGroupMsg)
    {
        qwGroupMsg.setUpdateTime(DateUtils.getNowDate());
        return qwGroupMsgMapper.updateQwGroupMsg(qwGroupMsg);
    }

    /**
     * 批量删除客户群发记录主
     *
     * @param ids 需要删除的客户群发记录主主键
     * @return 结果
     */
    @Override
    public int deleteQwGroupMsgByIds(Long[] ids)
    {
        qwGroupMsgItemMapper.deleteQwGroupMsgItemByGroupMsgId(ids);
        return qwGroupMsgMapper.deleteQwGroupMsgByIds(ids);
    }

    /**
     * 删除客户群发记录主信息
     *
     * @param id 客户群发记录主主键
     * @return 结果
     */
    @Override
    public int deleteQwGroupMsgById(Long id)
    {
        return qwGroupMsgMapper.deleteQwGroupMsgById(id);
    }

    /**
     *  定时任务处理群发消息
     * @Author sgw
     * @Date 2024/8/1 22:53
     **/
    @Override
    public void qwGroupMsgTask() {

        //发送消息组件表
        QwMsgTemplate msgTemplate=new QwMsgTemplate();

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

        //客户群发记录主表
        QwGroupMsg qwGroupMsg=new QwGroupMsg();

        List<QwGroupMsgVO> qwGroupMsgTask = qwGroupMsgMapper.getQwGroupMsgTask();
        qwGroupMsgTask.stream().forEach(item->{
            //文字+图片
            if (item.getMsgType()==1){
                msgTemplate.setImagePicUrl(item.getMediaPicUrl());
            }
            //图文
            if (item.getMsgType()==2){
                msgTemplate.setLinkTitle(item.getTitle());
                msgTemplate.setLinkPicurl(item.getPicurl());
                msgTemplate.setLinkDesc(item.getDescription());
                msgTemplate.setLinkUrl(item.getUrl());

            }
            if (item.getMsgType()==3){

            }
            if (item.getMsgType()==4){
                File fileOne = null;
                try {
                    fileOne = urlToFile(item.getFileUrl());
                    QwUploadResult file = qwApiService.upload(fileOne, "file", item.getCorpId());

                    msgTemplate.setFileMediaId(file.getMediaId());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            }
            if (item.getMsgType()==5){
                File fileOne = null;
                try {
                    fileOne = urlToFile(item.getVideoUrl());
                    QwUploadResult file = qwApiService.upload(fileOne, "video",item.getCorpId());
                    msgTemplate.setVideoMediaId(file.getMediaId());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            }

            qwGroupMsg.setId(item.getId());

            QwGetGroupmsgSendParam qwGetGroupmsgSendParam=new QwGetGroupmsgSendParam();

            //如果发送给客户群
            if (item.getChatType().equals("group")){

                HashMap<String, ArrayList<String>> listHashMap = JSON.parseObject(item.getFilterCustomers(), new com.alibaba.fastjson.TypeReference<HashMap<String, ArrayList<String>>>(){});

//                List<String> list = Arrays.stream(item.getSender().substring(1, item.getSender().length() - 1).split(","))
//                        .collect(Collectors.toCollection(ArrayList::new));
//                list.forEach(sender->{

                listHashMap.forEach((sender, arrayList) -> {
                            msgTemplate.setChatType(item.getChatType());
                            msgTemplate.setSender(sender);
                            msgTemplate.setChatIdList(arrayList);
                            msgTemplate.setAllowSelect(item.getAllowSelect()==1?true:false);
                            msgTemplate.setTextContent(item.getTextContent());
                            msgTemplate.setType(item.getMsgType());

                            //发送消息
                            QwAddMsgTemplateResult qwAddMsgTemplateResult = qwApiService.addMsgTemplate(msgTemplate,item.getCorpId());
                            if (qwAddMsgTemplateResult.getErrCode()!=0){
                                //发送失败
                                qwGroupMsg.setIsSend(0);
                                qwGroupMsgMapper.updateQwGroupMsg(qwGroupMsg);

                            }
                            else {
                                //发送成功
                                qwGroupMsg.setIsSend(1);
                                qwGroupMsgMapper.updateQwGroupMsg(qwGroupMsg);

                                qwGroupMsgUser.setChatType(item.getChatType());
                                qwGroupMsgUser.setCorpId(item.getCorpId());
                                qwGroupMsgUser.setCompanyId(item.getCompanyId());
                                qwGroupMsgUser.setGroupMsgId(item.getGroupMsgId());
                                qwGroupMsgUser.setMsgId(qwAddMsgTemplateResult.getMsgId());
                                qwGroupMsgUser.setUserId(sender);

                                //群发成员发送任务及执行结果反馈记录
                                qwGroupMsgUserMapper.insertQwGroupMsgUser(qwGroupMsgUser);

                                QwGetGroupMsgTask qwGetGroupMsgTask=new QwGetGroupMsgTask();
                                qwGetGroupMsgTask.setMsgid(qwAddMsgTemplateResult.getMsgId());
                                qwGetGroupMsgTask.setLimit(1000);

                                //获取群发成员发送任务列表 （只有状态为2,即成员选择发送了群聊后，才能看见 有哪些群聊（群聊列表））
                                QwGetGroupmsgTaskResult groupmsgTask = qwApiService.getGroupmsgTask(qwGetGroupMsgTask, item.getCorpId());

                                if (groupmsgTask.getErrCode()==2){


                                    //获取企业群发成员执行结果（发送给客户群的话，要成员选择发送了之后，才会有列表）
                                    qwGetGroupmsgSendParam.setUserid(sender);
                                    qwGetGroupmsgSendParam.setMsgid(qwAddMsgTemplateResult.getMsgId());
                                    qwGetGroupmsgSendParam.setLimit(1000);

                                    QwGroupmsgSendResult groupmsgSendResult = qwApiService.getGroupmsgSendResult(qwGetGroupmsgSendParam, item.getCorpId());

                                    if (groupmsgSendResult.getErrCode()!=0){
                                        throw new RuntimeException("获取企业群发成员执行结果失败:"+groupmsgSendResult.getErrMsg());
                                    }else {
                                        List<SendItemResult> sendList = groupmsgSendResult.getSendList();

                                        for (SendItemResult send: sendList) {

                                            qwGroupMsgUser.setChatType(item.getChatType());
                                            qwGroupMsgUser.setCorpId(item.getCorpId());
                                            qwGroupMsgUser.setCompanyId(item.getCompanyId());
                                            qwGroupMsgUser.setGroupMsgId(item.getId());
                                            qwGroupMsgUser.setUserId(send.getUserId());
                                            qwGroupMsgUser.setMsgId(qwAddMsgTemplateResult.getMsgId());
                                            //群聊id
                                            qwGroupMsgUser.setChatId(send.getChatId());
                                            //发送时间
                                            qwGroupMsgUser.setSendTime(send.getSendTime());
                                            //发送状态
                                            qwGroupMsgUser.setSendStatus(send.getStatus());

                                            //群发成员发送任务及执行结果反馈记录
                                            qwGroupMsgUserMapper.insertQwGroupMsgUser(qwGroupMsgUser);
                                        }
                                    }
                                }
                            }


                });




//                });


            }
            else if (item.getChatType().equals("single")) {

                QwCountCustomerParam qwCountCustomerParam = JSON.parseObject(item.getFilterCustomers(), QwCountCustomerParam.class);
                //根据 条件 筛选出预计发送的客户id列表
                ArrayList<String> customerList= qwExternalContactService.selectQwGroupMsgExpectCustomerList(qwCountCustomerParam, item.getCorpId());
                //客户列表
                msgTemplate.setExternalUseridList(customerList);

                //发送消息文本组装
                //群发任务类型()
                msgTemplate.setChatType(item.getChatType());

                msgTemplate.setAllowSelect(item.getAllowSelect()==1?true:false);
                msgTemplate.setTextContent(item.getTextContent());
                msgTemplate.setType(item.getMsgType());

                //发送消息
                QwAddMsgTemplateResult qwAddMsgTemplateResult = qwApiService.addMsgTemplate(msgTemplate, item.getCorpId());

                qwGroupMsg.setMsgid(qwAddMsgTemplateResult.getMsgId() == null ? null : qwAddMsgTemplateResult.getMsgId());

                if (qwAddMsgTemplateResult.getErrCode()!=0){
                    //发送失败 主表做记录
                    qwGroupMsg.setIsSend(0);

                }
                else if (qwAddMsgTemplateResult.getErrCode()==41063){
                    qwGroupMsg.setIsSend(2);

                }
                else {
                    qwGroupMsg.setIsSend(1);

                    QwGetGroupMsgTask qwGetGroupMsgTask=new QwGetGroupMsgTask();
                    qwGetGroupMsgTask.setMsgid(qwAddMsgTemplateResult.getMsgId());
                    qwGetGroupMsgTask.setLimit(1000);

                    //获取群发成员发送任务列表结果
                    QwGetGroupmsgTaskResult groupmsgTask = qwApiService.getGroupmsgTask(qwGetGroupMsgTask, item.getCorpId());
                    if (groupmsgTask.getErrCode()!=0){
                        //啥也不干

                    } else {
                        List<TaskItemResult> taskList = groupmsgTask.getTaskList();
                        //发送成员总数
                        int size = taskList.size();

                        qwGroupMsg.setFromUserNum(size);

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

                            String userId = list.getUserId();

                            //获取企业群发成员执行结果
                            qwGetGroupmsgSendParam.setUserid(userId);
                            qwGetGroupmsgSendParam.setMsgid(qwAddMsgTemplateResult.getMsgId());
                            qwGetGroupmsgSendParam.setLimit(1000);
                            QwGroupmsgSendResult groupmsgSendResult = qwApiService.getGroupmsgSendResult(qwGetGroupmsgSendParam, item.getCorpId());

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

                                    qwGroupMsgUser.setUserId(userId);
                                    qwGroupMsgUser.setStatus(list.getStatus());
                                    qwGroupMsgUser.setMsgId(qwAddMsgTemplateResult.getMsgId());
                                    qwGroupMsgUser.setChatType(item.getChatType());
                                    qwGroupMsgUser.setCorpId(item.getCorpId());
                                    qwGroupMsgUser.setCompanyId(item.getCompanyId());
                                    qwGroupMsgUser.setGroupMsgId(item.getId());
                                    qwGroupMsgUser.setExternalUserid(itemResult.getExternalUserId());
                                    qwGroupMsgUser.setSendStatus(itemResult.getStatus());
                                    qwGroupMsgUser.setSendTime(itemResult.getSendTime());

                                    qwGroupMsgUserMapper.insertQwGroupMsgUser(qwGroupMsgUser);


                                }
                            }


                        }

                    }

                }
                //更新群发消息表
                qwGroupMsgMapper.updateQwGroupMsg(qwGroupMsg);
            }

        });
    }


    /**
     *  url转临时文件filr
     */
    public static File urlToFile(String fileUrl) throws Exception {

        // 从URL中提取文件名，文件后缀
        String fileExtension = getFileExtension(new File(fileUrl).getName());
        String fileName = extractFileName(new URL(fileUrl))+new Date().getTime();
        File tempFile=null;
        if (!StringUtil.strIsNullOrEmpty(fileExtension)){
            // 创建一个临时文件
            tempFile = File.createTempFile(fileName, "."+fileExtension);
        }else {
            tempFile = File.createTempFile(fileName, null);
        }


        // 使用 try-with-resources 语句自动关闭资源
        try (BufferedInputStream in = new BufferedInputStream(new URL(fileUrl).openStream());
             FileOutputStream out = new FileOutputStream(tempFile)) {

            byte[] buffer = new byte[1024];
            int len;

            // 读取数据并写入到临时文件
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (IOException e) {
            // 处理异常，例如删除创建的临时文件
            tempFile.delete();
            throw e;
        }finally {

        }

        return tempFile;
    }

    /**
     *  获取文件名
     */
    private static String extractFileName(URL url) throws Exception {
        String path = url.getPath();
        int lastSlashIndex = path.lastIndexOf('/');
        String fileNameWithExt = path.substring(lastSlashIndex + 1);

        int dotIndex = fileNameWithExt.lastIndexOf('.');
        String baseName;
        if (dotIndex > 0) {
            // 如果有扩展名，移除扩展名
            baseName = fileNameWithExt.substring(0, dotIndex);
        } else {
            // 如果没有扩展名，直接使用文件名
            baseName = fileNameWithExt;
        }

        return baseName;
    }

    /**
     *  获取文件名后缀
     */

    public static String getFileExtension(String fileName) {
        int lastIndex = fileName.lastIndexOf('.');
        if (lastIndex != -1 && lastIndex + 1 < fileName.length()) {
            return fileName.substring(lastIndex + 1);
        }
        return ""; // 如果没有扩展名，返回空字符串
    }


    private R insertRecordsGroup(QwGroupMsg qwGroupMsg, QwGroupMsgItem qwGroupMsgItem, String corpId, Long companyId) {

        // 主表做记录
        int mainTableResult = qwGroupMsgMapper.insertQwGroupMsg(qwGroupMsg);
        if (mainTableResult > 0) {
            qwGroupMsgItem.setGroupMsgId(qwGroupMsg.getId());
            qwGroupMsgItem.setCorpId(corpId);
            qwGroupMsgItem.setCompanyId(companyId);
            // 附件表做记录
            int itemTableResult = qwGroupMsgItemMapper.insertQwGroupMsgItem(qwGroupMsgItem);
            if (itemTableResult > 0) {
                return R.ok();
            } else {
                return R.error("录入群群发消息附件表失败");
            }
        } else {
            return R.error("录入群群发消息主表失败");
        }
    }

    private R insertQwGroupMsgSinger(QwGroupMsg qwGroupMsg, QwGroupMsgItem qwGroupMsgItem, String corpId, Long companyId, QwAddMsgTemplateResult qwAddMsgTemplateResult) {
        int mainTableResult = qwGroupMsgMapper.insertQwGroupMsg(qwGroupMsg);
        if (mainTableResult > 0) {
            qwGroupMsgItem.setGroupMsgId(qwGroupMsg.getId());
            qwGroupMsgItem.setMsgId(qwAddMsgTemplateResult.getMsgId() == null ? null : qwAddMsgTemplateResult.getMsgId());
            qwGroupMsgItem.setCorpId(corpId);
            qwGroupMsgItem.setCompanyId(companyId);
            // 附件表做记录
            int itemTableResult = qwGroupMsgItemMapper.insertQwGroupMsgItem(qwGroupMsgItem);
            if (itemTableResult <= 0) {
                return R.error("录入群群发消息附件表失败");
            }
            return R.ok();
        } else {
            return R.error("录入群群发消息主表失败");
        }
    }


}
