package org.eco.als.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.eco.als.domain.KGraphTask;
import org.eco.als.domain.bo.ExtraKGraphTaskBo;
import org.eco.als.domain.bo.ExtraKGraphTaskStatusBo;
import org.eco.als.domain.bo.KGraphClauseBo;
import org.eco.als.domain.bo.KGraphTaskBo;
import org.eco.als.domain.vo.ExtraKGraphTaskVo;
import org.eco.als.domain.vo.KGraphClauseVo;
import org.eco.als.domain.vo.KGraphEntityVo;
import org.eco.als.domain.vo.KGraphTaskVo;
import org.eco.als.enums.GraphStatus;
import org.eco.als.mapper.KGraphTaskMapper;
import org.eco.als.service.IKGraphClauseService;
import org.eco.als.service.IKGraphEntityService;
import org.eco.als.service.IKGraphTaskService;
import org.eco.common.core.core.page.PageResult;
import org.eco.common.core.exception.BusinessException;
import org.eco.common.core.utils.HttpUtils;
import org.eco.common.core.utils.MapstructUtils;
import org.eco.common.orm.core.page.PageQuery;
import org.eco.common.orm.core.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.eco.als.domain.table.KGraphTaskTableDef.KGRAPH_TASK;

/**
 * 知识图谱任务Service业务层处理
 *
 * @author wgk
 * @date 2025-01-03
 */
@Service
@Slf4j
public class KGraphTaskServiceImpl extends BaseServiceImpl<KGraphTaskMapper, KGraphTask> implements IKGraphTaskService {
    @Resource
    private KGraphTaskMapper kGraphTaskMapper;
    @Resource
    private IKGraphClauseService kGraphClauseService;
    @Resource
    private IKGraphEntityService kGraphEntityService;

    @Value("${kgqa.clause-url}")
    private String clauseUrl;

    @Value("${kgqa.extract-url}")
    private String extractUrl;
    //
    @Value("${kgqa.storage-url}")
    private String storageUrl;

    @Override
    public QueryWrapper query() {
        return super.query().from(KGRAPH_TASK);
    }

    private QueryWrapper buildQueryWrapper(KGraphTaskBo kGraphTaskBo) {
        QueryWrapper queryWrapper = super.buildBaseQueryWrapper();
        queryWrapper.and(KGRAPH_TASK.TASK_NAME.like
            (kGraphTaskBo.getTaskName()));
        queryWrapper.and(KGRAPH_TASK.TASK_TYPE.eq
            (kGraphTaskBo.getTaskType()));
        queryWrapper.and(KGRAPH_TASK.OSS_ID.eq
            (kGraphTaskBo.getOssId()));
        queryWrapper.and(KGRAPH_TASK.STATUS.eq
            (kGraphTaskBo.getStatus()));
        queryWrapper.and(KGRAPH_TASK.REMARKS.eq
            (kGraphTaskBo.getRemarks()));
        queryWrapper.orderBy(KGRAPH_TASK.UPDATE_TIME.desc());
        return queryWrapper;
    }

    /**
     * 查询知识图谱任务
     *
     * @param id 知识图谱任务主键
     * @return 知识图谱任务
     */
    @Override
    public KGraphTaskVo selectById(Long id) {
        return this.getOneAs(query().where(KGRAPH_TASK.ID.eq(id)), KGraphTaskVo.class);

    }


    /**
     * 查询知识图谱任务列表
     *
     * @param kGraphTaskBo 知识图谱任务Bo
     * @return 知识图谱任务集合
     */
    @Override
    public List<KGraphTaskVo> selectList(KGraphTaskBo kGraphTaskBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(kGraphTaskBo);
        return this.listAs(queryWrapper, KGraphTaskVo.class);
    }

    /**
     * 分页查询知识图谱任务列表
     *
     * @param kGraphTaskBo 知识图谱任务Bo
     * @return 分页知识图谱任务集合
     */
    @Override
    public PageResult<KGraphTaskVo> selectPage(KGraphTaskBo kGraphTaskBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(kGraphTaskBo);
        Page<KGraphTaskVo> page = this.pageAs(PageQuery.build(), queryWrapper, KGraphTaskVo.class);
        return PageResult.build(page);
    }

