package com.junmp.jyzb.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.junmp.jyzb.entity.Inventory;
import com.junmp.jyzb.entity.InventorySummary;
import com.junmp.jyzb.service.EquipmentTypeService;
import com.junmp.jyzb.service.InventoryService;
import com.junmp.jyzb.service.InventorySummaryService;
import com.junmp.v2.common.bean.response.ApiRes;
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.message.api.MessageApi;
import com.junmp.v2.message.api.bean.req.MessageReq;
import com.junmp.v2.message.api.bean.req.MessageSendReq;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Api("消息推送")
@RequestMapping("/MessageSend")
@Slf4j
public class MessageSendController {
    @Resource
    private InventoryService inventoryService;

    @Resource
    private InventorySummaryService inventorySummaryService;

    @Resource
    private EquipmentTypeService equipmentTypeService;

    @Resource
    private MessageApi messageApi;

    @Resource
    private SysDictItemService sysDictItemService;




//    MessageSendReq sendReq = new MessageSendReq();
//                sendReq.setSendUserId("1000");
//                sendReq.setReceiveUserIds(userIds);
//                sendReq.setMsgTitle(msgtTitle);
//                sendReq.setBizType(bizType);
//                sendReq.setMsgContent(msgContent);
//                sendReq.setPriority("0");
//                sendReq.setSendTime(DateTime.now());
//                messageApi.sendMessage(sendReq);
//                messageApi.queryCount(new MessageReq());
//    /*推送发送未读数量*/
//                for(Long userId :userIdList){
//        MessageReq req1 = new MessageReq();
//        req1.setReadFlag(0);
//        req1.setReceiveUserId(userId);
//        Integer count1 = messageApi.queryCount(req1);
//        messageApi.pushMsgToUser(String.valueOf(userId),count1);

    //消息推送场景1：物资低于物资阈值
//    @PostMapping("/aaa")
//    public ApiRes<Boolean> action1() {
        //获取装备信息汇总，并且判断装备的汇总数量是否低于装备阈值，如果低于装备阈值，则进行消息提醒
        //所有待判断的物资
//        LambdaQueryWrapper<InventorySummary> wrapper = new LambdaQueryWrapper<InventorySummary>()
//                .eq(InventorySummary::getLocationType, 0);
//        //分页参数
//        int pageSize=1000;
//        int currentPage=1;
//        //获取装备的所有库存数量
//        long termCount= inventorySummaryService.count(wrapper);
//        List<InventorySummary> list=new ArrayList<>();
//        if (termCount>0) {
//            // 分页查询
//            while ((currentPage - 1) * pageSize < termCount) {
//                List<InventorySummary> inventorySummaryList = processPageData1(currentPage, pageSize);
//                currentPage++;
//                list.addAll(inventorySummaryList);
//            }
//        }
//        //超期物资查询出来之后，将超期物资进行消息推送提醒
//        //直接对list进行处理操作推送消息即可
//        for (InventorySummary inventorySummary:list) {
//            MessageSendReq sendReq = new MessageSendReq();
//            sendReq.setSendUserId("1000");
//            sendReq.setReceiveUserIds("1000");
//            sendReq.setMsgTitle("物资低于阈值");
//            //设置业务类型
//            SysDictItem one = sysDictItemService.getOne(new LambdaQueryWrapper<SysDictItem>()
//                    .eq(SysDictItem::getDictItemId, "1698969902300176385"));
//            sendReq.setBizType(one.getItemValue());
//            sendReq.setMsgContent(inventorySummary.getLocationName()+"仓库下的"+inventorySummary.getTypeName()+"，号型为："+inventorySummary.getSizeName()+"的物资低于阈值");
//            sendReq.setPriority("0");
//            sendReq.setSendTime(DateTime.now());
//            messageApi.sendMessage(sendReq);
//        }
//        messageApi.queryCount(new MessageReq());
//        /*推送发送未读数量*/
//        List<Long> userIdList=new ArrayList<>();
//        userIdList.add(1000L);
//        for(Long userId :userIdList){
//            MessageReq req1 = new MessageReq();
//            req1.setReadFlag(0);
//            req1.setReceiveUserId(userId);
//            Integer count1 = messageApi.queryCount(req1);
//            messageApi.pushMsgToUser(String.valueOf(userId),count1);
//        }
//        return ApiRes.success(true);
//    }
//    // 处理每页数据
//    private List<InventorySummary> processPageData1(long pageSize, long currentPage) {
//        //得到全局默认值(随机处理数据表中的一条数据为默认值)
//        Integer threshold = equipmentTypeService.getById(100001).getThreshold();
//        //查询inventory_summary表中的threshold字段是否存在值，
//        // 如果存在则用summary表中的字段进行比较物资阈值，如果不存在则默认使用全局物资阈值进行比较
//        LambdaQueryWrapper<InventorySummary> wrapper = new LambdaQueryWrapper<InventorySummary>()
//                .eq(InventorySummary::getLocationType, 0);
//        Page<InventorySummary> page = inventorySummaryService.page(PageFactory.getDefaultPage(pageSize, currentPage),wrapper);
//        List<InventorySummary> records = page.getRecords();
//        //使用自定义物资阈值进行比较
//        List<InventorySummary> collect1 = records.stream()
//                .filter(data -> ObjectUtil.isNotNull(data.getThreshold()))
//                .filter(data -> data.getNumber() <= data.getThreshold())
//                .collect(Collectors.toList());
//        //使用全局物资阈值进行比较
//        List<InventorySummary> collect2 = records.stream()
//                .filter(data -> data.getNumber() <= threshold && ObjectUtil.isNull(data.getThreshold()))
//                .collect(Collectors.toList());
//        //将数据存储到一个list中
//        List<InventorySummary> inventorySummaryList=new ArrayList<>();
//        inventorySummaryList.addAll(collect1);
//        inventorySummaryList.addAll(collect2);
//        return inventorySummaryList;

//    }


