package cn.iocoder.yudao.module.mes.service.goview;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.mes.controller.admin.goview.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.goview.GoviewDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.mes.dal.mysql.goview.GoviewMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.mes.enums.ErrorCodeConstants.*;

/**
 * 可视化大屏 Service 实现类
 *
 * @author 必硕科技
 */
@Service
@Validated
public class GoviewServiceImpl implements GoviewService {

    @Resource
    private GoviewMapper goviewMapper;

    @Override
    public Long createGoview(GoviewSaveReqVO createReqVO) {
        // 插入
        GoviewDO goview = BeanUtils.toBean(createReqVO, GoviewDO.class);
        if (!createReqVO.getDeviceIdsList().isEmpty()){
            String jsonString = JSON.toJSONString(createReqVO.getDeviceIdsList());
            goview.setDeviceIds(jsonString);

        }
        goviewMapper.insert(goview);
        // 返回
        return goview.getId();
    }

    @Override
    public void updateGoview(GoviewSaveReqVO updateReqVO) {
        // 校验存在
        validateGoviewExists(updateReqVO.getId());
        // 更新
        GoviewDO updateObj = BeanUtils.toBean(updateReqVO, GoviewDO.class);
        if (!updateReqVO.getDeviceIdsList().isEmpty()){
            String jsonString = JSON.toJSONString(updateReqVO.getDeviceIdsList());
            updateObj.setDeviceIds(jsonString);

        }

        goviewMapper.updateById(updateObj);
    }

    @Override
    public void deleteGoview(Long id) {
        // 校验存在
        validateGoviewExists(id);
        // 删除
        goviewMapper.deleteById(id);
    }

    private void validateGoviewExists(Long id) {
        if (goviewMapper.selectById(id) == null) {
            throw exception(GOVIEW_NOT_EXISTS);
        }
    }

    @Override
    public GoviewDO getGoview(Long id) {
        return goviewMapper.selectById(id);
    }

    @Override
    public PageResult<GoviewDO> getGoviewPage(GoviewPageReqVO pageReqVO) {
        return goviewMapper.selectPage(pageReqVO);
    }

}