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

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.system.constant.CommonConstant;
import cn.iocoder.yudao.module.system.controller.admin.houselocation.vo.*;
import cn.iocoder.yudao.module.system.controller.admin.log.vo.UserOperationLogSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.houselocation.WareHouseLocationDO;
import cn.iocoder.yudao.module.system.dal.dataobject.houselocation.WareHouseTakePointDO;
import cn.iocoder.yudao.module.system.dal.mysql.houselocation.WareHouseLocationMapper;
import cn.iocoder.yudao.module.system.enums.robot.LocationEnableEnum;
import cn.iocoder.yudao.module.system.enums.robot.LocationLockEnum;
import cn.iocoder.yudao.module.system.enums.robot.LocationUseStatusEnum;
import cn.iocoder.yudao.module.system.enums.robot.ReleaseTakeEnum;
import cn.iocoder.yudao.module.system.enums.robot.task.RobotTakeEnum;
import cn.iocoder.yudao.module.system.service.log.UserOperationLogService;
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.List;
import java.util.Map;
import java.util.function.Function;
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.HOUSE_LOCATION_NOT_EXISTS;

/**
 * 库位 Service 实现类
 *
 * @author 陈宾顺
 */
@Service
@Validated
public class HouseLocationServiceImpl extends ServiceImpl<WareHouseLocationMapper, WareHouseLocationDO> implements HouseLocationService {

    @Resource
    private WareHouseLocationMapper houseLocationMapper;

    @Resource
    private UserOperationLogService userOperationLogService;

