package cn.cslg.report.service.business;

import cn.cslg.report.common.model.vo.*;
import cn.cslg.report.common.model.vo.queryVo.QueryCMVO;
import cn.cslg.report.common.utils.CacheUtils;
import cn.cslg.report.common.utils.Response;
import cn.cslg.report.entity.*;

import cn.cslg.report.mapper.CompareMessageMapper;
import cn.cslg.report.service.OutInterfaceService;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
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;


@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class CompareMessageService extends ServiceImpl<CompareMessageMapper, CompareMessage> {
    private final TaskService taskService;
    private final FeatureService featureService;
    private final CacheUtils cacheUtils;
    private final OutInterfaceService outInterfaceService;
    private final AssoTaskPatentSplitService assoTaskPatentSplitService;

    /**
     * @author 李仁杰
     * @deprecated 保存对比记录
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean addCompareMessage(List<CompareMessageVO> vos) {
        // 获取登录人信息
        PersonnelVO personnelVO = cacheUtils.getLoginUser(StpUtil.getLoginIdAsInt());
        List<CompareMessage> compareMessages = new ArrayList<>();
        Features feature=new Features();
        //根据登录人Id,报告Id,标的专利号查询特征
        LambdaQueryWrapper<Features> wrapper = new LambdaQueryWrapper<>();
        if (vos.get(0).getTaskId() != null && vos.get(0).getSignPatentNo() != null) {
            wrapper.eq(Features::getTaskId, vos.get(0).getTaskId())
                    .eq(Features::getSignPatentNo, vos.get(0).getSignPatentNo());
            feature = featureService.list(wrapper).get(0);
        }if(vos.get(0).getReportId()!=null &&  vos.get(0).getSignPatentNo() != null ){
            wrapper.eq(Features::getReportId, vos.get(0).getReportId())
                    .eq(Features::getSignPatentNo, vos.get(0).getSignPatentNo());
             feature = featureService.list(wrapper).get(0);
        }
            //根据特征Id删除对比记录
            List<Features> features = featureService.list(wrapper);
            if (features != null && features.size() > 0) {
                List<Integer> Ids = featureService.list(wrapper).stream().map(Features::getId).collect(Collectors.toList());
                LambdaQueryWrapper<CompareMessage> queryWrapper = new LambdaQueryWrapper<CompareMessage>();
                queryWrapper.in(CompareMessage::getFeatureId, Ids);
                this.remove(queryWrapper);
            }
            //根据登录人Id,报告Id,标的专利号删除原有特征
            featureService.remove(wrapper);
            for (int i = 0; i < vos.size(); i++) {
                int order = 1;
                Features features1 = new Features();
                features1.setContent(vos.get(i).getContent());
                features1.setFeaturesOrder(order);
                if(vos.get(i).getTaskId()!=null) {
                    features1.setTaskId(vos.get(i).getTaskId());
                }
                features1.setSplitType(feature.getSplitType());
                features1.setSplitBy(feature.getSplitBy());
                features1.setPartnerId(personnelVO.getId());
                features1.setReportId(feature.getReportId());
                features1.setRightName(vos.get(i).getRightName());
                features1.setRightType(vos.get(i).getRightType());
                features1.setRightId(vos.get(i).getRightId());
                features1.setSignPatentNo(vos.get(i).getSignPatentNo());
                features1.setContentOut(vos.get(i).getContentOut());
                features1.setExplainText(vos.get(i).getExplainText());
                features1.insert();
                CompareMessage compareMessage = new CompareMessage();
                compareMessage.setFeatureId(features1.getId());
                compareMessage.setCompareResult(vos.get(i).getCompareResult());
                compareMessage.setTargetDescription(vos.get(i).getTargetDescription());
                compareMessage.setCompareDescription(vos.get(i).getCompareDescription());
                compareMessage.setReportId(feature.getReportId());
                if(feature.getTaskId()!=null) {
                    compareMessage.setTaskId(feature.getTaskId());
                }
                compareMessages.add(compareMessage);
                order += 1;
            }

        return this.saveBatch(compareMessages);
    }

    public Boolean updateCompareMessage(List<CompareMessage> compareMessageList) {
        List<Integer> ids =compareMessageList.stream().map(CompareMessage::getFeatureId).collect(Collectors.toList());
        if(ids.size()!=0){
            LambdaQueryWrapper<CompareMessage> queryWrapper =new LambdaQueryWrapper<CompareMessage>();
            queryWrapper.in(CompareMessage::getFeatureId,ids).isNull(CompareMessage::getTaskType);
            this.remove(queryWrapper);


           return this.saveOrUpdateBatch(compareMessageList);
        }
        return true;
    }

    public Boolean removeCompareMessage(List<Integer> ids) {
        return this.removeByIds(ids);
    }

    public Map<String, Object> queryCompareMessage(Integer taskId, String patentNo, Integer reportId) throws IOException {
        if(taskId!=null){
            Task task =taskService.getById(taskId);
            reportId =task.getReportId();
        }
        List<PatentRightVo> patentRightVos = new ArrayList<>();
        String resBody = outInterfaceService.getPatentRightFromPAS(patentNo);
        JSONObject jsonObject = JSONObject.parseObject(resBody);
        //解析jason获得标的专利的权要
        List<PatentRight> patentRightsOrgin = JSON.parseArray(jsonObject.getString("data"), PatentRight.class);
        //处理权要
        List<PatentRight> patentRights = featureService.FormatPatentRights(patentRightsOrgin,patentNo);
        //查询特征
        LambdaQueryWrapper<Features> queryWrapper = new LambdaQueryWrapper<>();
        if (reportId != null && reportId != 0) {
            queryWrapper.eq(Features::getReportId, reportId);
        }
        queryWrapper.eq(Features::getSignPatentNo, patentNo);
        List<Features> features = featureService.list(queryWrapper);
        List<Integer> featureIds = features.stream().map(Features::getId).collect(Collectors.toList());
        List<CompareMessage> compareMessages=new ArrayList<>();
        if(featureIds.size()>0){
        LambdaQueryWrapper<CompareMessage> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(CompareMessage::getFeatureId, featureIds);
        if (taskId != null) {
            queryWrapper1.eq(CompareMessage::getTaskId, taskId);
        }
        else {
            queryWrapper1.isNull(CompareMessage::getTaskType);
        }
            compareMessages = this.list(queryWrapper1);
        }

        List<CompareMessageVO> compareMessageVOS = new ArrayList<>();
        for (Features item: features){
            CompareMessageVO compareMessageVO = new CompareMessageVO();
            BeanUtil.copyProperties(item, compareMessageVO);
            CompareMessage compareMessage = new CompareMessage();
            if (compareMessages.size() != 0) {
                List<CompareMessage> compareMessageList = compareMessages.stream().filter(tem -> tem.getFeatureId().equals(item.getId())).collect(Collectors.toList());
                if (compareMessageList.size() != 0) {
                    compareMessage = compareMessageList.get(0);
                }

            }
            compareMessageVO.setCompareResult(compareMessage.getCompareResult());
            compareMessageVO.setCompareDescription(compareMessage.getCompareDescription());
            compareMessageVO.setTargetDescription(compareMessage.getTargetDescription());
            compareMessageVOS.add(compareMessageVO);
        }
        //将拆解的权要和特征装载到对象PatentRightVo
        for (int i = 0; i < patentRights.size(); i++) {
            List<CompareMessageVO> featuresList = new ArrayList<>();
            //对需要拆解的权要进行拆解
            if (compareMessageVOS != null && compareMessageVOS.size() != 0) {
                int rightId = patentRights.get(i).getSort();
                featuresList = compareMessageVOS.stream().filter(item -> item.getRightId().equals(rightId)).collect(Collectors.toList());
            }
            //装载到对象PatentRightVo
            PatentRightVo patentRightVo = new PatentRightVo();
            String name = "权要" + (i + 1);
            patentRightVo.setPatentId(patentRights.get(i).getPatentId());
            patentRightVo.setCompareMessageVOS(featuresList);
            patentRightVo.setContent(patentRights.get(i).getContent());
            patentRightVo.setSort(patentRights.get(i).getSort());
            patentRightVo.setType(patentRights.get(i).getType());
            patentRightVo.setContentOut(patentRights.get(i).getContentOut());
            patentRightVo.setRightName(name);
            patentRightVo.setSignPatentNo(patentNo);
            patentRightVos.add(patentRightVo);
        }
        Map<String, Object> map1 = assoTaskPatentSplitService.getSplitMessage(taskId, patentNo,reportId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("patentRightVos", patentRightVos);
        map.put("splitBy", map1.get("splitBy"));
        map.put("splitType", map1.get("splitType"));
        return map;
    }
    public IPage<JSONObject> queryComparedMessage(QueryCMVO queryCMVO) throws IOException {
        List<String> patentNos = this.baseMapper.getComparedMessage(queryCMVO);

        IPage<JSONObject> ipage = new Page<JSONObject>();
        if (patentNos.size() == 0) {
            ipage.setRecords(new ArrayList<>());
            ipage.setSize(0);
            ipage.setCurrent(queryCMVO.getCurrent());
            ipage.setTotal(0);

            return ipage;
        }
        PatentVO patentVO = new PatentVO();
        patentVO.setSize(100);
        patentVO.setCurrent(1);
        patentVO.setPatentNos(patentNos);
        patentVO.setPatentNo(queryCMVO.getPatentNo());
        patentVO.setPatentName(queryCMVO.getTitle());
        String res = outInterfaceService.getPatentFromPAS(patentVO, 1);
        JSONObject jsonObject = JSONObject.parseObject(res);
        JSONObject resData = JSONObject.parseObject(jsonObject.getString("data"));
        List<JSONObject> list = JSONArray.parseArray(resData.getString("records"), JSONObject.class);
        ipage.setRecords(list);
        ipage.setTotal(Integer.parseInt(resData.getString("total")));
        ipage.setSize(Integer.parseInt(resData.getString("size")));
        ipage.setCurrent(Integer.parseInt(resData.getString("current")));
        return ipage;
    }

    /**
     * @param taskId
     * @param patentNo
     * @return
     * @Autor lrj
     * @Deserption 查找协同任务对比记录
     */
    public Map<String, Object> querySynery(Integer taskId, String patentNo) throws IOException {
        Task task =taskService.getById(taskId);
        //根据 reportId 和 专利号查询特征Id
        LambdaQueryWrapper<Features>  wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(Features::getReportId,task.getReportId())
                .eq(Features::getSignPatentNo,patentNo);
        List<Features> features =featureService.list(wrapper);
        List<Integer> featureIds =features.stream().map(Features::getId).collect(Collectors.toList());
        LambdaQueryWrapper<CompareMessage> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(CompareMessage::getTaskId,taskId)
        .in(CompareMessage::getFeatureId,featureIds);
        List<CompareMessage> compareMessages =this.list(queryWrapper);
        if(compareMessages.size()==0){
            Map<String, Object> map = this.queryCompareMessage(null, patentNo, task.getReportId());
            return map;
        }


        return this.queryCompareMessage(taskId, patentNo, null);

    }

    public Map<String, Object> queryAllCompareMessage( String patentNo, Integer reportId) throws IOException {
        List<PatentRightVo> patentRightVos = new ArrayList<>();
        String resBody = outInterfaceService.getPatentRightFromPAS(patentNo);
        JSONObject jsonObject = JSONObject.parseObject(resBody);
        //解析jason获得标的专利的权要
        List<PatentRight> patentRightsOrgin = JSON.parseArray(jsonObject.getString("data"), PatentRight.class);
        //处理权要
        List<PatentRight> patentRights = featureService.FormatPatentRights(patentRightsOrgin,patentNo);
        //查询特征
        LambdaQueryWrapper<Features> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Features::getReportId, reportId);
        queryWrapper.eq(Features::getSignPatentNo, patentNo);
        List<Features> features = featureService.list(queryWrapper);
        List<Integer> featureIds = features.stream().map(Features::getId).collect(Collectors.toList());
        LambdaQueryWrapper<CompareMessage> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(CompareMessage::getFeatureId, featureIds);
        List<CompareMessage> compareMessages = this.list(queryWrapper1);
        List<CompareMessageVO> compareMessageVOS = new ArrayList<>();
        features.forEach(item -> {
            CompareMessageVO compareMessageVO = new CompareMessageVO();
            BeanUtil.copyProperties(item, compareMessageVO);
            CompareMessage compareMessage = new CompareMessage();
            if (compareMessages.size() != 0) {
                List<CompareMessage> compareMessageList = compareMessages.stream().filter(tem -> tem.getFeatureId().equals(item.getId())).collect(Collectors.toList());
                compareMessageList.forEach(
                        tem->{
                            if(tem.getTaskType()==null){
                                compareMessageVO.setCompareResult(tem.getCompareResult());
                                compareMessageVO.setCompareDescription(tem.getCompareDescription());
                                compareMessageVO.setTargetDescription(tem.getTargetDescription());
                                compareMessageVO.setCMid(tem.getId());
                            }
                            else  if(tem.getTaskType().equals(1)){
                                compareMessageVO.setCompareResult2(tem.getCompareResult());
                                compareMessageVO.setCompareDescription2(tem.getCompareDescription());
                                compareMessageVO.setTargetDescription2(tem.getTargetDescription());
                            }
                        }
                );

            }
            compareMessageVOS.add(compareMessageVO);
        });
        //将拆解的权要和特征装载到对象PatentRightVo
        for (int i = 0; i < patentRights.size(); i++) {

            List<CompareMessageVO> featuresList = new ArrayList<>();
            //对需要拆解的权要进行拆解
            if (compareMessageVOS != null && compareMessageVOS.size() != 0) {
                int rightId = patentRights.get(i).getSort();
                featuresList = compareMessageVOS.stream().filter(item -> item.getRightId().equals(rightId)).collect(Collectors.toList());
            }
            //装载到对象PatentRightVo
            PatentRightVo patentRightVo = new PatentRightVo();
            String name = "权要" + (i + 1);
            patentRightVo.setPatentId(patentRights.get(i).getPatentId());
            patentRightVo.setCompareMessageVOS(featuresList);
            patentRightVo.setContent(patentRights.get(i).getContent());
            patentRightVo.setSort(patentRights.get(i).getSort());
            patentRightVo.setType(patentRights.get(i).getType());
            patentRightVo.setContentOut(patentRights.get(i).getContentOut());
            patentRightVo.setRightName(name);
            patentRightVo.setSignPatentNo(patentNo);
            patentRightVos.add(patentRightVo);
        }
        Map<String, Object> map1 = assoTaskPatentSplitService.getSplitMessage(null, patentNo,reportId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("patentRightVos", patentRightVos);
        map.put("splitBy", map1.get("splitBy"));
        map.put("splitType", map1.get("splitType"));
        return map;
    }

    /**
     * @autor lrj
     * @param addSyneryVo
     * @return
     * @Descprtion 添加协同记录
     */

    public Boolean addSynery(AddSyneryVo addSyneryVo){
        // 根据任务Id获得任务信息
        Task task = taskService.getById(addSyneryVo.getTaskId());
        //根据专利号和报告ID获得特征Id
        LambdaQueryWrapper<Features> wrapper =new LambdaQueryWrapper<Features>();
        wrapper.select(Features::getId);
        wrapper.eq(Features::getReportId,task.getReportId());
        wrapper.eq(Features::getSignPatentNo,addSyneryVo.getPatentNo());
List<Features> features =featureService.list(wrapper);
List<Integer> Ids =features.stream().map(Features::getId).collect(Collectors.toList());
        //装载对比结果信息
        List<CompareMessage> compareMessages =addSyneryVo.getCompareMessageList();
        compareMessages.forEach(
                item->{
                    item.setTaskId(task.getId());
                    item.setTaskType(1);
                    item.setId(null);
                }
        );
        //删除对比记录
        if(Ids.size()!=0){
        LambdaQueryWrapper<CompareMessage> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(CompareMessage::getTaskId,task.getId())
                    .in(CompareMessage::getFeatureId,Ids);
        this.remove(queryWrapper);}
   return     this.saveBatch(compareMessages);

    }

    /**
     * @param patentNo
     * @param reportId
     * @return
     * @throws IOException
     */
    public Map<String, Object> queryforTemplate(String patentNo, Integer reportId) throws IOException {

        List<CompareMessageVO> lists = new ArrayList<>();
        String resBody = outInterfaceService.getPatentRightFromPAS(patentNo);
        JSONObject jsonObject = JSONObject.parseObject(resBody);
        //解析jason获得标的专利的权要
        List<PatentRight> patentRightsOrgin = JSON.parseArray(jsonObject.getString("data"), PatentRight.class);
        //处理权要
        List<PatentRight> patentRights = featureService.FormatPatentRights(patentRightsOrgin,patentNo);
        //查询特征
        LambdaQueryWrapper<Features> queryWrapper = new LambdaQueryWrapper<>();
        if (reportId != null && reportId != 0) {
            queryWrapper.eq(Features::getReportId, reportId);
        }
        queryWrapper.eq(Features::getSignPatentNo, patentNo);
        List<Features> features = featureService.list(queryWrapper);
        List<Integer> featureIds = features.stream().map(Features::getId).collect(Collectors.toList());
        List<CompareMessage> compareMessages=new ArrayList<>();
        if(featureIds.size()>0){
            LambdaQueryWrapper<CompareMessage> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.in(CompareMessage::getFeatureId, featureIds);
                queryWrapper1.isNull(CompareMessage::getTaskType);
            compareMessages = this.list(queryWrapper1);}
        List<CompareMessageVO> compareMessageVOS = new ArrayList<>();
        for (Features item: features){
            CompareMessageVO compareMessageVO = new CompareMessageVO();
            BeanUtil.copyProperties(item, compareMessageVO);
            CompareMessage compareMessage = new CompareMessage();
            if (compareMessages.size() != 0) {
                List<CompareMessage> compareMessageList = compareMessages.stream().filter(tem -> tem.getFeatureId().equals(item.getId())).collect(Collectors.toList());
                if (compareMessageList.size() != 0) {
                    compareMessage = compareMessageList.get(0);
                }

            }
            compareMessageVO.setCompareResult(compareMessage.getCompareResult());
            compareMessageVO.setCompareDescription(compareMessage.getCompareDescription());
            compareMessageVO.setTargetDescription(compareMessage.getTargetDescription());
            compareMessageVOS.add(compareMessageVO);
        }
        Integer mainRight =0;
        Integer right=0;
        //将拆解的权要和特征装载到对象PatentRightVo
        for (int i = 0; i < patentRights.size(); i++) {
            if(patentRights.get(i).getType()==1)
            {mainRight++;}
          right++;
            List<CompareMessageVO> featuresList = new ArrayList<>();
            //对需要拆解的权要进行拆解
            if (compareMessageVOS != null && compareMessageVOS.size() != 0) {
                int rightId = patentRights.get(i).getSort();
                featuresList = compareMessageVOS.stream().filter(item -> item.getRightId().equals(rightId)).collect(Collectors.toList());
            }
            for (CompareMessageVO item : featuresList) {
                item.setRightName("权要" + (patentRights.get(i).getSort() + 1));
                if(item.getCompareResult()==null){
                    item.setResultStr("待定");
                }
               else if(item.getCompareResult()==0){
                    item.setResultStr("不同");
                }
                else if(item.getCompareResult()==1)
                {item.setResultStr("相同");}
                else  {
                    item.setResultStr("待定");
                }
            }
            lists.addAll(featuresList);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("compareMessageVOs", lists);
        map.put("mainRight",mainRight);
        map.put("right",right);
        return map;
    }
    /**
     * funtion:删除报告时删除
     */
    public String deleteByreportID(Integer repotID){
        LambdaQueryWrapper<CompareMessage> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(CompareMessage::getReportId,repotID);
        List<CompareMessage> list = this.list(queryWrapper);
        if(list==null||list.size()==0){
            return Response.success();
        }
        remove(queryWrapper);
        return Response.success();

    }

}
