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.drowningWarning.DrowningWarningAddRequest;
import com.ruoyi.web.domain.dto.warning.drowningWarning.DrowningWarningEditRequest;
import com.ruoyi.web.domain.dto.warning.drowningWarning.DrowningWarningQueryRequest;
import com.ruoyi.web.domain.entity.DrowningWarning;
import com.ruoyi.web.domain.vo.DrowningWarningVO;
import com.ruoyi.web.mapper.DrowningWarningMapper;
import com.ruoyi.web.service.DrowningWarningService;
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 DrowningWarningServiceImpl extends ServiceImpl<DrowningWarningMapper, DrowningWarning>
        implements DrowningWarningService {
    /**
     * 添加
     *
     * @param drowningWarningAddRequest
     * @return
     */
    @Override
    public Integer addDrowningWarning(DrowningWarningAddRequest drowningWarningAddRequest) {
        if (drowningWarningAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            // 转换为实体对象
            DrowningWarning drowningWarning = new DrowningWarning();
            BeanUtil.copyProperties(drowningWarningAddRequest, drowningWarning);
            //数据校验
            validDrowningWarning(drowningWarning, BusinessType.INSERT);

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

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

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

    }

    /**
     * 编辑
     *
     * @param drowningWarningEditRequest
     */
    @Override
    public void editDrowningWarning(DrowningWarningEditRequest drowningWarningEditRequest) {
        // 判断是否存在
        Integer id = drowningWarningEditRequest.getId();
        DrowningWarning oldDrowningWarning = this.getById(id);
        if (oldDrowningWarning == null) {
            throw new ServiceException("没有找到防溺水预警数据");
        }
        DrowningWarning drowningWarning = new DrowningWarning();
        BeanUtil.copyProperties(drowningWarningEditRequest, drowningWarning);
        drowningWarning.setUpdateTime(new Date());
        // 数据校验
        validDrowningWarning(drowningWarning, BusinessType.UPDATE);
        // 操作数据库
        boolean result = this.updateById(drowningWarning);
        if (!result) {
            throw new ServiceException("修改防溺水预警数据操作失败");
        }
    }

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

    /**
     * 获取防溺水预警包装类
     *
     * @param drowningWarning
     * @return
     */
    @Override
    public DrowningWarningVO getDrowningWarningVO(DrowningWarning drowningWarning) {
        if (ObjectUtil.isEmpty(drowningWarning)) {
            throw new ServiceException("请求参数不存在");
        }
        DrowningWarningVO drowningWarningVO = new DrowningWarningVO();
        BeanUtils.copyProperties(drowningWarning, drowningWarningVO);
        return drowningWarningVO;
    }

    /**
     * 分页获取防溺水预警列表
     *
     * @param drowningWarningQueryRequest
     * @return
     */
    @Override
    public Page<DrowningWarningVO> getListDrowningWarningByPage(DrowningWarningQueryRequest drowningWarningQueryRequest) {
        long current = drowningWarningQueryRequest.getPageNum();
        long size = drowningWarningQueryRequest.getPageSize();
        Page<DrowningWarning> page = this.page(new Page<>(current, size),
                getQueryWrapper(drowningWarningQueryRequest));
        Page<DrowningWarningVO> drowningWarningVOPage = new Page<>();
        BeanUtils.copyProperties(page, drowningWarningVOPage, "records");
        List<DrowningWarningVO> voList = page.getRecords().stream()
                .map(drowningWarning -> {
                    DrowningWarningVO vo = new DrowningWarningVO();
                    BeanUtils.copyProperties(drowningWarning, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        drowningWarningVOPage.setRecords(voList);
        return drowningWarningVOPage;
    }

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

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







