/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.coldchain.modular.targetroom.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.coldchain.modular.monitortarget.entity.MonitorTarget;
import vip.xiaonuo.coldchain.modular.monitortarget.service.MonitorTargetService;
import vip.xiaonuo.common.enums.CommonDeleteFlagEnum;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.coldchain.modular.targetroom.entity.TargetRoom;
import vip.xiaonuo.coldchain.modular.targetroom.mapper.TargetRoomMapper;
import vip.xiaonuo.coldchain.modular.targetroom.param.TargetRoomAddParam;
import vip.xiaonuo.coldchain.modular.targetroom.param.TargetRoomEditParam;
import vip.xiaonuo.coldchain.modular.targetroom.param.TargetRoomIdParam;
import vip.xiaonuo.coldchain.modular.targetroom.param.TargetRoomPageParam;
import vip.xiaonuo.coldchain.modular.targetroom.service.TargetRoomService;

import java.util.List;

/**
 * 房间配置Service接口实现类
 *
 * @author hyh
 * @date  2024/12/31 00:05
 **/
@Service
public class TargetRoomServiceImpl extends ServiceImpl<TargetRoomMapper, TargetRoom> implements TargetRoomService {

    @Resource
    private MonitorTargetService monitorTargetService;

    @Override
    public Page<TargetRoom> page(TargetRoomPageParam targetRoomPageParam) {
        SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
        QueryWrapper<TargetRoom> queryWrapper = new QueryWrapper<TargetRoom>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(targetRoomPageParam.getName())) {
            queryWrapper.lambda().like(TargetRoom::getName, targetRoomPageParam.getName());
        }
        queryWrapper.lambda().eq(TargetRoom::getCreateOrg, loginUser.getOrgId()).eq(TargetRoom::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE);
        if(ObjectUtil.isAllNotEmpty(targetRoomPageParam.getSortField(), targetRoomPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(targetRoomPageParam.getSortOrder());
            queryWrapper.orderBy(true, targetRoomPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(targetRoomPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(TargetRoom::getSortCode);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TargetRoomAddParam targetRoomAddParam) {
        SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
        if (ifRoomExist(targetRoomAddParam.getName())) {
            throw new CommonException("该房间名已存在！请重新输入");
        }
        TargetRoom targetRoom = BeanUtil.toBean(targetRoomAddParam, TargetRoom.class);
         this.save(targetRoom);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(TargetRoomEditParam targetRoomEditParam) {
        TargetRoom targetRoom = this.queryEntity(targetRoomEditParam.getId());
        if (ifRoomExist(targetRoomEditParam.getName())) {
            throw new CommonException("该房间名已存在！请重新输入");
        }
        BeanUtil.copyProperties(targetRoomEditParam, targetRoom);
        this.updateById(targetRoom);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<TargetRoomIdParam> targetRoomIdParamList) {
        for (TargetRoomIdParam targetRoomIdParam : targetRoomIdParamList) {
            List<MonitorTarget> targetListByRoom = monitorTargetService.getTargetListByRoom(targetRoomIdParam.getId());
            if (!targetListByRoom.isEmpty()) {
                throw new CommonException("该房间中存在冰箱，不可删除！");
            }
        }
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(targetRoomIdParamList, TargetRoomIdParam::getId));
    }

    @Override
    public TargetRoom detail(TargetRoomIdParam targetRoomIdParam) {
        return this.queryEntity(targetRoomIdParam.getId());
    }

    @Override
    public TargetRoom queryEntity(String id) {
        TargetRoom targetRoom = this.getById(id);
        if(ObjectUtil.isEmpty(targetRoom)) {
            throw new CommonException("房间配置不存在，id值为：{}", id);
        }
        return targetRoom;
    }

    @Override
    public List<TargetRoom> myList() {
        SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
        LambdaQueryWrapper<TargetRoom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TargetRoom::getCreateOrg,loginUser.getOrgId())
                .eq(TargetRoom::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE)
                .orderByAsc(TargetRoom::getSortCode);
        List<TargetRoom> list = list(queryWrapper);
        list.forEach(targetRoom -> {
            targetRoom.setRegionCount(monitorTargetService.getTargetCount(null,targetRoom.getId()).getTotal());
        });
        return list;
    }

    @Override
    public Boolean ifRoomExist(String roomName) {
        SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
        LambdaQueryWrapper<TargetRoom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TargetRoom::getCreateOrg,loginUser.getOrgId())
                .eq(TargetRoom::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE)
                .eq(TargetRoom::getName, roomName);
        List<TargetRoom> list = list(queryWrapper);
        return !list.isEmpty();
    }

    @Override
    public TargetRoom getRoomByName(String roomName) {
        SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
        LambdaQueryWrapper<TargetRoom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TargetRoom::getCreateOrg,loginUser.getOrgId())
                .eq(TargetRoom::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE)
                .eq(TargetRoom::getName, roomName);
        return getOne(queryWrapper);
    }
}
