package org.dromara.elevator.service.impl;

import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.collections4.CollectionUtils;
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.EBehaviorMessage;
import org.dromara.elevator.domain.EElevatorInfo;
import org.dromara.system.domain.SysDept;
import org.dromara.system.mapper.SysDeptMapper;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.dromara.elevator.domain.bo.EBlackBoxInfoBo;
import org.dromara.elevator.domain.vo.EBlackBoxInfoVo;
import org.dromara.elevator.domain.EBlackBoxInfo;
import org.dromara.elevator.mapper.EBlackBoxInfoMapper;
import org.dromara.elevator.service.IEBlackBoxInfoService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Objects;

/**
 * 黑匣子信息;Service业务层处理
 *
 * @author zy
 * @date 2024-07-29
 */
@RequiredArgsConstructor
@Service
public class EBlackBoxInfoServiceImpl implements IEBlackBoxInfoService {

    private final EBlackBoxInfoMapper baseMapper;
    private final SysDeptMapper deptMapper;

    /**
     * 查询黑匣子信息;
     *
     * @param id 主键
     * @return 黑匣子信息;
     */
    @Override
    public EBlackBoxInfoVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询黑匣子信息;列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 黑匣子信息;分页列表
     */
    @Override
    public TableDataInfo<EBlackBoxInfoVo> queryPageList(EBlackBoxInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<EBlackBoxInfo> lqw = buildQueryWrapper(bo);
        Page<EBlackBoxInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的黑匣子信息;列表
     *
     * @param bo 查询条件
     * @return 黑匣子信息;列表
     */
    @Override
    public List<EBlackBoxInfoVo> queryList(EBlackBoxInfoBo bo) {
        LambdaQueryWrapper<EBlackBoxInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<EBlackBoxInfo> buildQueryWrapper(EBlackBoxInfoBo bo) {
        LambdaQueryWrapper<EBlackBoxInfo> lqw = buildBaseQueryWrapper(bo);

        lqw.orderByDesc(EBlackBoxInfo::getCreateTime);
        return lqw;
    }

    @NotNull
    private LambdaQueryWrapper<EBlackBoxInfo> buildBaseQueryWrapper(EBlackBoxInfoBo bo) {
        LambdaQueryWrapper<EBlackBoxInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getDeviceCode()), EBlackBoxInfo::getDeviceCode, bo.getDeviceCode());
        lqw.like(StringUtils.isNotBlank(bo.getDeviceName()), EBlackBoxInfo::getDeviceName, bo.getDeviceName());
        lqw.eq(StringUtils.isNotBlank(bo.getRegisterCode()), EBlackBoxInfo::getRegisterCode, bo.getRegisterCode());
        lqw.like(StringUtils.isNotBlank(bo.getElevatorName()), EBlackBoxInfo::getElevatorName, bo.getElevatorName());
        lqw.eq(StringUtils.isNotBlank(bo.getDeviceVersion()), EBlackBoxInfo::getDeviceVersion, bo.getDeviceVersion());
        lqw.eq(bo.getIsLine() != null, EBlackBoxInfo::getIsLine, bo.getIsLine());
        lqw.eq(StringUtils.isNotBlank(bo.getProjectId()), EBlackBoxInfo::getProjectId, bo.getProjectId());
        lqw.eq(bo.getIsElevator() != null, EBlackBoxInfo::getIsElevator, bo.getIsElevator());
        lqw.eq(bo.getEnergyType() != null, EBlackBoxInfo::getEnergyType, bo.getEnergyType());
        lqw.eq(bo.getStartType() != null, EBlackBoxInfo::getStartType, bo.getStartType());
        lqw.eq(StringUtils.isNotBlank(bo.getTenementId()), EBlackBoxInfo::getTenementId, bo.getTenementId());
        lqw.between(Objects.nonNull(bo.getStartTime()) && Objects.nonNull(bo.getEndTime()),
            EBlackBoxInfo::getFinallyTime, bo.getStartTime(), bo.getEndTime());
        lqw.in(CollectionUtils.isNotEmpty(bo.getRegisterCodes()), EBlackBoxInfo::getRegisterCode, bo.getRegisterCodes());

        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(EBlackBoxInfo::getDeptId, ids);
        });
        return lqw;
    }

    /**
     * 新增黑匣子信息;
     *
     * @param bo 黑匣子信息;
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(EBlackBoxInfoBo bo) {
        EBlackBoxInfo add = MapstructUtils.convert(bo, EBlackBoxInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改黑匣子信息;
     *
     * @param bo 黑匣子信息;
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(EBlackBoxInfoBo bo) {
        EBlackBoxInfo update = MapstructUtils.convert(bo, EBlackBoxInfo.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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

    @Override
    public EBlackBoxInfo queryBlackBoxInfo(String registerCode) {
        return baseMapper.selectOne(Wrappers.<EBlackBoxInfo>lambdaQuery()
            .eq(EBlackBoxInfo::getRegisterCode, registerCode)
            .last(" limit 1 "));
    }

    @Override
    public Long selectCount(EBlackBoxInfoBo bo) {
        return baseMapper.selectCount(this.buildBaseQueryWrapper(bo));
    }
}
