package com.agri.system.service.impl;

import com.agri.system.service.AgriService;
import com.agri.system.domain.SysAgriInfo;
import com.agri.system.domain.SysMessage;
import com.agri.system.domain.SysUserAgri;
import com.agri.system.service.ISysMessageService;
import com.agri.system.service.ISysUserAgriService;
import com.agri.system.util.UrlEncodeUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

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

@Service
public class AgriServiceImpl implements AgriService {


    @Resource
    private ISysUserAgriService userAgriService;

    @Resource
    private ISysMessageService messageService;

    // 保存离线设备消息
    @Override
    public List<SysMessage> saveMessage(List<SysAgriInfo> offlineList) {
        // 离线是否为空
        if (CollectionUtils.isEmpty(offlineList)) {
            return Collections.emptyList();
        }
        List<Long> idList
                = offlineList.stream().map(SysAgriInfo::getId).collect(Collectors.toList());

        List<SysUserAgri> agriUser
                = userAgriService.findAgriUser(new SysUserAgri(idList));

        List<SysMessage> msgList = new ArrayList<>();
        for (SysAgriInfo agriInfo : offlineList) {
            SysMessage message = new SysMessage();
            message.setImei(agriInfo.getImei());
            message.setTitle(agriInfo.getTitle());
            message.setMsgType("status");
            message.setReadStatus(0L);
            message.setContent("大棚【" + agriInfo.getAgriName() + " - " + agriInfo.getImei() + "】" + agriInfo.getMsg());
            message.setImgUrl("");
            message.setLinkUrl(UrlEncodeUtil.buildControlPageUrl(agriInfo, "/pages/home/control/index?agriInfo="));
            for (SysUserAgri userAgri : agriUser){
                message.setReceiver(userAgri.getUserId());
                msgList.add(message);
            }
        }
        if (CollectionUtils.isNotEmpty(msgList)) {
            messageService.saveBatch(msgList);
        }
        return msgList;

    }

    // 查询所有大棚的imei号
    @Override
    public List<String> queryAllGreenhouseImei(List<SysAgriInfo> agriInfos) {

        if (CollectionUtils.isEmpty(agriInfos)) {
            return Collections.emptyList();
        }
        return agriInfos.stream().map(SysAgriInfo::getImei).collect(Collectors.toList());
    }

}
