package com.xisc.pm.app.service.impl;

import com.xisc.boot.common.feign.pojo.MtUserInfo;
import com.xisc.boot.common.sys.UserClient;
import io.choerodon.core.domain.Page;
import io.choerodon.mybatis.pagehelper.PageHelper;
import io.choerodon.mybatis.pagehelper.domain.PageRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import com.xisc.pm.app.service.PmCdContLogService;
import org.springframework.stereotype.Service;
import com.xisc.pm.domain.entity.PmCdContLog;
import com.xisc.pm.domain.repository.PmCdContLogRepository;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 转用充当履历(PmCdContLog)应用服务
 *
 * @author 蒋雨航 yuhang.jiang02@hand-china.com
 * @since 2024-08-16 16:43:01
 */
@Service
public class PmCdContLogServiceImpl implements PmCdContLogService {
    @Autowired
    private PmCdContLogRepository pmCdContLogRepository;

    @Autowired
    private UserClient userClient;

    @Override
    public Page<PmCdContLog> selectList(PageRequest pageRequest, PmCdContLog pmCdContLog) {
        if (StringUtils.isNotBlank(pmCdContLog.getFuncId()) && StringUtils.isNotEmpty(pmCdContLog.getFuncId())) {
            List<String> funcIdList = Arrays.asList(pmCdContLog.getFuncId().split(","));
            pmCdContLog.setFuncIdList(funcIdList);
        }
        Page<PmCdContLog> page =  PageHelper.doPageAndSort(pageRequest, () -> pmCdContLogRepository.selectList(pmCdContLog));
        if (CollectionUtils.isEmpty(page.getContent())) {
            return page;
        }

        // 获取用户名称
        List<Long> userIdList = page.getContent().stream().map(PmCdContLog::getCreatedBy).distinct().collect(Collectors.toList());
        Map<Long, MtUserInfo> mtUserInfoMap = userClient.userInfoBatchGet(pmCdContLog.getTenantId(), userIdList);
        page.getContent().forEach(line->{
            if (!mtUserInfoMap.isEmpty() && mtUserInfoMap.containsKey(line.getCreatedBy())) {
                MtUserInfo mtUserInfo = mtUserInfoMap.get(line.getCreatedBy());
                line.setCreatedByName(Strings.concat(mtUserInfo.getLoginName(), mtUserInfo.getRealName()));
            }
        });
        return page;
    }

    @Override
    public void saveData(List<PmCdContLog> pmCdContLogs) {
        List<PmCdContLog> insertList = pmCdContLogs.stream().filter(line -> line.getLoadContLogId() == null).collect(Collectors.toList());
        List<PmCdContLog> updateList = pmCdContLogs.stream().filter(line -> line.getLoadContLogId() != null).collect(Collectors.toList());
        pmCdContLogRepository.batchInsertSelective(insertList);
        pmCdContLogRepository.batchUpdateByPrimaryKeySelective(updateList);
    }
}

