package com.junmp.jyzb.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.junmp.jyzb.api.bean.req.InvExpireReq;
import com.junmp.jyzb.entity.OrderMain;
import com.junmp.jyzb.mapper.InventoryMapper;
import com.junmp.jyzb.service.OrderMainService;
import com.junmp.jyzb.utils.DateTimeUtil;
import com.junmp.v2.db.api.factory.PageFactory;
import com.junmp.v2.dict.entity.SysDictItem;
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 com.junmp.v2.sys.user.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

/**
 * @author lxh
 * @description  超期未归还消息提醒
 * @since 2023/9/1 10:50
 * @param
 * @return
 **/
@Slf4j
@Component
public class InvOverDueMsg implements JobAction {

    @Resource
    private OrderMainService orderMainService;
    @Resource
    private MessageApi messageApi;

    @Resource
    private InventoryMapper inventoryMapper;

    @Resource
    private SysDictItemService sysDictItemService;

    @Override
    public void action() {
        //获取超期物资
        //先查询出 出入库单据为领用单的数据
        LambdaQueryWrapper<OrderMain> wrapper = new LambdaQueryWrapper<OrderMain>()
                .eq(OrderMain::getBussinessType, "use")
                .eq(OrderMain::getOrderType,"out");
        int pageSize =1000;
        int currentPage=1;
        long termCount= orderMainService.count(wrapper);
        List<OrderMain> list=new ArrayList<>();
        if (termCount>0) {
            // 分页查询
            while ((currentPage - 1) * pageSize < termCount) {
                List<OrderMain> orderMainList = processPageData(currentPage, pageSize);
                currentPage++;
                list.addAll(orderMainList);
            }
        }
        //将消息进行推送
        //我需要将orgId进行查询并去重
        Set<Long> uniqueOrgIDs = new HashSet<>();
        for (OrderMain orderMain:list) {
            uniqueOrgIDs.add(orderMain.getStartOrgId());
        }
        List<Long> uniqueOrgIDsList = new ArrayList<>(uniqueOrgIDs);
        //查询组织机构下面的所有仓管员的useId
//        List<InvExpireReq> userIdsList=inventoryMapper.selectUserListByOrgs(uniqueOrgIDsList);
        //并且查询出该领用单的领用人，再将消息推送给领用人
        List<String> userIdsList=new ArrayList<>();
        for (OrderMain orderMain:list) {

//                if (!ObjectUtil.isNull(orderMain.getReturnDate())){
//                    int i = orderMain.getReturnDate().compareTo(DateTimeUtil.getCurrentDateTime());
//                }
            if (!ObjectUtil.isNull(orderMain.getReturnDate())
                    && orderMain.getReturnDate().getTime()<DateTimeUtil.getCurrentDateTime().getTime() ){
                MessageSendReq sendReq = new MessageSendReq();
                sendReq.setReceiveUserIds(orderMain.getReturnUserId());
                sendReq.setMsgTitle("物资超期提醒");
                sendReq.setBizType("超期提醒");
                //设置业务类型
//                    SysDictItem one = sysDictItemService.getOne(new LambdaQueryWrapper<SysDictItem>()
//                            .eq(SysDictItem::getDictItemId, "over_due"));
//                    sendReq.setBizType(one.getItemValue());
                sendReq.setMsgContent("单据id为："+orderMain.getId()+"的领用单已超期，请及时查看处理");
                sendReq.setPriority("0");
                sendReq.setSendTime(DateTime.now());
                messageApi.sendMessage(sendReq);
                userIdsList.add(orderMain.getReturnUserId());
            }

        }

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

    }

    // 处理每页数据
    private List<OrderMain> processPageData(long pageSize, long currentPage) {
        //获取对应的借用单据数据
        Date currentDateTime = DateTimeUtil.getCurrentDateTime();
        LambdaQueryWrapper<OrderMain> wrapper = new LambdaQueryWrapper<OrderMain>()
                .eq(OrderMain::getBussinessType, "use")
                .eq(OrderMain::getOrderType,"out")
                .lt(OrderMain::getReturnDate,currentDateTime)
                .isNotNull(OrderMain::getReturnDate);
        List<OrderMain> records = orderMainService.page(PageFactory.getDefaultPage(pageSize, currentPage),wrapper).getRecords();
        return records;
    }
}
