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.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.stream.Collectors;

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

/**
 * 库区 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) {
        return houseAreaMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createOrEditOrDel(HouseAreaSaveReqVO createReqVO) {
        HouseAreaDO houseArea = BeanUtil.copyProperties(createReqVO, HouseAreaDO.class);
        houseAreaMapper.insertOrUpdate(houseArea);
        // -- 先判定这些点位是否在同一区域内 - 如果不在则提示 哪些点位不在同一区域内
        //1.获取原该线库绑定的点位列表
        List<PositionMapItemDO> oldList = createReqVO.getId() == null ? Collections.emptyList() :
                positionMapItemService.getByCondition(new PositionMapConditionDTO()
                        .setPositionMapId(createReqVO.getPositionMapId())
                        .setAreaId(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.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<List<PositionMapItemDO>> allList = CollectionUtils.compareLists(oldList, list,
                (oldVal, newVal) -> ObjectUtil.equal(oldVal.getAreaId(), newVal.getAreaId()));
        List<PositionMapItemDO> editList = new ArrayList<>();
        if (CollUtil.isNotEmpty(allList.get(0))) {
            List<PositionMapItemDO> editItemList = allList.get(0);
            editItemList.forEach(a -> a.setAreaId(houseArea.getId()));
            // -- 新增的 就是更改的 - 需要更新的
            editList.addAll(editItemList);
        }
        if (CollUtil.isNotEmpty(allList.get(2))) {
            //需要删除的就是取消掉的
            List<PositionMapItemDO> editItemList = allList.get(2);
            editItemList.forEach(a -> a.setAreaId(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.getAreaId() == null) {
                    a.setAreaId(null);
                    a.setAreaName(null);
                } else {
                    a.setAreaId(houseArea.getId());
                    a.setAreaName(houseArea.getAreaName());
                }
            });
            wareHouseLocationList.addAll(wareHouseLocationDOS);
            item.setDataJson(JSONUtil.toJsonStr(wareHouseLocationDOS));
        });
        if (CollUtil.isNotEmpty(editList)) {
            positionMapItemService.updateBatchById(editList);
        }
        if (CollUtil.isNotEmpty(wareHouseLocationList)) {
            houseLocationService.updateBatchById(wareHouseLocationList);
        }
    }

    @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
        positionMapItemService.emptyAreaId(areaDO.getPositionMapId(), id);
    }

}
