package com.taais.biz.service.impl;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

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.*;
import com.taais.biz.domain.vo.StartToInfraredTask;
import com.taais.biz.mapper.ToInfraredMapper;
import com.taais.biz.utils.ZipUtils;
import com.taais.common.core.config.TaaisConfig;
import com.taais.common.core.constant.Constants;
import com.taais.common.core.core.domain.CommonResult;
import com.taais.common.core.utils.MapstructUtils;
import com.taais.common.core.utils.StringUtils;
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 com.taais.system.domain.vo.SysOssVo;
import com.taais.system.service.ISysOssService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.taais.biz.mapper.TargetDetectionMapper;
import com.taais.biz.domain.bo.TargetDetectionBo;
import com.taais.biz.domain.vo.TargetDetectionVo;
import com.taais.biz.service.ITargetDetectionService;

import static com.taais.biz.constant.BizConstant.VideoStatus.NOT_START;
import static com.taais.biz.domain.table.TargetDetectionTableDef.TARGET_DETECTION;
import static com.taais.biz.service.impl.VideoStableServiceImpl.*;
import static com.taais.biz.service.impl.VideoStableServiceImpl.sendPostMsg;

/**
 * 目标检测Service业务层处理
 *
 * @author wangkang
 * 2024-09-29
 */
@Service
public class TargetDetectionServiceImpl extends BaseServiceImpl<TargetDetectionMapper, TargetDetection> implements ITargetDetectionService {
    @Value("${server.target_detection_stop_url}")
    private String target_detection_stop_url;

    @Resource
    private TargetDetectionMapper targetDetectionMapper;
    @Autowired
    private ISysOssService ossService;

    @Autowired
    private AlgorithmConfigTrackServiceImpl algorithmConfigTrackService;
    @Autowired
    private AlgorithmModelTrackServiceImpl algorithmModelTrackService;

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

    private QueryWrapper buildQueryWrapper(TargetDetectionBo targetDetectionBo) {
        QueryWrapper queryWrapper = super.buildBaseQueryWrapper();
        queryWrapper.and(TARGET_DETECTION.NAME.like
            (targetDetectionBo.getName()));
        queryWrapper.and(TARGET_DETECTION.STATUS.eq
            (targetDetectionBo.getStatus()));
        queryWrapper.and(TARGET_DETECTION.START_TIME.eq
            (targetDetectionBo.getStartTime()));
        queryWrapper.and(TARGET_DETECTION.END_TIME.eq
            (targetDetectionBo.getEndTime()));
        queryWrapper.and(TARGET_DETECTION.COST_SECOND.eq
            (targetDetectionBo.getCostSecond()));
        queryWrapper.and(TARGET_DETECTION.LOG.eq
            (targetDetectionBo.getLog()));
        queryWrapper.and(TARGET_DETECTION.REMARKS.eq
            (targetDetectionBo.getRemarks()));
        queryWrapper.and(TARGET_DETECTION.URL.eq
            (targetDetectionBo.getUrl()));
        queryWrapper.and(TARGET_DETECTION.INPUT_OSS_ID.eq
            (targetDetectionBo.getInputOssId()));
        queryWrapper.and(TARGET_DETECTION.INPUT_PATH.eq
            (targetDetectionBo.getInputPath()));
        queryWrapper.and(TARGET_DETECTION.OUTPUT_PATH.eq
            (targetDetectionBo.getOutputPath()));
        queryWrapper.and(TARGET_DETECTION.ZIP_FILE_PATH.eq
            (targetDetectionBo.getZipFilePath()));
        queryWrapper.and(TARGET_DETECTION.ALGORITHM_MODEL_ID.eq
            (targetDetectionBo.getAlgorithmModelId()));

        return queryWrapper;
    }

    /**
     * 查询目标检测
     *
     * @param id 目标检测主键
     * @return 目标检测
     */
    @Override
    public TargetDetectionVo selectById(Long id) {
        return this.getOneAs(query().where(TARGET_DETECTION.ID.eq(id)), TargetDetectionVo.class);

    }

    /**
     * 查询目标检测列表
     *
     * @param targetDetectionBo 目标检测Bo
     * @return 目标检测集合
     */
    @Override
    public List<TargetDetectionVo> selectList(TargetDetectionBo targetDetectionBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(targetDetectionBo);
        return this.listAs(queryWrapper, TargetDetectionVo.class);
    }

    /**
     * 分页查询目标检测列表
     *
     * @param targetDetectionBo 目标检测Bo
     * @return 分页目标检测集合
     */
    @Override
    public PageResult<TargetDetectionVo> selectPage(TargetDetectionBo targetDetectionBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(targetDetectionBo);
        Page<TargetDetectionVo> page = this.pageAs(PageQuery.build(), queryWrapper, TargetDetectionVo.class);
        return PageResult.build(page);
    }

