package cn.com.poc.thirdparty.resource.baidu.service.impl;

import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.entity.media.MediaType;
import cn.com.poc.common.service.BizFileUploadRecordService;
import cn.com.poc.common.utils.DocumentLoad;
import cn.com.poc.common.utils.FileUtils;
import cn.com.poc.common.utils.StringUtils;
import cn.com.poc.covenant.constants.ContractConstants;
import cn.com.poc.covenant.model.BizExtractionReviewTaskModel;
import cn.com.poc.covenant.service.BizExtractionReviewTaskService;
import cn.com.poc.thirdparty.resource.baidu.api.BaiduTextDiffApi;
import cn.com.poc.thirdparty.resource.baidu.entity.response.BaiduTextDiffResponse;
import cn.com.poc.thirdparty.resource.baidu.entity.response.text_diff.BaiduTextDiffQueryResult;
import cn.com.poc.thirdparty.resource.baidu.entity.result.BaiduTextDiffResult;
import cn.com.poc.thirdparty.resource.baidu.service.BaiduTextDiffService;
import cn.com.poc.thirdparty.resource.baidu.service.BaiduTokenService;
import cn.com.yict.framemax.core.exception.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @author alex.yao
 * @date 2025/6/25
 */
@Service
public class BaiduTextDiffServiceImpl implements BaiduTextDiffService {

    private final Logger logger = LoggerFactory.getLogger(BaiduTextDiffService.class);


    @Value("${baidu.text_diff.client_id}")
    private String clientId;

    @Value("${baidu.text_diff.client_secret}")
    private String clientSecret;

    @Resource
    private BaiduTextDiffApi baiduTextDiffApi;

    @Resource
    private BaiduTokenService baiduTokenService;

    @Resource
    private BizExtractionReviewTaskService bizExtractionReviewTaskService;

    @Resource
    private BizFileUploadRecordService bizFileUploadRecordService;

    @Override
    public String textDiff(File baseFile, File compareFile, BaiduTextDiffResponse.Param param, Long userId) {

        BaiduTextDiffResponse baiduTextDiffResponse = new BaiduTextDiffResponse();
        baiduTextDiffResponse.setBaseFile(baseFile);
        baiduTextDiffResponse.setCompareFile(compareFile);
        baiduTextDiffResponse.setParam(param);
        try {
            String taskId = createTextDiffTask(baiduTextDiffResponse, baiduTokenService.getToken(clientId, clientSecret));
            BizExtractionReviewTaskModel bizExtractionReviewTaskModel = new BizExtractionReviewTaskModel();
            bizExtractionReviewTaskModel.setTaskId(taskId);
            bizExtractionReviewTaskModel.setFileUrl(null);
            bizExtractionReviewTaskModel.setUserId(userId);
            bizExtractionReviewTaskModel.setFileName(baseFile.getName());
            bizExtractionReviewTaskModel.setActionType(ContractConstants.ActionType.textdiff);
            bizExtractionReviewTaskModel.setReviewStatus("RUN");
            bizExtractionReviewTaskModel.setContractType(ContractConstants.ContractType.contractTextdiff);
            bizExtractionReviewTaskService.save(bizExtractionReviewTaskModel);
            return taskId;
        } catch (Exception e) {
            logger.error("保存任务失败", e);
            throw new BusinessException("保存任务失败");
        }
    }

    @Override
    public String textDiff(String baseFileUrl, String compareFileUrl, BaiduTextDiffResponse.Param param, Long userId) {
        File baseFile = DocumentLoad.downloadURLDocument(baseFileUrl);
        File compareFile = DocumentLoad.downloadURLDocument(compareFileUrl);

        BaiduTextDiffResponse baiduTextDiffResponse = new BaiduTextDiffResponse();
        baiduTextDiffResponse.setBaseFile(baseFile);
        baiduTextDiffResponse.setCompareFile(compareFile);
        baiduTextDiffResponse.setParam(param);
        String taskId = createTextDiffTask(baiduTextDiffResponse, baiduTokenService.getToken(clientId, clientSecret));
        if (StringUtils.isBlank(taskId)) {
            throw new BusinessException("文档比对任务创建失败");
        }
        try {
            BizExtractionReviewTaskModel bizExtractionReviewTaskModel = new BizExtractionReviewTaskModel();
            bizExtractionReviewTaskModel.setTaskId(taskId);
            bizExtractionReviewTaskModel.setFileUrl(baseFileUrl);
            bizExtractionReviewTaskModel.setUserId(userId);
            bizExtractionReviewTaskModel.setFileName(bizFileUploadRecordService.getFileNameByFileUrl(baseFileUrl));
            bizExtractionReviewTaskModel.setActionType(ContractConstants.ActionType.textdiff);
            bizExtractionReviewTaskModel.setReviewStatus("RUN");
            bizExtractionReviewTaskModel.setContractType(ContractConstants.ContractType.contractTextdiff);
            bizExtractionReviewTaskService.save(bizExtractionReviewTaskModel);
            return taskId;
        } catch (Exception e) {
            logger.error("保存任务失败", e);
            throw new BusinessException("保存任务失败");
        }
    }

