package cn.iocoder.yudao.module.system.handler.mapnode.strategy;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.module.system.controller.admin.positionmap.dto.NodeBaseDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.information.DeviceInformationDO;
import cn.iocoder.yudao.module.system.service.information.DeviceInformationService;
import org.springframework.stereotype.Component;

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

import static com.baomidou.mybatisplus.core.toolkit.IdWorker.getId;

@Component
public class DeviceStrategyImpl implements NodeProcessingStrategy {
    @Resource
    private DeviceInformationService deviceInformationService;

    @Override
    public void processNodes(Long positionMapId, List<NodeBaseDTO> nodeBaseDTOS) {
        // -- 策略3 处理设备点
        // -- 将data里面的json 数据转为实体类 - 再对比节点id - 然后做新增删除修改操作
        List<DeviceInformationDO> newList = new ArrayList<>();
        // -- 拿到这个地图所绑定的设备 -
        List<DeviceInformationDO> oldList = deviceInformationService.getDeviceInfoBindByMapId(positionMapId);
        nodeBaseDTOS.forEach(item -> {
            if (item.getId() == null) {
                item.setId(getId());
            }
            item.setPositionMapId(positionMapId);
            DeviceInformationDO deviceInformationDO = JSONUtil.toBean(item.getDataJson(), DeviceInformationDO.class);
            deviceInformationDO.setLocationX(item.getLocationX());
            deviceInformationDO.setLocationY(item.getLocationY());
            deviceInformationDO.setActualLocationX(item.getActualLocationX());
            deviceInformationDO.setActualLocationY(item.getActualLocationY());
            deviceInformationDO.setPositionMapId(positionMapId);
            deviceInformationDO.setPositionMapItemId(item.getId());
            newList.add(deviceInformationDO);
            item.setDataJson(JSONUtil.toJsonStr(deviceInformationDO));
        });

        List<List<DeviceInformationDO>> list = CollectionUtils.compareLists(oldList, newList,
                (oldVal, newVal) -> ObjectUtil.equal(oldVal.getId(), newVal.getId()));
        deviceInformationService.batchEditOrDel(list);
    }
}
