package com.jeeplus.flowable.service.ext.iml;

import cn.hutool.extra.spring.SpringUtil;
import com.jeeplus.flowable.utils.FlowableUtils;
import com.jeeplus.sys.feign.ITenantApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.idm.api.User;
import org.flowable.idm.engine.impl.UserQueryImpl;
import org.flowable.idm.engine.impl.persistence.entity.UserEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * 扩展Flowable用户Service
 *
 * @author liugaofeng
 * @version 2021-09-02
 */
public class FlowUserQueryImpl extends UserQueryImpl {

    private static final long serialVersionUID = 1L;


    @Override
    public long executeCount(CommandContext commandContext) {
        return executeQuery ( ).size ( );
    }

    @Override
    public List <User> executeList(CommandContext commandContext) {
        return executeQuery ( );
    }

    protected List <User> executeQuery() {
        if ( getId ( ) != null ) {
            List <User> result = new ArrayList <> ( );
            result.add ( findById ( getId ( ) ) );
            return result;

        } else if ( getIdIgnoreCase ( ) != null ) {
            List <User> result = new ArrayList <> ( );
            result.add ( findById ( getIdIgnoreCase ( ) ) );
            return result;

        } else {
            return executeAllUserQuery ( );
        }
    }


    protected List <User> executeNameQuery(String name) {
        String fullName = name.replaceAll ( "%", "" );
        return executeUsersQuery ( fullName );
    }

    protected List <User> executeAllUserQuery() {
        return executeUsersQuery ( "" );
    }

    protected UserEntity findById(String userId) {
        String tenantId = SpringUtil.getBean ( ITenantApi.class ).getCurrentTenantId ( );
        UserDTO user = SpringUtil.getBean ( IUserApi.class ).getByLoginName ( userId, tenantId );
        return FlowableUtils.toFlowableUser ( user );
    }

    protected List <User> executeUsersQuery(String fullName) {


        return new ArrayList <> ( );
    }
}
