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.plugins.pagination.Page;
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.warning.environmentWarning.EnvironmentWarningAddRequest;
import com.ruoyi.web.domain.dto.warning.environmentWarning.EnvironmentWarningEditRequest;
import com.ruoyi.web.domain.dto.warning.environmentWarning.EnvironmentWarningQueryRequest;
import com.ruoyi.web.domain.entity.EnvironmentWarning;
import com.ruoyi.web.domain.vo.EnvironmentWarningVO;
import com.ruoyi.web.mapper.EnvironmentWarningMapper;
import com.ruoyi.web.service.EnvironmentWarningService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class EnvironmentWarningServiceImpl extends ServiceImpl<EnvironmentWarningMapper, EnvironmentWarning>
        implements EnvironmentWarningService {


    /**
     * 添加
     *
     * @param environmentWarningAddRequest
     * @return
     */
    @Override
    public Integer addEnvironmentWarning(EnvironmentWarningAddRequest environmentWarningAddRequest) {
        if (environmentWarningAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            // 转换为实体对象
            EnvironmentWarning environmentWarning = new EnvironmentWarning();
            BeanUtil.copyProperties(environmentWarningAddRequest, environmentWarning);
            //数据校验
            validEnvironmentWarning(environmentWarning, BusinessType.INSERT);

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

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public boolean deleteEnvironmentWarning(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<EnvironmentWarning> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);

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

    }

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

    /**
     * 校验数据
     *
     * @param environmentWarning
     */
    public void validEnvironmentWarning(EnvironmentWarning environmentWarning, BusinessType type) {
        if (ObjectUtil.isEmpty(environmentWarning)) {
            throw new ServiceException("数据为空");
        }
        // 从对象中取值
        Integer id = environmentWarning.getId();
        String location = environmentWarning.getLocation();
        String content = environmentWarning.getContent();
        Date date = environmentWarning.getDate();


        // 添加id无需校验，修改时，id 不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
//        if (StrUtil.isBlank(location)) {
//            throw new ServiceException("位置不能为空");
//        }
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public EnvironmentWarningVO getEnvironmentWarningById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        EnvironmentWarning environmentWarning = this.getById(id);
        return getEnvironmentWarningVO(environmentWarning);
    }

    /**
     * 获取包装类
     *
     * @param environmentWarning
     * @return
     */
    @Override
    public EnvironmentWarningVO getEnvironmentWarningVO(EnvironmentWarning environmentWarning) {
        if (ObjectUtil.isEmpty(environmentWarning)) {
            throw new ServiceException("请求参数不存在");
        }
        EnvironmentWarningVO environmentWarningVO = new EnvironmentWarningVO();
        BeanUtils.copyProperties(environmentWarning, environmentWarningVO);
        return environmentWarningVO;
    }


    /**
     * 分页获列表
     *
     * @param environmentWarningQueryRequest
     * @return
     */
    @Override
    public Page<EnvironmentWarningVO> getListEnvironmentWarningByPage(EnvironmentWarningQueryRequest environmentWarningQueryRequest) {
        long current = environmentWarningQueryRequest.getPageNum();
        long size = environmentWarningQueryRequest.getPageSize();
        Page<EnvironmentWarning> page = this.page(new Page<>(current, size),
                getQueryWrapper(environmentWarningQueryRequest));
        Page<EnvironmentWarningVO> environmentWarningVOPage = new Page<>();
        BeanUtils.copyProperties(page, environmentWarningVOPage, "records");
        List<EnvironmentWarningVO> voList = page.getRecords().stream()
                .map(environmentWarning -> {
                    EnvironmentWarningVO vo = new EnvironmentWarningVO();
                    BeanUtils.copyProperties(environmentWarning, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        environmentWarningVOPage.setRecords(voList);
        return environmentWarningVOPage;
    }

    /**
     * 获取查询条件
     *
     * @param environmentWarningQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<EnvironmentWarning> getQueryWrapper(EnvironmentWarningQueryRequest environmentWarningQueryRequest) {
        QueryWrapper<EnvironmentWarning> queryWrapper = new QueryWrapper<>();
        if (environmentWarningQueryRequest == null) {
            return queryWrapper;
        }

        // 从对象中取值
        Integer id = environmentWarningQueryRequest.getId();
        Date startTime = environmentWarningQueryRequest.getStartTime();
        Date endTime = environmentWarningQueryRequest.getEndTime();
        String sortField = environmentWarningQueryRequest.getSortField();
        String sortOrder = environmentWarningQueryRequest.getSortOrder();


        queryWrapper.eq(ObjectUtil.isNotEmpty(id), "id", id);

        // 日期范围查询（优先判断范围）
        if (startTime != null && endTime != null) {
            queryWrapper.between("date", startTime, endTime);
        } else if (startTime != null) {
            queryWrapper.ge("date", startTime); // >= 开始日期
        } else if (endTime != null) {
            queryWrapper.le("date", endTime);   // <= 结束日期
        }

        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), "ascend".equals(sortOrder), sortField);
        return queryWrapper;
    }
}