package com.njcn.csharmonic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.csharmonic.mapper.CsHarmonicPlanLineMapper;
import com.njcn.csharmonic.param.CsHarmonicPlanLineParam;
import com.njcn.csharmonic.pojo.po.CsHarmonicPlanLine;
import com.njcn.csharmonic.service.ICsHarmonicPlanLineService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xy
 * @since 2026-04-15
 */
@Service
@RequiredArgsConstructor
public class CsHarmonicPlanLineServiceImpl extends ServiceImpl<CsHarmonicPlanLineMapper, CsHarmonicPlanLine> implements ICsHarmonicPlanLineService {

    @Override
    public List<CsHarmonicPlanLine> getByPlanId(String id) {
        LambdaQueryWrapper<CsHarmonicPlanLine> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CsHarmonicPlanLine::getId, id);
        return this.list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePlanLines(CsHarmonicPlanLineParam param) {
        List<CsHarmonicPlanLine> planLineList = new ArrayList<>();
        for (String lineId : param.getLineIds()) {
            CsHarmonicPlanLine planLine = new CsHarmonicPlanLine();
            planLine.setId(param.getId());
            planLine.setLineId(lineId);
            planLineList.add(planLine);
        }
        this.saveBatch(planLineList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByLineIds(List<String> lineIds) {
        LambdaQueryWrapper<CsHarmonicPlanLine> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CsHarmonicPlanLine::getLineId, lineIds);
        this.remove(wrapper);
    }

    @Override
    public String getPlanIdByLineId(String lineId) {
        LambdaQueryWrapper<CsHarmonicPlanLine> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CsHarmonicPlanLine::getLineId, lineId)
                .last("LIMIT 1");
        CsHarmonicPlanLine planLine = this.getOne(wrapper);
        return planLine != null ? planLine.getId() : null;
    }
}
