package com.taais.biz.service.impl;

import java.io.IOException;
import java.util.*;

import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.taais.biz.constant.BizConstant;
import com.taais.biz.domain.AlgorithmConfig;
import com.taais.biz.domain.dto.TaskResultDTO;
import com.taais.biz.domain.dto.task.TestResultDto;
import com.taais.biz.domain.dto.task.TranResultDto;
import com.taais.biz.service.IAlgorithmConfigService;
import com.taais.biz.service.IAlgorithmModelService;
import com.taais.common.core.config.TaaisConfig;
import com.taais.common.core.utils.DateUtils;
import com.taais.common.core.utils.MapstructUtils;
import com.taais.common.core.utils.file.FileUtils;
import com.taais.common.orm.core.page.PageQuery;
import com.taais.common.core.core.page.PageResult;
import com.taais.common.orm.core.service.impl.BaseServiceImpl;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.list.TreeList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.taais.biz.mapper.AlgorithmBizProcessMapper;
import com.taais.biz.domain.AlgorithmBizProcess;
import com.taais.biz.domain.bo.AlgorithmBizProcessBo;
import com.taais.biz.domain.vo.AlgorithmBizProcessVo;
import com.taais.biz.service.IAlgorithmBizProcessService;
import org.springframework.util.CollectionUtils;

import static com.taais.biz.domain.table.AlgorithmBizProcessTableDef.ALGORITHM_BIZ_PROCESS;

/**
 * 算法业务处理Service业务层处理
 *
 * @author 0
 * 2024-06-14
 */
@Service
public class AlgorithmBizProcessServiceImpl extends BaseServiceImpl<AlgorithmBizProcessMapper, AlgorithmBizProcess> implements IAlgorithmBizProcessService {
    private static final Logger log = LoggerFactory.getLogger(AlgorithmBizProcessServiceImpl.class);
    @Resource
    private AlgorithmBizProcessMapper algorithmBizProcessMapper;
    @Resource
    private IAlgorithmConfigService algorithmConfigService;
    @Resource
    private IAlgorithmModelService algorithmModelService;

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

    private QueryWrapper buildQueryWrapper(AlgorithmBizProcessBo algorithmBizProcessBo) {
        QueryWrapper queryWrapper = super.buildBaseQueryWrapper();
        queryWrapper.and(ALGORITHM_BIZ_PROCESS.SUB_TASK_ID.eq
        (algorithmBizProcessBo.getSubTaskId()));
        queryWrapper.and(ALGORITHM_BIZ_PROCESS.NAME.like
        (algorithmBizProcessBo.getName()));
        queryWrapper.and(ALGORITHM_BIZ_PROCESS.TYPE.eq
        (algorithmBizProcessBo.getType()));
        queryWrapper.and(ALGORITHM_BIZ_PROCESS.STATUS.eq
        (algorithmBizProcessBo.getStatus()));

        return queryWrapper;
    }

    /**
     * 查询算法业务处理
     *
     * @param id 算法业务处理主键
     * @return 算法业务处理
     */
    @Override
    public AlgorithmBizProcessVo selectById(Long id) {
            return this.getOneAs(query().where(ALGORITHM_BIZ_PROCESS.ID.eq(id)), AlgorithmBizProcessVo.class);

    }

    /**
     * 查询算法业务处理列表
     *
     * @param algorithmBizProcessBo 算法业务处理Bo
     * @return 算法业务处理集合
     */
    @Override
    public List<AlgorithmBizProcessVo> selectList(AlgorithmBizProcessBo algorithmBizProcessBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(algorithmBizProcessBo);
            return this.listAs(queryWrapper, AlgorithmBizProcessVo.class);
    }

    /**
     * 分页查询算法业务处理列表
     *
     * @param algorithmBizProcessBo 算法业务处理Bo
     * @return 分页算法业务处理集合
     */
    @Override
    public PageResult<AlgorithmBizProcessVo> selectPage(AlgorithmBizProcessBo algorithmBizProcessBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(algorithmBizProcessBo);
            Page<AlgorithmBizProcessVo> page = this.pageAs(PageQuery.build(), queryWrapper, AlgorithmBizProcessVo.class);
        return PageResult.build(page);
    }

