package com.ssyf.module.robot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssyf.common.web.apicode.ApiCodeUser;
import com.ssyf.common.web.error.ServiceRuntimeException;
import com.ssyf.module.robot.domain.entity.RRobotAccount;
import com.ssyf.module.robot.domain.entity.RRobotConsumptionRecord;
import com.ssyf.module.robot.domain.entity.RRobotRunRecord;
import com.ssyf.module.robot.domain.entity.RRobotRunningInfo;
import com.ssyf.module.robot.domain.query.RRobotRunningInfoQuery;
import com.ssyf.module.robot.service.RRobotRunningInfoService;
import com.ssyf.module.robot.mapper.RRobotRunningInfoMapper;
import com.ssyf.plugs.mysql.helper.MybatisPlusHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
* @author ELSA
* @description 针对表【r_robot_running_info(机器人运行信息表)】的数据库操作Service实现
* @createDate 2025-12-12 10:19:24
*/
@Service
public class RRobotRunningInfoServiceImpl extends ServiceImpl<RRobotRunningInfoMapper, RRobotRunningInfo>
    implements RRobotRunningInfoService{

    @Override
    public RRobotRunningInfo addOne(RRobotRunningInfoQuery query) {
        if(StrUtil.isBlank(query.getRobotUuid())){
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode() , "机器人UUID不能为空");
        }
        RRobotRunningInfo RRobotRunningInfo = BeanUtil.toBean(query ,RRobotRunningInfo.class);
        RRobotRunningInfo.setUuid(IdUtil.simpleUUID());
        this.save(RRobotRunningInfo);
        return RRobotRunningInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeByUid(String uid) {
        checkedExistAndGet(uid);
        this.remove(createBaseWrapper(null).eq(RRobotRunningInfo::getUuid, uid));
    }

    @Override
    public void removeBatchByUids(List<String> uids) {
        this.remove(createBaseWrapper(null).in(RRobotRunningInfo::getUuid, uids));
    }

    @Override
    public void updateByUid(String uid, RRobotRunningInfoQuery query) {
        this.checkedExistAndGet(uid);
        //不能更新uid，和id
        query.setUuid(null);
        RRobotRunningInfo update = BeanUtil.toBean(query ,RRobotRunningInfo.class);
        LambdaQueryWrapper<RRobotRunningInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RRobotRunningInfo::getUuid, uid);
        this.update(update , wrapper);
    }

    @Override
    public RRobotRunningInfo getOneByUid(String uid) {
        return this.getOne(createBaseWrapper(null).eq(RRobotRunningInfo::getUuid, uid));
    }

    @Override
    public PageInfo<RRobotRunningInfo> getPage(RRobotRunningInfoQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        return PageInfo.of(this.list(createBaseWrapper(query)));
    }

    @Override
    public List<RRobotRunningInfo> getList(RRobotRunningInfoQuery query) {
        return this.list(createBaseWrapper(query));
    }

    @Override
    public RRobotRunningInfo checkedExistAndGet(String uid) {
        RRobotRunningInfo old = this.getOne(createBaseWrapper(null).eq(RRobotRunningInfo::getUuid, uid));
        if (old == null) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "数据不存在");
        }
        return old;
    }

    @Override
    public Integer countBy(RRobotRunningInfoQuery query) {
        return this.count(createBaseWrapper(query));
    }

    @Override
    public synchronized RRobotRunningInfo getOrCreated(RRobotAccount robotAccount) {
        LambdaQueryWrapper<RRobotRunningInfo> queryWrapper = createBaseWrapper(new RRobotRunningInfoQuery().setRobotUuid(robotAccount.getUuid()));
        queryWrapper.eq(RRobotRunningInfo::getRunningStatus, 1);
        queryWrapper.orderByDesc(RRobotRunningInfo::getLoginTime);
        queryWrapper.last("LIMIT 1");
        RRobotRunningInfo old = getOne(queryWrapper);
        if (old == null) {
            RRobotRunningInfo newOne = new RRobotRunningInfo();
            newOne.setUuid(IdUtil.simpleUUID());
            newOne.setRobotUuid(robotAccount.getUuid());
            newOne.setRobotAccount(robotAccount.getEmail());
            newOne.setRunningStatus(1);
            newOne.setCurrentBehavior(5);
            newOne.setLastUpdateTime(LocalDateTime.now());
            newOne.setLoginTime(LocalDateTime.now());
            this.save(newOne);

            return newOne;
        }
        return old;
    }

    @Override
    public RRobotRunningInfo getOneByRobotUuid(String uuid) {
        return this.getOne(createBaseWrapper(null).eq(RRobotRunningInfo::getRobotUuid, uuid));
    }

    private LambdaQueryWrapper<RRobotRunningInfo> createBaseWrapper(RRobotRunningInfoQuery query) {
        LambdaQueryWrapper<RRobotRunningInfo> wrapper = new LambdaQueryWrapper<>();
        if (query == null) {
            return wrapper;
        }
        wrapper.eq(StrUtil.isNotBlank(query.getRobotGroupUuid()) , RRobotRunningInfo::getRobotGroupUuid, query.getRobotGroupUuid());
        wrapper.eq(StrUtil.isNotBlank(query.getRobotGroupName()) , RRobotRunningInfo::getRobotGroupName , query.getRobotGroupName());
        wrapper.like(StrUtil.isNotBlank(query.getRobotNickName()) , RRobotRunningInfo::getRobotNickName, query.getRobotNickName());
        wrapper.eq(query.getCurrentBehavior() != null ,RRobotRunningInfo::getCurrentBehavior, query.getCurrentBehavior());
        wrapper.eq(StrUtil.isNotBlank(query.getLiveRoomId()) ,RRobotRunningInfo::getLiveRoomId, query.getLiveRoomId());
        wrapper.eq(StrUtil.isNotBlank(query.getAnchorId()) ,RRobotRunningInfo::getAnchorId, query.getAnchorId());

        wrapper.like(StrUtil.isNotBlank(query.getAnchorName()), RRobotRunningInfo::getAnchorName, query.getAnchorName());
        wrapper.like(StrUtil.isNotBlank(query.getLiveRoomName()), RRobotRunningInfo::getLiveRoomName, query.getLiveRoomName());

        wrapper.like(StrUtil.isNotBlank(query.getRobotAccount()), RRobotRunningInfo::getRobotAccount, query.getRobotAccount());
        wrapper.eq(query.getRunningStatus() != null ,RRobotRunningInfo::getRunningStatus, query.getRunningStatus());
        wrapper.like(StrUtil.isNotBlank(query.getUuid()) , RRobotRunningInfo::getUuid, query.getUuid());
        wrapper.like(StrUtil.isNotBlank(query.getRobotUuid()), RRobotRunningInfo::getRobotUuid, query.getRobotUuid());

        // 时间范围查询
        if (query.getRunningStartTime() != null) {
            wrapper.ge(RRobotRunningInfo::getLoginTime, query.getRunningStartTime());
        }
        if (query.getRunningEndTime() != null) {
            wrapper.le(RRobotRunningInfo::getLoginTime, query.getRunningEndTime());
        }
        
        // 示例排序逻辑
        if (CollectionUtil.isNotEmpty(query.getSorts())) {
            MybatisPlusHelper.orderAndIgnoreError(RRobotRunningInfo.class, wrapper, query.getSorts());
        } else {
            wrapper.orderByDesc(RRobotRunningInfo::getLastUpdateTime);
        }
        return wrapper;
    }
}




