package com.huimv.receiver.farm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.huimv.receiver.farm.dao.entity.SysCameraAreaEntity;
import com.huimv.receiver.farm.dao.repo.SysCameraAreaRepo;
import com.huimv.receiver.farm.service.INetIPService;
import com.huimv.receiver.utils.DateUtil;
import com.huimv.receiver.utils.TextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.List;

/**
 * @Project : huimv.shiwan
 * @Package : com.huimv.biosafety.uface.controller
 * @Description : TODO
 * @Version : 1.0
 * @Author : ZhuoNing
 * @Create : 2020-12-25
 **/
@Service
@Slf4j
public class NetIPServiceImpl implements INetIPService {
    @Autowired
    private TextUtil textUtil;
    @Autowired
    private SysCameraAreaRepo cameraAreaRepo;
    @Autowired
    private DateUtil dateUtil;

    @Override
    public void updateNetIP(String data) throws UnsupportedEncodingException, ParseException {
        JSONObject netIPJo = JSONObject.parseObject(textUtil.translateSymbol(data));
        log.info("接收牧场端发送的公网信息>>"+netIPJo);
        String farmId = netIPJo.getString("farmId");
        String farmName = netIPJo.getString("farmName");
        String netIp = netIPJo.getString("netIp");
        //--更新最新IP
        List<SysCameraAreaEntity> cameraAreaEntityList = cameraAreaRepo.findByFarmId(farmId);
        if(cameraAreaEntityList.size()>0){
            boolean sameIpState = false;
            for(SysCameraAreaEntity cameraAreaEntity:cameraAreaEntityList){
                if(cameraAreaEntity.getPublicUrl().trim().equalsIgnoreCase(netIp)){
                    sameIpState = true;
                    break;
                }else{
                    cameraAreaEntity.setPublicUrl(netIp);
                }
            }
            if(!sameIpState){
                cameraAreaRepo.saveAll(cameraAreaEntityList);
            }
            log.info(dateUtil.getTodayMissionText()+",已经完成牧场公网IP更新>>farmId="+farmId+",farmName="+farmName+"，更新公网IP和relay端口="+netIp);
        }
    }
}
