package com.junmp.jyzb.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import com.junmp.junmpProcess.dto.UserListDTO;
import com.junmp.junmpProcess.mapper.OrgUserMapper;
import com.junmp.jyzb.entity.VieWarrantyGroup;
import com.junmp.jyzb.mapper.PolicemanMapper;
import com.junmp.jyzb.mapper.VieWarrantyGroupMapper;
import com.junmp.v2.job.api.JobAction;
import com.junmp.v2.message.api.MessageApi;
import com.junmp.v2.message.api.bean.req.MessageSendReq;
import com.junmp.v2.message.db.entity.SysMessage;
import com.junmp.v2.message.db.service.SysMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
* @Author: Zhaojw
* @Description: 过期物资消息提醒(过质保期数量的消息提醒)
* @DateTime: 2023/7/14 16:25
* @Params:
* @Return
*/
@Slf4j
@Component
public class InvExpireMsg implements JobAction {

    @Resource
    private VieWarrantyGroupMapper vieWarrantyGroupMapper;

    @Resource
    private OrgUserMapper orgUserMapper;


    @Resource
    private MessageApi messageApi;
    
    @Resource
    private PolicemanMapper policemanMapper;

    @Resource
    private SysMessageService sysMessageService;

    @Override
    public void action() {
        //获取所有过质保装备
        List<VieWarrantyGroup> list = vieWarrantyGroupMapper.getExpireGroupList();

        //获取组织机构下的账号信息，方便消息推送
        if (CollectionUtil.isNotEmpty(list)){
            Map<String, List<VieWarrantyGroup>> orgInvMap = list.stream().collect(Collectors.groupingBy(VieWarrantyGroup::getOrgId));
            List<String> orgList = orgInvMap.keySet().stream().distinct().collect(Collectors.toList());
            String roleList="('1528003832557232130','1663372320355389441')";
            String orgString="(";
            for (String org :orgList)
            {
                orgString+=org+",";
            }

            orgString = orgString.substring(0, orgString.length() - 1);
            orgString+=")";//至此拼接完成
            List<UserListDTO> userList=orgUserMapper.QueryUserByRoleIdAndOrg(roleList,orgString);
            Map<String, Long> userOrgMap = userList.stream().collect(Collectors.toMap(UserListDTO::getUserID,
                    UserListDTO::getOrgId,
                    (existing, replacement) -> existing));
            List<String> userIdsList=new ArrayList<>(userOrgMap.keySet());
            //先查询到消息列表中是否有用户未读，如果未读，将消息进行修改更新时间和更新内容（不进行消息推送了），如果已读或者不在列表中，再次进行消息推送
            List<SysMessage> expireMessageList = policemanMapper.findExpireMessageList(userIdsList);
            if (CollectionUtil.isNotEmpty(expireMessageList)){
                Map<String, List<VieWarrantyGroup>> existOrgInvMap=new HashMap<>();
                Map<String, Long> existUserOrgMap=new HashMap<>();
                List<Long> existUserIdList = expireMessageList.stream().map(SysMessage::getReceiveUserId).collect(Collectors.toList());
                for (String userId:userOrgMap.keySet()) {
                    if (existUserIdList.contains(Long.valueOf(userId))){

                        existOrgInvMap.put(userOrgMap.get(userId).toString(),orgInvMap.get(userOrgMap.get(userId).toString()));
                        existUserOrgMap.put(userId,userOrgMap.get(userId));

                    }
                }
                for (String userId:existUserOrgMap.keySet()){
                    if (new ArrayList<>(userOrgMap.keySet()).contains(userId)){
                        userOrgMap.remove(userId);
                    }
                }
                for (String userId:existUserOrgMap.keySet()) {
                    for (SysMessage sysMessage:expireMessageList) {
                        if (userId.equals(sysMessage.getReceiveUserId().toString())){
                            sysMessage.setSendTime(new Date());
                            List<VieWarrantyGroup> orgInvList = existOrgInvMap.get(existUserOrgMap.get(userId).toString());
                            if (orgInvList.size()>=2){
                                VieWarrantyGroup vieWarrantyGroup1 = orgInvList.get(0);
                                VieWarrantyGroup vieWarrantyGroup2 = orgInvList.get(1);
                                sysMessage.setMsgContent(vieWarrantyGroup1.getTypeName()+","+vieWarrantyGroup2.getTypeName()+" 等装备过期，请及时进行报废处理");
                            }else {
                                VieWarrantyGroup vieWarrantyGroup1 = orgInvList.get(0);
                                sysMessage.setMsgContent(vieWarrantyGroup1.getTypeName()+" 装备过期，请及时进行报废处理");
                            }
                        }
                    }
                }
                sysMessageService.updateBatchById(expireMessageList);
            }
            //获取消息中的信息
            List<MessageSendReq> msgList = sendMsg(userOrgMap,orgInvMap);
            if (CollectionUtil.isNotEmpty(msgList)){
                msgList.forEach(msg->
                        {
                            messageApi.sendMessageNoToken(msg);
                        }
                );
            }
        }



    }


    public List<MessageSendReq> sendMsg(Map<String, Long> userOrgMap,Map<String, List<VieWarrantyGroup>> orgInvMap){
        List<MessageSendReq> msgList=new ArrayList<>();
        if (!userOrgMap.isEmpty() && !orgInvMap.isEmpty()){
            for (String userId:userOrgMap.keySet()) {
                List<VieWarrantyGroup> orgInvList = orgInvMap.get(userOrgMap.get(userId).toString());
                MessageSendReq sendReq = new MessageSendReq();
                sendReq.setReceiveUserIds(String.valueOf(userId));
                sendReq.setMsgTitle("装备到期提醒");
                sendReq.setBizType("assign/ExpireInventory");
                sendReq.setBizId(null);
                if (orgInvList.size()>=2){
                    VieWarrantyGroup vieWarrantyGroup1 = orgInvList.get(0);
                    VieWarrantyGroup vieWarrantyGroup2 = orgInvList.get(1);
                    sendReq.setMsgContent(vieWarrantyGroup1.getTypeName()+","+vieWarrantyGroup2.getTypeName()+" 等装备过期，请及时进行报废处理");
                }else {
                    VieWarrantyGroup vieWarrantyGroup1 = orgInvList.get(0);
                    sendReq.setMsgContent(vieWarrantyGroup1.getTypeName()+" 装备过期，请及时进行报废处理");
                }
                sendReq.setSendUserId("1000");
                sendReq.setPriority("0");
                sendReq.setSendTime(DateTime.now());
                msgList.add(sendReq);

            }

        }
        return msgList;
    }

}
