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

import com.xisc.boot.common.feign.pojo.MtUserInfo;
import com.xisc.boot.common.sys.UserClient;
import com.xisc.pm.app.service.PmPdRuleItemService;
import com.xisc.pm.domain.entity.PmPdRuleItem;
import com.xisc.pm.domain.repository.PmPdRuleItemRepository;
import io.choerodon.core.domain.Page;
import io.choerodon.core.exception.CommonException;
import io.choerodon.mybatis.pagehelper.PageHelper;
import io.choerodon.mybatis.pagehelper.domain.PageRequest;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.util.Strings;
import org.hzero.mybatis.domian.Condition;
import org.hzero.mybatis.util.Sqls;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 组板设计规则库(PmPdRuleItem)应用服务
 *
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @since 2024-07-30 14:15:28
 */
@Service
public class PmPdRuleItemServiceImpl implements PmPdRuleItemService {

    private PmPdRuleItemRepository pmPdRuleItemRepository;

    private UserClient userClient;

    public PmPdRuleItemServiceImpl(PmPdRuleItemRepository pmPdRuleItemRepository, UserClient userClient) {
        this.pmPdRuleItemRepository = pmPdRuleItemRepository;
        this.userClient = userClient;
    }

    @Override
    public Page<PmPdRuleItem> selectList(PageRequest pageRequest, PmPdRuleItem pmPdRuleItem) {
        return PageHelper.doPageAndSort(pageRequest, () -> pmPdRuleItemRepository.selectList(pmPdRuleItem));
    }

    @Override
    public List<PmPdRuleItem> queryList(PmPdRuleItem pmPdRuleItem) {
        List<PmPdRuleItem> pmPdRuleItemList = pmPdRuleItemRepository.selectList(pmPdRuleItem);
        if (CollectionUtils.isEmpty(pmPdRuleItemList)) {
            return pmPdRuleItemList;
        }
        List<Long> userIdList = pmPdRuleItemList.stream().map(PmPdRuleItem::getCreatedBy).distinct().collect(Collectors.toList());
        userIdList.addAll(pmPdRuleItemList.stream().map(PmPdRuleItem::getLastUpdatedBy).distinct().collect(Collectors.toList()));
        Map<Long, MtUserInfo> mtUserInfoMap = userClient.userInfoBatchGet(pmPdRuleItem.getTenantId(), userIdList);
        pmPdRuleItemList.forEach(line -> {
            // 获取创建人名称
            if (!mtUserInfoMap.isEmpty() && mtUserInfoMap.containsKey(line.getCreatedBy())) {
                MtUserInfo mtUserInfo = mtUserInfoMap.get(line.getCreatedBy());
                line.setCreatedByName(Strings.concat(mtUserInfo.getLoginName(),mtUserInfo.getRealName()));
            }
            // 获取更新人名称
            if (!mtUserInfoMap.isEmpty() && mtUserInfoMap.containsKey(line.getLastUpdatedBy())) {
                MtUserInfo mtUserInfo = mtUserInfoMap.get(line.getLastUpdatedBy());
                line.setUpdateByName(Strings.concat(mtUserInfo.getLoginName(),mtUserInfo.getRealName()));
            }
        });
        return pmPdRuleItemList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveData(Long tenantId, List<PmPdRuleItem> pmPdRuleItemList) {
        // 判断集合是否为空，为空则返回
        if (CollectionUtils.isEmpty(pmPdRuleItemList)) {
            return;
        }
        // 获取更新和新增的记录
        List<PmPdRuleItem> insertList = pmPdRuleItemList.stream().filter(line -> line.getRuleNoId() == null).collect(Collectors.toList());
        List<PmPdRuleItem> updateList = pmPdRuleItemList.stream().filter(line -> line.getRuleNoId() != null).collect(Collectors.toList());

        // 校验新增的记录的规则号是否存在
        if (CollectionUtils.isNotEmpty(insertList)) {
            List<Long> ruleNoList = insertList.stream().map(PmPdRuleItem::getRuleNo).collect(Collectors.toList());
            List<PmPdRuleItem> pdRuleItemList = pmPdRuleItemRepository.selectByCondition(Condition.builder(PmPdRuleItem.class)
                    .andWhere(Sqls.custom().andIn(PmPdRuleItem.FIELD_RULE_NO, ruleNoList))
                    .andWhere(Sqls.custom().andEqualTo(PmPdRuleItem.FIELD_TENANT_ID, tenantId))
                    .build());
            // 若存在改规则号，则报错已存在
            if (CollectionUtils.isNotEmpty(pdRuleItemList)) {
                throw new CommonException("pm.pd_rule_item_001", ruleNoList);
            }

        }
        // 批量插入
        pmPdRuleItemRepository.batchInsertSelective(insertList);
        // 批量更新
        pmPdRuleItemRepository.batchUpdateByPrimaryKeySelective(updateList);
    }
}

