package org.dromara.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.domain.bo.TblSensorRecordBo;
import org.dromara.domain.vo.TblSensorRecordVo;
import org.dromara.domain.TblSensorRecord;
import org.dromara.mapper.TblSensorRecordMapper;
import org.dromara.service.ITblSensorRecordService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 传感器实时数据Service业务层处理
 *
 * @author Lion Li
 * @date 2024-08-11
 */
@RequiredArgsConstructor
@Service
public class TblSensorRecordServiceImpl implements ITblSensorRecordService {

    private final TblSensorRecordMapper baseMapper;

    @Override
    public void createTable(Map<String, Object> map) {
        baseMapper.createTable(map);
    }

    /**
     * 查询传感器实时数据
     *
     * @param id 主键
     * @return 传感器实时数据
     */
    @Override
    public TblSensorRecordVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询传感器实时数据列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 传感器实时数据分页列表
     */
    @Override
    public TableDataInfo<TblSensorRecordVo> queryPageList(TblSensorRecordBo bo, PageQuery pageQuery) {
//        LambdaQueryWrapper<TblSensorRecord> lqw = buildQueryWrapper(bo);
//        Page<TblSensorRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
//        return TableDataInfo.build(result);
        if(bo.getParams()!=null){
            String startTime =  bo.getParams().get("startTime").toString();
            String endTime =  bo.getParams().get("endTime").toString();
            Date startTime1  = DateUtil.date(Long.parseLong(startTime)*1000);
            Date endTime1  = DateUtil.date(Long.parseLong(endTime)*1000);

            bo.getParams().put("startTime",DateUtil.format(startTime1,"yyyy-MM-dd HH:mm:ss"));
            bo.getParams().put("endTime",DateUtil.format(endTime1,"yyyy-MM-dd HH:mm:ss"));

            //计算月
            List<DateTime> dateList =DateUtil.rangeToList(startTime1,endTime1, DateField.MONTH);
            bo.getParams().put("datetimes",dateList.stream().map(date -> DateUtil.format(date,"yyyy_MM")).collect(Collectors.toList()));

        }

        TblSensorRecord r = new TblSensorRecord();
        r.setParams(bo.getParams());
        r.setId(bo.getId());
        r.setSensorId(bo.getSensorId());
        r.setPointName(bo.getPointName());
        r.setPointValue(bo.getPointValue());
        r.setCreateBy(bo.getCreateBy());
        r.setCreateDept(bo.getCreateDept());
        Page<TblSensorRecordVo> result = (Page<TblSensorRecordVo>) baseMapper.selectDataPage(pageQuery.build(),r);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的传感器实时数据列表
     *
     * @param bo 查询条件
     * @return 传感器实时数据列表
     */
    @Override
    public List<TblSensorRecordVo> queryList(TblSensorRecordBo bo) {
//        LambdaQueryWrapper<TblSensorRecord> lqw = buildQueryWrapper(bo);
//        Page<TblSensorRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
//        return TableDataInfo.build(result);
            if(bo.getParams()!=null){
                String startTime =  bo.getParams().get("startTime").toString();
                String endTime =  bo.getParams().get("endTime").toString();
                Date startTime1  = DateUtil.date(Long.parseLong(startTime)*1000);
                Date endTime1  = DateUtil.date(Long.parseLong(endTime)*1000);

                bo.getParams().put("startTime",DateUtil.format(startTime1,"yyyy-MM-dd HH:mm:ss"));
                bo.getParams().put("endTime",DateUtil.format(endTime1,"yyyy-MM-dd HH:mm:ss"));

                //计算月
                List<DateTime> dateList =DateUtil.rangeToList(startTime1,endTime1, DateField.MONTH);
                bo.getParams().put("datetimes",dateList.stream().map(date -> DateUtil.format(date,"yyyy_MM")).collect(Collectors.toList()));

            }
            TblSensorRecord r = new TblSensorRecord();
            r.setParams(bo.getParams());
            r.setId(bo.getId());
            r.setSensorId(bo.getSensorId());
            r.setPointName(bo.getPointName());
            r.setPointValue(bo.getPointValue());
            r.setCreateBy(bo.getCreateBy());
            r.setCreateDept(bo.getCreateDept());
            List<TblSensorRecordVo> result = baseMapper.selectData(r);
            return result;
    }

    private LambdaQueryWrapper<TblSensorRecord> buildQueryWrapper(TblSensorRecordBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TblSensorRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getSensorId() != null, TblSensorRecord::getSensorId, bo.getSensorId());
        lqw.like(StringUtils.isNotBlank(bo.getPointName()), TblSensorRecord::getPointName, bo.getPointName());
        lqw.eq(StringUtils.isNotBlank(bo.getPointValue()), TblSensorRecord::getPointValue, bo.getPointValue());
        return lqw;
    }

    /**
     * 新增传感器实时数据
     *
     * @param bo 传感器实时数据
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TblSensorRecordBo bo) {
        TblSensorRecord add = MapstructUtils.convert(bo, TblSensorRecord.class);
        if(bo.getParams()==null || bo.getParams().get("datetime")==null) return false;
        baseMapper.createTable(bo.getParams());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insertData(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改传感器实时数据
     *
     * @param bo 传感器实时数据
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TblSensorRecordBo bo) {
        TblSensorRecord update = MapstructUtils.convert(bo, TblSensorRecord.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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