package cn.cslg.report.service.business;

import cn.cslg.report.common.model.dto.PatentQueryFieldSourceDTO;
import cn.cslg.report.common.model.vo.PatentField;
import cn.cslg.report.common.model.vo.PatentQueryFieldSourceVO;
import cn.cslg.report.common.model.vo.ReportFieldVO;
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.mapper.ReportFieldMapper;
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.stream.Collectors;


/**
 * <p>
 * 专利信息自定义字段表 服务类
 * </p>
 *
 * @author 王岩
 * @since 2021-12-16
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
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;
    public String add(ReportField reportField) {
        ReportField temp = this.getProjectFieldByName(reportField.getName(), reportField.getReportId());
        if (temp != null) {
            return Response.error("字段名称已存在");
        }
        reportField.setPtype(reportField.getType() == 6 ? 2 : 1);
        reportField.setCreateBy(loginUtils.getId());
        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
  public String delete(Integer id) {
      this.removeById(id);
      reportFieldTextService.deleteByFieldId(id);
      reportFieldOptionService.deleteByFieldId(id);
      reportFieldTreeService.deleteByFieldId(id);
      reportFieldPatentLinkService.deleteByFieldId(id);
        return Response.success(true);
   }

   //获得自定义字段列表
  public String getPageList(ReportFieldVO reportFieldVO){
      LambdaQueryWrapper<ReportField> queryWrapper = new LambdaQueryWrapper<>();
      if (reportFieldVO.getName() != null) {
          queryWrapper.like(ReportField::getName, reportFieldVO.getName());
      }
      if(reportFieldVO.getReportType()!=null){
          queryWrapper.like(ReportField::getReportType, reportFieldVO.getReportType());
      }
      queryWrapper.orderByDesc(ReportField::getId);
      if (reportFieldVO.getSize() != null && reportFieldVO.getSize() != null) {
          List<ReportField> reportFields = this.page(new Page<>(reportFieldVO.getCurrent(), reportFieldVO.getSize()), queryWrapper).getRecords();
          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);
          return Response.success(reportFields);
      }

  }

    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);
    }

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

  //给报告添加默认自定义字段
    public void addDefaultField(Integer reportId, Integer reportType) {
        LambdaQueryWrapper<ReportField> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReportField::getType, reportType);
        queryWrapper.eq(ReportField::getReportId, null);
        List<ReportField> reportFields =this.list(queryWrapper);
        if(reportFields.size()!=0||reportFields!=null)
        {
         reportFields.forEach(p->p.setReportId(reportId));

        }
    }

    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();

    }

    public List<PatentQueryFieldSourceVO> getPatentQuerySourcePageList(PatentQueryFieldSourceVO params) {
        List<PatentQueryFieldSourceVO> list =new ArrayList<>();
        //根据fieldId 从patent_field中获得 自定义字段对象
        LambdaQueryWrapper<ReportField> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(ReportField::getId,params.getFieldId());
        ReportField reportField =this.list(wrapper).get(0);
        //根据自定义字段的类型，从三张值表中查询该自定义字段所有值的id
        Integer 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);
                reportFieldTrees.forEach(item->{
                    PatentQueryFieldSourceVO patentQueryFieldSourceVO=new PatentQueryFieldSourceVO();
                    patentQueryFieldSourceVO.setFieldId(params.getFieldId());
                    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())
                .in(ReportFieldPatentLink::getOptionId,valueIds);
        List<ReportFieldPatentLink> reportFieldPatentLinks =reportFieldPatentLinkService.list(lambdaQueryWrapper);
        list.forEach(tem->{
         List<ReportFieldPatentLink> part =reportFieldPatentLinks.stream().filter(tm->tm.getFieldId().equals(params.getFieldId())&&tm.getOptionId().equals(tem.getKey()
            )).collect(Collectors.toList());
         tem.setCount(part.size());
         tem.setType(type1);
        });
        //根据值id从ReportFieldPatentLink表中获得信息
        return list;

    }

//    public IPage<PatentQueryFieldSourceDTO> getPatentAttributeSourcePageList(PatentQueryFieldSourceVO params) {
//        this.setPatentQuerySourceParams(params);
//        if (params.getKey().equals("40-0")) {
//            Integer projectId = params.getProjectId();
//            List<PatentQueryFieldSourceDTO> dataList = baseMapper.getCountStatus(projectId);
//            List<PatentQueryFieldSourceDTO> lstA = new ArrayList<>();
//            List<PatentQueryFieldSourceDTO> lstB = new ArrayList<>();
//            dataList.forEach(item -> {
//                if (StringUtils.changeStringToString(item.getLabel(), "\\|").size() > 1) {
//                    lstA.add(item);
//                } else {
//                    lstB.add(item);
//                }
//            });
//            lstA.forEach(item -> {
//                List<String> stringList = StringUtils.changeStringToString(item.getLabel(), "\\|");
//
//                stringList.forEach(x -> {
//                    List<PatentQueryFieldSourceDTO> lstC = new ArrayList<>();
//                    for (PatentQueryFieldSourceDTO patentQueryFieldSourceDTO : lstB) {
//                        if (!lstB.stream().map(PatentQueryFieldSourceDTO::getLabel).collect(Collectors.toList()).contains(x)) {
//                            PatentQueryFieldSourceDTO a = new PatentQueryFieldSourceDTO();
//                            a.setCount(item.getCount());
//                            a.setLabel(x);
//                            lstC.add(a);
//                            break;
//                        }
//                        if (patentQueryFieldSourceDTO.getLabel().equals(x)) {
//                            patentQueryFieldSourceDTO.setCount(patentQueryFieldSourceDTO.getCount() + item.getCount());
//                        }
//                    }
//                    lstB.addAll(lstC);
//                });
//            });
//            List<SystemDict> systemDictList = systemDictService.getSystemDictListByType(Collections.singletonList(Constants.PATENT_STATUS));
//            lstB.forEach(b -> {
//                Integer status = Integer.parseInt(systemDictList.stream()
//                        .filter(systemDict -> systemDict.getType().equals(Constants.PATENT_STATUS) && systemDict.getLabel().equals(b.getLabel()))
//                        .findFirst()
//                        .orElse(new SystemDict()).getValue());
//                b.setValue(String.valueOf(status));
//            });
//            IPage<PatentQueryFieldSourceDTO> pageList = baseMapper.getPatentQuerySourcePageList(new Page<>(params.getCurrent(), params.getSize()), params, new ArrayList<>());
//            pageList.setRecords(lstB);
//            return pageList;
//        }
//        IPage<PatentQueryFieldSourceDTO> pageList = baseMapper.getPatentQuerySourcePageList(new Page<>(params.getCurrent(), params.getSize()), params, new ArrayList<>());
//        pageList.getRecords().forEach(item -> item.setIds(null));
//        return pageList;
//    }

//    private void setPatentQuerySourceParams(PatentQueryFieldSourceVO params) {
//        List<Integer> field = StringUtils.changeStringToInteger(params.getKey(), "-");
//        Integer type = 0;
//        Integer level = 0;
//        Integer status = 0;
//        switch (params.getKey()) {
//            case "18-6":
//            case "18-7":
//            case "18-8":
//            case "23-6":
//            case "23-7":
//            case "23-8":
//                params.setApplicantType(2);
//                break;
//            case "19-6":
//            case "19-7":
//            case "19-8":
//            case "24-6":
//            case "24-7":
//            case "24-8":
//                params.setApplicantType(1);
//                break;
//            case "29-17":
//            case "30-17":
//            case "29-18":
//            case "29-19":
//            case "29-20":
//            case "30-18":
//            case "30-19":
//            case "30-20":
//                params.setApplicantType(field.get(0) == 29 ? 2 : 1);
//                break;
//            default:
//                params.setCustomFieldId(field.get(0));
//                if (params.getType().equals("6") && field.get(1).equals(0)) {
//                    params.setCustomFieldTreeType(0);
//                } else {
//                    params.setCustomFieldTreeType(null);
//                }
//        }
//    }



    }





