package cn.cslg.pas.service.impl;

import cn.cslg.pas.common.model.dto.AssoProductPatentAddNewDTO;
import cn.cslg.pas.domain.asso.AssoProductPatent;
import cn.cslg.pas.mapper.asso.AssoProductPatentMapper;
import cn.cslg.pas.service.IAssoProductPatentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

/**
 * @Author chenyu
 * @Date 2023/4/14
 */
@Slf4j
@Service
public class AssoProductPatentServiceImpl extends ServiceImpl<AssoProductPatentMapper, AssoProductPatent> implements IAssoProductPatentService {
    /**
     * 新增多个专利和多个产品关联
     *
     * @param assoProductPatentAddNewDTO 新增多个专利和多个产品关联的DTO类
     */
    @Override
    public void addNewAssoProductPatent(AssoProductPatentAddNewDTO assoProductPatentAddNewDTO) {
        log.info("开始处理【新增专利和产品关联】的业务，参数为：{}", assoProductPatentAddNewDTO);
        //从DTO中获取要新增关联的多个专利号和产品ids
        List<String> patentNos = assoProductPatentAddNewDTO.getPatentNos();
        List<Integer> newProductIds = assoProductPatentAddNewDTO.getProductIds();
        ArrayList<AssoProductPatent> newAssoProductPatents = new ArrayList<>();
        for (String patentNo : patentNos) {
            for (Integer newProductId : newProductIds) {
                AssoProductPatent assoProductPatent = new AssoProductPatent()
                        .setPatentNo(patentNo)
                        .setProductId(newProductId);
                newAssoProductPatents.add(assoProductPatent);
            }
        }
        //先查库中已有的这些专利和产品的关联数据
        LambdaQueryWrapper<AssoProductPatent> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(AssoProductPatent::getPatentNo, patentNos);
        List<AssoProductPatent> oldAssoProductPatents = this.list(wrapper);
        if (oldAssoProductPatents != null && oldAssoProductPatents.size() > 0) {
            for (AssoProductPatent assoProductPatent : oldAssoProductPatents) {
                assoProductPatent.setId(null);
            }
        }
        //去重
        newAssoProductPatents.removeAll(oldAssoProductPatents);
        //去重后若还有，则为新的关联数据，入库
        if (newAssoProductPatents.size() > 0) {
            //产品和专利关联表插入数据
            log.info("数据入产品和专利关联表");
            this.saveBatch(newAssoProductPatents);
        }
        log.info("新增专利和产品关联完成");

    }

}
