package cn.cslg.report.service.business;

import cn.cslg.report.common.model.vo.*;
import cn.cslg.report.common.utils.CacheUtils;
import cn.cslg.report.common.utils.DataUtils;
import cn.cslg.report.common.utils.PatentUtils;
import cn.cslg.report.common.utils.Response;
import cn.cslg.report.common.utils.SecurityUtils.LoginUtils;

import cn.cslg.report.entity.*;
import cn.cslg.report.entity.asso.AssoTaskPersonel;
import cn.cslg.report.mapper.ReportFieldMapper;
import cn.cslg.report.service.OutInterfaceService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * <p>
 * 专利信息自定义字段表 服务类
 * </p>
 *
 * @author 王岩
 * @since 2021-12-16
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
@SuppressWarnings({"all"})
public class ReportFieldService extends ServiceImpl<ReportFieldMapper, ReportField> {
    private final ReportFieldMapper reportFieldMapper;
    private final LoginUtils loginUtils;
    private final ReportFieldTextService reportFieldTextService;
    private final ReportFieldOptionService reportFieldOptionService;
    private final ReportFieldTreeService reportFieldTreeService;
    private final ReportFieldPatentLinkService reportFieldPatentLinkService;
    private final AssoTaskPersonelService assoTaskPersonelService;
    private final ReportFieldService reportFieldService;
    private final CompareFilesService compareFilesService;
    private final OutInterfaceService outInterfaceService;
    private final CacheUtils cacheUtils;
    public List<ReportField> getProjectFieldByProjectId(Integer projectId) {
        LambdaQueryWrapper<ReportField> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReportField::getReportId, projectId);
        return this.list(queryWrapper);
    }

    //增加自定义字段
    public String add(ReportField reportField) {
        ReportField temp = this.getProjectFieldByName(reportField.getName(), reportField.getReportId());
        if (temp != null) {
            return Response.error("字段名称已存在");
        }
        PersonnelVO personnelVO =cacheUtils.getLoginUser(loginUtils.getId());
        reportField.setPtype(reportField.getType() == 6 ? 2 : 1);
        reportField.setCreateBy(loginUtils.getId());
        reportField.setTenantId(personnelVO.getTenantId());
        reportField.insert();
        return Response.success(reportField.getId());
    }

    //修改自定义字段
    public String edit(ReportField reportField) {
        ReportField temp = this.getProjectFieldByName(reportField.getName(), reportField.getReportId());
        if (temp != null && !temp.getId().equals(reportField.getId())) {
            return Response.error("字段名称已存在");
        }
        reportField.setPtype(reportField.getType() == 6 ? 2 : 1);

        reportField.updateById();
        return Response.success(true);
    }

    //删除自定义字段
    public String deleteReportId(int reportId, int id) {
        reportFieldMapper.deleteReportId(reportId, id);
        return Response.success();
    }

    @Transactional(rollbackFor = Exception.class)
    public String delete(Integer id) {
        this.removeById(id);
        reportFieldTextService.deleteByFieldId(id);
        reportFieldOptionService.deleteByFieldId(id);
        reportFieldTreeService.deleteByFieldId(id);
        reportFieldPatentLinkService.deleteByFieldId(id);
        return Response.success(true);
    }

    //根据报告Id删除自定义字段
    @Transactional(rollbackFor = Exception.class)
    public String deleteByReportId(Integer id) {
        LambdaQueryWrapper<ReportField> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReportField::getReportId, id);
        List<ReportField> reportFields = this.list(queryWrapper);
        reportFieldTextService.deleteByFieldId(id);
        reportFieldOptionService.deleteByFieldId(id);
        reportFieldTreeService.deleteByFieldId(id);
        reportFieldPatentLinkService.deleteByFieldId(id);
        this.remove(queryWrapper);
        return Response.success(true);
    }

    //获得自定义字段列表
    public String getPageList(ReportFieldVO reportFieldVO) throws IOException {
        LambdaQueryWrapper<ReportField> queryWrapper = new LambdaQueryWrapper<>();
        if (reportFieldVO.getReportId() != null) {
            queryWrapper.eq(ReportField::getReportId, reportFieldVO.getReportId());
        }
        if (reportFieldVO.getName() != null) {
            queryWrapper.like(ReportField::getName, reportFieldVO.getName());
        }
        if (reportFieldVO.getReportType() != null) {
            PersonnelVO personnelVO =cacheUtils.getLoginUser(loginUtils.getId());
            queryWrapper.eq(ReportField::getReportType, reportFieldVO.getReportType());
            queryWrapper.isNull((ReportField::getReportId));
            queryWrapper.eq(ReportField::getTenantId,personnelVO.getTenantId());
        }
        queryWrapper.orderByDesc(ReportField::getId);
        if (reportFieldVO.getSize() != null && reportFieldVO.getCurrent() != null) {
            //查询列表
            List<ReportField> reportFields = this.page(new Page<>(reportFieldVO.getCurrent(), reportFieldVO.getSize()), queryWrapper).getRecords();
            //调用方法，给查询出的列表装载创建人名称
            reportFields = setCreatePersonNames(reportFields);
            long count = this.count(queryWrapper);
            return Response.success(reportFields, DataUtils.setPageColumn(reportFieldVO.getSize(), reportFieldVO.getCurrent(), Math.toIntExact(count)));
        } else {
            //查询列表
            List<ReportField> reportFields = this.list(queryWrapper);
            //调用方法，给查询出的列表装载创建人名称
            reportFields = setCreatePersonNames(reportFields);

            return Response.success(reportFields);
        }

    }

    /**
     * 给获得的自定义字段列表装载创建人名称
     *
     * @param reportFields 自定义字段列表
     * @return 返回装载完所有创建人名称的自定义字段列表
     * @throws IOException 抛出异常
     */
    private List<ReportField> setCreatePersonNames(List<ReportField> reportFields) throws IOException {
        //从列表中取出所有创建人id，并存入集合 createPersonIds
        ArrayList<Integer> createPersonIds = new ArrayList<>();
        for (ReportField reportField : reportFields) {
            createPersonIds.add(reportField.getCreateBy());
        }
        //远程调用权限系统根据人员ids获取人员信息personnels
        String res = outInterfaceService.getPersonnelByIdsFromPCS(createPersonIds);
        JSONObject jsonObject = JSONObject.parseObject(res);
        List<Personnel> personnels = JSON.parseArray(jsonObject.getString("data"), Personnel.class);
        //遍历列表和人员信息集合 personnels，给列表装载创建人名称
        for (ReportField reportField : reportFields) {
            for (Personnel personnel : personnels) {
                if (reportField.getCreateBy().equals(personnel.getId())) {
                    reportField.setCreateName(personnel.getPersonnelName());
                }
            }
        }
        return reportFields;
    }

    /**
     * @param reportId 报告ID
     * @param patentNo 专利号
     * @return
     * @function 查询自定义自定
     */
    public List<PatentField> getPatentFieldByPatentIdAndProjectId(Integer reportId, String patentNo) {
        List<PatentField> dataList = new ArrayList<>();
        List<ReportFieldPatentLink> linkList = reportFieldPatentLinkService.getProjectPatentLinkByPatentAndProId(patentNo, reportId);
        List<Integer> fieldIds = linkList.stream().map(ReportFieldPatentLink::getFieldId).distinct().collect(Collectors.toList());
        //分类
        List<Integer> optionIds = linkList.stream().map(ReportFieldPatentLink::getOptionId).distinct().collect(Collectors.toList());
        List<ReportField> fieldList = this.getFieldListByIds(fieldIds);
        List<ReportFieldText> textList = reportFieldTextService.getProjectFieldTextByFieldIds(fieldIds);
        List<ReportFieldOption> optionList = reportFieldOptionService.getFieldOptionList(fieldIds);
        List<ReportFieldTree> treeList = reportFieldTreeService.getReportFieldTreeOptionByFieldIds(fieldIds);
        fieldList.forEach(field -> {
            PatentField data = new PatentField();
            data.setId(field.getId());
            data.setName(field.getName());
            data.setType(field.getType());
            //根据类型分类查询
            switch (field.getType()) {
                case 0:
                case 1:
                    //文本类型
                case 2:
                    data.setSelected(textList.stream().filter(item -> item.getFieldId().equals(field.getId()) && optionIds.contains(item.getId())).map(ReportFieldText::getText).distinct().collect(Collectors.toList()));
                    break;
                case 3:
                case 4:
                case 5:
                    //选项类型
                    data.setSelected(optionList.stream().filter(item -> item.getFieldId().equals(field.getId()) && optionIds.contains(item.getId())).map(ReportFieldOption::getName).distinct().collect(Collectors.toList()));
                    break;
                case 6:
                    //树类型
                    List<ReportFieldTree> trees = treeList.stream().filter(item -> item.getFieldId().equals(field.getId())).collect(Collectors.toList());
                    List<ReportFieldTree> optionTree = trees.stream().filter(item -> optionIds.contains(item.getId())).collect(Collectors.toList());
                    List<String> selected = new ArrayList<>();
                    optionTree.forEach(item -> selected.add(PatentUtils.getTreeNodeFullName(trees, item.getPath())));
                    data.setSelected(selected);
                    break;
            }
            dataList.add(data);
        });
        return dataList;
    }
    //查询自定义字段

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

    /**
     * @param name     自定义字段的名称
     * @param reportId 报告id
     * @return
     * @function 查询自定义字段
     */

    public ReportField getProjectFieldByName(String name, Integer reportId) {
        LambdaQueryWrapper<ReportField> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReportField::getName, name);
        queryWrapper.eq(ReportField::getReportId, reportId);
        return this.getOne(queryWrapper);
    }

    //给报告添加默认自定义字段
    public void addDefaultField(Integer reportId, Integer reportType) {
        PersonnelVO personnelVO = cacheUtils.getLoginUser(loginUtils.getId());
        Integer tenantId =personnelVO.getTenantId();
        //根据报告类型添加默认自定义字段
        LambdaQueryWrapper<ReportField> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReportField::getReportType, reportType);
        queryWrapper.isNull(ReportField::getReportId)
                 .eq(ReportField::getTenantId,tenantId);
        //默认自定义字段
        List<ReportField> reportFields = this.list(queryWrapper);
        if (reportFields != null && reportFields.size() != 0) {
            reportFields.forEach(p -> {
                        p.setReportId(reportId);
                        p.setOriginId(p.getId());
                        p.setId(null);
                        p.setCreateName(null);
                    }
            );
            reportFieldService.saveBatch(reportFields);
        }

        reportFields.forEach(p -> {
            if (p.getType().equals(1) || p.getType().equals(0) || p.getType().equals(2)) {

            }
            if (p.getType().equals(3) || p.getType().equals(4) || p.getType().equals(5)) {
                //根据自定义字段的ID 从表中查出选项列表
                LambdaQueryWrapper<ReportFieldOption> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(ReportFieldOption::getFieldId, p.getOriginId());
                List<ReportFieldOption> reportFieldOptions = reportFieldOptionService.list(wrapper);

                reportFieldOptionService.addBatchs(reportFieldOptions, p.getId());
            }

            if (p.getType().equals(6)) {
                LambdaQueryWrapper<ReportFieldTree> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(ReportFieldTree::getFieldId, p.getOriginId());
                List<ReportFieldTree> list = reportFieldTreeService.list(wrapper);
                reportFieldTreeService.addBatchs(list, p.getId());

            }
        });
    }


    public String getReportField(int reportId, int id) {
        List<ReportField> reportFields = reportFieldMapper.find(reportId, id);
        return Response.success(reportFields);
    }

    // 查询自定义字段
    public ReportField get(int id) {
        LambdaQueryWrapper<ReportField> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReportField::getId, id);
        return this.list(queryWrapper).get(0);
    }

    //修改自定义字段
    public String updateReportId(ReportField reportField) {
        reportFieldMapper.updateReportId(reportField);
        return Response.success();
    }

    //查询自定义字段
    public List<ReportField> selectAll(int id) throws IOException {
        LambdaQueryWrapper<ReportField> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReportField::getReportId, id);
        return this.list(queryWrapper);


    }

    /**
     * 1.接口 根据报告id 查询自定义字段 参数报告id
     * 返回该报告下所有的自定义字段
     */


    public String selectReportField(int reportId) throws IOException {
        List<ReportField> reportFields = this.selectAll(reportId);
        List<Integer> collect = reportFields.stream().map(ReportField::getReportType).collect(Collectors.toList());
        List<Integer> list = reportFields.stream().map(ReportField::getId).collect(Collectors.toList());
        for (int i = 0; i < list.size(); i++) {
            if (collect.get(i).equals(6)) {
                return Response.success(reportFieldTreeService.getReportFieldTreeNodeByFieldId(list.get(i)));
            } else {
                return Response.success(reportFieldOptionService.getListByFieldId(list.get(i)));
            }
        }
        return Response.success();

    }

    /**
     * @param params
     * @return
     * @function 查询自定义字段，统计与之相关的专利的数量
     */
    public List<PatentQueryFieldSourceVO> getPatentQuerySourcePageList(PatentQueryFieldSourceVO params) {
        //记录树最大长度
        Integer treeLevel = 0;
        List<PatentQueryFieldSourceVO> list = new ArrayList<>();
        //根据fieldId 从patent_field中获得 自定义字段对象
        LambdaQueryWrapper<ReportField> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ReportField::getId, params.getFieldId());
        if (this.list(wrapper).size() == 0) {
            return list;
        }
        ReportField reportField = this.list(wrapper).get(0);
        //获得所有专利号
        List<String> allNos = new ArrayList<>();
        // 如果是任务清单
        if (params.getTaskId() != null) {
            LambdaQueryWrapper<AssoTaskPersonel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AssoTaskPersonel::getTaskId, params.getTaskId());
            List<AssoTaskPersonel> assoTaskPersonels = assoTaskPersonelService.list(queryWrapper);
            allNos = assoTaskPersonels.stream().map(AssoTaskPersonel::getPatentNo).collect(Collectors.toList());
        }
        //所有对比文件
        else {
            LambdaQueryWrapper<CompareFiles> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CompareFiles::getReportId, reportField.getReportId());
            List<CompareFiles> compareFiles = compareFilesService.list(queryWrapper);
            allNos = compareFiles.stream().map(CompareFiles::getPatentNo).distinct().collect(Collectors.toList());

        }

        //根据自定义字段的类型，从三张值表中查询该自定义字段所有值的id
        int type1 = reportField.getType();
        switch (type1) {
            //数字
            case 0:
                //日期
            case 1:
                //文本
            case 2:
                LambdaQueryWrapper<ReportFieldText> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(ReportFieldText::getFieldId, params.getFieldId());
                List<ReportFieldText> reportFieldTexts = reportFieldTextService.list(queryWrapper);
                reportFieldTexts.forEach(item -> {
                    PatentQueryFieldSourceVO patentQueryFieldSourceVO = new PatentQueryFieldSourceVO();
                    patentQueryFieldSourceVO.setFieldId(params.getFieldId());
                    patentQueryFieldSourceVO.setKey(item.getId());
                    patentQueryFieldSourceVO.setLabel(item.getText());
                    list.add(patentQueryFieldSourceVO);
                });
                break;

            //单选
            case 4:

                //多选
            case 5:
                LambdaQueryWrapper<ReportFieldOption> queryWrapper5 = new LambdaQueryWrapper<>();
                queryWrapper5.eq(ReportFieldOption::getFieldId, params.getFieldId());

                List<ReportFieldOption> reportFieldOption = reportFieldOptionService.list(queryWrapper5);
                reportFieldOption.forEach(item -> {
                    PatentQueryFieldSourceVO patentQueryFieldSourceVO = new PatentQueryFieldSourceVO();
                    patentQueryFieldSourceVO.setFieldId(params.getFieldId());
                    patentQueryFieldSourceVO.setKey(item.getId());
                    patentQueryFieldSourceVO.setLabel(item.getName());
                    list.add(patentQueryFieldSourceVO);
                });
                break;
            //树
            case 6:
                LambdaQueryWrapper<ReportFieldTree> queryWrapper6 = new LambdaQueryWrapper<>();
                queryWrapper6.eq(ReportFieldTree::getFieldId, params.getFieldId());
                List<ReportFieldTree> reportFieldTrees = reportFieldTreeService.list(queryWrapper6);
                for (ReportFieldTree item : reportFieldTrees) {
                    PatentQueryFieldSourceVO patentQueryFieldSourceVO = new PatentQueryFieldSourceVO();
                    patentQueryFieldSourceVO.setFieldId(params.getFieldId());
                    String[] arr1 = item.getPath().split("\\/");
                    patentQueryFieldSourceVO.setPaths(Arrays.asList(arr1));
                    if (patentQueryFieldSourceVO.getPaths().size() > treeLevel) {
                        treeLevel = patentQueryFieldSourceVO.getPaths().size();
                    }
                    patentQueryFieldSourceVO.setKey(item.getId());
                    patentQueryFieldSourceVO.setLabel(item.getName());
                    list.add(patentQueryFieldSourceVO);
                }
                break;
        }
        List<Integer> valueIds = list.stream().map(PatentQueryFieldSourceVO::getKey).collect(Collectors.toList());
        LambdaQueryWrapper<ReportFieldPatentLink> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ReportFieldPatentLink::getFieldId, params.getFieldId());
        if (valueIds != null && valueIds.size() > 0) {
            lambdaQueryWrapper.in(ReportFieldPatentLink::getOptionId, valueIds);
        }
        List<ReportFieldPatentLink> reportFieldPatentLinks = reportFieldPatentLinkService.list(lambdaQueryWrapper);
        if (reportFieldPatentLinks.size() == 0) {
            list.forEach(item -> item.setCount(0));
            //未选择选项
            PatentQueryFieldSourceVO patentQueryFieldSourceVO = new PatentQueryFieldSourceVO();
            patentQueryFieldSourceVO.setFieldId(params.getFieldId());
            patentQueryFieldSourceVO.setKey(null);
            patentQueryFieldSourceVO.setLabel("未选择");
            patentQueryFieldSourceVO.setCount(allNos.size());
            list.add(patentQueryFieldSourceVO);
            return list;
        }
        //记录已被选择的数量
        Integer choosed = 0;
        for (PatentQueryFieldSourceVO tem : list) {
            List<ReportFieldPatentLink> part = reportFieldPatentLinks.stream().filter(tm -> tm.getFieldId().equals(params.getFieldId()) && tm.getOptionId().equals(tem.getKey()
            )).collect(Collectors.toList());
            //如果是任务清单列表
            if (params.getTaskId() != null) {
                List<String> partPatentNos = part.stream().map(ReportFieldPatentLink::getPatentNo).collect(Collectors.toList());
                List<String> jiaoList = new ArrayList<>(allNos);
                jiaoList.retainAll(partPatentNos);
                tem.setCount(jiaoList.size());
                choosed += jiaoList.size();
            } else {
                tem.setCount(part.size());
                choosed += part.size();
            }
            tem.setType(type1);
        }
