package com.docus.server.service.handler;

import cn.hutool.json.JSONUtil;
import com.docus.core.util.Func;
import com.docus.log.annotation.TrackRetryListener;
import com.docus.server.api.ocr.OcrApi;
import com.docus.server.dto.segmentation.FileDTO;
import com.docus.server.dto.segmentation.UploadBatchFileRequest;
import com.docus.server.entity.segmentation.*;
import com.docus.server.enums.OcrStatusEnum;
import com.docus.server.infrastructure.dao.IOcrBasicDao;
import com.docus.server.infrastructure.dao.IOcrFileInfoDao;
import com.docus.server.infrastructure.dao.IOcrUrlConfigDao;
import com.docus.server.infrastructure.dao.IOcrVersionDao;
import com.docus.server.service.IOcrRuleService;
import com.docus.server.service.IOcrSpecialRuleService;
import com.docus.server.service.impl.PlatformServiceImpl;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 开始分段处理器
 */
@Component
public class StartSegmentHandler {

    @Resource
    private OcrApi ocrApi;
    @Resource
    private IOcrFileInfoDao iOcrFileInfoDao;
    @Resource
    private IOcrSpecialRuleService iOcrSpecialRuleService;
    @Resource
    private IOcrRuleService iOcrRuleService;
    @Resource
    private IOcrVersionDao iOcrVersionDao;
    @Resource
    private IOcrUrlConfigDao iOcrUrlConfigDao;
    @Resource
    private IOcrBasicDao iOcrBasicDao;
    @Resource
    private PlatformServiceImpl  platformService;

    @TrackRetryListener("START_SEGMENT")
    public void startSegment(String patientId) {

        boolean isSpecialFile = false;
        OcrSpecialResult lastSpecialResul = null;


        OcrVersion ocrVersion = iOcrVersionDao.findOneBy("isEnable", "1");
        if (ocrVersion==null){
            throw new RuntimeException("当前没有启用的版本号");
        }
        Integer version = ocrVersion.getVersion();

        //根据病案号查询文件列表
        List<OcrBasic> ocrBasicList = iOcrBasicDao.findBy("patientId",patientId);
        String url = iOcrUrlConfigDao.findBy("version",version).get(0).getUrl();
        List<OcrFileInfo> fileInfoList = iOcrFileInfoDao.findBy("patientId",patientId);

        List<File> files = new ArrayList<>(fileInfoList.size());
        List<FileDTO> fileDTOList = new ArrayList<>(fileInfoList.size());
        for (OcrFileInfo fileInfo:fileInfoList) {

            //遍历文件列表 获取ocr识别结果
            List<String> ocrTextList = ocrApi.getText(fileInfo.getPicCutUrl(),url);

            fileInfo.setOcrText(Func.toJson(ocrTextList));
            fileInfo.setOcrStatus(OcrStatusEnum.COMPLETE);
            fileInfo.setOcrFinishTime(new Date());
            //判断上次是否特殊文件开始  需要判断是否特殊文件结尾
            if (isSpecialFile){
                fileInfo.setAssortId(lastSpecialResul.getAssortId());
                fileInfo.setAssortName(lastSpecialResul.getAssortName());
                fileInfo.setRuleId(lastSpecialResul.getRuleId());
                boolean b = iOcrSpecialRuleService.handleSpecialRuleEnd(lastSpecialResul, ocrTextList);
                if (b){
                    //当前分段为特殊分段结尾
                    isSpecialFile = false;
                    lastSpecialResul = null;
                }
                continue;
            }
            //优先判断是否特殊规则开始
            OcrSpecialResult ocrSpecialResult = iOcrSpecialRuleService.handleSpecialRule(ocrTextList,version);
            //判断是否属于某个分段
            if (ocrSpecialResult!=null){
                fileInfo.setAssortId(ocrSpecialResult.getAssortId());
                fileInfo.setAssortName(ocrSpecialResult.getAssortName());
                fileInfo.setRuleId(ocrSpecialResult.getRuleId());
                fileInfo.setHitKey(ocrSpecialResult.getHitKey());
                fileInfo.setRate(ocrSpecialResult.getRate());

                isSpecialFile = true;
                lastSpecialResul = ocrSpecialResult;
                continue;
            }
            OcrRuleResult ocrRuleResult = iOcrRuleService.handleRule(ocrTextList,version);
            //更新文件数据的分段
            if (ocrRuleResult!=null){
                fileInfo.setAssortId(ocrRuleResult.getAssortId());
                fileInfo.setAssortName(ocrRuleResult.getAssortName());
                fileInfo.setRuleId(ocrRuleResult.getRuleId());
                fileInfo.setHitKey(ocrRuleResult.getHitKey());
                fileInfo.setRate(ocrRuleResult.getRate());
            }

            File file  = new File(fileInfo.getPicUrl());
            files.add(file);

            FileDTO fileDTO = new FileDTO();
            fileDTO.setAssortId(fileInfo.getAssortId());
            fileDTO.setFileTitle(fileInfo.getFileTitle());
            fileDTO.setSort(fileInfo.getSort());
            fileDTO.setUploadFileName(fileInfo.getPicName());
            fileDTO.setSerialNumber(fileInfo.getSerialNumber());

            fileDTOList.add(fileDTO);
        }
        //更新数据库表
        List<OcrBasic> collect = ocrBasicList.stream().peek(p -> {
            p.setOcrFinishTime(new Date());
            p.setOcrStatue(OcrStatusEnum.COMPLETE);
        }).collect(Collectors.toList());

        iOcrBasicDao.updateBatchById(collect,iOcrBasicDao.DEFAULT_BATCH_SIZE);
        iOcrFileInfoDao.updateBatchById(fileInfoList,iOcrFileInfoDao.DEFAULT_BATCH_SIZE);

        //数据上传到3.0
        OcrBasic ocrBasic =ocrBasicList.get(0);

        UploadBatchFileRequest request = new UploadBatchFileRequest();
        request.setInpatientNo(ocrBasic.getInpatientNo());
        request.setPatientId(patientId);
        request.setName(ocrBasic.getName());
        request.setTestData(0);
        request.setFileInfo(JSONUtil.toJsonStr(fileDTOList));

        platformService.uploadPlatform(files, null);
    }
}
