package org.dromara.elevator.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
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.dromara.common.mybatis.helper.DataBaseHelper;
import org.dromara.elevator.domain.bo.BehaviorMessageStatisticsBo;
import org.dromara.elevator.domain.bo.EConfirmMessageBo;
import org.dromara.system.domain.SysDept;
import org.dromara.system.mapper.SysDeptMapper;
import org.springframework.stereotype.Service;
import org.dromara.elevator.domain.bo.EBehaviorMessageBo;
import org.dromara.elevator.domain.vo.EBehaviorMessageVo;
import org.dromara.elevator.domain.EBehaviorMessage;
import org.dromara.elevator.mapper.EBehaviorMessageMapper;
import org.dromara.elevator.service.IEBehaviorMessageService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 行为消息;Service业务层处理
 *
 * @author zy
 * @date 2024-07-29
 */
@RequiredArgsConstructor
@Service
public class EBehaviorMessageServiceImpl implements IEBehaviorMessageService {

    private final EBehaviorMessageMapper baseMapper;
    private final SysDeptMapper deptMapper;

    /**
     * 查询行为消息;
     *
     * @param id 主键
     * @return 行为消息;
     */
    @Override
    public EBehaviorMessageVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询行为消息;列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 行为消息;分页列表
     */
    @Override
    public TableDataInfo<EBehaviorMessageVo> queryPageList(EBehaviorMessageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<EBehaviorMessage> lqw = buildQueryWrapper(bo);
        if (Objects.isNull(pageQuery.getPageNum()) || Objects.isNull(pageQuery.getPageSize())) {
            pageQuery.setPageNum(1);
            pageQuery.setPageSize(1000);
        }
        if (bo.getLargeScreenFlag() && CollectionUtils.isEmpty(bo.getMsgIds())) {
            Page<EBehaviorMessageVo> res = new Page<>();
            res.setTotal(0L);
            res.setRecords(new ArrayList<>());
            return TableDataInfo.build(res);
        }

        Page<EBehaviorMessageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的行为消息;列表
     *
     * @param bo 查询条件
     * @return 行为消息;列表
     */
    @Override
    public List<EBehaviorMessageVo> queryList(EBehaviorMessageBo bo) {
        LambdaQueryWrapper<EBehaviorMessage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<EBehaviorMessage> buildQueryWrapper(EBehaviorMessageBo bo) {
        if (bo.getLargeScreenFlag() && CollectionUtils.isNotEmpty(bo.getElevatorNumList())) {
            QueryWrapper<EBehaviorMessage> queryWrapper = new QueryWrapper<>();
            queryWrapper.select(" Max(id) As id ");
            queryWrapper.in("elevator_num", bo.getElevatorNumList());
            queryWrapper.groupBy(" elevator_num ");
            bo.setMsgIds(this.baseMapper.selectList(queryWrapper).stream().map(EBehaviorMessage::getId).collect(Collectors.toList()));
        }

        LambdaQueryWrapper<EBehaviorMessage> lqw = Wrappers.lambdaQuery();
        lqw.in(CollectionUtils.isNotEmpty(bo.getMsgIds()), EBehaviorMessage::getId, bo.getMsgIds());

        lqw.eq(StringUtils.isNotBlank(bo.getFaultCode()), EBehaviorMessage::getFaultCode, bo.getFaultCode());
        lqw.like(StringUtils.isNotBlank(bo.getFaultName()), EBehaviorMessage::getFaultName, bo.getFaultName());
        lqw.eq(StringUtils.isNotBlank(bo.getDeviceCode()), EBehaviorMessage::getDeviceCode, bo.getDeviceCode());
        lqw.eq(StringUtils.isNotBlank(bo.getElevatorNum()), EBehaviorMessage::getElevatorNum, bo.getElevatorNum());
        lqw.like(StringUtils.isNotBlank(bo.getElevatorName()), EBehaviorMessage::getElevatorName, bo.getElevatorName());
        lqw.between(bo.getHappenTimeStart() != null && bo.getHappenTimeEnd() != null ,EBehaviorMessage::getHappenTime, bo.getHappenTimeStart(), bo.getHappenTimeEnd());
        lqw.eq(bo.getRecoverTime() != null, EBehaviorMessage::getRecoverTime, bo.getRecoverTime());
        lqw.eq(StringUtils.isNotBlank(bo.getSource()), EBehaviorMessage::getSource, bo.getSource());
        lqw.eq(StringUtils.isNotBlank(bo.getFloor()), EBehaviorMessage::getFloor, bo.getFloor());
        lqw.eq(StringUtils.isNotBlank(bo.getPicture()), EBehaviorMessage::getPicture, bo.getPicture());
        lqw.eq(bo.getState() != null, EBehaviorMessage::getState, bo.getState());
        lqw.eq(StringUtils.isNotBlank(bo.getAffirmPeople()), EBehaviorMessage::getAffirmPeople, bo.getAffirmPeople());
        lqw.eq(StringUtils.isNotBlank(bo.getCause()), EBehaviorMessage::getCause, bo.getCause());
        lqw.eq(StringUtils.isNotBlank(bo.getCauseAnalyse()), EBehaviorMessage::getCauseAnalyse, bo.getCauseAnalyse());
        lqw.eq(StringUtils.isNotBlank(bo.getExplain()), EBehaviorMessage::getExplain, bo.getExplain());
        lqw.eq(StringUtils.isNotBlank(bo.getVideoAddress()), EBehaviorMessage::getVideoAddress, bo.getVideoAddress());

        lqw.and(ObjectUtil.isNotNull(bo.getDeptId()), w -> {
            List<SysDept> deptList = deptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                .select(SysDept::getDeptId)
                .apply(DataBaseHelper.findInSet(bo.getDeptId(), "ancestors")));
            List<Long> ids = StreamUtils.toList(deptList, SysDept::getDeptId);
            ids.add(bo.getDeptId());
            w.in(EBehaviorMessage::getDeptId, ids);
        }).orderByDesc(EBehaviorMessage::getCreateTime);
        return lqw;
    }

    /**
     * 新增行为消息;
     *
     * @param bo 行为消息;
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(EBehaviorMessageBo bo) {
        EBehaviorMessage add = MapstructUtils.convert(bo, EBehaviorMessage.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改行为消息;
     *
     * @param bo 行为消息;
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(EBehaviorMessageBo bo) {
        EBehaviorMessage update = MapstructUtils.convert(bo, EBehaviorMessage.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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

    /**
     * 消息确认
     * @param bo
     * @return
     */
    @Override
    public Boolean confirmMessage(EConfirmMessageBo bo) {
        EBehaviorMessage message = baseMapper.selectById(bo.getId());
        if (Objects.isNull(message)) {
            throw new ServiceException("暂未查询到此消息记录!");
        }
        message.setCause(bo.getCause());
        message.setCauseCode(bo.getCauseCode());
        message.setCauseAnalyse(bo.getCauseAnalyse());
        message.setCauseAnalyseCode(bo.getCauseAnalyseCode());
        message.setExplain(bo.getExplain());
        message.setAffirmPeople(bo.getAffirmPeople());
        message.setRecoverTime(new Date());
        message.setState(1);

        return baseMapper.updateById(message) > 0;
    }

    @Override
    public List<EBehaviorMessage> queryStatisticsBehaviorList(Long id) {
        return baseMapper.selectList(Wrappers.<EBehaviorMessage>lambdaQuery()
            .gt(EBehaviorMessage::getId, id).orderByAsc(EBehaviorMessage::getId)
            .last(" limit 3000 "));
    }

    @Override
    public List<EBehaviorMessage> queryBehaviorMessageList(BehaviorMessageStatisticsBo bo) {
        return baseMapper.selectList(Wrappers.<EBehaviorMessage>lambdaQuery()
            .in(CollectionUtils.isNotEmpty(bo.getElevatorNumList()),EBehaviorMessage::getElevatorNum, bo.getElevatorNumList())
            .eq(StringUtils.isNotBlank(bo.getElevatorNum()), EBehaviorMessage::getElevatorNum, bo.getElevatorNum())
            .between(EBehaviorMessage::getHappenTime, bo.getStartTime(), bo.getEndTime()));
    }

    @Override
    public EBehaviorMessage queryFirstBehaviorMessage(String elevatorNum) {
        return baseMapper.selectOne(Wrappers.<EBehaviorMessage>lambdaQuery()
            .eq(EBehaviorMessage::getElevatorNum, elevatorNum)
            .orderByAsc(EBehaviorMessage::getHappenTime)
            .last(" limit 1 "));
    }

    @Override
    public EBehaviorMessage queryLastBehaviorMessage(String elevatorNum) {
        return baseMapper.selectOne(Wrappers.<EBehaviorMessage>lambdaQuery()
            .eq(EBehaviorMessage::getElevatorNum, elevatorNum)
            .orderByDesc(EBehaviorMessage::getHappenTime)
            .last(" limit 1 "));
    }
}
