package cn.cslg.pas.service;

import cn.cslg.pas.common.model.params.PatentSimpleFamilyParams;
import cn.cslg.pas.common.utils.PatentUtils;
import cn.cslg.pas.common.utils.StringUtils;
import cn.cslg.pas.domain.Patent;
import cn.cslg.pas.domain.PatentSimpleFamily;
import cn.cslg.pas.domain.PatentSimpleFamilyLink;
import cn.cslg.pas.mapper.PatentSimpleFamilyLinkMapper;
import cn.cslg.pas.mapper.PatentSimpleFamilyMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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 PatentSimpleFamilyService extends ServiceImpl<PatentSimpleFamilyMapper, PatentSimpleFamily> {

    private final PatentService patentService;
    private final PatentApplicantService patentApplicantService;
    private final PatentSimpleFamilyLinkService patentSimpleFamilyLinkService;
    private final PatentSimpleFamilyLinkMapper patentSimpleFamilyLinkMapper;

    public PatentSimpleFamily getPatentSimpleFamilyByIdsAndType(List<Integer> ids, Integer type) {
        if (ids == null || ids.size() == 0) {
            return null;
        }
        LambdaQueryWrapper<PatentSimpleFamily> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(PatentSimpleFamily::getId, ids);
        queryWrapper.eq(PatentSimpleFamily::getType, type);
        List<PatentSimpleFamily> patentSimpleFamilies = this.list(queryWrapper);
        if (patentSimpleFamilies.size() == 0) {
            return null;
        }
        return patentSimpleFamilies.get(0);
    }

    public List<PatentSimpleFamily> getPatentSimpleFamilyByIds(List<Integer> ids) {
        if (ids == null || ids.size() == 0) {
            return null;
        }
        LambdaQueryWrapper<PatentSimpleFamily> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(PatentSimpleFamily::getId, ids);
        return this.list(queryWrapper);
    }

    public void importPatentSimpleFamily(Patent patent, List<PatentSimpleFamily> importPatentSimpleFamilyList, List<PatentSimpleFamilyLink> importPatentSimpleFamilyLinkList) {
        List<PatentSimpleFamilyLink> importPatentSimpleFamilyLink = importPatentSimpleFamilyLinkList.stream().filter(item -> item.getFamilyId().equals(patent.getSimpleFamily())).collect(Collectors.toList());
        List<PatentSimpleFamilyLink> importPatentInpadocFamilyLink = importPatentSimpleFamilyLinkList.stream().filter(item -> item.getFamilyId().equals(patent.getInpadocFamily())).collect(Collectors.toList());
        List<PatentSimpleFamilyLink> importPatentPatSnapFamilyLink = importPatentSimpleFamilyLinkList.stream().filter(item -> item.getFamilyId().equals(patent.getPatSnapFamily())).collect(Collectors.toList());
        PatentSimpleFamilyParams patentSimpleFamilyParams = new PatentSimpleFamilyParams();
        patentSimpleFamilyParams.setPatentId(patent.getId());
        patentSimpleFamilyParams.setPatentNo(patent.getPatentNo());
        patentSimpleFamilyParams.setSimpleFamily(importPatentSimpleFamilyLink.stream().map(PatentSimpleFamilyLink::getPatentNo).collect(Collectors.toList()));
        patentSimpleFamilyParams.setInpadocFamily(importPatentInpadocFamilyLink.stream().map(PatentSimpleFamilyLink::getPatentNo).collect(Collectors.toList()));
        patentSimpleFamilyParams.setPatSnapFamily(importPatentPatSnapFamilyLink.stream().map(PatentSimpleFamilyLink::getPatentNo).collect(Collectors.toList()));
        this.updatePatentSimpleFamily(patentSimpleFamilyParams);
    }

    /**
     * @param params 简单同族相关信息
     */
    public void updatePatentSimpleFamily(PatentSimpleFamilyParams params) {
        if (params.getSimpleFamily() != null && params.getSimpleFamily().size() != 0) {
            this.updateData(params.getSimpleFamily(), params.getPatentNo(), params.getPatentId(), 1);
        }
        if (params.getInpadocFamily() != null && params.getInpadocFamily().size() != 0) {
            this.updateData(params.getInpadocFamily(), params.getPatentNo(), params.getPatentId(), 2);
        }
        if (params.getPatSnapFamily() != null && params.getPatSnapFamily().size() != 0) {
            this.updateData(params.getPatSnapFamily(), params.getPatentNo(), params.getPatentId(), 3);
        }
    }

    /**
     * 专利信息简单同族关联表"os_patent_simplefamily"新增数据
     *
     * @param type     1是简单同族 2.INPADOC同族
     * @param patentNO 公开号
     * @return 返回新增后的数据
     */
    public PatentSimpleFamily add(Integer type, String patentNO) {
        PatentSimpleFamily patentSimpleFamily = new PatentSimpleFamily();
        patentSimpleFamily.setType(type);
        patentSimpleFamily.setPatentNo(patentNO);
        patentSimpleFamily.insert();
        return patentSimpleFamily;
    }

    public void updateData(List<String> familyNo, String patentNo, Integer patentId, Integer type) {
        //0.合并专利号
        if (!familyNo.contains(patentNo)) {
            familyNo.add(patentNo);
        }
        //1.根据专利号（faimlyNo + patentNo）从专利基础信息表中获取专利数据，以受理国家、申请日由小到大排序
        List<Patent> patent1s = patentService.getPublicDateAndPatentNoByPatentNo(familyNo);

        //2.从1步取得的专利清单获取第一个CN专利号，作为插入Family表中的专利号，如果没有CN专利，则取第一个专利号
        String temPatentNo = "";
        if (patent1s != null) {
            Patent patentTem = patent1s.stream().filter(item -> PatentUtils.getPatentCountry(item.getPatentNo()) == "CN").findFirst().orElse(null);
            if (patentTem == null) {
                patentTem = patent1s.get(0);
            }
            temPatentNo = patentTem.getPatentNo();
        } else {
            temPatentNo = patentNo;
        }
        String familyPatent = temPatentNo;
        //根据专利号查询同族信息
        LambdaQueryWrapper<PatentSimpleFamily> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(PatentSimpleFamily::getPatentNo, familyNo)
                .eq(PatentSimpleFamily::getType, type);
        List<PatentSimpleFamily> simpleFamilies = this.list(wrapper);
        //获得同族专利的同族id
        List<Integer> familyIds = simpleFamilies.stream().map(PatentSimpleFamily::getId).collect(Collectors.toList());
        //查询是否有满足条件的
        PatentSimpleFamily simpleFamily = simpleFamilies.stream().filter(item -> item.getPatentNo().equals(familyPatent) && item.getType().equals(type)).findFirst().orElse(null);
        if (simpleFamily == null) {
            simpleFamily = this.add(type, familyPatent);
        }
        familyIds.remove(simpleFamily.getId());

        //3.根据专利号（faimlyNo + patentNo）和同族类型从family关联表中取数据
        List<PatentSimpleFamilyLink> patentSimpleFamilyLinkList = patentSimpleFamilyLinkMapper.getPatentFamilyLinkByPatentNo(familyNo, type);

        //5.专利号（faimlyNo + patentNo）和第三步获得的记录比较，如果没有则在关联表中添加一条记录
        for (String temPN : familyNo) {
            PatentSimpleFamilyLink temp = patentSimpleFamilyLinkList.stream().filter(item -> item.getPatentNo().equals(temPN)).findFirst().orElse(null);
            if (temp == null) {
                //5.1 如果关联表中没有记录,添加一个
                PatentSimpleFamilyLink patentSimpleFamilyLink = new PatentSimpleFamilyLink();
                patentSimpleFamilyLink.setFamilyId(simpleFamily.getId());
                patentSimpleFamilyLink.setPatentNo(temPN);
                patentSimpleFamilyLink.insert();
            } else {
                //5.2 如果关联表中有记录，判断familyid是否跟temFailyID相同，不相同则更新记录
                if (temp.getFamilyId() != simpleFamily.getId()) {
                    temp.setFamilyId(simpleFamily.getId());
                    temp.updateById();
                }
            }
        }
        //6.如果同族关联表有数据则更新，无数据则插入一条数据
        Patent patent1 = patent1s.stream().filter(item -> item.getPatentNo().equals(familyPatent)).findFirst().orElse(null);
        if (patent1 != null) {
            switch (type) {
                case 1:
                    if (patent1.getSimpleFamily() != simpleFamily.getId()) {
                        patent1.setSimpleFamily(simpleFamily.getId());
                        patent1.updateById();
                    }
                    break;
                case 2:
                    if (patent1.getInpadocFamily() != simpleFamily.getId()) {
                        patent1.setInpadocFamily(simpleFamily.getId());
                        patent1.updateById();
                    }
                    break;
                case 3:
                    if (patent1.getPatSnapFamily() != simpleFamily.getId()) {
                        patent1.setPatSnapFamily(simpleFamily.getId());
                        patent1.updateById();
                    }
                    break;
            }

        }
        if (familyIds.size() != 0) {
            //删除同族关联信息
            LambdaQueryWrapper<PatentSimpleFamilyLink> linkWrapper = new LambdaQueryWrapper<>();
            linkWrapper.in(PatentSimpleFamilyLink::getId, familyIds);
            patentSimpleFamilyLinkService.remove(linkWrapper);
            //删除其他同族信息
            LambdaUpdateWrapper<PatentSimpleFamily> deleteWrapper = new LambdaUpdateWrapper<>();
            deleteWrapper.in(PatentSimpleFamily::getId, familyIds);
            this.remove(deleteWrapper);
        }
    }


}
