package org.matrix.remote.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.matrix.local.entity.Project;
import org.matrix.local.entity.User;
import org.matrix.local.entity.UserProject;
import org.matrix.local.mapper.KsProjectMapper;
import org.matrix.local.mapper.KsUserMapper;
import org.matrix.local.mapper.KsUserProjectMapper;
import org.matrix.remote.entity.ZtProject;
import org.matrix.remote.entity.ZtUser;
import org.matrix.remote.entity.ZtUserView;
import org.matrix.remote.mapper.ZtProjectMapper;
import org.matrix.remote.mapper.ZtUserMapper;
import org.matrix.remote.mapper.ZtUserViewMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static java.util.Objects.nonNull;

@Service
public class TransHelper {

    @Autowired
    private ZtUserMapper ztUserMapper;
    @Autowired
    private ZtUserViewMapper ztUserViewMapper;
    @Autowired
    private ZtProjectMapper ztProjectMapper;
    @Autowired
    private KsUserMapper ksUserMapper;
    @Autowired
    private KsProjectMapper ksProjectMapper;
    @Autowired
    private KsUserProjectMapper ksUserProjectMapper;

    public User user(ZtUser ztUser) {
        return new User(Long.valueOf(ztUser.getId()), ztUser.getRealname(), ztUser.getAccount(), ztUser.getPassword());
    }

    public Project project(ZtProject ztProject) {
        return new Project(Long.valueOf(ztProject.getId()), ztProject.getName());
    }

    public List<UserProject> userProjects(ZtUserView ztUserView) {
        User user = ksUserMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getAccount, ztUserView.getAccount()));
        if (nonNull(user)) {
            Long userId = user.getId();
            return toList(ztUserView.getProjects()).stream()
                    .map(Integer::parseInt)
                    .map(id -> ztProjectMapper.selectById(id))
                    .filter(ztProject -> Objects.equals("0", ztProject.getDeleted()))
                    .map(this::findProjectId)
                    .map(projectId -> new UserProject(null, userId, projectId))
                    .collect(Collectors.toList());
        } else {
            return new ArrayList<>();
        }
    }


    public Long findProjectId(ZtProject ztProject) {
        if (nonNull(ztProject.getProject()) && ztProject.getProject() > 0) {
            return Long.valueOf(ztProject.getProject());
        } else {
            return Long.valueOf(ztProject.getId());
        }
    }

    public List<String> toList(String content) {
        List<String> result = Arrays.stream(content.split(",")).collect(Collectors.toList());
        result.remove(0);
        return result;
    }

}
