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.PmSampleReserveBtService;
import com.xisc.pm.domain.entity.PmSampleReserveBt;
import com.xisc.pm.domain.entity.PmSampleReserveBtTra;
import com.xisc.pm.domain.repository.PmSampleReserveBtRepository;
import com.xisc.pm.domain.repository.PmSampleReserveBtTraRepository;
import com.xisc.pm.infra.util.BeanUtils;
import io.choerodon.core.domain.Page;
import io.choerodon.core.exception.CommonException;
import io.choerodon.core.oauth.DetailsHelper;
import io.choerodon.mybatis.pagehelper.PageHelper;
import io.choerodon.mybatis.pagehelper.domain.PageRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.util.Strings;
import org.hzero.mybatis.domian.Condition;
import org.hzero.mybatis.util.Sqls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 预留试样基表(PmSampleReserveBt)应用服务
 *
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @since 2024-12-18 15:15:14
 */
@Service
public class PmSampleReserveBtServiceImpl implements PmSampleReserveBtService {
    @Autowired
    private PmSampleReserveBtRepository pmSampleReserveBtRepository;

    @Autowired
    private PmSampleReserveBtTraRepository pmSampleReserveBtTraRepository;

    @Autowired
    private UserClient userClient;

    @Override
    public Page<PmSampleReserveBt> selectList(PageRequest pageRequest, PmSampleReserveBt pmSampleReserveBt) {
        Page<PmSampleReserveBt> page = PageHelper.doPageAndSort(pageRequest, () -> pmSampleReserveBtRepository.selectList(pmSampleReserveBt));
        if (CollectionUtils.isEmpty(page.getContent())) {
            return new Page<>();
        }
        List<Long> userIdList = page.getContent().stream().map(PmSampleReserveBt::getCreatedBy).distinct().collect(Collectors.toList());
        userIdList.addAll(page.getContent().stream().map(PmSampleReserveBt::getLastUpdatedBy).distinct().collect(Collectors.toList()));
        Map<Long, MtUserInfo> mtUserInfoMap = userClient.userInfoBatchGet(pmSampleReserveBt.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()));
            }
            // 获取更新人名称
            if (!mtUserInfoMap.isEmpty() && mtUserInfoMap.containsKey(line.getLastUpdatedBy())) {
                MtUserInfo mtUserInfo = mtUserInfoMap.get(line.getLastUpdatedBy());
                line.setUpdateByName(Strings.concat(mtUserInfo.getLoginName(),mtUserInfo.getRealName()));
            }
        });
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveData(List<PmSampleReserveBt> pmSampleReserveBtList, Long tenantId) {
        // 校验唯一性
        List<String> stNoList = pmSampleReserveBtList.stream().map(PmSampleReserveBt::getStNo).distinct().collect(Collectors.toList());
        if (stNoList.size() < pmSampleReserveBtList.size()) {
            throw new CommonException("pm.sample_reserve_bt_001");
        }
        List<Long> psrbIdList = pmSampleReserveBtList.stream().filter(item -> item.getPsrbId() != null).map(PmSampleReserveBt::getPsrbId).collect(Collectors.toList());
        List<PmSampleReserveBt> existSampleReserveBtList = pmSampleReserveBtRepository.selectByCondition(Condition.builder(PmSampleReserveBt.class)
                .andWhere(Sqls.custom().andIn(PmSampleReserveBt.FIELD_ST_NO, stNoList))
                .andWhere(Sqls.custom().andNotIn(PmSampleReserveBt.FIELD_PSRB_ID, psrbIdList, true))
                .andWhere(Sqls.custom().andEqualTo(PmSampleReserveBt.FIELD_TENANT_ID, tenantId))
                .build());
        Map<String, PmSampleReserveBt> existSampleReserveBtMap = existSampleReserveBtList.stream().collect(Collectors.toMap(PmSampleReserveBt::getStNo, Function.identity()));
        for (PmSampleReserveBt pmSampleReserveBt : pmSampleReserveBtList) {
            if (existSampleReserveBtMap.containsKey(pmSampleReserveBt.getStNo())) {
                throw new CommonException("pm.sample_reserve_bt_002", pmSampleReserveBt.getStNo());
            }
        }
        List<PmSampleReserveBt> insertList = pmSampleReserveBtList.stream().filter(line -> line.getPsrbId() == null).collect(Collectors.toList());
        List<PmSampleReserveBt> updateList = pmSampleReserveBtList.stream().filter(line -> line.getPsrbId() != null).collect(Collectors.toList());
        pmSampleReserveBtRepository.batchInsertSelective(insertList);
        pmSampleReserveBtRepository.batchUpdateByPrimaryKeySelective(updateList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUi(Long tenantId, List<PmSampleReserveBt> pmSampleReserveBtList) {
        if (CollectionUtils.isNotEmpty(pmSampleReserveBtList)) {
            // 删除
            pmSampleReserveBtRepository.batchDeleteByPrimaryKey(pmSampleReserveBtList);

            // 获取时间和当前操作人信息
            Date now = new Date();
            String username = DetailsHelper.getUserDetails().getUsername();
            List<PmSampleReserveBtTra> insertPmSampleReserveBtTraList = new ArrayList<>(pmSampleReserveBtList.size());
            for (PmSampleReserveBt pmSampleReserveBt : pmSampleReserveBtList) {
                PmSampleReserveBtTra pmSampleReserveBtTra = new PmSampleReserveBtTra();

                // 设置操作类型为删除（D），并记录操作时间和用户
                BeanUtils.copy(pmSampleReserveBt, pmSampleReserveBtTra);
                pmSampleReserveBtTra.setOperationType("D");
                pmSampleReserveBtTra.setOperationTime(now);
                pmSampleReserveBtTra.setOperationUser(username);
                insertPmSampleReserveBtTraList.add(pmSampleReserveBtTra);
            }
            // 插入删除记录到对应履历表
            pmSampleReserveBtTraRepository.batchInsertSelective(insertPmSampleReserveBtTraList);
        }
    }
}

