package com.njcn.harmonic.common.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.harmonic.common.mapper.SysExcelRelationMapper;
import com.njcn.harmonic.common.pojo.vo.SysExcelRelationVO;
import com.njcn.harmonic.common.service.ISysExcelRelationService;
import com.njcn.harmonic.pojo.param.excel.ExcelParam;
import com.njcn.harmonic.pojo.po.excel.SysExcelRelation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xy
 * @since 2026-01-27
 */
@Service
@Slf4j
@RequiredArgsConstructor
@DS("sjzx")
public class SysExcelRelationServiceImpl extends ServiceImpl<SysExcelRelationMapper, SysExcelRelation> implements ISysExcelRelationService {

    @Override
    public SysExcelRelationVO getRelation(String id) {
        SysExcelRelationVO vo = new SysExcelRelationVO();
        LambdaQueryWrapper<SysExcelRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysExcelRelation::getSysExcelId, id);
        List<SysExcelRelation> list = this.list(queryWrapper);
        vo.setSysExcelId(id);
        if (!list.isEmpty()) {
            vo.setRelationIds(list.stream().map(SysExcelRelation::getSysExcelRptTempId).collect(Collectors.toList()));
        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean bandRelation(ExcelParam.ListExcelParam param) {
        //先删除
        LambdaQueryWrapper<SysExcelRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysExcelRelation::getSysExcelId, param.getId());
        this.remove(queryWrapper);
        //再绑定
        if (!param.getModelIds().isEmpty()) {
            List<SysExcelRelation> list = param.getModelIds().stream().map(id -> {
                SysExcelRelation relation = new SysExcelRelation();
                relation.setSysExcelId(param.getId());
                relation.setSysExcelRptTempId(id);
                return relation;
            }).collect(Collectors.toList());
            this.saveBatch(list);
        }
        return true;
    }
}