//当是树类型时，对数量进行格式化
        if (type1 == 6) {
            for (int i = treeLevel; i > 1; i--) {
                int t = i;
                List<PatentQueryFieldSourceVO> temList = list.stream().filter(item -> item.getPaths().size() == t).collect(Collectors.toList());
                for (PatentQueryFieldSourceVO vo : list) {
                    if (vo.getPaths().size() == t - 1) {
                        List<Integer> counts = temList.stream().filter(item -> item.getPaths().containsAll(vo.getPaths())).map(PatentQueryFieldSourceVO::getCount).collect(Collectors.toList());
                        Integer count = 0;
                        for (Integer intg : counts) {
                            count += intg;
                        }
                        vo.setCount(vo.getCount() + count);
                    }
                }
            }
        }
        //未选择选项
        PatentQueryFieldSourceVO patentQueryFieldSourceVO = new PatentQueryFieldSourceVO();
        patentQueryFieldSourceVO.setFieldId(params.getFieldId());
        patentQueryFieldSourceVO.setKey(null);
        patentQueryFieldSourceVO.setLabel("未选择");
        patentQueryFieldSourceVO.setCount(allNos.size() - choosed);
        list.add(patentQueryFieldSourceVO);

        //获得所有未选择的数量
        //根据值id从ReportFieldPatentLink表中获得信息
        return list;

    }

    /**
     * @param params
     * @return
     * @throws IOException
     * @funtion 查询标引内容关联专利
     */
    public List<String> getString(SourceVO params, List<String> allPatentNos) throws IOException {
        List<String> list = new ArrayList<>();
        List<ReportFieldPatentLink> reportFieldPatentLinks = new ArrayList<>();
        LambdaQueryWrapper<ReportFieldPatentLink> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ReportFieldPatentLink::getFieldId, params.getFieldId());
        if (params.getKey() != null) {
            lambdaQueryWrapper.eq(ReportFieldPatentLink::getOptionId, params.getKey());
            reportFieldPatentLinks = reportFieldPatentLinkService.list(lambdaQueryWrapper);
            list = reportFieldPatentLinks.stream().map(ReportFieldPatentLink::getPatentNo).collect(Collectors.toList());
        } else {
            reportFieldPatentLinks = reportFieldPatentLinkService.list(lambdaQueryWrapper);
            List<String> patentNos = reportFieldPatentLinks.stream().map(ReportFieldPatentLink::getPatentNo).collect(Collectors.toList());
            allPatentNos.removeAll(patentNos);
            list = allPatentNos;
        }

        return list;
    }


    /**
     * 模糊查询自定义字段（参数：自定义字段的id，和模糊查询的字段文本类型）
     * 文本类型，单选，数字类型不用查
     *
     * @return 返回自定义字段
     */

    public String getReportField(PatentQueryFieldSourceVO params) {
        if (params.getName() != null && params.getName() != "") {
            List<PatentQueryFieldSourceVO> list = new ArrayList<>();
            LambdaQueryWrapper<ReportField> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ReportField::getId, params.getFieldId());
            ReportField reportField = this.list(wrapper).get(0);
            int type1 = reportField.getType();
            if (type1 == 1 || type1 == 2 || type1 == 3) {
                LambdaQueryWrapper<ReportFieldText> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(ReportFieldText::getFieldId, params.getFieldId());

                queryWrapper.like(ReportFieldText::getText, params.getName());
                List<ReportFieldText> list1 = reportFieldTextService.list(queryWrapper);
                for (ReportFieldText a : list1) {
                    PatentQueryFieldSourceVO param = new PatentQueryFieldSourceVO();
                    LambdaQueryWrapper<ReportFieldPatentLink> wrapper1 = new LambdaQueryWrapper<>();
                    wrapper1.eq(ReportFieldPatentLink::getFieldId, a.getFieldId()).eq(ReportFieldPatentLink::getOptionId, a.getId());
                    param.setName(a.getText());
                    param.setCount(reportFieldPatentLinkService.list(wrapper1).size());
                    param.setFieldId(a.getFieldId());
                    param.setKey(a.getId());
                    param.setType(type1);
                    list.add(param);
                }

            } else if (type1 == 5 || type1 == 4) {
                LambdaQueryWrapper<ReportFieldOption> queryWrapper5 = new LambdaQueryWrapper<>();
                queryWrapper5.eq(ReportFieldOption::getFieldId, params.getFieldId());

                queryWrapper5.like(ReportFieldOption::getName, params.getName());

                List<ReportFieldOption> list1 = reportFieldOptionService.list(queryWrapper5);
                for (ReportFieldOption a : list1) {
                    PatentQueryFieldSourceVO param = new PatentQueryFieldSourceVO();
                    LambdaQueryWrapper<ReportFieldPatentLink> wrapper1 = new LambdaQueryWrapper<>();
                    wrapper1.eq(ReportFieldPatentLink::getFieldId, a.getFieldId()).eq(ReportFieldPatentLink::getOptionId, a.getId());
                    param.setName(a.getName());
                    param.setCount(reportFieldPatentLinkService.list(wrapper1).size());
                    param.setType(type1);
                    param.setFieldId(a.getFieldId());
                    param.setKey(a.getId());

                    list.add(param);
                }

            } else if (type1 == 6) {
                LambdaQueryWrapper<ReportFieldTree> queryWrapper6 = new LambdaQueryWrapper<>();
                queryWrapper6.eq(ReportFieldTree::getFieldId, params.getFieldId());
                queryWrapper6.like(ReportFieldTree::getName, params.getName());
                List<ReportFieldTree> list1 = reportFieldTreeService.list(queryWrapper6);
                for (ReportFieldTree a : list1) {
                    PatentQueryFieldSourceVO param = new PatentQueryFieldSourceVO();
                    LambdaQueryWrapper<ReportFieldPatentLink> wrapper1 = new LambdaQueryWrapper<>();
                    wrapper1.eq(ReportFieldPatentLink::getFieldId, a.getFieldId()).eq(ReportFieldPatentLink::getOptionId, a.getId());
                    param.setName(a.getName());
                    param.setType(type1);
                    param.setFieldId(a.getFieldId());
                    param.setKey(a.getId());
                    param.setCount(reportFieldPatentLinkService.list(wrapper1).size());
                    list.add(param);
                }

            }
            return Response.success(list);
        } else {
            List<PatentQueryFieldSourceVO> list = new ArrayList<>();
            //根据fieldId 从patent_field中获得 自定义字段对象
            LambdaQueryWrapper<ReportField> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ReportField::getId, params.getFieldId());
            if (this.list(wrapper).size() == 0) {
                return Response.success(list);
            }
            ReportField reportField = this.list(wrapper).get(0);
            //获得所有专利号
            List<String> allNos = new ArrayList<>();
            // 如果是任务清单
            if (params.getTaskId() != null) {
                LambdaQueryWrapper<AssoTaskPersonel> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AssoTaskPersonel::getTaskId, params.getTaskId());
                List<AssoTaskPersonel> assoTaskPersonels = assoTaskPersonelService.list(queryWrapper);
                allNos = assoTaskPersonels.stream().map(AssoTaskPersonel::getPatentNo).collect(Collectors.toList());
            }
            //所有对比文件
            else {
                LambdaQueryWrapper<CompareFiles> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(CompareFiles::getReportId, reportField.getReportId());
                List<CompareFiles> compareFiles = compareFilesService.list(queryWrapper);
                allNos = compareFiles.stream().map(CompareFiles::getPatentNo).collect(Collectors.toList());

            }

            //根据自定义字段的类型，从三张值表中查询该自定义字段所有值的id
            int type1 = reportField.getType();
            switch (type1) {
                //数字
                case 0:
                    //日期
                case 1:
                    //文本
                case 2:
                    LambdaQueryWrapper<ReportFieldText> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(ReportFieldText::getFieldId, params.getFieldId());
                    List<ReportFieldText> reportFieldTexts = reportFieldTextService.list(queryWrapper);
                    reportFieldTexts.forEach(item -> {
                        PatentQueryFieldSourceVO patentQueryFieldSourceVO = new PatentQueryFieldSourceVO();
                        patentQueryFieldSourceVO.setFieldId(params.getFieldId());
                        patentQueryFieldSourceVO.setKey(item.getId());
                        patentQueryFieldSourceVO.setName(item.getText());
                        patentQueryFieldSourceVO.setType(type1);
                        list.add(patentQueryFieldSourceVO);
                    });
                    break;

                //单选
                case 4:

                    //多选
                case 5:
                    LambdaQueryWrapper<ReportFieldOption> queryWrapper5 = new LambdaQueryWrapper<>();
                    queryWrapper5.eq(ReportFieldOption::getFieldId, params.getFieldId());

                    List<ReportFieldOption> reportFieldOption = reportFieldOptionService.list(queryWrapper5);
                    reportFieldOption.forEach(item -> {
                        PatentQueryFieldSourceVO patentQueryFieldSourceVO = new PatentQueryFieldSourceVO();
                        patentQueryFieldSourceVO.setFieldId(params.getFieldId());
                        patentQueryFieldSourceVO.setKey(item.getId());
                        patentQueryFieldSourceVO.setName(item.getName());
                        list.add(patentQueryFieldSourceVO);
                    });
                    break;
                //树
                case 6:
                    LambdaQueryWrapper<ReportFieldTree> queryWrapper6 = new LambdaQueryWrapper<>();
                    queryWrapper6.eq(ReportFieldTree::getFieldId, params.getFieldId());
                    List<ReportFieldTree> reportFieldTrees = reportFieldTreeService.list(queryWrapper6);
                    reportFieldTrees.forEach(item -> {
                        PatentQueryFieldSourceVO patentQueryFieldSourceVO = new PatentQueryFieldSourceVO();
                        patentQueryFieldSourceVO.setFieldId(params.getFieldId());
                        patentQueryFieldSourceVO.setKey(item.getId());
                        patentQueryFieldSourceVO.setName(item.getName());
                        patentQueryFieldSourceVO.setType(type1);
                        list.add(patentQueryFieldSourceVO);
                    });
                    break;
            }
            List<Integer> valueIds = list.stream().map(PatentQueryFieldSourceVO::getKey).collect(Collectors.toList());
            LambdaQueryWrapper<ReportFieldPatentLink> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ReportFieldPatentLink::getFieldId, params.getFieldId());
            if (valueIds != null && valueIds.size() > 0) {
                lambdaQueryWrapper.in(ReportFieldPatentLink::getOptionId, valueIds)
                        .eq(ReportFieldPatentLink::getFieldId, params.getFieldId());
            }
            List<ReportFieldPatentLink> reportFieldPatentLinks = reportFieldPatentLinkService.list(lambdaQueryWrapper);
            if (reportFieldPatentLinks.size() == 0) {
                list.forEach(item -> item.setCount(0));
                //未选择选项
                PatentQueryFieldSourceVO patentQueryFieldSourceVO = new PatentQueryFieldSourceVO();
                patentQueryFieldSourceVO.setFieldId(params.getFieldId());
                patentQueryFieldSourceVO.setKey(null);
                patentQueryFieldSourceVO.setLabel("未选择");
                patentQueryFieldSourceVO.setCount(allNos.size());
                patentQueryFieldSourceVO.setType(type1);
                list.add(patentQueryFieldSourceVO);
                return Response.success(list);
            }
            //记录已被选择的数量
            Integer choosed = 0;
            for (PatentQueryFieldSourceVO tem : list) {
                List<ReportFieldPatentLink> part = reportFieldPatentLinks.stream().filter(tm -> tm.getFieldId().equals(params.getFieldId()) && tm.getOptionId().equals(tem.getKey()
                )).collect(Collectors.toList());
                //如果是任务清单列表
                if (params.getTaskId() != null) {
                    List<String> partPatentNos = part.stream().map(ReportFieldPatentLink::getPatentNo).collect(Collectors.toList());
                    List<String> jiaoList = new ArrayList<>(allNos);
                    jiaoList.retainAll(partPatentNos);
                    tem.setCount(jiaoList.size());
                    choosed += jiaoList.size();
                } else {
                    tem.setCount(part.size());
                    choosed += part.size();
                }
                tem.setType(type1);
            }
            //未选择选项
            PatentQueryFieldSourceVO patentQueryFieldSourceVO = new PatentQueryFieldSourceVO();
            patentQueryFieldSourceVO.setFieldId(params.getFieldId());
            patentQueryFieldSourceVO.setKey(null);
            patentQueryFieldSourceVO.setName("未选择");
            patentQueryFieldSourceVO.setCount(allNos.size() - choosed);
            patentQueryFieldSourceVO.setType(type1);
            list.add(patentQueryFieldSourceVO);
            //获得所有未选择的数量
            //根据值id从ReportFieldPatentLink表中获得信息
            return Response.success(list);


        }
    }

    /**
     * 自定义字段的id查询专利号
     * 并集：当自定义字段的id相同的时候取并集
     * 交集：当自定义字段的id不同的时候取交集
     *
     * @param params PatentQueryFieldSourceVO
     * @return PatentQueryFieldSourceVO
     * @throws IOException
     */

    public List<String> getPatentNo(List<SourceVO> params, List<String> allPatentNos) throws IOException {

        if (params.size() == 0) {
            List<String> list = new ArrayList<>();
            return list;
        } else {
            return this.getPatentNo2(params);
        }

    }


    public List<String> getPatentNo2(List<SourceVO> params) throws IOException {
        List<String> str = new ArrayList<>();
        if (params.size() == 0) {
            return str;
        }
        if (params.size() == 1) {
            LambdaQueryWrapper<ReportFieldPatentLink> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ReportFieldPatentLink::getOptionId, params.get(0).getKey());
            lambdaQueryWrapper.eq(ReportFieldPatentLink::getFieldId, params.get(0).getFieldId());
            List<ReportFieldPatentLink> list = reportFieldPatentLinkService.list(lambdaQueryWrapper);
            str = list.stream().map(ReportFieldPatentLink::getPatentNo).collect(Collectors.toList());
            return str;


        }
        List<List<SourceVO>> lists = new ArrayList<>();
        for (int i = 0; i < params.size() - 1; i++) {
            List<SourceVO> list = new ArrayList<>();
            list.add(params.get(i));
            for (int j = i + 1; j < params.size(); j++) {
                //找到自定义字段相同的字段
                if (params.get(i).getFieldId().equals(params.get(j).getFieldId())) {
                    list.add(params.get(j));
                    //有相同的就删除
                    params.remove(list.get(j));
                }
            }
            lists.add(list);

        }

        LambdaQueryWrapper<ReportFieldPatentLink> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        for (List<SourceVO> list : lists) {
            lambdaQueryWrapper.and(Wrapper -> {
                List<Integer> collect1 = list.stream().map(SourceVO::getFieldId).collect(Collectors.toList());
                List<Integer> collect = list.stream().map(SourceVO::getKey).collect(Collectors.toList());
                Wrapper.eq(ReportFieldPatentLink::getFieldId, collect1.get(0));
                Wrapper.in(ReportFieldPatentLink::getOptionId, collect);
            });

        }

        List<ReportFieldPatentLink> list = reportFieldPatentLinkService.list(lambdaQueryWrapper);
        List<String> collect = list.stream().map(ReportFieldPatentLink::getPatentNo).collect(Collectors.toList());
        return collect;


    }


    public List<String> getPatentNo1(List<SourceVO> params, Integer reportId, Integer taskId, Integer taskStatus) throws IOException {
        List<Map<String, Object>> mapList = new ArrayList<>();
        while (params.size() > 0) {
            Map<String, Object> map = new HashMap<>();
            Integer haveNull = 0;
            List<SourceVO> list = new ArrayList<>();
            list.add(params.get(0));
            if (params.get(0).getKey() == null) {
                haveNull = 1;
            }
            if (params.size() != 1) {
                for (int j = 1; j < params.size(); j++) {
                    //找到自定义字段相同的字段
                    if (params.get(0).getFieldId().equals(params.get(j).getFieldId())) {
                        if (params.get(j).getKey() == null) {
                            haveNull = 1;
                        }
                        list.add(params.get(j));
                    }
                }
            }
            map.put("field", params.get(0).getFieldId());
            map.put("optionList", list);
            map.put("haveNull", haveNull);
            mapList.add(map);
            params.removeAll(list);
        }
        List<String> collect = new ArrayList<>();
        if (taskId != null) {
            collect = baseMapper.getFieldTaskPNos(mapList, taskId, taskStatus);
        } else {
            if (reportId != null) {
                collect = baseMapper.getFieldPatentNos(mapList, reportId);
            }
        }
        return collect;

    }

    /**
     * @param reportId
     * @return
     * @description 根据报告Id获得自定义字段信息
     */
    public List<Map<String, Object>> getFieldsMap(Integer reportId) {
        //根据reportId获得自定义字段
        LambdaQueryWrapper<ReportField> reportFieldWrapper = new LambdaQueryWrapper<ReportField>();
        reportFieldWrapper.eq(ReportField::getReportId, reportId);
        List<ReportField> reportFields = this.list(reportFieldWrapper);
        List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
        //根据自定义字段类型装载map
        if (reportFields.size() != 0) {
            for (ReportField item : reportFields) {
                int type1 = item.getType();
                switch (type1) {
                    //数字
                    case 0:
                        //日期
                    case 1:
                        //文本
                    case 2:
                        LambdaQueryWrapper<ReportFieldText> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(ReportFieldText::getFieldId, item.getId());
                        List<ReportFieldText> reportFieldTexts = reportFieldTextService.list(queryWrapper);
                        reportFieldTexts.forEach(tem -> {
                                    Map<String, Object> map = new HashMap<>();
                                    map.put("CId", tem.getId());
                                    map.put("FId", tem.getFieldId());
                                    map.put("CName", tem.getText());
                                    lists.add(map);
                                }
                        );
                        break;

                    //单选
                    case 4:

                        //多选
                    case 5:
                        LambdaQueryWrapper<ReportFieldOption> queryWrapper5 = new LambdaQueryWrapper<>();
                        queryWrapper5.eq(ReportFieldOption::getFieldId, item.getId());
                        List<ReportFieldOption> reportFieldOption = reportFieldOptionService.list(queryWrapper5);
                        reportFieldOption.forEach(tem -> {
                            Map<String, Object> map = new HashMap<>();
                            map.put("CId", tem.getId());
                            map.put("FId", tem.getFieldId());
                            map.put("CName", tem.getName());
                            lists.add(map);
                        });
                        break;
                    //树
                    case 6:
                        LambdaQueryWrapper<ReportFieldTree> queryWrapper6 = new LambdaQueryWrapper<>();
                        queryWrapper6.eq(ReportFieldTree::getFieldId, item.getId());
                        List<ReportFieldTree> reportFieldTrees = reportFieldTreeService.list(queryWrapper6);
                        reportFieldTrees.forEach(tem -> {
                            Map<String, Object> map = new HashMap<>();
                            map.put("CId", tem.getId());
                            map.put("FId", tem.getFieldId());
                            map.put("CName", tem.getName());
                            lists.add(map);
                        });
                        break;
                }


            }
        }
        return lists;
    }
}





