package com.njcn.gather.plan.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.gather.device.pojo.po.PqStandardDev;
import com.njcn.gather.plan.mapper.AdPlanStandardDevMapper;
import com.njcn.gather.plan.pojo.po.AdPlanStandardDev;
import com.njcn.gather.plan.service.IAdPlanStandardDevService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * @author caozehui
 * @date 2025-07-16
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdPlanStandardDevServiceImpl extends ServiceImpl<AdPlanStandardDevMapper, AdPlanStandardDev> implements IAdPlanStandardDevService {

    @Override
    public boolean addAdPlanStandardDev(String planId, List<String> standardDevIds) {
        List<AdPlanStandardDev> adPlanStandardDevList = new ArrayList<>();
        for (String standardDevId : standardDevIds) {
            AdPlanStandardDev adPlanStandardDev = new AdPlanStandardDev();
            adPlanStandardDev.setPlanId(planId);
            adPlanStandardDev.setStandardDevId(standardDevId);
            adPlanStandardDevList.add(adPlanStandardDev);
        }
        return this.saveBatch(adPlanStandardDevList);
    }

    @Override
    public boolean updateAdPlanStandardDev(String planId, List<String> standardDevIds) {
        this.deleteAdPlanStandardDev(Collections.singletonList(planId));
        return this.addAdPlanStandardDev(planId, standardDevIds);
    }

    @Override
    public boolean deleteAdPlanStandardDev(List<String> planIds) {
        if (CollectionUtil.isNotEmpty(planIds)) {
            QueryWrapper<AdPlanStandardDev> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("Plan_Id", planIds);
            return this.remove(queryWrapper);
        }
        return false;
    }

    @Override
    public boolean deleteAdPlanStandardDev(String planId, List<String> standardDevIds) {
        if (CollectionUtil.isNotEmpty(standardDevIds)) {
            QueryWrapper<AdPlanStandardDev> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("Plan_Id", planId).in("Standard_Dev_Id", standardDevIds);
            return this.remove(queryWrapper);
        }
        return false;
    }

    @Override
    public String getStandardDevNameStrByPlanId(String id) {
        List<PqStandardDev> pqStandardDevs = this.baseMapper.listByPlanId(Collections.singletonList(id));
        return pqStandardDevs.stream().map(PqStandardDev::getName).reduce((a, b) -> a + "," + b).orElse("");
    }

    @Override
    public List<AdPlanStandardDev> listByPlanId(List<String> planIds) {
        return this.lambdaQuery().in(AdPlanStandardDev::getPlanId, planIds).list();
    }
}
