package com.supervision.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.supervision.domain.IrSession;
import com.supervision.domain.IrSessionParam;
import com.supervision.service.IrSessionParamService;
import com.supervision.mapper.IrSessionParamMapper;
import com.supervision.service.IrSessionService;
import com.supervision.vo.session.SessionParamReqVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author flevance
* @description 针对表【ir_session_param(会话参数)】的数据库操作Service实现
* @createDate 2024-03-21 13:14:43
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class IrSessionParamServiceImpl extends ServiceImpl<IrSessionParamMapper, IrSessionParam>
    implements IrSessionParamService{

    @Autowired
    private IrSessionService irSessionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveSessionParam(SessionParamReqVO sessionParamReqVO) {

        String sessionId = sessionParamReqVO.getSessionId();
        Assert.notEmpty(sessionId, "会话ID不能为空");
        Integer count = irSessionService.lambdaQuery().eq(IrSession::getId, sessionId).count();
        Assert.isTrue(count > 0, "会话不存在");

        Map<String, IrSessionParam> sessionParamMap = super.lambdaQuery().eq(IrSessionParam::getSessionId,sessionId).list()
                .stream().collect(Collectors.toMap(IrSessionParam::getParamName, i -> i));

        // 组装数据
        List<IrSessionParam> irSessionParamList = sessionParamReqVO.toIrSessionParamList().stream().filter(i -> StrUtil.isNotEmpty(i.getParamName())).map(i -> {
            IrSessionParam irSessionParam = sessionParamMap.get(i.getParamName());
            if (Objects.nonNull(irSessionParam)) {
                irSessionParam.setParamValue(i.getParamValue());
                return irSessionParam;
            }
            return i;

        }).collect(Collectors.toList());
        return super.saveOrUpdateBatch(irSessionParamList);
    }

    @Override
    public SessionParamReqVO findSessionParam(String sessionId) {
        Assert.notEmpty(sessionId, "会话ID不能为空");
        Map<String, String> paramMap = super.lambdaQuery().eq(IrSessionParam::getSessionId, sessionId).list()
                .stream().collect(Collectors.toMap(IrSessionParam::getParamName, i -> null == i.getParamValue() ? "" : i.getParamValue()));

        return new SessionParamReqVO(sessionId, paramMap.get(SessionParamReqVO.name2Alias()),
                paramMap.get(SessionParamReqVO.cardNumber2Alias()), paramMap.get(SessionParamReqVO.idNumber2Alias()));
    }
}




