package org.dromara.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
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.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.domain.blackManage.BlackManage;
import org.dromara.domain.blackManage.vo.BlackManageVo;
import org.dromara.domain.illegalParking.IllegalParking;
import org.dromara.domain.illegalParking.bo.IllegalParkingBo;
import org.dromara.domain.illegalParking.vo.IllegalParkingVo;
import org.dromara.mapper.BlackManageMapper;
import org.dromara.mapper.IllegalParkingMapper;
import org.dromara.service.IIllegalParkingService;
import org.springframework.stereotype.Service;

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

import static org.dromara.common.core.constant.Constants.*;

/**
 * 违章停车登记Service业务层处理
 *
 * @author boman
 * @date 2025-04-11
 */
@RequiredArgsConstructor
@Service
public class IllegalParkingServiceImpl implements IIllegalParkingService {

    private final IllegalParkingMapper baseMapper;
    private final BlackManageMapper blackManageMapper;


    /**
     * 查询违章停车登记
     *
     * @param illegalParkingId 主键
     * @return 违章停车登记
     */
    @Override
    public IllegalParkingVo queryById(Long illegalParkingId) {
        IllegalParkingVo illegalParkingVo = baseMapper.selectVoById(illegalParkingId);
        String plateNumber = illegalParkingVo.getPlateNumber();
        IllegalParkingBo bo = new IllegalParkingBo();
        bo.setPlateNumber(plateNumber);
        List<IllegalParkingVo> illegalParkingVos = queryList(bo);
        if (illegalParkingVos != null && !illegalParkingVos.isEmpty()) {
            illegalParkingVo.setChildren(illegalParkingVos);
        }
        return illegalParkingVo;
    }

    /**
     * 分页查询违章停车登记列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 违章停车登记分页列表
     */
    @Override
    public TableDataInfo<IllegalParkingVo> queryPageList(IllegalParkingBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<IllegalParking> lqw = buildQueryWrapper(bo);
        Page<IllegalParkingVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (result.getRecords() != null && !result.getRecords().isEmpty()) {
            for (IllegalParkingVo parking : result.getRecords()) {
                String plateNumber = parking.getPlateNumber();
                IllegalParkingBo ibo = new IllegalParkingBo();
                ibo.setPlateNumber(plateNumber);
                List<IllegalParkingVo> illegalParkingVos = queryList(ibo);
                if (illegalParkingVos != null && !illegalParkingVos.isEmpty()) {
                    parking.setChildren(illegalParkingVos);
                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的违章停车登记列表
     *
     * @param bo 查询条件
     * @return 违章停车登记列表
     */
    @Override
    public List<IllegalParkingVo> queryList(IllegalParkingBo bo) {
        LambdaQueryWrapper<IllegalParking> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<IllegalParking> buildQueryWrapper(IllegalParkingBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<IllegalParking> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(IllegalParking::getIllegalParkingId);
        lqw.eq(StringUtils.isNotBlank(bo.getPlateNumber()), IllegalParking::getPlateNumber, bo.getPlateNumber());
        lqw.eq(bo.getPortalId() != null, IllegalParking::getPortalId, bo.getPortalId());
        lqw.eq(StringUtils.isNotBlank(bo.getVisitPortal()), IllegalParking::getVisitPortal, bo.getVisitPortal());
        lqw.eq(StringUtils.isNotBlank(bo.getMobileNumber()), IllegalParking::getMobileNumber, bo.getMobileNumber());
        lqw.like(StringUtils.isNotBlank(bo.getVisitName()), IllegalParking::getVisitName, bo.getVisitName());
        lqw.eq(StringUtils.isNotBlank(bo.getIllegalPhoto()), IllegalParking::getIllegalPhoto, bo.getIllegalPhoto());
        lqw.eq(StringUtils.isNotBlank(bo.getCarType()), IllegalParking::getCarType, bo.getCarType());
        lqw.eq(StringUtils.isNotBlank(bo.getIsBlack()), IllegalParking::getIsBlack, bo.getIsBlack());
        return lqw;
    }

    /**
     * 新增违章停车登记
     *
     * @param bo 违章停车登记
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(IllegalParkingBo bo) {
        IllegalParking add = MapstructUtils.convert(bo, IllegalParking.class);
        validEntityBeforeSave(add);
        //从redis中查询车牌黑名单次数
        String key = BLACK_PLATE_NUMBER + LoginHelper.getTenantId();
        long blackNum = 0;
        if (!RedisUtils.hasKey(key)) {
            //没有就从数据库查询
            BlackManageVo blackManageVo = blackManageMapper.selectVoOne(new LambdaQueryWrapper<BlackManage>().eq(BlackManage::getBlackType, ONE));
            blackNum = blackManageVo.getBlackNum();
            RedisUtils.setAtomicValue(key, blackNum);
        } else {
            blackNum = RedisUtils.getAtomicValue(key);
        }
        //查询该车牌号的违停次数
        List<IllegalParkingVo> illegalParkingVos = baseMapper.selectVoList(new LambdaQueryWrapper<IllegalParking>().eq(IllegalParking::getPlateNumber, add.getPlateNumber()));
        long count = illegalParkingVos == null ? 0 : illegalParkingVos.size();
        if (count + 1 > blackNum) {
            add.setIsBlack(Y);
            //todo 给道闸下发黑名单
        }
        //判断该车牌号
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setIllegalParkingId(add.getIllegalParkingId());
        }
        return flag;
    }

    /**
     * 修改违章停车登记
     *
     * @param bo 违章停车登记
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(IllegalParkingBo bo) {
        IllegalParking update = MapstructUtils.convert(bo, IllegalParking.class);
        validEntityBeforeSave(update);
        //从redis中查询车牌黑名单次数
        String key = BLACK_PLATE_NUMBER + LoginHelper.getTenantId();
        long blackNum = 0;
        if (!RedisUtils.hasKey(key)) {
            //没有就从数据库查询
            BlackManageVo blackManageVo = blackManageMapper.selectVoOne(new LambdaQueryWrapper<BlackManage>().eq(BlackManage::getBlackType, ONE));
            blackNum = blackManageVo.getBlackNum();
            RedisUtils.setAtomicValue(key, blackNum);
        } else {
            blackNum = RedisUtils.getAtomicValue(key);
        }
        //查询该车牌号的违停次数
        List<IllegalParkingVo> illegalParkingVos = baseMapper.selectVoList(new LambdaQueryWrapper<IllegalParking>().eq(IllegalParking::getPlateNumber, update.getPlateNumber()));
        long count = illegalParkingVos == null ? 0 : illegalParkingVos.size();
        if (count + 1 > blackNum) {
            update.setIsBlack(Y);
            //todo 给道闸下发黑名单
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(IllegalParking 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 R<Void> cancel(IllegalParkingBo bo) {
        //todo 单次解除
        bo.setIsBlack(N);
        IllegalParking update = MapstructUtils.convert(bo, IllegalParking.class);
        validEntityBeforeSave(update);
        boolean bl = baseMapper.updateById(update) > 0;
        //todo 给道闸下发解除黑名单
        if (bl) {
            return R.ok();
        }
        return R.fail();
    }
}