    @Resource
    private WareHouseTakePointService houseTakePointService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createHouseLocation(WareHouseLocationSaveReqVO createReqVO) {
        // 插入
        WareHouseLocationDO houseLocation = BeanUtils.toBean(createReqVO, WareHouseLocationDO.class);
        houseLocationMapper.insert(houseLocation);
        // 返回
        return houseLocation.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateHouseLocation(WareHouseLocationSaveReqVO updateReqVO) {
        // 校验存在
        validateHouseLocationExists(updateReqVO.getId());

        WareHouseLocationDO wareHouseLocationDO = houseLocationMapper.selectById(updateReqVO.getId());
        // 更新
        WareHouseLocationDO updateObj = BeanUtils.toBean(updateReqVO, WareHouseLocationDO.class);

        houseLocationMapper.updateById(updateObj);

        String str = getChangeInfo(wareHouseLocationDO, updateObj);

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

        str = "修改库位信息:" + updateReqVO.getLocationNo() + CommonConstant.SYMBOL + str;

        UserOperationLogSaveReqVO operationLog = UserOperationLogSaveReqVO.builder()
                .operateAction(str)
                .nickName(SecurityFrameworkUtils.getLoginUserNickname()).build();
        userOperationLogService.createUserOperationLog(operationLog);
    }

    public String getChangeInfo(WareHouseLocationDO wareHouseLocationDO, WareHouseLocationDO updateReqVO) {
        String str = "";
        if (!wareHouseLocationDO.getLocationEnable().equals(updateReqVO.getLocationEnable())) {
            if (LocationEnableEnum.YES.getType().equals(updateReqVO.getLocationEnable())) {
                str = str + " 设置库位" + LocationEnableEnum.YES.getMsg() + " ";
            } else {
                str = str + " 设置库位" + LocationEnableEnum.NO.getMsg() + " ";
            }
        }
        if (!wareHouseLocationDO.getLocationUseStatus().equals(updateReqVO.getLocationUseStatus())) {
            if (LocationUseStatusEnum.YES.getType().equals(updateReqVO.getLocationUseStatus())) {
                str = str + " 设置库位" + LocationUseStatusEnum.YES.getMsg() + " ";
            } else {
                str = str + " 设置库位" + LocationUseStatusEnum.NO.getMsg() + " ";
            }
        }

        if (ObjectUtil.isNotEmpty(updateReqVO.getSkuInfo()) && ObjectUtil.isNotEmpty(wareHouseLocationDO.getSkuInfo())
                && !wareHouseLocationDO.getSkuInfo().equals(updateReqVO.getSkuInfo())) {
            str = str + " 设置库位物料信息 " + wareHouseLocationDO.getSkuInfo();
        } else if (ObjectUtil.isNotEmpty(updateReqVO.getSkuInfo()) && ObjectUtil.isNotEmpty(wareHouseLocationDO.getSkuInfo())
                && wareHouseLocationDO.getSkuInfo().equals(updateReqVO.getSkuInfo())) {

        } else if (ObjectUtil.isEmpty(updateReqVO.getSkuInfo()) && ObjectUtil.isNotEmpty(wareHouseLocationDO.getSkuInfo())) {
            str = str + " 设置库位物料信息为空";
        } else if (ObjectUtil.isNotEmpty(updateReqVO.getSkuInfo()) && ObjectUtil.isEmpty(wareHouseLocationDO.getSkuInfo())) {
            str = str + " 设置库位物料信息为 " + updateReqVO.getSkuInfo();
        }

        if (!wareHouseLocationDO.getLocationLock().equals(updateReqVO.getLocationLock())
                && LocationLockEnum.NO.getType().equals(updateReqVO.getLocationLock())) {
            str = str + " 设置库位锁定状态为锁定";
        } else if (!wareHouseLocationDO.getLocationLock().equals(updateReqVO.getLocationLock())
                && LocationLockEnum.YES.getType().equals(updateReqVO.getLocationLock())) {
            str = str + " 设置库位锁定状态为正常";
        }

        return str;
    }

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

    private void validateHouseLocationExists(Long id) {
        if (houseLocationMapper.selectById(id) == null) {
            throw exception(HOUSE_LOCATION_NOT_EXISTS);
        }
    }

    @Override
    public WareHouseLocationDO getHouseLocation(Long id) {
        return houseLocationMapper.selectById(id);
    }

    @Override
    public PageResult<WareHouseLocationDO> getHouseLocationPage(WareHouseLocationPageReqVO pageReqVO) {
        return houseLocationMapper.selectPage(pageReqVO);
    }

    @Override
    public List<WareHouseLocationRespVO> getLocationByName(WareHouseLocationVO requestVO) {
        if (RobotTakeEnum.TO_LOCATION.getType().equals(requestVO.getType())
                || RobotTakeEnum.TO_LANE.getType().equals(requestVO.getType())
                || RobotTakeEnum.TO_LINE_POINT.getType().equals(requestVO.getType())
                || RobotTakeEnum.TO_AREA.getType().equals(requestVO.getType())) {
            return houseLocationMapper.getLocationByName(requestVO);
        } else if (RobotTakeEnum.TO_POINT.getType().equals(requestVO.getType())) {
            WareHouseTakePointSaveReqVO reqVO = new WareHouseTakePointSaveReqVO();
            reqVO.setPointName(requestVO.getLocationNo());
            List<WareHouseTakePointDO> houseTakePointList = houseTakePointService.getHouseTakePointList(reqVO);
            if (ObjectUtil.isEmpty(houseTakePointList)) {
                return null;
            }
            List<WareHouseLocationRespVO> list = new ArrayList<>();
            for (WareHouseTakePointDO wareHouseTakePointDO : houseTakePointList) {
                WareHouseLocationRespVO houseLocationRespVO = new WareHouseLocationRespVO();
                houseLocationRespVO.setId(wareHouseTakePointDO.getId());
                houseLocationRespVO.setLocationNo(wareHouseTakePointDO.getPointName());
                list.add(houseLocationRespVO);
            }
            return list;
        }
        return null;
    }

    @Override
    public List<WareHouseLocationDO> getByMapItemId(Long mapId, Long mapItemId) {
        return houseLocationMapper.selectList(new LambdaQueryWrapper<WareHouseLocationDO>()
                .eq(WareHouseLocationDO::getMapId, mapId)
                .eq(WareHouseLocationDO::getMapItemId, mapItemId));
    }

    @Override
    public List<WareHouseLocationDO> getLocationByLocationNumbers(List<Long> locationNumbers) {
        return houseLocationMapper.selectList(new LambdaQueryWrapper<WareHouseLocationDO>()
                .in(WareHouseLocationDO::getLocationNumber, locationNumbers));
    }

    @Override
    public void updateLocationLaneNameByLaneId(Long laneId, String laneName) {
        houseLocationMapper.updateLocationLaneNameByLaneId(laneId, laneName);
    }

    @Override
    public void updateLocationLaneNameEmptyByLaneId(Long laneId) {
        houseLocationMapper.updateLocationLaneNameEmptyByLaneId(laneId);
    }

    @Override
    public void updateLocationAreaNameEmptyByAreaId(Long areaId) {
        houseLocationMapper.updateLocationAreaNameEmptyByAreaId(areaId);
    }

    /**
     * 获取这个地图对应的库位和坐标信息
     *
     * @param mapId
     * @return
     */
    @Override
    public List<WareHouseLocationItemRespVO> getLocationsXYByMapId(Long mapId) {
        return houseLocationMapper.getLocationsXYByMapId(mapId);
    }

    @Override
    public void deleteHouseLocationByMapId(Long mapId) {
        houseLocationMapper.deleteHouseLocationByMapId(mapId);
    }

    /**
     * 查询有货或者有锁定的库位
     *
     * @param mapId
     * @return
     */
    @Override
    public List<WareHouseLocationDO> getInStockLockLocationByMapId(Long mapId) {
        return houseLocationMapper.getInStockLockLocationByMapId(mapId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateHouseLocationList(List<WareHouseLocationSaveReqVO> list) {
        List<WareHouseLocationDO> locationDOList = BeanUtils.toBean(list, WareHouseLocationDO.class);
        List<String> locationNos = locationDOList.stream().map(WareHouseLocationDO::getLocationNo).collect(Collectors.toList());
        List<WareHouseLocationDO> locations = houseLocationMapper.selectList(new LambdaQueryWrapper<WareHouseLocationDO>()
                .in(WareHouseLocationDO::getLocationNo, locationNos));
        Map<Long, WareHouseLocationDO> locationMap =
                locations.stream().collect(Collectors.toMap(WareHouseLocationDO::getId, Function.identity(), (v1, v2) -> v1));

        houseLocationMapper.updateById(locationDOList);

        StringBuilder str = new StringBuilder();
        for (WareHouseLocationDO updateLocation : locationDOList) {
            WareHouseLocationDO oldLocation = locationMap.get(updateLocation.getId());
            if (ObjectUtil.isEmpty(oldLocation)) {
                continue;
            }
            String updateStr = getChangeInfo(oldLocation, updateLocation);
            if (ObjectUtil.isNotEmpty(updateStr)) {
                str.append("修改库位信息:").append(oldLocation.getLocationNo()).append("_").append(updateStr).append(";");
            }
        }

        if (ObjectUtil.isEmpty(str.toString())) {
            return;
        }

        if (str.length() > 100) {
            str = new StringBuilder(str.substring(0, 95));
        }

        UserOperationLogSaveReqVO operationLog = UserOperationLogSaveReqVO.builder()
                .operateAction(str.toString())
                .nickName(SecurityFrameworkUtils.getLoginUserNickname()).build();
        userOperationLogService.createUserOperationLog(operationLog);
    }

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

    @Override
    public List<WareHouseLocationDO> getByMapId(Long positionMapId) {
        return houseLocationMapper.selectList(new LambdaQueryWrapperX<WareHouseLocationDO>()
                .eq(WareHouseLocationDO::getMapId, positionMapId));
    }

}
