package com.foreverwin.mesnac.equip.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.meapi.model.Resrce;
import com.foreverwin.mesnac.meapi.service.ResrceService;
import com.foreverwin.modular.core.exception.BusinessException;
import com.foreverwin.modular.core.util.CommonMethods;
import com.foreverwin.modular.core.util.FrontPage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.foreverwin.mesnac.equip.model.ResourceStatusReceive;
import com.foreverwin.mesnac.equip.mapper.ResourceStatusReceiveMapper;
import com.foreverwin.mesnac.equip.service.ResourceStatusReceiveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 设备状态表-接口 服务实现类
 * </p>
 *
 * @author pavel.Liu
 * @since 2021-07-13
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ResourceStatusReceiveServiceImpl extends ServiceImpl<ResourceStatusReceiveMapper, ResourceStatusReceive> implements ResourceStatusReceiveService {

    private static Logger logger = LoggerFactory.getLogger(ResourceStatusReceiveServiceImpl.class);

    @Autowired
    private ResourceStatusReceiveMapper resourceStatusReceiveMapper;
    @Autowired
    private ResrceService resrceService;

    @Override
    public IPage<ResourceStatusReceive> selectPage(FrontPage<ResourceStatusReceive> frontPage, ResourceStatusReceive resourceStatusReceive) {
        QueryWrapper<ResourceStatusReceive> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(resourceStatusReceive);
        return super.page(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<ResourceStatusReceive> selectList(ResourceStatusReceive resourceStatusReceive) {
        QueryWrapper<ResourceStatusReceive> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(resourceStatusReceive);
        return super.list(queryWrapper);
    }

    /**
     * 设备状态：运行/RUN(301|已启用)；停机/DOW(302|已禁用);维修/REPAIR(4/预定停机);封存/SEAL(303|保留);空闲/FREE(2|备用)
     * @param text
     * @return
     */
    @Override
    public void updateResourceStatusByMq(String text) {
        String user = CommonMethods.getUser();
        JSONObject jsonObject = JSONObject.parseObject(text);
        // 传输数据的唯一标识HANDLE，站点、设备编号、状态
        String handle = jsonObject.getString("TRANID");
        String site = jsonObject.getString("SITE");
        String resource = jsonObject.getString("RESOURCE");
        String sendStatus = jsonObject.getString("STATUS");
        // 数据传输时间
        String sendTime = jsonObject.getString("SEND_TIME");
        DateTimeFormatter dataFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(sendTime,dataFormatter);

        if (StringUtil.isBlank(handle)) {
            throw BusinessException.build("唯一标识不能为空！");
        }
        if (StringUtil.isBlank(site)) {
            throw BusinessException.build("站点不能为空！");
        }
        if (StringUtil.isBlank(resource)) {
            throw BusinessException.build("设备编号不能为空！");
        }
        String resourceHandle = HandleEnum.RESOURCE.getHandle(site, resource);
        Resrce resourceById = resrceService.getById(resourceHandle);
        if (resourceById == null){
            throw BusinessException.build("未找到设备编号为" + resource + "的设备！");
        }
        if (StringUtil.isBlank(sendStatus)) {
            throw BusinessException.build("设备状态不能为空！");
        }

        // 获取最新数据
        ResourceStatusReceive resourceStatus = resourceStatusReceiveMapper.getOneByMaxCreateDateTime(site,resource);
        if (resourceStatus != null){
            resourceStatus.setStatus(sendStatus);
            resourceStatus.setCreateUser(user);
            resourceStatus.setCreatedDateTime(resourceStatus.getModifiedDateTime());
            resourceStatus.setModifiedDateTime(dateTime);
            resourceStatus.setModifyUser(user);
            resourceStatusReceiveMapper.updateById(resourceStatus);
        }else{
            // 数据库录入新数据
            ResourceStatusReceive resourceStatusReceive = new ResourceStatusReceive();
            resourceStatusReceive.setHandle(UUID.randomUUID().toString());
            resourceStatusReceive.setSite(site);
            resourceStatusReceive.setResrce(resource);
            resourceStatusReceive.setStatus(sendStatus);
            resourceStatusReceive.setCreateUser(user);
            resourceStatusReceive.setCreatedDateTime(dateTime);
            resourceStatusReceive.setModifyUser(user);
            resourceStatusReceive.setModifiedDateTime(dateTime);
            resourceStatusReceiveMapper.insert(resourceStatusReceive);
            logger.info("设备编号：" + resource + "，记录第一笔数据！");
        }
    }

}