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.parkingspot.ParkingSpotDO;
import cn.iocoder.yudao.module.system.service.parkingspot.ParkingSpotService;
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 ParkingSpotStrategyImpl implements NodeProcessingStrategy {
    @Resource
    private ParkingSpotService parkingSpotService;

    @Override
    public void processNodes(Long positionMapId, List<NodeBaseDTO> nodeBaseDTOS) {
        // -- 策略4 处理停车点
        // -- 将data里面的json 数据转为实体类 - 再对比节点id - 然后做新增删除修改操作
        // ---------------      dataJSON里面没有具体的类的id - 然后库位要根据层数添加 多个库位数据 即 一个点位 对应多个库位
        List<ParkingSpotDO> newList = new ArrayList<>();
        nodeBaseDTOS.forEach(item -> {
            if (item.getId() == null) {
                item.setId(getId());
            }
            item.setPositionMapId(positionMapId);
            ParkingSpotDO parkingSpotDO = JSONUtil.toBean(item.getDataJson(), ParkingSpotDO.class);
            if (parkingSpotDO.getId() == null) {
                parkingSpotDO.setId(getId());
            }
            parkingSpotDO.setLocationX(item.getLocationX());
            parkingSpotDO.setLocationY(item.getLocationY());
            parkingSpotDO.setActualLocationX(item.getActualLocationX());
            parkingSpotDO.setActualLocationY(item.getActualLocationY());

            parkingSpotDO.setPositionMapId(positionMapId);
            parkingSpotDO.setPositionMapItemId(item.getId());
            newList.add(parkingSpotDO);
            item.setDataJson(JSONUtil.toJsonStr(parkingSpotDO));
            });

        List<ParkingSpotDO> oldList = parkingSpotService.getByMapId(positionMapId);
        List<List<ParkingSpotDO>> list = CollectionUtils.compareLists(oldList, newList,
                (oldVal, newVal) -> ObjectUtil.equal(oldVal.getId(), newVal.getId()));
        parkingSpotService.batchSaveOrEditOrDel(positionMapId, list);
    }
}