    /**
     * 新增目标检测
     *
     * @param targetDetectionBo 目标检测Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insert(TargetDetectionBo targetDetectionBo) {
        // 检查input_oss_id是否存在
        if (ObjectUtil.isNull(targetDetectionBo.getInputOssId())) {
            return false;
        }

        SysOssVo ossEntity = ossService.getById(targetDetectionBo.getInputOssId());
        if (ObjectUtil.isNull(ossEntity)) {
            return false;
        }

        TargetDetection targetDetection = new TargetDetection();

        targetDetection.setInputOssId(targetDetectionBo.getInputOssId());
        targetDetection.setUrl(ossEntity.getUrl());

        String filePath = ossEntity.getFileName();
        String localPath = TaaisConfig.getProfile();
        String resourcePath = localPath + StringUtils.substringAfter(filePath, Constants.RESOURCE_PREFIX);
        targetDetection.setInputPath(resourcePath);

        String fileName = StringUtils.substringAfterLast(filePath, "/");
        String fileName_without_suffix = removeFileExtension(fileName);

        Path path = Paths.get(resourcePath);
        Path outPath = path.resolveSibling(fileName_without_suffix + "_images" + System.currentTimeMillis());
        targetDetection.setOutputPath(outPath.toString());

        targetDetection.setZipFilePath(path.resolveSibling(fileName_without_suffix + ".zip").toString());

        targetDetection.setName(targetDetectionBo.getName());
        targetDetection.setStatus(NOT_START);
        targetDetection.setRemarks(targetDetectionBo.getRemarks());

        targetDetection.setAlgorithmModelId(targetDetectionBo.getAlgorithmModelId());

        return this.save(targetDetection);// 使用全局配置的雪花算法主键生成器生成ID值
    }

    /**
     * 修改目标检测
     *
     * @param targetDetectionBo 目标检测Bo
     * @return 结果:true 更新成功，false 更新失败
     */
    @Override
    public boolean update(TargetDetectionBo targetDetectionBo) {
        TargetDetection targetDetection = MapstructUtils.convert(targetDetectionBo, TargetDetection.class);
        if (ObjectUtil.isNotNull(targetDetection) && ObjectUtil.isNotNull(targetDetection.getId())) {
            boolean updated = this.updateById(targetDetection);
            return updated;
        }
        return false;
    }

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

    @Override
    public CommonResult start(Long id) {
        TargetDetection targetDetection = getById(id);

        SysOssVo inputOssEntity = ossService.getById(targetDetection.getInputOssId());

        String filePath = inputOssEntity.getFileName();
        String localPath = TaaisConfig.getProfile();
        String resourcePath = localPath + StringUtils.substringAfter(filePath, Constants.RESOURCE_PREFIX);

        String fileName = StringUtils.substringAfterLast(filePath, "/");
        String fileName_without_suffix = removeFileExtension(fileName);

        Path path = Paths.get(resourcePath);
        Path inputPath = path.resolveSibling(fileName_without_suffix + "_images");
        Path outputPath = path.resolveSibling(fileName_without_suffix + "_to_infrared");

        makeDir(inputPath.toString());
        makeDir(outputPath.toString());

        ZipUtils.unzip(resourcePath, inputPath.toString());

        targetDetection.setInputPath(inputPath.toString());
        targetDetection.setOutputPath(outputPath.toString());

        targetDetection.setStartTime(new Date());

        AlgorithmModelTrack algorithmModelTrack = algorithmModelTrackService.getById(targetDetection.getAlgorithmModelId());
        AlgorithmConfigTrack algorithmConfigTrack = algorithmConfigTrackService.getById(algorithmModelTrack.getAlgorithmId());

        StartToInfraredTask startToInfraredTask = new StartToInfraredTask();
        startToInfraredTask.setBizId(targetDetection.getId());

        // if (algorithmConfigTrack.getType() == AlgorithmType.TRAIN) {
        startToInfraredTask.setModel_path(algorithmModelTrack.getModelAddress());
        // }

        startToInfraredTask.setOtherParams(algorithmConfigTrack.getParameterConfig());
        startToInfraredTask.setSource_dir(targetDetection.getInputPath());
        startToInfraredTask.setResult_dir(targetDetection.getOutputPath());

        startToInfraredTask.setBizType(BizConstant.BizType.TARGET_DETECTION);

        HttpResponseEntity responseEntity = sendPostMsg(algorithmConfigTrack.getAlgorithmAddress(), startToInfraredTask);
        if (ObjectUtil.isNotNull(responseEntity) && responseEntity.getStatus() == 200) {
            targetDetection.setStatus(BizConstant.VideoStatus.RUNNING);
            updateById(targetDetection);
            return CommonResult.success("任务开始成功，请等待完成");
        } else {
            targetDetection.setStatus(BizConstant.VideoStatus.FAILED);
            updateById(targetDetection);
            return CommonResult.fail("任务开始失败，请检查！");
        }
    }

    @Override
    public CommonResult stop(Long id) {
        TargetDetection targetDetection = getById(id);

        HttpResponseEntity responseEntity = sendPostMsg(target_detection_stop_url, targetDetection);
        if (ObjectUtil.isNotNull(responseEntity) && responseEntity.getStatus() == 200) {
            targetDetection.setStatus(BizConstant.VideoStatus.INTERRUPTED);
            updateById(targetDetection);
            return CommonResult.fail("终止任务成功");
        } else {
            return CommonResult.fail("终止任务失败");
        }
    }

    @Override
    public CommonResult getResult(TaskTrackResultBo taskTrackResultBo) {
        Long id = taskTrackResultBo.getId();
        String status = taskTrackResultBo.getStatus();
        String msg = taskTrackResultBo.getMsg();
        TargetDetection entity = getById(id);
        entity.setLog(msg);
        entity.setStatus("200".equals(status) ? BizConstant.VideoStatus.END : BizConstant.VideoStatus.FAILED);
        entity.setEndTime(new Date());
        try {
            entity.setCostSecond((entity.getEndTime().getTime() - entity.getStartTime().getTime()) / 1000);
        } catch (Exception e) {
            entity.setCostSecond(null);
        }
        updateById(entity);
        return CommonResult.success();
    }
}
