package cn.cslg.pas.service;

import cn.cslg.pas.domain.PatentInventorLink;
import cn.cslg.pas.mapper.PatentInventorLinkMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 专利表、发明人关联表 服务类
 * </p>
 *
 * @author 王岩
 * @since 2022-02-24
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class PatentInventorLinkService extends ServiceImpl<PatentInventorLinkMapper, PatentInventorLink> {

    public List<PatentInventorLink> getPatentInventorLinkByPatentIds(List<Integer> patentIds) {
        if (patentIds == null || patentIds.size() == 0) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<PatentInventorLink> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(PatentInventorLink::getPatentId, patentIds);
        return this.list(queryWrapper);
    }

    public List<PatentInventorLink> getPatentInventorLinkByPatentId(Integer patentId) {
        LambdaQueryWrapper<PatentInventorLink> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PatentInventorLink::getPatentId, patentId);
        return this.list(queryWrapper);
    }

    public void updatePatentInventLink(List<Integer> inventorIds, Integer patentId, Integer firstId) {
        //先根据专利id删除专利与发明人关联表"os_patent_inventor_relation"原数据
        this.deleteByPatentId(patentId);
        //创建专利与发明人关联表"os_patent_inventor_relation"实体类对象集合，准备批量插入数据
        List<PatentInventorLink> dataList = inventorIds.stream().map(id -> {
            PatentInventorLink patentInventorLink = new PatentInventorLink();
            patentInventorLink.setPatentId(patentId);
            patentInventorLink.setInventorId(id);
            patentInventorLink.setFirst(firstId.equals(id) ? 1 : 0);
            return patentInventorLink;
        }).collect(Collectors.toList());
        if (dataList.size() != 0) {
            //专利与发明人关联数据插入专利与发明人关联表"os_patent_inventor_relation"
            this.saveOrUpdateBatch(dataList);
        }
    }

    public void delete(Integer inventorId, Integer patentId) {
        this.remove(Wrappers.<PatentInventorLink>lambdaQuery().eq(PatentInventorLink::getInventorId, inventorId).eq(PatentInventorLink::getPatentId, patentId));
    }

    public void deleteByPatentId(Integer patentId) {
        this.remove(Wrappers.<PatentInventorLink>lambdaQuery().eq(PatentInventorLink::getPatentId, patentId));
    }
}