    private String createTextDiffTask(BaiduTextDiffResponse baiduTextDiffResponse, String token) {
        BaiduTextDiffResult baiduTextDiffResult = baiduTextDiffApi.textDiff(baiduTextDiffResponse, token);
        if (baiduTextDiffResult == null || !baiduTextDiffResult.getError_code().equals(0)) {
            if (baiduTextDiffResult != null
                    && baiduTextDiffResult.getError_code() != null
                    && StringUtils.isNotBlank(baiduTextDiffResult.getError_msg())) {
                logger.error("文档比对任务创建失败，错误码：{}，错误信息：{}", baiduTextDiffResult.getError_code(), baiduTextDiffResult.getError_msg());
            }
            throw new BusinessException("文档比对任务创建失败");
        }
        return baiduTextDiffResult.getResult().getTaskId();
    }

    @Override
    public String queryTextDiffTask(String taskId) throws Exception {
        BizExtractionReviewTaskModel bizExtractionReviewTaskModel = new BizExtractionReviewTaskModel();
        bizExtractionReviewTaskModel.setTaskId(taskId);
        bizExtractionReviewTaskModel.setActionType(ContractConstants.ActionType.textdiff);
        bizExtractionReviewTaskModel.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizExtractionReviewTaskModel> models = bizExtractionReviewTaskService.findByExample(bizExtractionReviewTaskModel, null);
        if (CollectionUtils.isEmpty(models)) {
            throw new BusinessException("任务不存在");
        }
        BizExtractionReviewTaskModel taskModel = models.get(0);
        String status = StringUtils.EMPTY;
        if ("RUN".equals(taskModel.getReviewStatus())) {
            String token = baiduTokenService.getToken(clientId, clientSecret);
            BaiduTextDiffQueryResult baiduTextDiffQueryResult = baiduTextDiffApi.queryTask(taskId, token);
            if (baiduTextDiffQueryResult == null || !baiduTextDiffQueryResult.getError_code().equals(0)) {
                if (baiduTextDiffQueryResult != null
                        && baiduTextDiffQueryResult.getError_code() != null
                        && StringUtils.isNotBlank(baiduTextDiffQueryResult.getError_msg())) {
                    logger.error("查询文档对比任务，错误码：{}，错误信息：{}", baiduTextDiffQueryResult.getError_code(), baiduTextDiffQueryResult.getError_msg());
                }
                throw new BusinessException("查询文档对比任务失败");
            }

            if ("success".equals(baiduTextDiffQueryResult.getResult().getStatus())) {
                taskModel.setReviewStatus("END");
                bizExtractionReviewTaskService.save(taskModel);
                status = "END";
            } else if ("failed".equals(baiduTextDiffQueryResult.getResult().getStatus())) {
                taskModel.setReviewStatus("FAIL");
                bizExtractionReviewTaskService.save(taskModel);
                status = "FAIL";
            } else {
                status = "RUN";
            }
        }
        return status;
    }

    @Override
    public String getSDKUrl(String taskId) {
        String baseUrl = "https://textmind-sdk.bce.baidu.com/textmind/sdk/textdiff/{taskId}?access_token={access_token}";
        String token = baiduTokenService.getToken(clientId, clientSecret);
        baseUrl = baseUrl.replace("{taskId}", taskId).replace("{access_token}", token);
        return baseUrl;
    }

}