    /**
     * 新增算法业务处理
     *
     * @param algorithmBizProcessBo 算法业务处理Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insert(AlgorithmBizProcessBo algorithmBizProcessBo) {
    AlgorithmBizProcess algorithmBizProcess =MapstructUtils.convert(algorithmBizProcessBo, AlgorithmBizProcess. class);
        boolean save = this.save(algorithmBizProcess);
        algorithmBizProcessBo.setId(algorithmBizProcess.getId());
        algorithmBizProcessBo.setVersion(algorithmBizProcess.getVersion());
        return save;//使用全局配置的雪花算法主键生成器生成ID值
    }

    /**
     * 修改算法业务处理
     *
     * @param algorithmBizProcessBo 算法业务处理Bo
     * @return 结果:true 更新成功，false 更新失败
     */
    @Override
    public boolean update(AlgorithmBizProcessBo algorithmBizProcessBo) {
        AlgorithmBizProcess algorithmBizProcess =MapstructUtils.convert(algorithmBizProcessBo, AlgorithmBizProcess. class);
        if (ObjectUtil.isNotNull(algorithmBizProcess) && ObjectUtil.isNotNull(algorithmBizProcess.getId())){
            boolean updated = this.updateById(algorithmBizProcess);
                return updated;
        }
        return false;
    }

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

    public List<AlgorithmBizProcessVo> getStatus0ProcessBySubtaskId(Long subtaskId) {
        return mapper.getStatus0ProcessBySubtaskId(subtaskId);
    }

    public List<AlgorithmBizProcessVo> getProcessBySubtaskId(Long subtaskId) {
        return mapper.getProcessBySubtaskId(subtaskId);
    }

    @Override
    public String taskResult(TaskResultDTO resultDTO) {
        Long bizId = resultDTO.getBizId();
        AlgorithmBizProcess bizProcess = this.getById(bizId);
        if(bizProcess == null){
            log.error("任务数据没有找到,resultDTO:{}",resultDTO);
            return "任务数据没有找到,resultDTO:"+ resultDTO;
        }
        if (resultDTO.getStatus() == 200) {
            bizProcess.setStatus(BizConstant.TASK_STATUS_SUCCEED);
        } else if (resultDTO.getStatus() == 500) {
            bizProcess.setStatus(BizConstant.TASK_STATUS_FAILED);
        } else {
            log.error("不可能的分支");
        }
//        bizProcess.setLog(resultDTO.getMsg());
        Date now = new Date();
        Date startTime = bizProcess.getStartTime();
        bizProcess.setEndTime(now);
        if (startTime != null) {
            bizProcess.setCostSecond(DateUtils.differentSecondByDate(startTime, now));
        }
        this.updateById(bizProcess);
        // todo allen 暂时注释
//        algorithmModelService.createModelByBizProcess(bizProcess);
        algorithmBizProcessMapper.updateTaskAndSubtask(resultDTO.getBizId(),resultDTO.getBizType());
        return null;
    }

    @Override
    public TranResultDto getTranResult(Long subtaskId) {
        List<AlgorithmBizProcessVo> bizProcessVoList = getProcessBySubtaskId(subtaskId);
        TranResultDto tranResultDto = new TranResultDto();
        for (AlgorithmBizProcessVo bizProcessVo : bizProcessVoList) {
            AlgorithmConfig algorithmConfig = algorithmConfigService.getById(bizProcessVo.getAlgorithmId());
            tranResultDto.getAgNameList().add(algorithmConfig.getAlgorithmName());
            tranResultDto.getRcureList().add(bizProcessVo.getResultPath()+BizConstant.R_CURVE);
            tranResultDto.getPcureList().add(bizProcessVo.getResultPath()+BizConstant.P_CURVE);
            tranResultDto.getF1cureList().add(bizProcessVo.getResultPath()+BizConstant.F1_CURVE);
        }
        return tranResultDto;
    }

    @Override
    public TestResultDto getTestResult(Long subtaskId) throws IOException {
        List<AlgorithmBizProcessVo> bizProcessVoList = getProcessBySubtaskId(subtaskId);
        TestResultDto resultDto = new TestResultDto();
        List<String> fileNames = Collections.emptyList();
        // 构建原始图片
        if (!CollectionUtils.isEmpty(bizProcessVoList)) {
            resultDto.getAgNameList().add(BizConstant.ORIGINAL_IMAGE);
            AlgorithmBizProcessVo bizProcessVo = bizProcessVoList.get(0);
            String preprocessPath = bizProcessVo.getPreprocessPath();
            fileNames = FileUtils.getAllFileNamesAndExtensions(TaaisConfig.getProfile() + preprocessPath);
            if (!CollectionUtils.isEmpty(fileNames)) {
                for (String name : fileNames) {
                    List<String> list = new TreeList<>();
                    resultDto.getResultList().add(list);
                    list.add(preprocessPath + name);
                }
            }
        }

        // 构建生成图片
        for (AlgorithmBizProcessVo bizProcessVo : bizProcessVoList) {
            AlgorithmConfig algorithmConfig = algorithmConfigService.getById(bizProcessVo.getAlgorithmId());
            resultDto.getAgNameList().add(algorithmConfig.getAlgorithmName());
            String resultPath = bizProcessVo.getResultPath();
            for (int index = 0; index < fileNames.size(); index++) {
                List<String> list = resultDto.getResultList().get(index);
                list.add(resultPath + fileNames.get(index));
            }
        }
        return resultDto;
    }

}
