package com.supervision.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.supervision.config.domain.UserInfo;
import com.supervision.domain.IrSession;
import com.supervision.domain.IrSessionParam;
import com.supervision.exception.BusinessException;
import com.supervision.mapper.RobotDataMapper;
import com.supervision.service.IrSessionHistoryService;
import com.supervision.service.IrSessionParamService;
import com.supervision.service.IrSessionService;
import com.supervision.mapper.IrSessionMapper;
import com.supervision.util.UserUtil;
import com.supervision.vo.session.CreateAjResVO;
import com.supervision.vo.session.FinishSessionVO;
import com.supervision.vo.session.NewSessionReqVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.supervision.domain.IrSessionHistory;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author flevance
 * @description 针对表【ir_session(会话表)】的数据库操作Service实现
 * @createDate 2024-03-21 13:14:43
 */
@Service
@RequiredArgsConstructor
public class IrSessionServiceImpl extends ServiceImpl<IrSessionMapper, IrSession>
        implements IrSessionService {

    private final IrSessionHistoryService irSessionHistoryService;

    private final IrSessionParamService irSessionParamService;

    @Resource
    private RobotDataMapper robotDataMapper;

    @Override
    public List<CreateAjResVO> queryAjBeforeCreatSession(String keyword) {
        Integer ajid = null;
        if (NumberUtil.isNumber(keyword)) {
            ajid = NumberUtil.parseInt(keyword);
        }
        return robotDataMapper.queryAjByAjidOrAjmc(ajid, keyword);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public IrSession createNewSession(NewSessionReqVO newSessionReqVO) {
        if (StrUtil.isBlank(newSessionReqVO.getCaseNumber())) {
            throw new BusinessException("案件号不能为空");
        }
        UserInfo user = UserUtil.getUser();
        IrSession irSession = new IrSession();
        irSession.setSessionName(newSessionReqVO.getCaseName());
        irSession.setSessionState(1);
        irSession.setUserId(user.getId());
        irSession.setVideoSpeed(newSessionReqVO.getSpeed());
        irSession.setBroadcastType(newSessionReqVO.getType());
        this.save(irSession);
        IrSessionParam irSessionParam = new IrSessionParam();
        irSessionParam.setSessionId(irSession.getId());
        irSessionParam.setParamName("ajid");
        irSessionParam.setParamValue(newSessionReqVO.getCaseNumber());
        irSessionParam.setParamType("String");
        irSessionParamService.save(irSessionParam);
        return irSession;
    }

    @Override
    public IPage<IrSession> querySessionPage(String sessionName, Integer pageSize, Integer pageNum) {
        UserInfo user = UserUtil.getUser();
        return this.lambdaQuery().like(StrUtil.isNotBlank(sessionName), IrSession::getSessionName, sessionName).eq(IrSession::getUserId, user.getId())
                .orderBy(true, false,IrSession::getCreateTime)
                .page(new Page<>(pageNum, pageSize));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finishSession(FinishSessionVO finishSessionVO) {
        IrSession irSession = Optional.ofNullable(this.getById(finishSessionVO.getSessionId())).orElseThrow(() -> new BusinessException("未找到的会话"));
        if (irSession.getSessionState() == 2) {
            throw new BusinessException("会话已结束");
        }
        // 更新会话
        irSession.setSessionState(2);
        if (ObjUtil.isNotEmpty(finishSessionVO.getSessionScore())) {
            irSession.setSessionScore(finishSessionVO.getSessionScore());
        }
        this.updateById(irSession);
        // 更新会话历史
        if (CollUtil.isNotEmpty(finishSessionVO.getAnswerHistoryIdList()) && Objects.nonNull(finishSessionVO.getReasonType())){
            irSessionHistoryService.lambdaUpdate().set(IrSessionHistory::getScoreCause, 2).
                    set(IrSessionHistory::getDealState, finishSessionVO.getReasonType())
                    .in(IrSessionHistory::getId, finishSessionVO.getAnswerHistoryIdList()).update();
        }

    }

    @Override
    public List<IrSessionHistory> querySessionHistory(String sessionId) {
        return irSessionHistoryService.lambdaQuery().eq(IrSessionHistory::getSessionId, sessionId).list();
    }

    @Override
    public void deleteSession(List<String> sessionList) {
        if (CollUtil.isEmpty(sessionList)) {
            throw new BusinessException("会话ID不能为空");
        }
        this.removeByIds(sessionList);
    }
}




