package com.junmp.jyzb.task;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.junmp.jyzb.api.bean.req.InvExpireReq;
import com.junmp.jyzb.entity.Inventory;
import com.junmp.jyzb.mapper.InventoryMapper;
import com.junmp.jyzb.service.InventoryService;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.dict.service.SysDictItemService;
import com.junmp.v2.job.api.JobAction;
import com.junmp.v2.message.api.MessageApi;
import com.junmp.v2.message.api.bean.req.MessageReq;
import com.junmp.v2.message.api.bean.req.MessageSendReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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


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


    @Resource
    private InventoryService inventoryService;

    @Resource
    private InventoryMapper inventoryMapper;

    @Resource
    private MessageApi messageApi;

    @Resource
    private SysDictItemService sysDictItemService;

    @Override
    public void action() {
        LambdaQueryWrapper<Inventory> wrapper = new LambdaQueryWrapper<>();
        // 分页参数
        int pageSize = 1000; // 每页记录数，可以根据需求调整
        int currentPage = 1; // 当前页数

        //所有待判断的物资(只获取仓库下的过质保期数量)
        //除去销毁出库数
        wrapper.eq(Inventory::getTermState, 0);
        wrapper.ne(Inventory::getState,"destory");

        long termCount= inventoryService.count(wrapper);
        List<Inventory> list=new ArrayList<>();
        if (termCount>0) {
            // 分页查询
            while ((currentPage - 1) * pageSize < termCount) {
                int startPageSize=(currentPage - 1) * pageSize ;
                List<Inventory> inventoryList = processPageData(startPageSize, pageSize);
                currentPage++;
                list.addAll(inventoryList);
            }
        }
        //超期物资查询出来之后，将超期物资进行消息推送提醒
        //直接对list进行处理操作推送消息即可
        //需要对该所有超期物资进行分组
        List<InvExpireReq> invExpireReqList=new ArrayList<>();
        List<Long> orgIdsList=new ArrayList<>();
        for (Inventory inventory : list) {
            if (invExpireReqList.size()==0){
                InvExpireReq invExpireReq = new InvExpireReq();
                BeanPlusUtil.copyProperties(inventory,invExpireReq);
                invExpireReq.setSumExpireNumber(1);
                invExpireReqList.add(invExpireReq);
                orgIdsList.add(inventory.getOrgId());
                continue;
            }
            boolean found = false;
            for (InvExpireReq groupedSum : invExpireReqList) {
                if (groupedSum.getOrgId().equals(inventory.getOrgId()) && groupedSum.getLocationId().equals(inventory.getLocationId())
                        && groupedSum.getSizeId().equals(inventory.getSizeId()) && groupedSum.getTypeId().equals(inventory.getTypeId())) {
                    groupedSum.setSumExpireNumber(groupedSum.getSumExpireNumber()+1);
                    found = true;
                    break;
                }
            }
            if (!found) {
                InvExpireReq invExpireReq = new InvExpireReq();
                BeanPlusUtil.copyProperties(inventory,invExpireReq);
                invExpireReq.setSumExpireNumber(1);
                invExpireReqList.add(invExpireReq);
                orgIdsList.add(inventory.getOrgId());
            }
        }
        //根据分好组的数据查询出所有的需要被提醒的组织机构id，并且查询出组织机构下的仓管员信息，并且将消息进行推送
        //再将汇总list进行遍历获取不重复的组织机构
        Set<Long> uniqueOrgIDs = new HashSet<>(orgIdsList);
        List<Long> uniqueOrgIDsList = new ArrayList<>(uniqueOrgIDs);
        //查询组织机构下面的所有仓管员的useId
        List<InvExpireReq> userIdsList=inventoryMapper.selectUserListByOrgs(uniqueOrgIDsList);

        //获取到之后，将该条信息进行消息推送
        for (InvExpireReq invExpireReq:invExpireReqList ) {
            for (InvExpireReq userIds:userIdsList) {
                if (invExpireReq.getOrgId()==userIds.getOrgId()){
                    MessageSendReq sendReq = new MessageSendReq();
                    sendReq.setReceiveUserIds(userIds.getUserId());
                    sendReq.setMsgTitle("过质保期提醒");
                    sendReq.setBizType("过质保提醒");
                    sendReq.setMsgContent(invExpireReq.getLocationName()+"下的"+invExpireReq.getTypeName()+
                            invExpireReq.getSizeName()+"装备已经过质保期,数量为"+invExpireReq.getSumExpireNumber());
                    sendReq.setPriority("0");
                    sendReq.setSendTime(DateTime.now());
                    messageApi.sendMessage(sendReq);
                }
            }
        }

        /*推送发送未读数量*/
        for(InvExpireReq userIds:userIdsList){
            MessageReq req1 = new MessageReq();
            req1.setReadFlag(0);
            req1.setReceiveUserId(Long.parseLong(userIds.getUserId()));
            Integer count1 = messageApi.queryCount(req1);
            messageApi.pushMsgToUser(userIds.getUserId(),count1);
        }
    }

    // 处理每页数据
    private List<Inventory> processPageData(long startPageSize, long currentPage)
    {
        List<Object[]> searchItem =new ArrayList<>();
        Object[] criteria=new Object[]{0,"destory",startPageSize,currentPage};
        searchItem.add(criteria);
        List<Inventory> list = inventoryMapper.searchExpireEqs(searchItem);
        list.forEach(o->o.setTermState(1));
        inventoryService.saveOrUpdateBatch(list);
        return list;


    }


}