    /**
     * 新增知识图谱任务
     *
     * @param kGraphTaskBo 知识图谱任务Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insert(KGraphTaskBo kGraphTaskBo) {
        KGraphTask kGraphTask = MapstructUtils.convert(kGraphTaskBo, KGraphTask.class);
        //使用全局配置的雪花算法主键生成器生成ID值
        return this.save(kGraphTask);
    }

    @Override
    public boolean proTask(KGraphTaskBo kGraphTaskBo) {
        log.info("进入处理：{}", kGraphTaskBo.getTaskType());
        KGraphTaskVo kGraphTaskVo = this.selectById(kGraphTaskBo.getId());
        Long ossId = kGraphTaskVo.getOssId();
        if(ObjectUtil.isEmpty(kGraphTaskVo)) {
            throw new BusinessException("任务为空，请核实任务ID");
        }
        String result;
        JSONObject jsonObject;
        ExtraKGraphTaskVo extraGraphTaskVo = new ExtraKGraphTaskVo();
        switch (kGraphTaskBo.getTaskType()) {
            case "0":
                updateStatus(kGraphTaskBo, kGraphTaskVo.getVersion(), GraphStatus.STATUS_1.getCode());
                // 知识图谱执行分句
                Map<String, Object> map = new HashMap<>();
                map.put("ossId", ossId);
                map.put("taskId", kGraphTaskBo.getId());
                result = HttpUtils.postJson(clauseUrl, map);
                jsonObject = JSONUtil.parseObj(result);
                if (!StrUtil.equals("200", jsonObject.getStr("code"))) {
                    throw new BusinessException(jsonObject.getStr("msg"));
                }
                break;
            case "2":
                updateStatus(kGraphTaskBo, kGraphTaskVo.getVersion(), GraphStatus.STATUS_3.getCode());
                // 知识图谱抽取
                KGraphClauseBo kGraphClauseBo = new KGraphClauseBo();
                kGraphClauseBo.setTaskId(kGraphTaskBo.getId());
                List<KGraphClauseVo> graphClauseVos = kGraphClauseService.selectList(kGraphClauseBo);
                extraGraphTaskVo.setTaskId(kGraphTaskBo.getId());
                extraGraphTaskVo.setGraphClauseList(graphClauseVos);
                result = HttpUtils.postJson(extractUrl, extraGraphTaskVo);
                jsonObject = JSONUtil.parseObj(result);
                if (!StrUtil.equals("200", jsonObject.getStr("code"))) {
                    throw new BusinessException(jsonObject.getStr("msg"));
                }
                kGraphClauseBo.setStatus(GraphStatus.STATUS_3.getCode());
                kGraphClauseService.update(kGraphClauseBo);
                break;
            case "4":
                updateStatus(kGraphTaskBo, kGraphTaskVo.getVersion(), GraphStatus.STATUS_5.getCode());
                // 知识图谱入库
                List<KGraphEntityVo> graphEntityVos = kGraphEntityService.selectListByTaskId(kGraphTaskBo.getId());
                extraGraphTaskVo.setTaskId(kGraphTaskBo.getId());
                extraGraphTaskVo.setOssId(ossId);
                extraGraphTaskVo.setGraphEntityList(graphEntityVos);
                result = HttpUtils.postJson(storageUrl, extraGraphTaskVo);
                jsonObject = JSONUtil.parseObj(result);
                if (!StrUtil.equals("200", jsonObject.getStr("code"))) {
                    throw new BusinessException(jsonObject.getStr("msg"));
                }
                break;
            default:
                throw new BusinessException("任务类型错误");
        }
        return true;
    }

    private void updateStatus(KGraphTaskBo kGraphTaskBo, Integer version, String status) {
        kGraphTaskBo.setStatus(status);
        kGraphTaskBo.setVersion(version);
        this.update(kGraphTaskBo);
    }

    /**
     * 新增知识图谱任务，前台提供主键值，一般用于导入的场合
     *
     * @param kGraphTaskBo 知识图谱任务Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insertWithPk(KGraphTaskBo kGraphTaskBo) {
        KGraphTask kGraphTask = MapstructUtils.convert(kGraphTaskBo, KGraphTask.class);
        return kGraphTaskMapper.insertWithPk(kGraphTask) > 0;//前台传来主键值
    }

    /**
     * 修改知识图谱任务
     *
     * @param kGraphTaskBo 知识图谱任务Bo
     * @return 结果:true 更新成功，false 更新失败
     */
    @Override
    public boolean update(KGraphTaskBo kGraphTaskBo) {
        KGraphTask kGraphTask = MapstructUtils.convert(kGraphTaskBo, KGraphTask.class);
        if (ObjectUtil.isNotNull(kGraphTask) && ObjectUtil.isNotNull(kGraphTask.getId())) {
            return this.updateById(kGraphTask);
        }
        return false;
    }

    /**
     * 批量删除知识图谱任务
     *
     * @param ids 需要删除的知识图谱任务主键集合
     * @return 结果:true 删除成功，false 删除失败
     */
    @Transactional
    @Override
    public boolean deleteByIds(Long[] ids) {
        return this.removeByIds(Arrays.asList(ids));
    }

    @Override
    public boolean resultCallback(ExtraKGraphTaskBo extraKGraphTaskBo) {
        if (StrUtil.equals(extraKGraphTaskBo.getTaskType(), "1")) {
            boolean isSave = kGraphClauseService.saveBatch(extraKGraphTaskBo.getGraphClauseList());
            if (!isSave) {
                return false;
            }

        } else if (StrUtil.equals(extraKGraphTaskBo.getTaskType(), "2")) {
            boolean isSave = kGraphEntityService.saveBatch(extraKGraphTaskBo.getGraphEntityList());
            if (!isSave) {
                return false;
            }
        }
        KGraphTaskVo kGraphTaskVo = this.selectById(extraKGraphTaskBo.getTaskId());
        KGraphTaskBo kGraphTaskBo = new KGraphTaskBo();
        kGraphTaskBo.setId(extraKGraphTaskBo.getTaskId());
        kGraphTaskBo.setVersion(kGraphTaskVo.getVersion());
        kGraphTaskBo.setStatus(StrUtil.equals(extraKGraphTaskBo.getTaskType(), "1") ? GraphStatus.STATUS_2.getCode() : GraphStatus.STATUS_4.getCode());
        return this.update(kGraphTaskBo);
    }

    @Override
    public boolean statusCallback(ExtraKGraphTaskStatusBo extraKGraphTaskStatusBo) {
        KGraphTaskVo kGraphTaskVo = this.selectById(extraKGraphTaskStatusBo.getTaskId());
        KGraphTaskBo kGraphTaskBo = new KGraphTaskBo();
        kGraphTaskBo.setId(extraKGraphTaskStatusBo.getTaskId());
        kGraphTaskBo.setVersion(kGraphTaskVo.getVersion());
        kGraphTaskBo.setStatus(extraKGraphTaskStatusBo.getStatus());
        return this.update(kGraphTaskBo);
    }
}
