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

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.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.housearea.vo.HouseAreaPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.housearea.vo.HouseAreaSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.housearea.vo.HouseAreaVO;
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.houselocation.WareHouseLocationDO;
import cn.iocoder.yudao.module.system.dal.dataobject.positionmap.PositionMapItemDO;
import cn.iocoder.yudao.module.system.dal.mysql.housearea.HouseAreaMapper;
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 HouseAreaServiceImpl extends ServiceImpl<HouseAreaMapper, HouseAreaDO> implements HouseAreaService {

    @Resource
    private HouseAreaMapper houseAreaMapper;
    @Resource
    private PositionMapItemService positionMapItemService;
    @Resource
    private HouseLocationService houseLocationService;

    @Override
    public Long createHouseArea(HouseAreaSaveReqVO createReqVO) {
        // 插入
        HouseAreaDO houseArea = BeanUtils.toBean(createReqVO, HouseAreaDO.class);
        houseAreaMapper.insert(houseArea);
        // 返回
        return houseArea.getId();
    }

    @Override
    public void updateHouseArea(HouseAreaSaveReqVO updateReqVO) {
        // 校验存在
        validateHouseAreaExists(updateReqVO.getId());
        // 更新
        HouseAreaDO updateObj = BeanUtils.toBean(updateReqVO, HouseAreaDO.class);
        houseAreaMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHouseArea(Long id) {
        // 校验存在
        validateHouseAreaExists(id);
        // 删除
        houseAreaMapper.deleteById(id);
    }

    private void validateHouseAreaExists(Long id) {
        if (houseAreaMapper.selectById(id) == null) {
            throw exception(HOUSE_AREA_NOT_EXISTS);
        }
    }

    @Override
    public HouseAreaDO getHouseArea(Long id) {
        return houseAreaMapper.selectById(id);
    }

    @Override
    public PageResult<HouseAreaDO> getHouseAreaPage(HouseAreaPageReqVO pageReqVO) {
        PageResult<HouseAreaDO> houseAreaDOPageResult = houseAreaMapper.selectPage(pageReqVO);
        if (CollUtil.isNotEmpty(houseAreaDOPageResult.getList())) {
            List<Long> ids = houseAreaDOPageResult.getList().stream().map(HouseAreaDO::getId).collect(Collectors.toList());
            List<PositionMapItemDO> list = positionMapItemService.list(new LambdaQueryWrapper<PositionMapItemDO>()
                    .eq(PositionMapItemDO::getPositionMapId, pageReqVO.getPositionMapId())
                    .in(PositionMapItemDO::getAreaId, ids));
            if (CollUtil.isNotEmpty(list)) {
                Map<Long, List<Long>> map = CollectionUtils.convertMultiMap(list, PositionMapItemDO::getAreaId, PositionMapItemDO::getId);
                for (HouseAreaDO houseAreaDO : houseAreaDOPageResult.getList()) {
                    houseAreaDO.setMapItemIds(map.getOrDefault(houseAreaDO.getId(), Collections.emptyList()));
                }
            }
        }
        return houseAreaDOPageResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HouseAreaVO createOrEditOrDel(HouseAreaSaveReqVO createReqVO) {
        // 判断名称唯一
        Long count = houseAreaMapper.selectCount(
                new LambdaQueryWrapper<HouseAreaDO>()
                        .eq(HouseAreaDO::getPositionMapId, createReqVO.getPositionMapId())
                        .eq(HouseAreaDO::getAreaName, createReqVO.getAreaName())
                        .ne(ObjectUtil.isNotNull(createReqVO.getId()), HouseAreaDO::getId, createReqVO.getId())
        );
        if (count > 0) {
            throw exception(DUPLICATE_RESERVOIR_NAME);
        }
        HouseAreaDO houseArea = BeanUtil.copyProperties(createReqVO, HouseAreaDO.class);
        houseAreaMapper.insertOrUpdate(houseArea);

        //2.查询目前的地图所有的库位点位列表 - 如果没有的话 - 就设为空列表先 -
        List<PositionMapItemDO> list = positionMapItemService.getByCondition(new PositionMapConditionDTO()
                .setPositionMapId(createReqVO.getPositionMapId())
                .setType(NodeTypeEnum.WARE.getType())
                .setIds(createReqVO.getMapItemIds())
                .setAreaId(createReqVO.getId()));

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

        List<WareHouseLocationDO> wareHouseLocationList = new ArrayList<>();
        for (PositionMapItemDO item : list) {
            List<WareHouseLocationDO> wareHouseLocationDOS = JSONUtil.toList(item.getDataJson(), WareHouseLocationDO.class);
            for (WareHouseLocationDO locationDO : wareHouseLocationDOS) {
                locationDO.setAreaId(houseArea.getId());
                locationDO.setAreaName(houseArea.getAreaName());
                locationDO.setSkuInfo(createReqVO.getSkuInfo());
            }
            wareHouseLocationList.addAll(wareHouseLocationDOS);
            item.setAreaId(houseArea.getId());
            item.setDataJson(JSONUtil.toJsonStr(wareHouseLocationDOS));
        }
        if (CollUtil.isNotEmpty(list)) {
            positionMapItemService.updateBatchById(list);
        }
        if (CollUtil.isNotEmpty(wareHouseLocationList)) {
            houseLocationService.updateBatchById(wareHouseLocationList);
        }
        return new HouseAreaVO().setId(houseArea.getId()).setAreaName(houseArea.getAreaName());
    }

    @Override
    public List<HouseAreaDO> getHouseAreaList(Long positionMapId) {
        return houseAreaMapper.selectList(new LambdaQueryWrapper<HouseAreaDO>()
                .eq(HouseAreaDO::getPositionMapId, positionMapId)
                .orderByAsc(HouseAreaDO::getId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        HouseAreaDO areaDO = this.getById(id);
        this.removeById(id);
        //获取当前库区所对应的地图
        //  点位中包含库区id的数据设为null
        List<PositionMapItemDO> items = positionMapItemService.getByCondition(new PositionMapConditionDTO().setAreaId(id).setPositionMapId(areaDO.getPositionMapId()));
        for (PositionMapItemDO item : items) {
            item.setAreaId(null);
            List<WareHouseLocationDO> wareHouseLocationDOS = JSONUtil.toList(item.getDataJson(), WareHouseLocationDO.class);
            for (WareHouseLocationDO wareHouseLocationDO : wareHouseLocationDOS) {
                wareHouseLocationDO.setAreaId(null);
                wareHouseLocationDO.setAreaName(null);
//                wareHouseLocationDO.setSkuInfo(null);
            }
            item.setDataJson(JSONUtil.toJsonStr(wareHouseLocationDOS));
        }
        positionMapItemService.updateBatchById(items);
        houseLocationService.updateLocationAreaNameEmptyByAreaId(id);
//        positionMapItemService.emptyAreaId(areaDO.getPositionMapId(), id);
    }

    @Override
    public void deleteHouseAreaByMapId(Long mapId) {
        houseAreaMapper.deleteHouseAreaByMapId(mapId);
    }

}
