package com.qmth.sop.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.sop.business.bean.dto.OrgUserNameDto;
import com.qmth.sop.business.bean.result.TFFlowLogResult;
import com.qmth.sop.business.entity.TFFlowLog;
import com.qmth.sop.business.mapper.TFFlowLogMapper;
import com.qmth.sop.business.service.SysUserService;
import com.qmth.sop.business.service.TFFlowLogService;
import com.qmth.sop.common.contant.SystemConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 流程流水表 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2023-07-17
 */
@Service
public class TFFlowLogServiceImpl extends ServiceImpl<TFFlowLogMapper, TFFlowLog> implements TFFlowLogService {

    @Resource
    SysUserService sysUserService;

    /**
     * 根据实体id查询
     *
     * @param objectId
     * @return
     */
    @Override
    public List<TFFlowLogResult> findByObjectId(Long objectId) {
        List<TFFlowLogResult> tfFlowLogResultList = this.baseMapper.findByObjectId(objectId);
        for (TFFlowLogResult t : tfFlowLogResultList) {
            if (Objects.nonNull(t) && Objects.nonNull(t.getPendApproveId())) {
                List<String> userList = Arrays.asList(t.getPendApproveId().split(SystemConstant.LIST_JOIN_SPLIT));
                List<OrgUserNameDto> orgUserNameDtoList = sysUserService.findOrgUserName(userList.stream().map(s -> Long.parseLong(s)).collect(Collectors.toList()));
                List<String> userName = orgUserNameDtoList.stream().map(s -> s.getOrgUserName()).collect(Collectors.toList());
                t.setPendApproveUserName(StringUtils.join(userName, SystemConstant.LIST_JOIN_SPLIT));
            }
            if (Objects.nonNull(t) && Objects.nonNull(t.getApproveId())) {
                List<OrgUserNameDto> orgUserNameDtoList = sysUserService.findOrgUserName(Arrays.asList(t.getApproveId()));
                List<String> userName = orgUserNameDtoList.stream().map(s -> s.getOrgUserName()).collect(Collectors.toList());
                t.setApproveUserName(StringUtils.join(userName, SystemConstant.LIST_JOIN_SPLIT));
            }
        }
        return tfFlowLogResultList;
    }

    /**
     * 查询最后一条日志审批记录
     *
     * @param flowId
     * @return
     */
    @Override
    public TFFlowLog findByLastFlowLog(Long flowId) {
        return this.baseMapper.findByLastFlowLog(flowId);
    }

    /**
     * 查询最后一条日志审批记录
     *
     * @param flowId
     * @return
     */
    @Override
    public String findByLastFlowLogApproveUser(Long flowId) {
        return this.baseMapper.findByLastFlowLogApproveUser(flowId);
    }
}
