package cn.com.poc.covenant.scheduler;
import java.util.Date;
import java.time.OffsetDateTime;

import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.poc.covenant.constants.ContractConstants;
import cn.com.poc.covenant.entity.BizExtractionDocFlowEntity;
import cn.com.poc.covenant.model.BizExtractionReviewTaskModel;
import cn.com.poc.covenant.service.BizExtractionDocFlowService;
import cn.com.poc.covenant.service.BizExtractionReviewTaskService;
import cn.com.poc.thirdparty.resource.baidu.api.BaiduTokenAPI;
import cn.com.poc.thirdparty.resource.baidu.api.TextReviewApi;
import cn.com.poc.thirdparty.resource.baidu.entity.response.TextReviewResultQueryResponse;
import cn.com.poc.thirdparty.resource.baidu.entity.response.text_diff.BaiduTextDiffQueryResult;
import cn.com.poc.thirdparty.resource.baidu.service.BaiduTextDiffService;
import cn.com.poc.thirdparty.resource.text_in.api.TextInClient;
import cn.com.poc.thirdparty.resource.text_in.entity.doc_flow.FileFetchRequest;
import cn.com.poc.thirdparty.resource.text_in.entity.doc_flow.fileFetchResponse.FileFetchResponse;
import cn.com.poc.thirdparty.resource.text_in.entity.extraction.entity.ExtractionResult;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.frame.service.FmxParamConfigService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author alex.yao
 * @date 2025/5/21
 */
@Component
public class ExtractionReviewScheduler {

    private final TextInClient textInClient = new TextInClient();

    @Resource
    private BizExtractionReviewTaskService bizExtractionReviewTaskService;
    @Resource
    private TextReviewApi textReviewApi;
    @Resource
    private FmxParamConfigService fmxConfigService;
    @Resource
    private BaiduTokenAPI baiduTokenAPI;

    @Resource
    private BaiduTextDiffService baiduTextDiffService;

    @Resource
    private BizExtractionDocFlowService bizExtractionDocFlowService;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void extraction() throws Exception {
        // 执行任务
        BizExtractionReviewTaskModel bizExtractionReviewTaskModel = new BizExtractionReviewTaskModel();
        bizExtractionReviewTaskModel.setReviewStatus("RUN");
        bizExtractionReviewTaskModel.setActionType(ContractConstants.ActionType.extract);
        bizExtractionReviewTaskModel.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizExtractionReviewTaskModel> models = bizExtractionReviewTaskService.findByExample(bizExtractionReviewTaskModel, null);
        if (CollectionUtils.isNotEmpty(models)) {
            for (BizExtractionReviewTaskModel model : models) {
                String textInTaskId = model.getTextInTaskId();
                ExtractionResult extractionResult = textInClient.extractedResults(textInTaskId);
                if (extractionResult == null) {
                    model.setReviewStatus("ERROR");
                } else if (extractionResult.getCode().equals(209L)) {
                    model.setReviewStatus("RUN");
                } else if (extractionResult.getCode().equals(200L)) {
                    model.setReviewStatus("END");
                } else {
                    model.setReviewStatus("ERROR");
                    model.setReviewErrorMsg(extractionResult.getMsg());
                }
            }
            bizExtractionReviewTaskService.saveAll(models);
        }
    }

    @Scheduled(cron = "0 0/1 * * * ?")
    public void textReviewTaskQuery() throws Exception {
        // 执行任务
        BizExtractionReviewTaskModel bizExtractionReviewTaskModel = new BizExtractionReviewTaskModel();
        bizExtractionReviewTaskModel.setReviewStatus("RUN");
        bizExtractionReviewTaskModel.setActionType(ContractConstants.ActionType.textreview);
        bizExtractionReviewTaskModel.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizExtractionReviewTaskModel> models = bizExtractionReviewTaskService.findByExample(bizExtractionReviewTaskModel, null);
        if (CollectionUtils.isNotEmpty(models)) {

            String clientId = fmxConfigService.getParam("baidu.textmind.clientId");
            String clientSecret = fmxConfigService.getParam("baidu.textmind.clientSecret");

            String accessToken = baiduTokenAPI.getToken(clientId, clientSecret).getAccess_token();

            for (BizExtractionReviewTaskModel model : models) {
                String textInTaskId = model.getTextInTaskId();
                TextReviewResultQueryResponse textReviewResponse = textReviewApi.textReviewTaskQuery(textInTaskId, accessToken);
                if (textReviewResponse == null) {
                    model.setReviewStatus("ERROR");
                } else if ("0".equals(textReviewResponse.getError_code())) {
                    if (textReviewResponse.getResult() != null && "success".equals(textReviewResponse.getResult().getStatus())) {
                        model.setReviewStatus("END");
                    }
                } else {
                    model.setReviewStatus("ERROR");
                }
            }
            bizExtractionReviewTaskService.saveAll(models);
        }
    }

