package org.dromara.project.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.sse.dto.SseMessageDto;
import org.dromara.common.sse.utils.SseMessageUtils;
import org.dromara.constant.DesignMapFileConstant;
import org.dromara.project.domain.BusProject;
import org.dromara.project.domain.BusProjectFile;
import org.dromara.project.domain.dto.projectfile.BusProjectFileQueryReq;
import org.dromara.project.domain.dto.projectfile.BusProjectFileUpdateReq;
import org.dromara.project.domain.dto.projectfile.BusProjectFileUploadDxfReq;
import org.dromara.project.domain.vo.projectfile.BusProjectFileVo;
import org.dromara.project.mapper.BusProjectFileMapper;
import org.dromara.project.service.IBusProjectFileService;
import org.dromara.project.service.IBusProjectService;
import org.dromara.utils.Dxf2JsonUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 项目文件存储Service业务层处理
 *
 * @author lcj
 * @date 2025-04-23
 */
@Slf4j
@Service
public class BusProjectFileServiceImpl extends ServiceImpl<BusProjectFileMapper, BusProjectFile>
    implements IBusProjectFileService {

    @Resource
    private IBusProjectService projectService;

    @Resource
    private ScheduledExecutorService scheduledExecutorService;

    private static final ConcurrentHashMap<String, Boolean> USER_TASK_RUNNING = new ConcurrentHashMap<>();

    /**
     * 查询项目文件存储
     *
     * @param id 主键
     * @return 项目文件存储
     */
    @Override
    public BusProjectFileVo queryById(Long id) {
        BusProjectFile projectFile = this.getById(id);
        if (projectFile == null) {
            throw new ServiceException("对应项目文件存储信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(projectFile);
    }

    /**
     * 分页查询项目文件存储列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 项目文件存储分页列表
     */
    @Override
    public TableDataInfo<BusProjectFileVo> queryPageList(BusProjectFileQueryReq req, PageQuery pageQuery) {
        Page<BusProjectFile> projectFilePage = this.page(pageQuery.build(), this.buildQueryWrapper(req));
        return TableDataInfo.build(this.getVoPage(projectFilePage));
    }

    /**
     * 查询符合条件的项目文件存储列表
     *
     * @param req 查询条件
     * @return 项目文件存储列表
     */
    @Override
    public List<BusProjectFileVo> queryList(BusProjectFileQueryReq req) {
        LambdaQueryWrapper<BusProjectFile> lqw = this.buildQueryWrapper(req);
        return this.list(lqw).stream().map(this::getVo).toList();
    }

    /**
     * 修改项目文件存储
     *
     * @param req 项目文件存储
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BusProjectFileUpdateReq req) {
        // 将实体类和 DTO 进行转换
        BusProjectFile projectFile = new BusProjectFile();
        BeanUtils.copyProperties(req, projectFile);
        // 数据校验
        validEntityBeforeSave(projectFile);
        // 判断是否存在
        BusProjectFile oldProjectFile = this.getById(projectFile.getId());
        if (oldProjectFile == null) {
            throw new ServiceException("修改项目文件存储失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        boolean update = this.updateById(projectFile);
        if (!update) {
            throw new ServiceException("修改项目文件存储失败，数据库异常", HttpStatus.ERROR);
        }
        return true;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusProjectFile entity) {
        // TODO 做一些数据校验,如唯一约束
        Long projectId = entity.getProjectId();
        if (projectId == null) {
            throw new ServiceException("项目id不能为空", HttpStatus.BAD_REQUEST);
        }
        if (projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 校验并批量删除项目文件存储信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        Long userId = LoginHelper.getUserId();
        List<BusProjectFile> projectFileList = this.listByIds(ids);
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
            List<Long> projectId = projectFileList.stream().map(BusProjectFile::getProjectId).toList();
            projectService.validAuth(projectId, userId);
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 根据id获取JSON文件
     *
     * @param id 主键
     * @return JSON文件
     */
    @Override
    public JSONObject getJSONFile(Long id) {
        BusProjectFile projectFile = this.getById(id);
        if (projectFile == null) {
            throw new ServiceException("对应项目文件存储信息不存在", HttpStatus.NOT_FOUND);
        }
        Long userId = LoginHelper.getUserId();
        // 获取当前登录用户key值
        String string = String.valueOf(userId + projectFile.getProjectId());
        String md5 = MD5.create().digestHex16(string);
        // 判断当前用户是否已经有一个正在处理的任务
        Boolean alreadyRunning = USER_TASK_RUNNING.get(md5);
        if (alreadyRunning != null && alreadyRunning) {
            throw new ServiceException("正在转换，请稍后重试", HttpStatus.CONFLICT);
        }
        String filePath = projectFile.getFilePath();
        String suffix = FileUtil.getSuffix(FileUtil.getName(filePath));
        if (!suffix.equals(DesignMapFileConstant.JSONFileSuffix)) {
            throw new ServiceException("文件格式不正确，只能解析json文件", HttpStatus.BAD_REQUEST);
        }
        JSONObject jsonObject;
        try {
            String property = System.getProperty("user.dir");
            Path path = Paths.get(property, filePath);
            String jsonStr = Files.readString(path, StandardCharsets.UTF_8);
            jsonObject = JSONUtil.parseObj(jsonStr);
        } catch (IOException e) {
            throw new ServiceException("文件读取失败", HttpStatus.ERROR);
        }
        return jsonObject;
    }

    /**
     * 上传dxf文件并转换为json
     *
     * @param file 文件
     * @param req  请求
     * @return 是否上传文件成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean uploadDxf2Json(MultipartFile file, BusProjectFileUploadDxfReq req) {
        Long userId = LoginHelper.getUserId();
        // 获取当前登录用户key值
        String string = String.valueOf(userId + req.getProjectId());
        String md5 = MD5.create().digestHex16(string);
        // 判断当前用户是否已经有一个正在处理的任务
        Boolean alreadyRunning = USER_TASK_RUNNING.putIfAbsent(md5, true);
        if (alreadyRunning != null && alreadyRunning) {
            throw new ServiceException("当前有一个正在处理的转换任务，请等待完成后再上传", HttpStatus.CONFLICT);
        }
        // 校验文件是否为空
        if (file == null) {
            throw new ServiceException("dxf文件不能为空", HttpStatus.BAD_REQUEST);
        }
        // 校验是否为 dxf 文件
        String fileName = file.getOriginalFilename();
        String suffix = FileUtil.getSuffix(fileName);
        if (!Objects.equals(suffix, DesignMapFileConstant.DXFFileSuffix)) {
            throw new ServiceException("文件格式不正确，只能上传.dxf后缀的文件", HttpStatus.BAD_REQUEST);
        }
        // 校验项目是否存在
        Long projectId = req.getProjectId();
        BusProject project = projectService.getById(projectId);
        if (project == null) {
            throw new ServiceException("项目信息不存在", HttpStatus.NOT_FOUND);
        }
        // 获取当前项目根目录
        String projectRoot = System.getProperty("user.dir");
        String bashPath = DesignMapFileConstant.getDxfProjectPath(projectId);
        String filePath = projectRoot + File.separator + bashPath;
        String uuid = IdUtil.fastSimpleUUID();
        if (!FileUtil.exist(filePath)) {
            FileUtil.mkdir(filePath);
        }
        String inputDXFPath = filePath + File.separator + uuid + "." + suffix;
        try {
            // 保存文件
            File savedFile = new File(inputDXFPath);
            file.transferTo(savedFile);
        } catch (IOException e) {
            throw new ServiceException("dxf 文件保存失败");
        }
        // 构造 JSON 输出路径
        String outputJSONPath = filePath + File.separator + uuid + "." + DesignMapFileConstant.JSONFileSuffix;
        // 获取 dxf2json.exe 路径
        String exePath = projectRoot + File.separator + DesignMapFileConstant.DXF_BASE_PATH + File.separator + "main.exe";
        String sourceEPSG = DesignMapFileConstant.EPSG4524;
        String targetEPSG = DesignMapFileConstant.EPSG4326;
        BusProjectFile oldProjectFile = this.lambdaQuery()
            .eq(BusProjectFile::getProjectId, projectId)
            .one();
        Long projectFileId;
        String dxfFilePath = bashPath + File.separator + uuid + "." + suffix;
        if (oldProjectFile != null) {
            // 删除之前的文件
            try {
                FileUtil.del(projectRoot + File.separator + oldProjectFile.getFilePath());
                FileUtil.del(projectRoot + File.separator + oldProjectFile.getRemark());
            } catch (Exception e) {
                log.error("删除项目文件失败", e);
            }
            projectFileId = oldProjectFile.getId();
            BusProjectFile projectFile = new BusProjectFile();
            projectFile.setId(projectFileId);
            projectFile.setFileName(fileName);
            projectFile.setRemark(dxfFilePath);
            boolean result = this.updateById(projectFile);
            if (!result) {
                throw new ServiceException("数据库更新异常");
            }
        } else {
            projectFileId = null;
        }
        SseMessageDto messageDto = new SseMessageDto();
        messageDto.setMessage("DXF 文件上传成功，正在转换中......");
        messageDto.setUserIds(List.of(userId));
        SseMessageUtils.publishMessage(messageDto);
        scheduledExecutorService.execute(() -> {
            try {
                // 构造命令行参数
                Dxf2JsonUtils.dxf2json(exePath, inputDXFPath, outputJSONPath, sourceEPSG, targetEPSG);
                String jsonFilePath = bashPath + File.separator + uuid + "." + DesignMapFileConstant.JSONFileSuffix;
                String jsonFileName = FileUtil.getPrefix(fileName) + "." + DesignMapFileConstant.JSONFileSuffix;
                // 修改数据库信息
                BusProjectFile projectFile = new BusProjectFile();
                projectFile.setId(projectFileId);
                projectFile.setFilePath(jsonFilePath);
                projectFile.setFileName(jsonFileName);
                projectFile.setFileType(DesignMapFileConstant.JSONFileSuffix);
                projectFile.setProjectId(projectId);
                projectFile.setRemark(dxfFilePath);
                boolean update = this.saveOrUpdate(projectFile);
                if (!update) throw new ServiceException("数据库修改异常");
                messageDto.setMessage("DXF 文件转换成 GeoJSON 成功");
                SseMessageUtils.publishMessage(messageDto);
            } catch (Exception e) {
                log.error("DXF 转换失败", e);
                messageDto.setMessage("DXF 文件转换失败，请联系管理员处理");
                SseMessageUtils.publishMessage(messageDto);
            } finally {
                // 无论成功或失败都释放状态
                USER_TASK_RUNNING.remove(md5);
            }
        });
        return true;
    }

    /**
     * 获取项目文件存储视图对象
     *
     * @param projectFile 项目文件存储对象
     * @return 项目文件存储视图对象
     */
    @Override
    public BusProjectFileVo getVo(BusProjectFile projectFile) {
        // 对象转封装类
        BusProjectFileVo projectFileVo = new BusProjectFileVo();
        if (projectFile == null) {
            return projectFileVo;
        }
        BeanUtils.copyProperties(projectFile, projectFileVo);
        return projectFileVo;
    }

    /**
     * 获取项目文件存储查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusProjectFile> buildQueryWrapper(BusProjectFileQueryReq req) {
        LambdaQueryWrapper<BusProjectFile> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        Long projectId = req.getProjectId();
        String fileType = req.getFileType();
        String fileName = req.getFileName();
        lqw.like(StringUtils.isNotBlank(fileName), BusProjectFile::getFileName, fileName);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusProjectFile::getProjectId, projectId);
        lqw.eq(StringUtils.isNotBlank(fileType), BusProjectFile::getFileType, fileType);
        return lqw;
    }

    /**
     * 获取项目文件存储分页对象视图
     *
     * @param projectFilePage 项目文件存储分页对象
     * @return 项目文件存储分页对象视图
     */
    @Override
    public Page<BusProjectFileVo> getVoPage(Page<BusProjectFile> projectFilePage) {
        List<BusProjectFile> projectFileList = projectFilePage.getRecords();
        Page<BusProjectFileVo> projectFileVoPage = new Page<>(
            projectFilePage.getCurrent(),
            projectFilePage.getSize(),
            projectFilePage.getTotal());
        if (CollUtil.isEmpty(projectFileList)) {
            return projectFileVoPage;
        }
        List<BusProjectFileVo> projectFileVoList = projectFileList.stream().map(this::getVo).toList();
        projectFileVoPage.setRecords(projectFileVoList);
        return projectFileVoPage;
    }
}
