package com.cf.imes.module.system.api.process;

import com.cf.imes.framework.common.util.object.BeanUtils;
import com.cf.imes.module.system.api.process.dto.ProcessListReqDTO;
import com.cf.imes.module.system.api.process.dto.ProcessRespDTO;
import com.cf.imes.module.system.dal.dataobject.process.ProcessDO;
import com.cf.imes.module.system.dal.dataobject.process.ProcessGroupDO;
import com.cf.imes.module.system.dal.mysql.process.ProcessGroupMapper;
import com.cf.imes.module.system.dal.mysql.process.ProcessMapper;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

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

import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cf.imes.module.system.enums.ErrorCodeConstants.PROCESS_GROUP_NOT_EXISTS;

@RestController // 提供 RESTful API 接口，给 Feign 调用
@Validated
public class ProcessGroupApiImpl implements ProcessGroupApi {

    @Resource
    private ProcessGroupMapper processGroupMapper;

    @Resource
    private ProcessMapper processMapper;

    @Override
    public Boolean getProcessGroup(Long groupId) {
        if (processGroupMapper.selectById(groupId) == null)
            return false;
        return true;
    }

    @Override
    public ProcessListReqDTO getProcessGroupDetail(Long groupId) {

        ProcessGroupDO processGroupDO = processGroupMapper.selectById(groupId);

        if (processGroupDO == null)
            throw exception(PROCESS_GROUP_NOT_EXISTS);
        String[] items = processGroupDO.getItems().split(",");
        List<ProcessRespDTO> lists = new ArrayList<>();
        ProcessListReqDTO processListReqDTO = BeanUtils.toBean(processGroupDO, ProcessListReqDTO.class).setLists(lists);
        for (String item : items) {
            ProcessDO processDO = processMapper.selectById(Long.parseLong(item));

            processListReqDTO.getLists().add(BeanUtils.toBean(processDO, ProcessRespDTO.class));
        }
        return processListReqDTO;
    }
}
