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.module.system.controller.admin.houselane.vo.HouseLaneVO;
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.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.core.conditions.query.LambdaQueryWrapper;
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.Map;
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.*;


/**
 * 线库/巷道 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) {
        PageResult<WareHouseLaneDO> houseLaneDOPageResult = houseLaneMapper.selectPage(pageReqVO);
        if (CollUtil.isNotEmpty(houseLaneDOPageResult.getList())) {
            List<Long> ids = houseLaneDOPageResult.getList().stream().map(WareHouseLaneDO::getId).collect(Collectors.toList());
            List<PositionMapItemDO> list = positionMapItemService.list(new LambdaQueryWrapper<PositionMapItemDO>()
                    .eq(PositionMapItemDO::getPositionMapId, pageReqVO.getPositionMapId())
                    .in(PositionMapItemDO::getLaneId, ids));
            if (CollUtil.isNotEmpty(list)) {
                Map<Long, List<Long>> map = CollectionUtils.convertMultiMap(list, PositionMapItemDO::getLaneId, PositionMapItemDO::getId);
                for (WareHouseLaneDO wareHouseLaneDO : houseLaneDOPageResult.getList()) {
                    wareHouseLaneDO.setMapItemIds(map.getOrDefault(wareHouseLaneDO.getId(), Collections.emptyList()));
                }
            }
        }
        return houseLaneDOPageResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HouseLaneVO createOrEditOrDel(WareHouseLaneSaveReqVO createReqVO) {
        // 判断名称唯一
        Long num = houseLaneMapper.selectCount(
                new LambdaQueryWrapper<WareHouseLaneDO>()
                        .eq(WareHouseLaneDO::getLaneName, createReqVO.getLaneName())
                        .eq(WareHouseLaneDO::getPositionMapId, createReqVO.getPositionMapId())
                        .ne(ObjectUtil.isNotNull(createReqVO.getId()), WareHouseLaneDO::getId, createReqVO.getId())
        );
        if (num > 0) {
            throw exception(DUPLICATE_LINE_LIBRARY_NAME);
        }
        WareHouseLaneDO houseLane = BeanUtil.copyProperties(createReqVO, WareHouseLaneDO.class);
        houseLaneMapper.insertOrUpdate(houseLane);

        //查询目前的点位列表 - 如果没有的话 - 就设为空列表先 -
        List<PositionMapItemDO> list = positionMapItemService.getByCondition(new PositionMapConditionDTO()
                .setPositionMapId(createReqVO.getPositionMapId())
                .setLaneId(createReqVO.getId())
                .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<WareHouseLocationDO> wareHouseLocationList = new ArrayList<>();
        for (PositionMapItemDO item : list) {
            item.setLaneId(houseLane.getId());
            List<WareHouseLocationDO> wareHouseLocationDOS = JSONUtil.toList(item.getDataJson(), WareHouseLocationDO.class);
            for (WareHouseLocationDO wareHouseLocationDO : wareHouseLocationDOS) {
                wareHouseLocationDO.setLaneId(houseLane.getId());
                wareHouseLocationDO.setLaneName(houseLane.getLaneName());
            }
            wareHouseLocationList.addAll(wareHouseLocationDOS);
            item.setDataJson(JSONUtil.toJsonStr(wareHouseLocationDOS));
        }
        if (CollUtil.isNotEmpty(list)) {
            positionMapItemService.updateBatchById(list);
        }
        if (CollUtil.isNotEmpty(wareHouseLocationList)) {
            houseLocationService.updateBatchById(wareHouseLocationList);
        }
        houseLocationService.updateLocationLaneNameByLaneId(createReqVO.getId(), createReqVO.getLaneName());
        return new HouseLaneVO().setId(houseLane.getId()).setLaneName(houseLane.getLaneName());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        WareHouseLaneDO wareHouseLaneDO = this.getById(id);
        List<PositionMapItemDO> items = positionMapItemService.getByCondition(new PositionMapConditionDTO().setLaneId(id).setPositionMapId(wareHouseLaneDO.getPositionMapId()));
        for (PositionMapItemDO item : items) {
            item.setLaneId(null);
            List<WareHouseLocationDO> wareHouseLocationDOS = JSONUtil.toList(item.getDataJson(), WareHouseLocationDO.class);
            for (WareHouseLocationDO wareHouseLocationDO : wareHouseLocationDOS) {
                wareHouseLocationDO.setLaneId(null);
                wareHouseLocationDO.setLaneName(null);
            }
            item.setDataJson(JSONUtil.toJsonStr(wareHouseLocationDOS));
        }
        positionMapItemService.updateBatchById(items);
        this.removeById(id);
        //  点位中包含线库id的数据设为null
        positionMapItemService.emptyLaneId(wareHouseLaneDO.getPositionMapId(), id);
        houseLocationService.updateLocationLaneNameEmptyByLaneId(id);
    }

    @Override
    public void deleteHouseLaneByMapId(Long mapId) {
        houseLaneMapper.deleteHouseLaneByMapId(mapId);
    }
}
