package com.qingyun.service.service.impl;

import com.github.difflib.patch.DeltaType;
import com.qingyun.common.exception.ServiceException;
import com.qingyun.common.helper.LoginHelper;
import com.qingyun.service.compare.*;
import com.qingyun.service.compare.factory.FileComparisonStrategyFactory;
import com.qingyun.service.compare.strategy.FileComparisonStrategy;
import com.qingyun.service.domain.ContractCompareResult;
import com.qingyun.service.mapper.ContractCompareResultMapper;
import com.qingyun.service.utils.PdfUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import com.qingyun.common.utils.MapstructUtils;
import com.qingyun.mybatisplus.page.TableDataInfo;
import com.qingyun.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.qingyun.service.domain.bo.ContractCompareTaskBo;
import com.qingyun.service.domain.vo.ContractCompareTaskVo;
import com.qingyun.service.domain.ContractCompareTask;
import com.qingyun.service.mapper.ContractCompareTaskMapper;
import com.qingyun.service.service.IContractCompareTaskService;

import com.qingyun.mybatisplus.core.ServicePlusImpl;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.*;

/**
 * 对比任务Service业务层处理
 *
 * @author jianlu
 * @date 2025-07-11
 */
@RequiredArgsConstructor
@Service
@Slf4j
@SuppressWarnings("all")
public class ContractCompareTaskServiceImpl extends ServicePlusImpl<ContractCompareTaskMapper, ContractCompareTask, ContractCompareTaskVo> implements IContractCompareTaskService {

    private final ContractCompareResultMapper compareResultMapper;

    private final PdfUtil pdfUtil;

    private final PdfDiffWithPosition pdfDiffWithPosition;

    private final FileComparisonStrategyFactory strategyFactory;

    private final SqlSessionFactory sqlSessionFactory;

    private static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(5);

    /**
     * 查询对比任务
     */
    @Override
    public ContractCompareTaskVo queryById(Long taskId) {
        ContractCompareTaskVo contractCompareTaskVo = baseMapper.selectVoById(taskId);
        return contractCompareTaskVo;
    }

    /**
     * 查询对比任务列表
     */
    @Override
    public TableDataInfo<ContractCompareTaskVo> queryPageList(String contractName, PageQuery pageQuery) {
        LambdaQueryWrapper<ContractCompareTask> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(contractName), ContractCompareTask::getFirstContractName, contractName)
            .or()
            .like(StringUtils.isNotBlank(contractName), ContractCompareTask::getSecondContractName, contractName);
        // 创建时间降序
        lqw.orderByDesc(ContractCompareTask::getCreateTime);
        Page<ContractCompareTaskVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询对比任务列表
     */
    @Override
    public List<ContractCompareTaskVo> queryList(ContractCompareTaskBo bo) {
        LambdaQueryWrapper<ContractCompareTask> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ContractCompareTask> buildQueryWrapper(ContractCompareTaskBo bo) {
        LambdaQueryWrapper<ContractCompareTask> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCompareRule()), ContractCompareTask::getCompareRule, bo.getCompareRule());
        // 创建时间降序
        lqw.orderByDesc(ContractCompareTask::getCreateTime);
        return lqw;
    }

    /**
     * 新增对比任务
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertByBo(ContractCompareTaskBo bo) {
        ContractCompareTask add = MapstructUtils.convert(bo, ContractCompareTask.class);
        add.setStatus(2);
        add.setUserId(LoginHelper.getUserId());
        add.setDeptId(LoginHelper.getDeptId());
        add.setCreateTime(new Date());
        add.setCreateBy(LoginHelper.getUsername());
        int insert = baseMapper.insert(add);
        if (insert < 1) {
            throw new ServiceException("新增失败");
        }
        return add.getTaskId();
    }

    /**
     * 修改对比任务
     */
    @Override
    public Boolean updateByBo(ContractCompareTaskBo bo) {
        ContractCompareTask update = MapstructUtils.convert(bo, ContractCompareTask.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ContractCompareTask entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除对比任务
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 执行任务
     *
     * @param taskId
     * @return
     */
    @Async
    @Override
    public void executeTask(FileComparisonStrategy strategy, ContractCompareTask task) {
        Future<?> future = EXECUTOR.submit(() -> {
            try {
                // 比对
                List<DiffRegion> diff = strategy.compare(task);
                // 组装并保存结果
                strategy.assembleAndSaveResult(task, diff);
            } catch (Exception e) {
                log.error("任务执行失败: {}", task.getTaskId(), e);
                task.setStatus(4);
                task.setErrorMsg("执行异常: " + e.getMessage());
                baseMapper.updateById(task);
            }
        });

        try {
            future.get(600, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            log.warn("任务超时: {}", task.getTaskId());
            task.setStatus(4);
            task.setErrorMsg("任务执行超时");
            baseMapper.updateById(task);
            future.cancel(true);
        } catch (Exception e) {
            log.error("任务执行异常", e);
            task.setStatus(4);
            task.setErrorMsg("系统异常");
            baseMapper.updateById(task);
        }
    }
}
