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

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.mqtt.api.task.dto.Pose2ds;
import cn.iocoder.yudao.module.system.config.poperties.ZnConfigConstant;
import cn.iocoder.yudao.module.system.constant.robot.RobotTaskChcheConstant;
import cn.iocoder.yudao.module.system.controller.admin.log.vo.UserOperationLogSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.positionmap.dto.PositionMapConditionDTO;
import cn.iocoder.yudao.module.system.controller.admin.positionmap.dto.PositionMapConfigDTO;
import cn.iocoder.yudao.module.system.controller.admin.positionmap.vo.PositionMapItemPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.positionmap.vo.PositionMapItemSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.robot.vo.RobotWarnMsgSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.houselocation.WareHouseLocationDO;
import cn.iocoder.yudao.module.system.dal.dataobject.positionmap.PositionChangePointBindingDO;
import cn.iocoder.yudao.module.system.dal.dataobject.positionmap.PositionMapItemDO;
import cn.iocoder.yudao.module.system.dal.mysql.positionmap.PositionChangePointBindingMapper;
import cn.iocoder.yudao.module.system.dal.mysql.positionmap.PositionMapItemMapper;
import cn.iocoder.yudao.module.system.enums.common.ZeroOneEnum;
import cn.iocoder.yudao.module.system.enums.item.PositionMapItemEnum;
import cn.iocoder.yudao.module.system.enums.item.UseStatusEnum;
import cn.iocoder.yudao.module.system.service.log.UserOperationLogService;
import cn.iocoder.yudao.module.system.service.robot.RobotWarnMsgService;
import cn.iocoder.yudao.module.system.util.redis.RedisUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.hutool.core.collection.CollUtil.isNotEmpty;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.MAP_EXIST_BINDING_POINT;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.MAP_EXIST_TASK_EXIST_TASK;

