package cn.iocoder.yudao.module.pms.service.iotwebtopoproject;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.pms.controller.admin.iotwebtopoproject.vo.IotWebtopoProjectPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotwebtopoproject.vo.IotWebtopoProjectSaveReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotwebtopoprojectdevice.vo.IotWebtopoProjectDevicePageReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotwebtopoproject.IotWebtopoProjectDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotwebtopoprojectdevice.IotWebtopoProjectDeviceDO;
import cn.iocoder.yudao.module.pms.dal.mysql.iotwebtopoproject.IotWebtopoProjectMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.iotwebtopoprojectdevice.IotWebtopoProjectDeviceMapper;
import com.google.common.collect.ImmutableMap;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.pms.enums.ErrorCodeConstant.IOT_WEBTOPO_PROJECT_NOT_EXISTS;

/**
 * 组态项目列 Service 实现类
 *
 * @author ruiqi
 */
@Service
@Validated
public class IotWebtopoProjectServiceImpl implements IotWebtopoProjectService {

    @Resource
    private IotWebtopoProjectMapper iotWebtopoProjectMapper;

    @Resource
    private IotWebtopoProjectDeviceMapper iotWebtopoProjectDeviceMapper;

    @Override
    public Long createIotWebtopoProject(IotWebtopoProjectSaveReqVO createReqVO) {
        // 插入
        // 如果没有传 deptId 获取当前登录人的部门id
        if (ObjUtil.isEmpty(createReqVO.getDeptId())) {
            // 查询当前登录人所属公司
            Long loginUserDeptId = SecurityFrameworkUtils.getLoginUserDeptId();
            createReqVO.setDeptId(loginUserDeptId);
        }
        IotWebtopoProjectDO iotWebtopoProject = BeanUtils.toBean(createReqVO, IotWebtopoProjectDO.class);
        iotWebtopoProjectMapper.insert(iotWebtopoProject);
        // 添加关联的设备信息
        List<Long> deviceIds = createReqVO.getLinkedDeviceIds();
        if (CollUtil.isNotEmpty(deviceIds)) {
            List<IotWebtopoProjectDeviceDO> linkedDevices = new ArrayList<>();
            deviceIds.forEach(deviceId -> {
                IotWebtopoProjectDeviceDO tempDevice = new IotWebtopoProjectDeviceDO();
                tempDevice.setProjectId(iotWebtopoProject.getId());
                tempDevice.setDeviceId(deviceId);
                linkedDevices.add(tempDevice);
            });
            if (CollUtil.isNotEmpty(linkedDevices)) {
                boolean flag = iotWebtopoProjectDeviceMapper.insertBatch(linkedDevices);
            }
        }
        // 返回
        return iotWebtopoProject.getId();
    }

    @Override
    public void updateIotWebtopoProject(IotWebtopoProjectSaveReqVO updateReqVO) {
        // 校验存在
        validateIotWebtopoProjectExists(updateReqVO.getId());
        // 更新
        IotWebtopoProjectDO updateObj = BeanUtils.toBean(updateReqVO, IotWebtopoProjectDO.class);
        iotWebtopoProjectMapper.updateById(updateObj);
        // 更新组态项目已经绑定的设备列表
        List<Long> deviceIds = updateReqVO.getLinkedDeviceIds();
        if (CollUtil.isNotEmpty(deviceIds)) {
            // 先删除再新增
            int count = iotWebtopoProjectDeviceMapper.deleteByMap(ImmutableMap.of(
                    "project_id", updateObj.getId()
            ));
            List<IotWebtopoProjectDeviceDO> linkedDevices = new ArrayList<>();
            deviceIds.forEach(deviceId -> {
                IotWebtopoProjectDeviceDO tempDevice = new IotWebtopoProjectDeviceDO();
                tempDevice.setProjectId(updateReqVO.getId());
                tempDevice.setDeviceId(deviceId);
                linkedDevices.add(tempDevice);
            });
            if (CollUtil.isNotEmpty(linkedDevices)) {
                boolean flag = iotWebtopoProjectDeviceMapper.insertBatch(linkedDevices);
            }
        }
    }

    @Override
    public void deleteIotWebtopoProject(Long id) {
        // 校验存在
        validateIotWebtopoProjectExists(id);
        // 删除
        iotWebtopoProjectMapper.deleteById(id);
    }

    private void validateIotWebtopoProjectExists(Long id) {
        if (iotWebtopoProjectMapper.selectById(id) == null) {
            throw exception(IOT_WEBTOPO_PROJECT_NOT_EXISTS);
        }
    }

    @Override
    public IotWebtopoProjectDO getIotWebtopoProject(Long id) {
        return iotWebtopoProjectMapper.selectById(id);
    }

    @Override
    public PageResult<IotWebtopoProjectDO> getIotWebtopoProjectPage(IotWebtopoProjectPageReqVO pageReqVO) {
        return iotWebtopoProjectMapper.selectPage(pageReqVO);
    }

    @Override
    public Long copyProject(IotWebtopoProjectSaveReqVO createReqVO) {
        // 拷贝组态项目 提高组态图制作效率
        Long projectId = createReqVO.getId();
        if (ObjUtil.isEmpty(projectId)) {
            throw exception(IOT_WEBTOPO_PROJECT_NOT_EXISTS);
        }
        IotWebtopoProjectDO existProject = iotWebtopoProjectMapper.selectById(projectId);
        if (ObjUtil.isEmpty(existProject)) {
            throw exception(IOT_WEBTOPO_PROJECT_NOT_EXISTS);
        }
        IotWebtopoProjectDO newProject = new IotWebtopoProjectDO();
        newProject.setDeptId(existProject.getDeptId());
        newProject.setProjectName(createReqVO.getProjectName());
        newProject.setThumbnail(existProject.getThumbnail());
        newProject.setDataModel(existProject.getDataModel());
        newProject.setCreateTime(LocalDateTime.now());
        newProject.setRemark(createReqVO.getRemark());
        int num = iotWebtopoProjectMapper.insert(newProject);

        // 配置新项目关联的设备
        List<IotWebtopoProjectDeviceDO> projectDevices = new ArrayList<>();
        IotWebtopoProjectDevicePageReqVO reqVO = new IotWebtopoProjectDevicePageReqVO();
        reqVO.setProjectId(projectId);
        reqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<IotWebtopoProjectDeviceDO> pageDevices = iotWebtopoProjectDeviceMapper.selectPage(reqVO);
        if (ObjUtil.isNotEmpty(pageDevices)) {
            List<IotWebtopoProjectDeviceDO> devices = pageDevices.getList();
            if (CollUtil.isNotEmpty(devices)) {
                devices.forEach(device -> {
                    IotWebtopoProjectDeviceDO projectDevice = new IotWebtopoProjectDeviceDO();
                    projectDevice.setProjectId(newProject.getId());
                    projectDevice.setDeviceId(device.getDeviceId());
                    projectDevice.setCreateTime(LocalDateTime.now());
                    projectDevices.add(projectDevice);
                });
            }
        }
        if (CollUtil.isNotEmpty(projectDevices)) {
            boolean flag = iotWebtopoProjectDeviceMapper.insertBatch(projectDevices);
        }
        return newProject.getId();
    }

}