package cn.iocoder.yudao.module.system.service.houselane;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.enums.NodeTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.controller.admin.houselane.vo.WareHouseLanePageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.houselane.vo.WareHouseLaneSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.positionmap.dto.PositionMapConditionDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.housearea.HouseAreaDO;
import cn.iocoder.yudao.module.system.dal.dataobject.houselane.WareHouseLaneDO;
import cn.iocoder.yudao.module.system.dal.dataobject.houselocation.WareHouseLocationDO;
import cn.iocoder.yudao.module.system.dal.dataobject.positionmap.PositionMapItemDO;
import cn.iocoder.yudao.module.system.dal.mysql.houselane.WareHouseLaneMapper;
import cn.iocoder.yudao.module.system.service.houselocation.HouseLocationService;
import cn.iocoder.yudao.module.system.service.positionmap.PositionMapItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.THERE_ARE_ALREADY_STORAGE_LOCATIONS_IN_OTHER_LINE_WAREHOUSES;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.THE_LINE_LIBRARY_POINTS_ARE_NOT_LOCATED_IN_THE_SAME_AREA;


/**
 * 线库/巷道 Service 实现类
 *
 * @author 陈宾顺
 */
@Service
@Validated
public class WareHouseLaneServiceImpl extends ServiceImpl<WareHouseLaneMapper, WareHouseLaneDO> implements WareHouseLaneService {

    @Resource
    private WareHouseLaneMapper houseLaneMapper;
    @Resource
    private PositionMapItemService positionMapItemService;
    @Resource
    private HouseLocationService houseLocationService;

    @Override
    public WareHouseLaneDO getHouseLane(Long id) {
        WareHouseLaneDO wareHouseLaneDO = houseLaneMapper.selectById(id);
        List<PositionMapItemDO> mapItemDOS = positionMapItemService.getByCondition(new PositionMapConditionDTO()
                .setLaneId(id)
                .setType(NodeTypeEnum.WARE.getType())
        );
        List<Long> mapIds = mapItemDOS.stream().map(PositionMapItemDO::getId).collect(Collectors.toList());
        wareHouseLaneDO.setMapItemIds(mapIds);
        return wareHouseLaneDO;
    }

    @Override
    public PageResult<WareHouseLaneDO> getHouseLanePage(WareHouseLanePageReqVO pageReqVO) {
        return houseLaneMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createOrEditOrDel(WareHouseLaneSaveReqVO createReqVO) {
        WareHouseLaneDO houseLane = BeanUtil.copyProperties(createReqVO, WareHouseLaneDO.class);
        houseLaneMapper.insertOrUpdate(houseLane);
        // -- 先判定这些点位是否在同一区域内 - 如果不在则提示 哪些点位不在同一区域内
        //1.获取原该线库绑定的点位列表
        List<PositionMapItemDO> oldList = createReqVO.getId() == null ? Collections.emptyList() :
                positionMapItemService.getByCondition(new PositionMapConditionDTO()
                        .setPositionMapId(createReqVO.getPositionMapId())
                        .setLaneId(createReqVO.getId())
                        .setType(NodeTypeEnum.WARE.getType()));

        //2.查询目前的点位列表 - 如果没有的话 - 就设为空列表先 -
        List<PositionMapItemDO> list = CollUtil.isEmpty(createReqVO.getMapItemIds()) ? Collections.emptyList() :
                positionMapItemService.getByCondition(new PositionMapConditionDTO()
                        .setPositionMapId(createReqVO.getPositionMapId())
                        .setType(NodeTypeEnum.WARE.getType())
                        .setIds(createReqVO.getMapItemIds()));

        //3.判定当前这些点位是否已经有包含线库了 -
        List<PositionMapItemDO> containList = list.stream().filter(a -> a.getLaneId() != null && !a.getLaneId().equals(createReqVO.getId())).collect(Collectors.toList());
        // todo - 这里如果设置的库位已经有绑定其他线库了 - 该如何处理 - 目前我们做提示 - 后续看要不要覆盖
        if (CollUtil.isNotEmpty(containList)) {
            throw exception(THERE_ARE_ALREADY_STORAGE_LOCATIONS_IN_OTHER_LINE_WAREHOUSES);
        }
        if (CollUtil.isNotEmpty(list)) {
            // 判定是否都在同一区域内
            long count = list.stream().map(PositionMapItemDO::getAreaId).distinct().count();
            if (count > 1) {
                throw exception(THE_LINE_LIBRARY_POINTS_ARE_NOT_LOCATED_IN_THE_SAME_AREA);
            }
        }

        // -- 这里去判断更新点位的线库信息
        List<List<PositionMapItemDO>> allList = CollectionUtils.compareLists(oldList, list,
                (oldVal, newVal) -> ObjectUtil.equal(oldVal.getLaneId(), newVal.getLaneId()));
        List<PositionMapItemDO> editList = new ArrayList<>();
        if (CollUtil.isNotEmpty(allList.get(0))) {
            List<PositionMapItemDO> editItemList = allList.get(0);
            editItemList.forEach(a -> a.setLaneId(houseLane.getId()));
            // -- 新增的 就是更改的 - 需要更新的
            editList.addAll(editItemList);
        }
        if (CollUtil.isNotEmpty(allList.get(1))) {
            // -- 需要更新的
            editList.addAll(allList.get(1));
        }
        if (CollUtil.isNotEmpty(allList.get(2))) {
            //需要删除的就是取消掉的
            List<PositionMapItemDO> editItemList = allList.get(2);
            editItemList.forEach(a -> a.setLaneId(null));
            editList.addAll(allList.get(2));
        }

        List<WareHouseLocationDO> wareHouseLocationList = new ArrayList<>();
        editList.forEach(item -> {
            List<WareHouseLocationDO> wareHouseLocationDOS = JSONUtil.toList(item.getDataJson(), WareHouseLocationDO.class);
            wareHouseLocationDOS.forEach(a -> {
                if (item.getLaneId() == null) {
                    a.setLaneId(null);
                    a.setLaneName(null);
                } else {
                    a.setLaneId(houseLane.getId());
                    a.setLaneName(houseLane.getLaneName());
                }
            });
            wareHouseLocationList.addAll(wareHouseLocationDOS);
            item.setDataJson(JSONUtil.toJsonStr(wareHouseLocationDOS));
        });
        if (CollUtil.isNotEmpty(editList)) {
            positionMapItemService.updateBatchById(editList);
        }
        if (CollUtil.isNotEmpty(wareHouseLocationList)) {
            houseLocationService.updateBatchById(wareHouseLocationList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        WareHouseLaneDO wareHouseLaneDO = this.getById(id);
        this.removeById(id);
        //  点位中包含线库id的数据设为null
        positionMapItemService.emptyLaneId(wareHouseLaneDO.getPositionMapId(), id);
    }
}