    //消息推送场景2：物资超期

    //消息推送场景3：过质保期
    @PostMapping("/ccc")
    public void action3() {
//        LambdaQueryWrapper<Inventory> wrapper = new LambdaQueryWrapper<>();
//        // 分页参数
//        int pageSize = 1000; // 每页记录数，可以根据需求调整
//        int currentPage = 1; // 当前页数
//
//        //所有待判断的物资
//        wrapper.eq( Inventory::getTermState, 0);
//        //获取未超期的物资数量(并且他的state不是销毁状态)
//        long termCount= inventoryService.count(wrapper);
//        List<Inventory> list=new ArrayList<>();
//        if (termCount>0) {
//            // 分页查询
//            while ((currentPage - 1) * pageSize < termCount) {
//                List<Inventory> inventoryList = processPageData3(currentPage, pageSize);
//                currentPage++;
//                list.addAll(inventoryList);
//            }
//        }
//        System.out.println(list);
//        //超期物资查询出来之后，将超期物资进行消息推送提醒
//        //直接对list进行处理操作推送消息即可

    }

    // 处理每页数据
    private List<Inventory> processPageData3(long pageSize, long currentPage)
    {
        LocalDate localdate =LocalDate.now();
        // 使用LambdaQueryWrapper构建查询条件
        LambdaQueryWrapper<Inventory> wrapper = Wrappers.lambdaQuery();
        wrapper.eq( Inventory::getTermState, 0);
        //如果 生产日期 < 当前日期减去质保数,表示该装备已经超过质保期
        wrapper.apply("production_date <= DATE_SUB({0}, INTERVAL warranty_period DAY)", "1970-03-01 00:00:00");
        //获取过质保期的物资信息
        List<Inventory> page= inventoryService.page(PageFactory.getDefaultPage(pageSize,currentPage),wrapper).getRecords();
        page.forEach(o->o.setTermState(1));
        inventoryService.saveOrUpdateBatch(page);
        return page;

    }

}
