package com.ruoyi.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.web.domain.dto.environmentWarningThreshold.EnvironmentWarningThresholdAddRequest;
import com.ruoyi.web.domain.dto.environmentWarningThreshold.EnvironmentWarningThresholdEditRequest;
import com.ruoyi.web.domain.dto.environmentWarningThreshold.EnvironmentWarningThresholdQueryRequest;
import com.ruoyi.web.domain.entity.EnvironmentWarningThreshold;
import com.ruoyi.web.domain.entity.EnvironmentWarningThresholdRole;
import com.ruoyi.web.domain.vo.EnvironmentWarningThresholdVO;
import com.ruoyi.web.mapper.EnvironmentWarningThresholdMapper;
import com.ruoyi.web.service.EnvironmentWarningThresholdRoleService;
import com.ruoyi.web.service.EnvironmentWarningThresholdService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class EnvironmentWarningThresholdServiceImpl extends ServiceImpl<EnvironmentWarningThresholdMapper, EnvironmentWarningThreshold>
        implements EnvironmentWarningThresholdService {

    @Resource
    private EnvironmentWarningThresholdRoleService environmentWarningThresholdRoleService;

    /**
     * 添加
     *
     * @param environmentWarningThresholdAddRequest
     * @return
     */
    @Override
    public Integer addEnvironmentWarningThreshold(EnvironmentWarningThresholdAddRequest environmentWarningThresholdAddRequest) {
        if (environmentWarningThresholdAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            // 转换为实体对象
            EnvironmentWarningThreshold environmentWarningThreshold = new EnvironmentWarningThreshold();
            BeanUtil.copyProperties(environmentWarningThresholdAddRequest, environmentWarningThreshold);
            //数据校验
            validEnvironmentWarningThreshold(environmentWarningThreshold, BusinessType.INSERT);

            // 保存到数据库
            this.save(environmentWarningThreshold);
            return environmentWarningThreshold.getId();
        } catch (Exception e) {
            log.error("添加失败", e);
            throw new ServiceException("添加失败");
        }
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public boolean deleteEnvironmentWarningThreshold(String ids) {
        if (StrUtil.isBlank(ids)) {
            throw new ServiceException("id不能为空或id异常");
        }

        // 2. 分割ID字符串为List<Integer>
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .map(Long::parseLong)
                .collect(Collectors.toList());

        if (idList.isEmpty()) {
            throw new ServiceException("ID格式异常");
        }

        // 3. 构建删除条件
        QueryWrapper<EnvironmentWarningThreshold> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);

        // 4. 执行删除（返回是否删除成功）
        return remove(queryWrapper);

    }

    /**
     * 编辑
     *
     * @param environmentWarningThresholdEditRequest
     */
    @Override
    public void editEnvironmentWarningThreshold(EnvironmentWarningThresholdEditRequest environmentWarningThresholdEditRequest) {
        // 判断是否存在
        Integer id = environmentWarningThresholdEditRequest.getId();
        EnvironmentWarningThreshold oldEnvironmentWarningThreshold = this.getById(id);
        if (oldEnvironmentWarningThreshold == null) {
            throw new ServiceException("没有找到人居环境预警阈值");
        }
        EnvironmentWarningThreshold environmentWarningThreshold = new EnvironmentWarningThreshold();
        BeanUtil.copyProperties(environmentWarningThresholdEditRequest, environmentWarningThreshold);
        environmentWarningThreshold.setUpdateTime(new Date());
        // 数据校验
        validEnvironmentWarningThreshold(environmentWarningThreshold, BusinessType.UPDATE);
        // 操作数据库
        boolean result = this.updateById(environmentWarningThreshold);
        if (!result) {
            throw new ServiceException("修改人居环境预警阈值操作失败");
        }
    }

    /**
     * 校验数据
     *
     * @param environmentWarningThreshold
     */
    public void validEnvironmentWarningThreshold(EnvironmentWarningThreshold environmentWarningThreshold, BusinessType type) {
        if (ObjectUtil.isEmpty(environmentWarningThreshold)) {
            throw new ServiceException("数据为空");
        }
        // 从对象中取值
        Integer id = environmentWarningThreshold.getId();
        String typeId = environmentWarningThreshold.getTypeId();
        Integer level = environmentWarningThreshold.getLevel();
        String low = environmentWarningThreshold.getLow();
        String high = environmentWarningThreshold.getHigh();

        // 添加id无需校验，修改时，id 不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(typeId)) {
            throw new ServiceException("环境类型不能为空");
        }
        if (ObjectUtil.isEmpty(level)) {
            throw new ServiceException("等级不能为空");
        }
        if (StrUtil.isBlank(low)) {
            throw new ServiceException("下限不能为空");
        }
        if (StrUtil.isBlank(high)) {
            throw new ServiceException("上限不能为空");
        }
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public EnvironmentWarningThresholdVO getEnvironmentWarningThresholdById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        EnvironmentWarningThreshold environmentWarningThreshold = this.getById(id);
        return getEnvironmentWarningThresholdVO(environmentWarningThreshold);
    }

    /**
     * 获取包装类
     *
     * @param environmentWarningThreshold
     * @return
     */
    @Override
    public EnvironmentWarningThresholdVO getEnvironmentWarningThresholdVO(EnvironmentWarningThreshold environmentWarningThreshold) {
        if (ObjectUtil.isEmpty(environmentWarningThreshold)) {
            throw new ServiceException("请求参数不存在");
        }
        EnvironmentWarningThresholdVO environmentWarningThresholdVO = new EnvironmentWarningThresholdVO();
        BeanUtils.copyProperties(environmentWarningThreshold, environmentWarningThresholdVO);
        String typeId = environmentWarningThreshold.getTypeId();
        QueryWrapper<EnvironmentWarningThresholdRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type_id", typeId);
        EnvironmentWarningThresholdRole one = environmentWarningThresholdRoleService.getOne(queryWrapper);
        String type = one.getType();
        environmentWarningThresholdVO.setType(type);
        return environmentWarningThresholdVO;
    }


    /**
     * 分页获取列表
     *
     * @param environmentWarningThresholdQueryRequest
     * @return
     */
    @Override
    public List<EnvironmentWarningThresholdVO> getListEnvironmentWarningThreshold(EnvironmentWarningThresholdQueryRequest environmentWarningThresholdQueryRequest) {

        if (environmentWarningThresholdQueryRequest == null) {
            throw new ServiceException("请求参数不能为空");
        }
        Integer id = environmentWarningThresholdQueryRequest.getId();
        String typeId = environmentWarningThresholdQueryRequest.getTypeId();

        QueryWrapper<EnvironmentWarningThreshold> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjectUtil.isNotEmpty(id),"id",id)
                .eq(StrUtil.isNotEmpty(typeId),"type_id",typeId);
        List<EnvironmentWarningThreshold> list = this.list(queryWrapper);
        return list.stream().map(this::getEnvironmentWarningThresholdVO).collect(Collectors.toList());
    }

}




