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.earthquakeWarning.EarthquakeWarningAddRequest;
import com.ruoyi.web.domain.dto.warning.earthquakeWarning.EarthquakeWarningEditRequest;
import com.ruoyi.web.domain.dto.warning.earthquakeWarning.EarthquakeWarningQueryRequest;
import com.ruoyi.web.domain.entity.EarthquakeWarning;
import com.ruoyi.web.domain.vo.EarthquakeWarningVO;
import com.ruoyi.web.mapper.EarthquakeWarningMapper;
import com.ruoyi.web.service.EarthquakeWarningService;
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 EarthquakeWarningServiceImpl extends ServiceImpl<EarthquakeWarningMapper, EarthquakeWarning>
        implements EarthquakeWarningService {
    /**
     * 添加
     *
     * @param earthquakeWarningAddRequest
     * @return
     */
    @Override
    public Integer addEarthquakeWarning(EarthquakeWarningAddRequest earthquakeWarningAddRequest) {
        if (earthquakeWarningAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            // 转换为实体对象
            EarthquakeWarning earthquakeWarning = new EarthquakeWarning();
            BeanUtil.copyProperties(earthquakeWarningAddRequest, earthquakeWarning);
            //数据校验
            validEarthquakeWarning(earthquakeWarning, BusinessType.INSERT);

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

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

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

    }

    /**
     * 编辑
     *
     * @param earthquakeWarningEditRequest
     */
    @Override
    public void editEarthquakeWarning(EarthquakeWarningEditRequest earthquakeWarningEditRequest) {
        // 判断是否存在
        Integer id = earthquakeWarningEditRequest.getId();
        EarthquakeWarning oldEarthquakeWarning = this.getById(id);
        if (oldEarthquakeWarning == null) {
            throw new ServiceException("没有找到地震监测预警数据");
        }
        EarthquakeWarning earthquakeWarning = new EarthquakeWarning();
        BeanUtil.copyProperties(earthquakeWarningEditRequest, earthquakeWarning);
        earthquakeWarning.setUpdateTime(new Date());
        // 数据校验
        validEarthquakeWarning(earthquakeWarning, BusinessType.UPDATE);
        // 操作数据库
        boolean result = this.updateById(earthquakeWarning);
        if (!result) {
            throw new ServiceException("修改地震监测预警数据操作失败");
        }
    }

    /**
     * 校验数据
     *
     * @param earthquakeWarning
     */
    public void validEarthquakeWarning(EarthquakeWarning earthquakeWarning, BusinessType type) {
        if (ObjectUtil.isEmpty(earthquakeWarning)) {
            throw new ServiceException("数据为空");
        }
        // 从对象中取值
        Integer id = earthquakeWarning.getId();
        String location = earthquakeWarning.getLocation();
        String content = earthquakeWarning.getContent();
        Date date = earthquakeWarning.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 EarthquakeWarningVO getEarthquakeWarningById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        EarthquakeWarning earthquakeWarning = this.getById(id);
        return getEarthquakeWarningVO(earthquakeWarning);
    }

    /**
     * 获取地震监测预警包装类
     *
     * @param earthquakeWarning
     * @return
     */
    @Override
    public EarthquakeWarningVO getEarthquakeWarningVO(EarthquakeWarning earthquakeWarning) {
        if (ObjectUtil.isEmpty(earthquakeWarning)) {
            throw new ServiceException("请求参数不存在");
        }
        EarthquakeWarningVO earthquakeWarningVO = new EarthquakeWarningVO();
        BeanUtils.copyProperties(earthquakeWarning, earthquakeWarningVO);
        return earthquakeWarningVO;
    }

    /**
     * 分页获取地震监测预警列表
     *
     * @param earthquakeWarningQueryRequest
     * @return
     */
    @Override
    public Page<EarthquakeWarningVO> getListEarthquakeWarningByPage(EarthquakeWarningQueryRequest earthquakeWarningQueryRequest) {
        long current = earthquakeWarningQueryRequest.getPageNum();
        long size = earthquakeWarningQueryRequest.getPageSize();
        Page<EarthquakeWarning> page = this.page(new Page<>(current, size),
                getQueryWrapper(earthquakeWarningQueryRequest));
        Page<EarthquakeWarningVO> earthquakeWarningVOPage = new Page<>();
        BeanUtils.copyProperties(page, earthquakeWarningVOPage, "records");
        List<EarthquakeWarningVO> voList = page.getRecords().stream()
                .map(earthquakeWarning -> {
                    EarthquakeWarningVO vo = new EarthquakeWarningVO();
                    BeanUtils.copyProperties(earthquakeWarning, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        earthquakeWarningVOPage.setRecords(voList);
        return earthquakeWarningVOPage;
    }

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

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