/**
 * 仓库点位地图子表 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class PositionMapItemServiceImpl extends ServiceImpl<PositionMapItemMapper, PositionMapItemDO> implements PositionMapItemService {

    @Resource
    private PositionMapItemMapper positionMapItemMapper;
    @Resource
    private RedisUtil redisUtil;

    @Resource
    private UserOperationLogService userOperationLogService;

    @Resource
    private RobotWarnMsgService warnMsgService;

    @Resource
    private PositionChangePointBindingMapper positionChangePointBindingMapper;

    @Autowired
    private ZnConfigConstant znConfigConstant;

    @Override
    public Long createPositionMapItem(PositionMapItemSaveReqVO createReqVO) {
        // 插入
        PositionMapItemDO positionMapItem = BeanUtils.toBean(createReqVO, PositionMapItemDO.class);
        positionMapItemMapper.insert(positionMapItem);

        UserOperationLogSaveReqVO operationLog = UserOperationLogSaveReqVO.builder().operateAction("添加路径点 " + positionMapItem.getSortNum())
                .nickName(SecurityFrameworkUtils.getLoginUserNickname()).build();
        userOperationLogService.createUserOperationLog(operationLog);
        // 返回
        return positionMapItem.getId();
    }

    @Override
    public void updatePositionMapItem(PositionMapItemSaveReqVO updateReqVO) {
        // 更新
        PositionMapItemDO updateObj = BeanUtils.toBean(updateReqVO, PositionMapItemDO.class);
        positionMapItemMapper.updateById(updateObj);
    }

    @Override
    public void deletePositionMapItem(Long id) {
        // 删除
        positionMapItemMapper.deleteById(id);
    }

    @Override
    public PositionMapItemDO getPositionMapItem(Long id) {
        return positionMapItemMapper.selectById(id);
    }

    @Override
    public PageResult<PositionMapItemDO> getPositionMapItemPage(PositionMapItemPageReqVO pageReqVO) {
        return positionMapItemMapper.selectPage(pageReqVO);
    }

    @Override
    public List<PositionMapItemDO> getByMapId(Long positionMapId) {
        return positionMapItemMapper.selectList(new LambdaQueryWrapperX<PositionMapItemDO>()
                .eq(PositionMapItemDO::getPositionMapId, positionMapId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSaveOrEditOrDel(Long positionMapId, List<List<PositionMapItemDO>> list) {
        //批量添加、修改、删除
        if (isNotEmpty(list.get(0))) {
            list.get(0).forEach(a -> a.setPositionMapId(positionMapId));
            positionMapItemMapper.insertBatch(list.get(0));
        }
        if (isNotEmpty(list.get(1))) {
            list.get(1).forEach(a -> a.setPositionMapId(positionMapId));
            positionMapItemMapper.updateBatch(list.get(1));
        }
        if (isNotEmpty(list.get(2))) {
            positionMapItemMapper.deleteByIds(convertList(list.get(2), PositionMapItemDO::getId));
        }
    }


    @Override
    public List<PositionMapItemDO> getByCondition(PositionMapConditionDTO dto) {
        return positionMapItemMapper.selectList(new LambdaQueryWrapperX<PositionMapItemDO>()
                .eqIfPresent(PositionMapItemDO::getPositionMapId, dto.getPositionMapId())
                .eqIfPresent(PositionMapItemDO::getType, dto.getType())
                .inIfPresent(PositionMapItemDO::getId, dto.getIds())
                .eqIfPresent(PositionMapItemDO::getAreaId, dto.getAreaId())
                .eqIfPresent(PositionMapItemDO::getLaneId, dto.getLaneId()));
    }

    @Override
    public void emptyAreaId(Long positionMapId, Long areaId) {
        positionMapItemMapper.emptyAreaId(positionMapId, areaId);
    }

    @Override
    public void emptyLaneId(Long mapId, Long laneId) {
        positionMapItemMapper.emptyLaneId(mapId, laneId);
    }

    @Override
    public Object getAGVPointInformation(String macAddress) {
        String pose2dKey = RobotTaskChcheConstant.ROBOT_INFORMATION_POSE_BAT + macAddress;
        try {
            // 睡眠 0.5s 以确保获取到是最新的数据
            Thread.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return redisUtil.get(pose2dKey);
    }

    @Override
    public void setMapItemIdle(Long id) {
        PositionMapItemDO positionMapItem = positionMapItemMapper.selectById(id);
        //预占，说明是车子在前往这个点位的路上出故障了，需要把这个点位设置为未使用
        if (!UseStatusEnum.PRE_OCCUPANCY.getType().equals(positionMapItem.getUseStatus())) {
            return;
        }

        PositionMapItemDO item = PositionMapItemDO.builder().id(id).useStatus(UseStatusEnum.FREE.getType()).build();
        positionMapItemMapper.updateById(item);
    }

    @Override
    public List<PositionMapItemDO> getPositionMapItemByMapAndType(Long mapId, Integer type) {
        return positionMapItemMapper.selectList(new LambdaQueryWrapperX<PositionMapItemDO>()
                .eq(PositionMapItemDO::getPositionMapId, mapId)
                .eq(PositionMapItemDO::getType, type)
                .orderByDesc(PositionMapItemDO::getId));
    }

    /**
     * 获取使用中的点位
     * @param idList
     * @return
     */
    @Override
    public List<PositionMapItemDO> getPositionMapItemByIds(List<Long> idList) {
        return positionMapItemMapper.selectList(new LambdaQueryWrapperX<PositionMapItemDO>()
                .in(PositionMapItemDO::getId, idList));
    }

    @Override
    public Long getUUid() {
        return IdUtil.getSnowflakeNextId();
    }

    /**
     * 根据排序查询区域变更点
     * @param sortNum
     * @return
     */
    @Override
    public List<PositionMapItemSaveReqVO> getItemBySortNum(Long sortNum) {
        List<PositionMapItemDO> positionMapItemDO = positionMapItemMapper.selectList(new LambdaQueryWrapperX<PositionMapItemDO>()
                .eqIfPresent(PositionMapItemDO::getType, PositionMapItemEnum.CHANGE.getType())
                .likeIfPresent(PositionMapItemDO::getSortNum, sortNum+""));
        if (ObjectUtil.isEmpty(positionMapItemDO)) {
            return null;
        }
        List<PositionMapItemSaveReqVO> bean = BeanUtils.toBean(positionMapItemDO, PositionMapItemSaveReqVO.class);
        return bean;
    }

    /**
     * 根据ID获取排序的MAP
     * @param itemIds
     * @return
     */
    @Override
    public Map<Long, Long> getSortNumMapByIds(List<Long> idList) {
        List<PositionMapItemDO> list = positionMapItemMapper.selectList(new LambdaQueryWrapperX<PositionMapItemDO>()
                .in(PositionMapItemDO::getId, idList));
        return list.stream().collect(Collectors.toMap(PositionMapItemDO::getId, PositionMapItemDO::getSortNum));
    }

    @Override
    public void deleteByMapId(Long mapId) {
        positionMapItemMapper.deleteByMapId(mapId);
    }

    /**
     * 校验此地图的交换点，有没有被其他地图绑定
     * @param mapId
     */
    @Override
    public void checkHaveBindChangePoint(Long mapId) {
        List<PositionMapItemDO> list = positionMapItemMapper.selectList(new LambdaQueryWrapperX<PositionMapItemDO>()
                .eq(PositionMapItemDO::getPositionMapId, mapId)
                .eq(PositionMapItemDO::getType,PositionMapItemEnum.CHANGE.getType()));
        if (ObjectUtil.isEmpty(list)) {
            return;
        }

        List<Long> ids = list.stream().map(PositionMapItemDO::getId).collect(Collectors.toList());

        List<PositionChangePointBindingDO> bindingList = positionChangePointBindingMapper.selectList(new LambdaQueryWrapperX<PositionChangePointBindingDO>()
                .ne(PositionChangePointBindingDO::getPositionMapId, mapId)
                .in(PositionChangePointBindingDO::getEndPointId, ids));

        if (ObjectUtil.isEmpty(bindingList)) {
            return;
        }

        List<Long> sortNums = bindingList.stream().map(PositionChangePointBindingDO::getStartingPointSortNum).collect(Collectors.toList());

        warnMsgService.sendWarnMsgToWebsocket(MAP_EXIST_TASK_EXIST_TASK.getMsg());
        RobotWarnMsgSaveReqVO warnMsgSaveReqVO = new RobotWarnMsgSaveReqVO();
        String locationStr = StringUtils.join(sortNums, ",");
        if (locationStr.length() > 160) {
            locationStr = locationStr.substring(0,160);
        }
        warnMsgSaveReqVO.setWarnMsg(MAP_EXIST_BINDING_POINT.getMsg()+locationStr);
        warnMsgSaveReqVO.setWarnLevel(4);
        warnMsgSaveReqVO.setWarnCode("MAP");
        warnMsgSaveReqVO.setSolveTime(LocalDateTime.now());
        warnMsgService.createWarnMsg(warnMsgSaveReqVO);
        throw exception(MAP_EXIST_BINDING_POINT);
    }

    @Override
    public PositionMapConfigDTO getCheckDistance() {
        PositionMapConfigDTO configDTO = new PositionMapConfigDTO();
        configDTO.setMapCheckDistance(znConfigConstant.getMapCheckDistance());
        configDTO.setMapArcOffset(znConfigConstant.getMapArcOffset());
        return configDTO;
    }

    @Override
    public void setMapItemUse(Long releaseId, String robotNo) {
        positionMapItemMapper.setMapItemUse(releaseId,robotNo);
    }

}
