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.controller.screen.dto.HeLiuQuXian;
import com.ruoyi.web.domain.dto.lotEnvironment.LotEnvironmentAddRequest;
import com.ruoyi.web.domain.dto.lotEnvironment.LotEnvironmentEditRequest;
import com.ruoyi.web.domain.dto.lotEnvironment.LotEnvironmentQueryRequest;
import com.ruoyi.web.domain.entity.LotEnvironment;
import com.ruoyi.web.domain.vo.LotEnvironmentVO;
import com.ruoyi.web.mapper.LotEnvironmentMapper;
import com.ruoyi.web.service.LotEnvironmentService;
import org.springframework.beans.factory.annotation.Autowired;
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 LotEnvironmentServiceImpl extends ServiceImpl<LotEnvironmentMapper, LotEnvironment>
        implements LotEnvironmentService {

    /**
     * 添加
     *
     * @param lotEnvironmentAddRequest
     * @return
     */
    @Override
    public Integer addLotEnvironment(LotEnvironmentAddRequest lotEnvironmentAddRequest) {
        if (lotEnvironmentAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            // 转换为实体对象
            LotEnvironment lotEnvironment = new LotEnvironment();
            BeanUtil.copyProperties(lotEnvironmentAddRequest, lotEnvironment);
            //数据校验
            validLotEnvironment(lotEnvironment, BusinessType.INSERT);

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

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

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

    }

    /**
     * 编辑
     *
     * @param lotEnvironmentEditRequest
     */
    @Override
    public void editLotEnvironment(LotEnvironmentEditRequest lotEnvironmentEditRequest) {
        // 判断是否存在
        Integer id = lotEnvironmentEditRequest.getId();
        LotEnvironment oldLotEnvironment = this.getById(id);
        if (oldLotEnvironment == null) {
            throw new ServiceException("没有找到物联网人居环境监测数据");
        }
        LotEnvironment lotEnvironment = new LotEnvironment();
        BeanUtil.copyProperties(lotEnvironmentEditRequest, lotEnvironment);
        lotEnvironment.setUpdateTime(new Date());
        // 数据校验
        validLotEnvironment(lotEnvironment, BusinessType.UPDATE);
        // 操作数据库
        boolean result = this.updateById(lotEnvironment);
        if (!result) {
            throw new ServiceException("修改物联网人居环境监测操作失败");
        }
    }

    /**
     * 校验数据
     *
     * @param lotEnvironment
     */
    public void validLotEnvironment(LotEnvironment lotEnvironment, BusinessType type) {
        if (ObjectUtil.isEmpty(lotEnvironment)) {
            throw new ServiceException("数据为空");
        }
        // 从对象中取值
        Integer id = lotEnvironment.getId();
        String waterLevel = lotEnvironment.getWaterLevel();
        String temperature = lotEnvironment.getTemperature();
        String humidity = lotEnvironment.getHumidity();
        String rainfall = lotEnvironment.getRainfall();
        String windSpeed = lotEnvironment.getWindSpeed();
        String windDirection = lotEnvironment.getWindDirection();
        Date date = lotEnvironment.getDate();


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

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public LotEnvironmentVO getLotEnvironmentById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        LotEnvironment lotEnvironment = this.getById(id);
        return getLotEnvironmentVO(lotEnvironment);
    }

    /**
     * 获取人居环境监测包装类
     *
     * @param lotEnvironment
     * @return
     */
    @Override
    public LotEnvironmentVO getLotEnvironmentVO(LotEnvironment lotEnvironment) {
        if (ObjectUtil.isEmpty(lotEnvironment)) {
            throw new ServiceException("请求参数不存在");
        }
        LotEnvironmentVO lotEnvironmentVO = new LotEnvironmentVO();
        BeanUtils.copyProperties(lotEnvironment, lotEnvironmentVO);
        return lotEnvironmentVO;
    }

    /**
     * 分页获取人居环境监测列表
     *
     * @param lotEnvironmentQueryRequest
     * @return
     */
    @Override
    public Page<LotEnvironmentVO> getListLotEnvironmentByPage(LotEnvironmentQueryRequest lotEnvironmentQueryRequest) {
        long current = lotEnvironmentQueryRequest.getPageNum();
        long size = lotEnvironmentQueryRequest.getPageSize();
        Page<LotEnvironment> page = this.page(new Page<>(current, size),
                getQueryWrapper(lotEnvironmentQueryRequest));
        Page<LotEnvironmentVO> lotEnvironmentVOPage = new Page<>();
        BeanUtils.copyProperties(page, lotEnvironmentVOPage, "records");
        List<LotEnvironmentVO> voList = page.getRecords().stream()
                .map(lotEnvironment -> {
                    LotEnvironmentVO vo = new LotEnvironmentVO();
                    BeanUtils.copyProperties(lotEnvironment, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        lotEnvironmentVOPage.setRecords(voList);
        return lotEnvironmentVOPage;
    }

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

        // 从对象中取值
        Integer id = lotEnvironmentQueryRequest.getId();
        Date startTime = lotEnvironmentQueryRequest.getStartTime();
        Date endTime = lotEnvironmentQueryRequest.getEndTime();
        String sortField = lotEnvironmentQueryRequest.getSortField();
        String sortOrder = lotEnvironmentQueryRequest.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;
    }

    @Override
    public List<LotEnvironment> heLiuQuXian() {

        return this.list(new QueryWrapper<LotEnvironment>().orderByAsc("id").last("limit 50"));
    }
}




