package cn.cslg.pas.service;

import cn.cslg.pas.common.core.base.Constants;
import cn.cslg.pas.common.model.PatentCell;
import cn.cslg.pas.common.model.vo.KeyValueVO;
import cn.cslg.pas.common.utils.JsonUtils;
import cn.cslg.pas.common.utils.StringUtils;
import cn.cslg.pas.domain.Patent;
import cn.cslg.pas.domain.PatentAffair;
import cn.cslg.pas.domain.SystemDict;
import cn.cslg.pas.common.utils.DateUtils;
import cn.cslg.pas.mapper.PatentAffairMapper;
import cn.cslg.pas.common.model.params.PatentAffairParams;
import cn.cslg.pas.common.utils.PatentUtils;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 专利信息事务信息表 服务类
 * </p>
 *
 * @author 王岩
 * @since 2022-02-24
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class PatentAffairService extends ServiceImpl<PatentAffairMapper, PatentAffair> {

    private final SystemDictService systemDictService;
    private final PatentService patentService;

    public List<PatentAffair> getPatentAffairByPatentId(Integer patentId) {
        LambdaQueryWrapper<PatentAffair> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PatentAffair::getPatentId, patentId);
        queryWrapper.orderByDesc(PatentAffair::getDateTime);
        List<PatentAffair> dataList = this.list(queryWrapper);
        List<SystemDict> systemDictList = systemDictService.getSystemDictListByType(Arrays.asList(Constants.PATENT_STATUS, Constants.PATENT_SIMPLE_STATUS));
        dataList.forEach(item -> {
            if (item.getContent() != null) {
                List<KeyValueVO> lst = JSONArray.parseArray(item.getContent(), KeyValueVO.class);
//                List<KeyValueVO> lst = JsonUtils.jsonToList(item.getContent(), KeyValueVO.class);
                KeyValueVO flag;
                for (int i = 0; i < Objects.requireNonNull(lst).size() - 1; i++) {
                    for (int j = 0; j < lst.size() - i - 1; j++) {
                        if (DateUtils.strToDate(lst.get(j).getInpadocData().get(0).getContent()).compareTo(DateUtils.strToDate(lst.get(j + 1).getInpadocData().get(0).getContent())) < 0) {
                            flag = lst.get(j);
                            lst.set(j, lst.get(j + 1));
                            lst.set(j + 1, flag);
                        }
                    }
                }
                item.setInpadoc(lst);
            }
            Patent patent = patentService.getById(item.getPatentId());

            item.setCreateTime(DateUtils.formatDate(item.getDateTime(), DateUtils.YYYY_MM_DD));
            if (patent != null) {
                item.setCreateSimpleStatus(systemDictList.stream().filter(systemDict -> systemDict.getType().equals(Constants.PATENT_SIMPLE_STATUS) && systemDict.getValue().equals(String.valueOf(patent.getSimpleStatus()))).findFirst().orElse(new SystemDict()).getLabel());
            }
            item.setCreateStatus(systemDictList.stream().filter(systemDict -> systemDict.getType().equals(Constants.PATENT_STATUS) && systemDict.getValue().equals(String.valueOf(item.getStatus()))).findFirst().orElse(new SystemDict()).getLabel());
        });

        return dataList;
    }

    public List<PatentAffair> getPatentAffairListByPatentIds(List<Integer> patentIds) {
        if (patentIds == null || patentIds.size() == 0) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<PatentAffair> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(PatentAffair::getPatentId, patentIds);
        return this.list(queryWrapper);
    }

    public void importPatentAffair(Patent localPatent, List<Patent> importPatentList, List<PatentAffair> importPatentAffairList) {
        this.deleteByPatentId(localPatent.getId());
        Patent importPatent = importPatentList.stream().filter(item -> item.getPatentNo().equals(localPatent.getPatentNo())).findFirst().orElse(new Patent());
        List<PatentAffair> importPatentAffairs = importPatentAffairList.stream().filter(item -> item.getPatentId().equals(importPatent.getId())).collect(Collectors.toList());
        for (PatentAffair patentAffair : importPatentAffairs) {
            patentAffair.setId(null);
            patentAffair.setPatentId(localPatent.getId());
        }
        this.saveOrUpdateBatch(importPatentAffairs);
    }

    public void updatePatientAffair(PatentAffairParams params) {
        if (params.getStatusList() != null) {
            this.deleteByPatentId(params.getPatentId());
            PatentAffair patentAffair = new PatentAffair();
            patentAffair.setPatentId(params.getPatentId());
            patentAffair.setStatus(params.getStatusList());
            patentAffair.setContent(params.getContent());
            patentAffair.setDateTime(params.getDateTime());
            patentAffair.setSimpleStatus(params.getSimpleStatus());
            this.saveOrUpdate(patentAffair);
        }
    }
    //批量上传法律状态
    public void updatePatientAffairs(List<PatentCell.PatentAffair> params,Integer patentId) {
        List<SystemDict> systemDictList = systemDictService.getSystemDictListByType(Collections.singletonList(Constants.PATENT_SIMPLE_STATUS));
        this.deleteByPatentId(patentId);
        List<PatentAffair> patentAffairs =new ArrayList<>();
        params.forEach(
                item->{
                    Integer simpleStatus = Integer.parseInt(systemDictList.stream()
                            .filter(systemDict -> systemDict.getType().equals(Constants.PATENT_SIMPLE_STATUS) && systemDict.getLabel().equals(item.getSimpleStatus()))
                            .findFirst()
                            .orElse(new SystemDict()).getValue());
                    PatentAffair patentAffair = new PatentAffair();
                    patentAffair.setPatentId(patentId);
                    patentAffair.setStatus(item.getStatus());
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
                    Date date = null;
                    try {
                        date = simpleDateFormat.parse(item.getDateTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Integer ts = (int) date.getTime();
                    patentAffair.setDateTime(ts);
                    patentAffair.setSimpleStatus(simpleStatus);
                    patentAffairs.add(patentAffair);
                }
        );
        if(patentAffairs.size()>0){
        this.saveOrUpdateBatch(patentAffairs);}
    }

    public void deleteByPatentId(Integer patentId) {
        this.remove(Wrappers.<PatentAffair>lambdaQuery().eq(PatentAffair::getPatentId, patentId));
    }

}
