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.houselocation.vo.WareHouseTakePointSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.positionmap.dto.NodeBaseDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.houselocation.WareHouseTakePointDO;
import cn.iocoder.yudao.module.system.enums.map.PointTypeEnum;
import cn.iocoder.yudao.module.system.service.houselocation.WareHouseTakePointService;
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 CheckStrategyImpl implements NodeProcessingStrategy{

    @Resource
    private WareHouseTakePointService houseTakePointService;

    @Override
    public void processNodes(Long positionMapId, List<NodeBaseDTO> nodeBaseDTOS) {
        // -- 策略3 处理设备点
        // -- 将data里面的json 数据转为实体类 - 再对比节点id - 然后做新增删除修改操作
        List<WareHouseTakePointDO> newList = new ArrayList<>();
        // -- 拿到这个地图所绑定的设备 -

        WareHouseTakePointSaveReqVO reqVO = new WareHouseTakePointSaveReqVO();
        reqVO.setPositionMapId(positionMapId);
        reqVO.setPointType(PointTypeEnum.TAKE.getType());
        List<WareHouseTakePointDO> oldList = houseTakePointService.getHouseTakePointList(reqVO);
        for (NodeBaseDTO item : nodeBaseDTOS) {
            if (item.getId() == null) {
                item.setId(getId());
            }
            item.setPositionMapId(positionMapId);
            if(ObjectUtil.isEmpty(item.getDataJson())) {
                continue;
            }

            List<WareHouseTakePointDO> wareHouseTakePointDOS = JSONUtil.toList(item.getDataJson(), WareHouseTakePointDO.class);

            for (WareHouseTakePointDO wareHouseTakePointDO : wareHouseTakePointDOS) {
                wareHouseTakePointDO.setPointType(PointTypeEnum.TAKE.getType());
                wareHouseTakePointDO.setPositionMapId(positionMapId);
                wareHouseTakePointDO.setPositionMapItemId(item.getId());
                newList.add(wareHouseTakePointDO);
            }
            item.setDataJson(JSONUtil.toJsonStr(wareHouseTakePointDOS));
        }

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



}
