package cn.cslg.report.service.business;

import cn.cslg.report.common.core.base.Constants;
import cn.cslg.report.common.model.dto.CustomFieldLabelDTO;
import cn.cslg.report.common.model.dto.PatentQueryFieldSourceDTO;
import cn.cslg.report.common.model.vo.CompareFilesVO;
import cn.cslg.report.common.model.vo.PatentIndexSettingVO;
import cn.cslg.report.common.model.vo.PatentQueryFieldSourceVO;
import cn.cslg.report.common.model.vo.PatentVO;

import cn.cslg.report.common.utils.JsonUtils;
import cn.cslg.report.common.utils.Response;
import cn.cslg.report.common.utils.StringUtils;
import cn.cslg.report.entity.*;
import cn.cslg.report.mapper.CompareFilesMapper;
import cn.cslg.report.service.OutInterfaceService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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 lombok.extern.slf4j.Slf4j;

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.stream.Collectors;
@SuppressWarnings({"all"})
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class CompareFilesService extends ServiceImpl<CompareFilesMapper, CompareFiles> {
    private final CompareFilesMapper compareFilesMapper;
    private final OutInterfaceService outInterfaceService;
    private final ReportService reportService;
    private final ReportFieldService reportFieldService;
    private final ReportFieldTreeService reportFieldTreeService;
    private final ReportFieldOptionService reportFieldOptionService;
    private final AssoComapareFielService assoComapareFielService;
    private final ReportFieldPatentLinkService reportFieldPatentLinkService;
    private final  SysDictItemService sysDictItemService;

    @Transactional(rollbackFor = Exception.class)
    public String addCompareFile(CompareFilesVO compareFilesVO) throws IOException {
        //查询标的专利信息
        Report report = reportService.getById(compareFilesVO.getReportId());
        //根据标的专利号获得专利信息
        String res1 = outInterfaceService.getPatentFromPAS( report.getSignPatentNo());
        JSONObject res1Object = JSONObject.parseObject(res1);
        JSONObject patentNoJSON = JSONObject.parseObject(res1Object.get("data").toString());
            //获得引用专利号
            String quote =patentNoJSON.get("quote").toString().replace(" ","");
            List<String> quotes = Arrays.asList(quote.split("\\|"));
            //获得同族专利号
        List<String> familyPatentNos =new ArrayList<>();
        if(patentNoJSON.containsKey("family")) {
            String familyJson = patentNoJSON.get("family").toString();
            familyPatentNos = JsonUtils.jsonToList(JsonUtils.objectToJson(familyJson), String.class);
        }
        LambdaQueryWrapper<CompareFiles> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompareFiles::getReportId, compareFilesVO.getReportId());
        List<CompareFiles> compareFile1 = this.list(queryWrapper);
        List<String> patentNoList = compareFile1.stream().map(CompareFiles::getPatentNo).collect(Collectors.toList());
        List<CompareFiles> compareFiles = new ArrayList<>();
        PatentVO patentVO = new PatentVO();
        patentVO.setStartNumber(compareFilesVO.getStartNumber() - 1);
        patentVO.setEndNumber(compareFilesVO.getEndNumber());
        patentVO.setReportId(compareFilesVO.getReportId());
        patentVO.setPatentNos(patentNoList);
        String res = outInterfaceService.getComPatentNos(patentVO);
        JSONObject jsonObject = JSONObject.parseObject(res);
        List<String> patentNos = JSONArray.parseArray(jsonObject.get("data").toString(), String.class);
        patentNos.removeAll(compareFilesVO.getIsDelete());
        patentNos.addAll(compareFilesVO.getIsAdd());
        patentNos.removeAll(patentNoList);
        for(int i=0;i<patentNos.size();i++){
            CompareFiles compareFiles1 = new CompareFiles();
            compareFiles1.setPatentNo(patentNos.get(i));
            compareFiles1.setReportId(compareFilesVO.getReportId());
            if (quotes.size() != 0 && quotes.contains(patentNos.get(i))) {
                compareFiles1.setRemark("引");
            }
            if (familyPatentNos.size() != 0 && familyPatentNos.contains(patentNos.get(i))) {
                compareFiles1.setRemark("同");
            }
            compareFiles.add(compareFiles1);
        }

        this.saveBatch(compareFiles);
        return Response.success();
    }

    public String getCompareFile(PatentVO patentVO) throws IOException {
        LambdaQueryWrapper<CompareFiles> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompareFiles::getReportId, patentVO.getReportId());

        List<CompareFiles> compareFiles = this.list(queryWrapper);
        List<String> patentNos = compareFiles.stream().map(CompareFiles::getPatentNo).collect(Collectors.toList());
        String res;
        if (patentVO.getState() == 1) {
            patentVO.setPatentNos(patentNos);
            res = outInterfaceService.getPatentFromPAS(patentVO, 1);

        } else {
            LambdaQueryWrapper<Report> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.select(Report::getSignPatentNo);
            wrapper1.eq(Report::getId, patentVO.getReportId());
            String signPatentNO = reportService.list(wrapper1).get(0).getSignPatentNo();
            patentNos.add(signPatentNO);
            patentVO.setNotInPatentNos(patentNos);
            res = outInterfaceService.getPatentFromPAS(patentVO, 0);

        }
        JSONObject jsonObject = JSONObject.parseObject(res);
        JSONObject resData = JSONObject.parseObject(jsonObject.getString("data"));
        List<JSONObject> list = JSONArray.parseArray(resData.getString("records"), JSONObject.class);
        List<String> temNos = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (patentNos.contains(list.get(i).get("patentNo").toString())) {
                temNos.add(list.get(i).get("patentNo").toString());
            }

        }
        int i = compareFilesMapper.selectedTotal(patentVO.getReportId());
        Map<String, Object> map = new HashMap<>();
        map.put("datas", resData);
        map.put("select", temNos);
        map.put("selectedTotal", i);
        return Response.success(map);
    }

    //获得已经确定的对比专利详情
    public String getSureCompareFile(PatentVO patentVO) throws IOException {
        LambdaQueryWrapper<CompareFiles> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompareFiles::getReportId, patentVO.getReportId());
        List<CompareFiles> compareFiles = this.list(queryWrapper);
        List<String> patentNos = compareFiles.stream().map(CompareFiles::getPatentNo).collect(Collectors.toList());
        patentVO.setPatentNos(patentNos);
        String res = outInterfaceService.getPatentFromPAS(patentVO, 1);
        return res;
    }

    public String getCompareNos(Integer reportId) throws IOException {
        LambdaQueryWrapper<CompareFiles> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompareFiles::getReportId, reportId);
        List<CompareFiles> compareFiles = this.list(queryWrapper);
        List<String> patentNos = compareFiles.stream().map(CompareFiles::getPatentNo).collect(Collectors.toList());
        return Response.success(patentNos);
    }

    //删除单个对比专利
    public String deletePatentNo(CompareFilesVO compareFilesVO) throws IOException {
        List<String> patentNos = new ArrayList<>();
        //是否根据范围删除
        if (compareFilesVO.getStartNumber() != null && compareFilesVO.getEndNumber() != null && compareFilesVO.getEndNumber() > compareFilesVO.getStartNumber()) {
            LambdaQueryWrapper<CompareFiles> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(CompareFiles::getPatentNo)
                    .eq(CompareFiles::getReportId, compareFilesVO.getReportId())
                    .last("limit" + (compareFilesVO.getStartNumber() - 1) + "," + compareFilesVO.getEndNumber());
            patentNos = this.list(wrapper).stream().map(CompareFiles::getPatentNo).collect(Collectors.toList());
        }
        if (compareFilesVO.getIsDelete() != null) {
            patentNos.removeAll(compareFilesVO.getIsDelete());
        }
        if (compareFilesVO.getIsAdd() != null) {
            patentNos.addAll(compareFilesVO.getIsAdd());
        }
        if (patentNos.size() != 0) {
            LambdaQueryWrapper<CompareFiles> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(CompareFiles::getPatentNo, patentNos);
            this.remove(lambdaQueryWrapper);
        }
        return Response.success();
    }

    public String dele(int id)throws IOException{
        CompareFiles compareFiles = new CompareFiles();
        compareFiles.deleteById(id);
        return Response.success();
    }

    public List<CustomFieldLabelDTO> setAll(Integer reportId, String patentNos) throws IOException{
        List<CustomFieldLabelDTO> dataList = new ArrayList<>();
        List<ReportField> reportFields = reportFieldService.selectAll(reportId);


        for(ReportField reportField:reportFields) {
            PatentIndexSettingVO params = new PatentIndexSettingVO();
            CustomFieldLabelDTO data = new CustomFieldLabelDTO();
            params.setPatentNo(patentNos);
            params.setType(reportField.getType());
            params.setFieldId(reportField.getId());
            params.setReportId(reportField.getReportId());
            data.setName(reportField.getName());
            data.setId(reportField.getId());
            data.setType(reportField.getType());
            data.setSelected(reportFieldPatentLinkService.getPatentIndexSetting(params));
            dataList.add(data);

        }

        return dataList;



    }

    @Transactional(rollbackFor = Exception.class)
    public void getPatentIndexSetting(PatentIndexSettingVO params)throws IOException {
       reportFieldPatentLinkService.updatePatentIndexSetting(params);

    }
    public IPage<PatentQueryFieldSourceDTO> getPatentQuerySourcePageList(PatentQueryFieldSourceVO params) {
        return this.getPatentAttributeSourcePageList(params);
    }

    public IPage<PatentQueryFieldSourceDTO> getPatentAttributeSourcePageList(PatentQueryFieldSourceVO params) {

        return  null;
    }


}
