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

import com.xisc.pm.api.dto.PmHtolStaticDTO;
import com.xisc.pm.app.service.PmHtolStaticService;
import com.xisc.pm.domain.entity.PmHtolStatic;
import com.xisc.pm.domain.entity.PmHtolStaticTra;
import com.xisc.pm.domain.repository.PmHtolStaticRepository;
import com.xisc.pm.domain.repository.PmHtolStaticTraRepository;
import com.xisc.pm.infra.constant.Constants;
import com.xisc.pm.infra.util.BeanUtils;
import io.choerodon.core.domain.Page;
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.hzero.boot.platform.lov.adapter.LovAdapter;
import org.hzero.boot.platform.lov.dto.LovValueDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 以优充次静态表(PmHtolStatic)应用服务
 *
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @since 2024-07-25 10:07:37
 */
@Service
public class PmHtolStaticServiceImpl implements PmHtolStaticService {

    private PmHtolStaticRepository pmHtolStaticRepository;

    private PmHtolStaticTraRepository pmHtolStaticTraRepository;

    private LovAdapter lovAdapter;

    public PmHtolStaticServiceImpl(PmHtolStaticRepository pmHtolStaticRepository, PmHtolStaticTraRepository pmHtolStaticTraRepository, LovAdapter lovAdapter) {
        this.pmHtolStaticRepository = pmHtolStaticRepository;
        this.pmHtolStaticTraRepository = pmHtolStaticTraRepository;
        this.lovAdapter = lovAdapter;
    }

    @Override
    public Page<PmHtolStatic> selectList(PageRequest pageRequest, PmHtolStatic pmHtolStatic) {
        return PageHelper.doPageAndSort(pageRequest, () -> pmHtolStaticRepository.selectList(pmHtolStatic));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveData(Long tenantId, List<PmHtolStatic> pmHtolStaticList) {
        // 检查数据列表是否为空，如果为空则直接返回
        if (CollectionUtils.isEmpty(pmHtolStaticList)) {
            return;
        }
        // 获取当前时间及操作人信息
        Date now = new Date();
        String username = DetailsHelper.getUserDetails().getUsername();
        List<PmHtolStaticTra> insertPmHtolStaticTraList = new ArrayList<>(pmHtolStaticList.size());

        // 分离需要插入和更新的列表
        List<PmHtolStatic> insertList = pmHtolStaticList.stream().filter(line -> line.getPmHtolStaticId() == null).collect(Collectors.toList());
        List<PmHtolStatic> updateList = pmHtolStaticList.stream().filter(line -> line.getPmHtolStaticId() != null).collect(Collectors.toList());

        // 记录历史表
        for (PmHtolStatic pmHtolStatic : updateList) {
            PmHtolStaticTra pmHtolStaticTra = new PmHtolStaticTra();
            BeanUtils.copy(pmHtolStatic, pmHtolStaticTra);

            // 设置操作类型为更新（U），并记录操作时间和用户
            pmHtolStaticTra.setOperationType("U");
            pmHtolStaticTra.setOperationTime(now);
            pmHtolStaticTra.setOperationUser(username);
            insertPmHtolStaticTraList.add(pmHtolStaticTra);

        }
        // 更新或者新增
        pmHtolStaticRepository.batchUpdateByPrimaryKeySelective(updateList);
        pmHtolStaticRepository.batchInsertSelective(insertList);

        for (PmHtolStatic pmHtolStatic : insertList) {
            PmHtolStaticTra pmHtolStaticTra = new PmHtolStaticTra();
            BeanUtils.copy(pmHtolStatic, pmHtolStaticTra);

            // 设置操作类型为新增（I），并记录操作时间和用户
            pmHtolStaticTra.setOperationType("I");
            pmHtolStaticTra.setOperationTime(now);
            pmHtolStaticTra.setOperationUser(username);
            insertPmHtolStaticTraList.add(pmHtolStaticTra);

        }
        // 插入保存或者更新记录到对应履历表
        pmHtolStaticTraRepository.batchInsertSelective(insertPmHtolStaticTraList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteForUi(List<PmHtolStatic> pmHtolStaticList) {
        if (CollectionUtils.isNotEmpty(pmHtolStaticList)) {
            // 删除
            pmHtolStaticRepository.batchDeleteByPrimaryKey(pmHtolStaticList);

            // 记录历史表
            Date now = new Date();
            String username = DetailsHelper.getUserDetails().getUsername();
            List<PmHtolStaticTra> insertPmHtolStaticTraList = new ArrayList<>(pmHtolStaticList.size());
            for (PmHtolStatic pmHtolStatic : pmHtolStaticList) {
                PmHtolStaticTra pmHtolStaticTra = new PmHtolStaticTra();

                // 设置操作类型为删除（D），并记录操作时间和服务用户。
                BeanUtils.copy(pmHtolStatic, pmHtolStaticTra);
                pmHtolStaticTra.setOperationType("D");
                pmHtolStaticTra.setOperationTime(now);
                pmHtolStaticTra.setOperationUser(username);
                insertPmHtolStaticTraList.add(pmHtolStaticTra);

            }
            // 插入删除记录到对应履历表
            pmHtolStaticTraRepository.batchInsertSelective(insertPmHtolStaticTraList);
        }
    }

    @Override
    public List<PmHtolStaticDTO> exportList(PmHtolStatic pmHtolStatic) {
        List<PmHtolStatic> pmHtolStaticList = pmHtolStaticRepository.selectList(pmHtolStatic);

        // 如果集合为空，则返回
        if (CollectionUtils.isEmpty(pmHtolStaticList)) {
            return Collections.EMPTY_LIST;
        }

        // 获取生效值集含义
        List<PmHtolStaticDTO> resultList = new ArrayList<>();
        List<LovValueDTO> lovValueList = lovAdapter.queryLovValue(Constants.LovCode.XISC_WHETHER_FLAG_01, pmHtolStatic.getTenantId());
        if (CollectionUtils.isNotEmpty(lovValueList)) {
            Map<String, String> lovValueMap = lovValueList.stream().collect(Collectors.toMap(LovValueDTO::getValue, LovValueDTO::getMeaning));
            pmHtolStaticList.forEach(line -> {
                line.setValidFlagDesc(lovValueMap.get(line.getValidFlag()));
                PmHtolStaticDTO pmHtolStaticDTO = new PmHtolStaticDTO();
                BeanUtils.copy(line, pmHtolStaticDTO);
                resultList.add(pmHtolStaticDTO);
            });
        }
        return resultList;
    }

}

