package org.dromara.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.app.domain.AppWateringLog;
import org.dromara.app.domain.bo.AppWateringLogBo;
import org.dromara.app.domain.vo.AppWateringLogVo;
import org.dromara.app.mapper.AppWateringLogMapper;
import org.dromara.app.service.IAppWateringLogService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 浇水记录Service业务层处理
 *
 * @author Lion Li
 * @date 2026-04-25
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AppWateringLogServiceImpl implements IAppWateringLogService {

    private final AppWateringLogMapper baseMapper;

    /**
     * 查询浇水记录
     *
     * @param id 主键
     * @return 浇水记录
     */
    @Override
    public AppWateringLogVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询浇水记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 浇水记录分页列表
     */
    @Override
    public TableDataInfo<AppWateringLogVo> queryPageList(AppWateringLogBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppWateringLog> lqw = buildQueryWrapper(bo);
        Page<AppWateringLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的浇水记录列表
     *
     * @param bo 查询条件
     * @return 浇水记录列表
     */
    @Override
    public List<AppWateringLogVo> queryList(AppWateringLogBo bo) {
        LambdaQueryWrapper<AppWateringLog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppWateringLog> buildQueryWrapper(AppWateringLogBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppWateringLog> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(AppWateringLog::getId);
        lqw.eq(bo.getUserId() != null, AppWateringLog::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getDeviceNo()), AppWateringLog::getDeviceNo, bo.getDeviceNo());
        lqw.eq(StringUtils.isNotBlank(bo.getCommandId()), AppWateringLog::getCommandId, bo.getCommandId());
        lqw.eq(bo.getScheduleId() != null, AppWateringLog::getScheduleId, bo.getScheduleId());
        lqw.eq(bo.getStartTime() != null, AppWateringLog::getStartTime, bo.getStartTime());
        lqw.eq(bo.getEndTime() != null, AppWateringLog::getEndTime, bo.getEndTime());
        lqw.eq(StringUtils.isNotBlank(bo.getDurationMin()), AppWateringLog::getDurationMin, bo.getDurationMin());
        lqw.eq(StringUtils.isNotBlank(bo.getZones()), AppWateringLog::getZones, bo.getZones());
        lqw.eq(StringUtils.isNotBlank(bo.getTriggerType()), AppWateringLog::getTriggerType, bo.getTriggerType());
        lqw.like(StringUtils.isNotBlank(bo.getRemark()), AppWateringLog::getRemark, bo.getRemark());
      //  lqw.eq(bo.getCreateTime() != null, AppWateringLog::getCreateTime, bo.getCreateTime());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
                AppWateringLog::getCreateTime, params.get("beginTime"), params.get("endTime"));

        return lqw;
    }

    /**
     * 新增浇水记录
     *
     * @param bo 浇水记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(AppWateringLogBo bo) {
        AppWateringLog add = MapstructUtils.convert(bo, AppWateringLog.class);
        if (add.getScheduleId() == null) {
            add.setScheduleId(0L);
        }
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean saveEstimatedScheduleLog(AppWateringLogBo bo) {
        if (bo == null || StringUtils.isBlank(bo.getDeviceNo()) || bo.getScheduleId() == null || bo.getStartTime() == null) {
            return false;
        }
        if (existsScheduleLog(bo.getDeviceNo(), bo.getScheduleId(), bo.getStartTime())) {
            return false;
        }
        bo.setTriggerType("0");
        bo.setStatus("0");
        if (StringUtils.isBlank(bo.getRemark())) {
            bo.setRemark("设备离线，按排程自动补记");
        }
        return insertByBo(bo);
    }

    @Override
    public Boolean confirmScheduleLog(AppWateringLogBo bo) {
        if (bo == null || StringUtils.isBlank(bo.getDeviceNo()) || bo.getScheduleId() == null || bo.getStartTime() == null) {
            return insertByBo(bo);
        }

        AppWateringLog estimatedLog = baseMapper.selectOne(
            Wrappers.<AppWateringLog>lambdaQuery()
                .eq(AppWateringLog::getDeviceNo, bo.getDeviceNo())
                .eq(AppWateringLog::getScheduleId, bo.getScheduleId())
                .eq(AppWateringLog::getStartTime, bo.getStartTime())
                .eq(AppWateringLog::getTriggerType, "0")
                .like(AppWateringLog::getRemark, "自动补记")
                .last("limit 1")
        );
        if (estimatedLog == null) {
            AppWateringLog runningLog = findMatchingRunningScheduleLog(bo);
            if (runningLog != null) {
                AppWateringLog update = MapstructUtils.convert(bo, AppWateringLog.class);
                update.setId(runningLog.getId());
                return baseMapper.updateById(update) > 0;
            }
            AppWateringLog finishedLog = findMatchingFinishedLog(bo);
            if (finishedLog != null) {
                AppWateringLog update = MapstructUtils.convert(bo, AppWateringLog.class);
                update.setId(finishedLog.getId());
                return baseMapper.updateById(update) > 0;
            }
            if (existsScheduleLog(bo.getDeviceNo(), bo.getScheduleId(), bo.getStartTime())) {
                return true;
            }
            return insertByBo(bo);
        }

        AppWateringLog update = MapstructUtils.convert(bo, AppWateringLog.class);
        update.setId(estimatedLog.getId());
        update.setRemark("设备离线期间执行，联网后补传确认");
        return baseMapper.updateById(update) > 0;
    }

    private AppWateringLog findMatchingRunningScheduleLog(AppWateringLogBo bo) {
        if (bo.getStartTime() == null || StringUtils.isBlank(bo.getDurationMin()) || bo.getEndTime() == null) {
            return null;
        }
        return baseMapper.selectOne(
            Wrappers.<AppWateringLog>lambdaQuery()
                .eq(AppWateringLog::getDeviceNo, bo.getDeviceNo())
                .between(AppWateringLog::getStartTime, minuteStart(bo.getStartTime()), minuteEnd(bo.getStartTime()))
                .eq(StringUtils.isNotBlank(bo.getTriggerType()), AppWateringLog::getTriggerType, bo.getTriggerType())
           //     .between(AppWateringLog::getEndTime, minuteStart(bo.getEndTime()), minuteEnd(bo.getEndTime()))
                .eq(AppWateringLog::getStatus, "1")
                .last("limit 1")
        );
    }

    private AppWateringLog findMatchingFinishedLog(AppWateringLogBo bo) {
        if (bo.getStartTime() == null) {
            return null;
        }
        return baseMapper.selectOne(
            Wrappers.<AppWateringLog>lambdaQuery()
                .eq(AppWateringLog::getDeviceNo, bo.getDeviceNo())
                .between(AppWateringLog::getStartTime, minuteStart(bo.getStartTime()), minuteEnd(bo.getStartTime()))
                .eq(StringUtils.isNotBlank(bo.getTriggerType()), AppWateringLog::getTriggerType, bo.getTriggerType())
                .eq(AppWateringLog::getStatus, "0")
                .orderByDesc(AppWateringLog::getEndTime)
                .orderByDesc(AppWateringLog::getCreateTime)
                .orderByDesc(AppWateringLog::getId)
                .last("limit 1")
        );
    }

    private Date minuteStart(Date time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    private Date minuteEnd(Date time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    /**
     * 修改浇水记录
     *
     * @param bo 浇水记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(AppWateringLogBo bo) {
        AppWateringLog update = MapstructUtils.convert(bo, AppWateringLog.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    private boolean existsScheduleLog(String deviceNo, Long scheduleId, Date startTime) {
        return baseMapper.exists(
            Wrappers.<AppWateringLog>lambdaQuery()
                .eq(AppWateringLog::getDeviceNo, deviceNo)
                .eq(AppWateringLog::getScheduleId, scheduleId)
                .eq(AppWateringLog::getStartTime, startTime)
                .eq(AppWateringLog::getTriggerType, "0")
        );
    }

    @Override
    public Boolean finishManualLog(String deviceNo, Long userId, Date endTime) {
        return finishManualLog(deviceNo, userId, endTime, "手动停止浇水");
    }

    @Override
    public Boolean finishManualLog(String deviceNo, Long userId, Date endTime, String remark) {
        if (StringUtils.isBlank(deviceNo) || userId == null || endTime == null) {
            return false;
        }

        AppWateringLog activeLog = baseMapper.selectOne(
            Wrappers.<AppWateringLog>lambdaQuery()
                .eq(AppWateringLog::getDeviceNo, deviceNo)
                .eq(AppWateringLog::getUserId, userId)
                .eq(AppWateringLog::getTriggerType, "1")
                .isNull(AppWateringLog::getEndTime)
                .orderByDesc(AppWateringLog::getStartTime)
                .orderByDesc(AppWateringLog::getCreateTime)
                .orderByDesc(AppWateringLog::getId)
                .last("limit 1")
        );
        if (activeLog == null) {
            return false;
        }

        LambdaUpdateWrapper<AppWateringLog> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(AppWateringLog::getId, activeLog.getId())
            .isNull(AppWateringLog::getEndTime)
            .set(AppWateringLog::getEndTime, endTime)
            .set(StringUtils.isNotBlank(remark), AppWateringLog::getRemark, remark);
        if (activeLog.getStartTime() != null) {
            long durationMillis = endTime.getTime() - activeLog.getStartTime().getTime();
            long durationMin = Math.max(durationMillis, 0L) / 60000L;
            updateWrapper.set(AppWateringLog::getDurationMin, String.valueOf(durationMin));
        }
        return baseMapper.update(null, updateWrapper) > 0;
    }

    @Override
    public int finishRunningLogsByDevice(String deviceNo, Date endTime, String remark) {
        if (StringUtils.isBlank(deviceNo) || endTime == null) {
            return 0;
        }

        AppWateringLog activeLog = baseMapper.selectOne(
            Wrappers.<AppWateringLog>lambdaQuery()
                .eq(AppWateringLog::getDeviceNo, deviceNo)
                .eq(AppWateringLog::getStatus, "1")
                .orderByDesc(AppWateringLog::getStartTime)
                .orderByDesc(AppWateringLog::getCreateTime)
                .orderByDesc(AppWateringLog::getId)
                .last("limit 1")
        );
        if (activeLog == null) {
            return 0;
        }

        LambdaUpdateWrapper<AppWateringLog> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(AppWateringLog::getId, activeLog.getId())
            .set(AppWateringLog::getEndTime, endTime)
            .set(AppWateringLog::getStatus, "0")
            .set(StringUtils.isNotBlank(remark), AppWateringLog::getRemark, remark);
        if (activeLog.getStartTime() != null) {
            long durationMillis = endTime.getTime() - activeLog.getStartTime().getTime();
            long durationMin = Math.max(durationMillis, 0L) / 60000L;
            updateWrapper.set(AppWateringLog::getDurationMin, String.valueOf(durationMin));
        }
        return baseMapper.update(null, updateWrapper);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppWateringLog entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除浇水记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public Long queryCount(Long userId) {
        return baseMapper.selectCount(new QueryWrapper<AppWateringLog>().eq("user_id",userId));
    }

    @Override
    public Long queryByMonCount(Long userId) {

        return baseMapper.selectByMonCout(userId);
    }

    @Override
    public Long queryByWeekCount(Long userId) {

        return baseMapper.selectByWeekCount(userId);
    }

    @Override
    public Long queryByTriggerTypeCount(Long userId, String triggerType) {
        return baseMapper.selectByTriggerTypeCount(userId,triggerType);
    }


    @Override
    public Long queryByTotalWateringTime(Long userId) {
        return baseMapper.selectByTotalWateringTime(userId);
    }
}
