package com.huimv.env.admin.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huimv.env.admin.common.token.TokenSign;
import com.huimv.env.admin.common.utils.Result;
import com.huimv.env.admin.common.utils.ResultCode;
import com.huimv.env.admin.entity.BasePigpen;
import com.huimv.env.admin.entity.PortWarningInfo;
import com.huimv.env.admin.entity.Terminal;
import com.huimv.env.admin.entity.vo.*;
import com.huimv.env.admin.mapper.TerminalMapper;
import com.huimv.env.admin.mapper.TerminalPortMapper;
import com.huimv.env.admin.service.IBasePigpenService;
import com.huimv.env.admin.service.IPortWarningInfoService;
import com.huimv.env.admin.service.ITerminalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author newspaper
 * @since 2024-05-09
 */
@RestController
@CrossOrigin
@RequestMapping("/port-warning-info")
public class PortWarningInfoController {

    @Autowired
    private IPortWarningInfoService portWarningInfoService;
    @Autowired
    private ITerminalService terminalService;
    @Autowired
    private TerminalMapper terminalMapper;
    @Autowired
    private IBasePigpenService basePigpenService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/page")
    public Result page(HttpServletRequest httpServletRequest,@RequestBody WarningPageParam warningPageParam){
        String startTime = warningPageParam.getStartTime();
        String endTime = warningPageParam.getEndTime();
        if (ObjectUtil.isNotEmpty(startTime)){
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
        }
        Integer userId = TokenSign.getMemberIdByJwtToken(httpServletRequest);
        Page<PortWarningInfo> page = new Page<>(warningPageParam.getPageNum(),warningPageParam.getPageSize());
        LambdaQueryWrapper<PortWarningInfo> queryWrapper = new QueryWrapper<PortWarningInfo>().lambda()
                .eq(PortWarningInfo::getFarmId,warningPageParam.getFarmId())
                .eq(ObjectUtil.isNotEmpty(warningPageParam.getWarningType()), PortWarningInfo::getWarningType, warningPageParam.getWarningType())
                .between(ObjectUtil.isNotEmpty(startTime), PortWarningInfo::getCreateTime, startTime, endTime)
                .orderByDesc(PortWarningInfo::getCreateTime);

        Integer locationId = warningPageParam.getLocationId();
        if (ObjectUtil.isNotEmpty(locationId)){
            List<BasePigpen> basePigpens = basePigpenService.list(new QueryWrapper<BasePigpen>().lambda().like(BasePigpen::getOther2, locationId).eq(BasePigpen::getFType, 4));
            List buildIds = basePigpens.stream().map(BasePigpen::getId).collect(Collectors.toList());
            queryWrapper.in(PortWarningInfo::getLocationId,buildIds);
        }
        Page<PortWarningInfo> warningInfoPage = portWarningInfoService.page(page, queryWrapper);
        List<PortWarningInfo> records = warningInfoPage.getRecords();
        for (PortWarningInfo record : records) {
            if (!redisTemplate.opsForSet().isMember("User:"+userId+":read",record.getId())) {
                record.setIsRead(0);
            }else {
                record.setIsRead(1);
            }
        }
        warningInfoPage.setRecords(records);
        return new Result(ResultCode.SUCCESS,warningInfoPage);
    }

    @PostMapping("/read")
    public Result read(HttpServletRequest httpServletRequest, @RequestBody WarningReadParam warningReadParam){
        Integer userId = TokenSign.getMemberIdByJwtToken(httpServletRequest);
        Integer warningId = warningReadParam.getWarningId();
        redisTemplate.opsForSet().add("User:"+userId+":read",warningId);
        return Result.SUCCESS();
    }

    @PostMapping("/unReadCount")
    public Result unReadCount(HttpServletRequest httpServletRequest, @RequestBody WarningUnReadCountParam warningUnReadCountParam){
        Integer userId = TokenSign.getMemberIdByJwtToken(httpServletRequest);
        Integer farmId = warningUnReadCountParam.getFarmId();
        int count = portWarningInfoService.count(new QueryWrapper<PortWarningInfo>().lambda().eq(PortWarningInfo::getFarmId,farmId));
        Set<Integer> members = redisTemplate.opsForSet().members("User:" + userId + ":read");
        int size = members.size();
        return new Result(ResultCode.SUCCESS,count - size);
    }


}