    @Scheduled(cron = "0/10 * * * * ? ")
    public void docFlowTaskQuery() throws Exception {
        // 执行任务
        BizExtractionReviewTaskModel bizExtractionReviewTaskModel = new BizExtractionReviewTaskModel();
        bizExtractionReviewTaskModel.setReviewStatus("RUN");
        bizExtractionReviewTaskModel.setActionType(ContractConstants.ActionType.docFlow);
        bizExtractionReviewTaskModel.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizExtractionReviewTaskModel> models = bizExtractionReviewTaskService.findByExample(bizExtractionReviewTaskModel, null);
        if (CollectionUtils.isNotEmpty(models)) {

            //获取workspaceId
            String workspaceId = fmxConfigService.getParam("textin.docflow.workspaceId");
            if(StringUtils.isBlank(workspaceId)){
                throw new BusinessException("请配置workspaceId");
            }

            for (BizExtractionReviewTaskModel model : models) {
                FileFetchRequest fileFetchRequest = new FileFetchRequest();
                fileFetchRequest.setCategory(model.getContractType());
                fileFetchRequest.setFileid(model.getTextInTaskId());
                fileFetchRequest.setWorkspaceid(workspaceId);

                FileFetchResponse fileFetchResponse = textInClient.fileFetch(fileFetchRequest);

                if (fileFetchResponse == null ) {
                    model.setReviewStatus("RUN");
                } else if (fileFetchResponse.getCode() == 200L) {
                    if (fileFetchResponse.getResult() != null && fileFetchResponse.getResult().getFiles().get(0).getRecognitionStatus() == 1) {
                        model.setReviewStatus("END");
                        model.setReviewErrorMsg(fileFetchResponse.getMessage());
                        BizExtractionDocFlowEntity bizExtractionDocFlowEntity = new BizExtractionDocFlowEntity();
                        bizExtractionDocFlowEntity.setBizTextInTaskId(model.getTextInTaskId());
                        bizExtractionDocFlowEntity.setBizDocFlowStamps(JsonUtils.serialize(fileFetchResponse.getResult().getFiles().get(0).getData().getStamps()));
                        bizExtractionDocFlowEntity.setBizDocFlowTables(JsonUtils.serialize(fileFetchResponse.getResult().getFiles().get(0).getData().getTables()));
                        bizExtractionDocFlowEntity.setBizDocFlowFields(JsonUtils.serialize(fileFetchResponse.getResult().getFiles().get(0).getData().getFields()));
                        bizExtractionDocFlowEntity.setBizDocFlowHandwritings(JsonUtils.serialize(fileFetchResponse.getResult().getFiles().get(0).getData().getHandwritings()));
                        bizExtractionDocFlowEntity.setBizDocFlowItems(JsonUtils.serialize(fileFetchResponse.getResult().getFiles().get(0).getData().getItems()));
                        bizExtractionDocFlowService.save(bizExtractionDocFlowEntity);
                    }else{
                        model.setReviewStatus("RUN");

                    }
                }else {
                    model.setReviewStatus("ERROR");
                    model.setReviewErrorMsg(fileFetchResponse.getMessage());
                }
            }
            bizExtractionReviewTaskService.saveAll(models);
        }
    }


    /**
     * 文本对比任务查询
     * pending：排队中；processing：运行中；success：成功；failed：失败
     *
     * @throws Exception
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void textDiffTaskQuery() throws Exception {
        // 执行任务
        BizExtractionReviewTaskModel bizExtractionReviewTaskModel = new BizExtractionReviewTaskModel();
        bizExtractionReviewTaskModel.setReviewStatus("RUN");
        bizExtractionReviewTaskModel.setActionType(ContractConstants.ActionType.textdiff);
        bizExtractionReviewTaskModel.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizExtractionReviewTaskModel> models = bizExtractionReviewTaskService.findByExample(bizExtractionReviewTaskModel, null);
        if (CollectionUtils.isNotEmpty(models)) {
            for (BizExtractionReviewTaskModel model : models) {
                baiduTextDiffService.queryTextDiffTask(model.getTaskId());
            }
        }
    }
}
