package com.chushang.task.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chushang.common.mq.produce.MqProduceService;
import com.chushang.common.mybatis.page.CommonParam;
import com.chushang.common.mybatis.utils.PageResult;
import com.chushang.datascope.annotation.DataScope;
import com.chushang.datascope.constants.ScopeConstants;
import com.chushang.task.entity.TaskInfo;
import com.chushang.task.enums.TaskStatusEnum;
import com.chushang.task.mapper.TaskInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @auther: zhao
 * @date: 2024/6/7 18:19
 */
@Slf4j
@Service
public class TaskInfoService extends ServiceImpl<TaskInfoMapper, TaskInfo> implements IService<TaskInfo> {

    @Resource
    MqProduceService<TaskInfo> mqProduceService;

    @DataScope(deptAlias = "t")
    public PageResult pagePostList(TaskInfo sysPost, CommonParam commonParam){
        IPage<TaskInfo> page = this.page(
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(commonParam.getPage(), commonParam.getLimit()),
                buildWrapper(sysPost, commonParam)
        );
        return new PageResult(page);
    }

    public Wrapper<TaskInfo> buildWrapper(TaskInfo taskInfo, CommonParam commonParam) {
        return new QueryWrapper<TaskInfo>()
                .orderBy(true, "asc".equals(commonParam.getIsAsc()), commonParam.getOrderBy())
                .lambda()
                .eq(null != taskInfo.getTaskId(), TaskInfo::getTaskId, taskInfo.getTaskId())
                .like(null != taskInfo.getApplicationName(), TaskInfo::getApplicationName, taskInfo.getApplicationName())
                .eq(StringUtils.isNotEmpty(taskInfo.getTaskName()), TaskInfo::getTaskName, taskInfo.getTaskName())
                .eq(null != taskInfo.getTaskStatus(), TaskInfo::getTaskStatus, taskInfo.getTaskStatus())
                .like(StringUtils.isNotEmpty(taskInfo.getClassName()), TaskInfo::getClassName, taskInfo.getClassName())
                .like(StringUtils.isNotEmpty(taskInfo.getMethodName()), TaskInfo::getMethodName, taskInfo.getMethodName())
                .in(ObjectUtils.isNotEmpty(taskInfo.getSqlParam().get(ScopeConstants.DATA_SCOPE)), TaskInfo::getDeptId, taskInfo.getSqlParam().get(ScopeConstants.DATA_SCOPE));
    }

    public void joinQueue(TaskInfo taskInfo){
        mqProduceService.send(taskInfo.getApplicationName() + 1, taskInfo);

        taskInfo.setTaskStatus(TaskStatusEnum.DISPATCH.getCode());
        updateById(taskInfo);
    }

}
