package top.continew.admin.business.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.x.file.storage.core.FileInfo;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.continew.admin.business.file.CommonMultipartFile;
import top.continew.admin.business.mapper.TaskRecordHistoryMapper;
import top.continew.admin.business.model.entity.TaskRecordHistoryDO;
import top.continew.admin.business.model.query.TaskRecordHistoryQuery;
import top.continew.admin.business.model.req.TaskRecordHistoryAddReq;
import top.continew.admin.business.model.req.TaskRecordHistoryEditReq;
import top.continew.admin.business.model.resp.TaskRecordHistoryResp;
import top.continew.admin.business.service.TaskRecordHistoryService;
import top.continew.admin.system.service.FileService;
import top.continew.admin.system.service.UserService;
import top.continew.starter.data.mp.util.QueryWrapperHelper;
import top.continew.starter.extension.crud.model.query.PageQuery;
import top.continew.starter.extension.crud.model.resp.PageResp;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * 音视图文生成记录业务实现
 *
 * @author jiay
 * @since 2025/05/23 07:51
 */
@Service
@RequiredArgsConstructor
public class TaskRecordHistoryServiceImpl extends ServiceImpl<TaskRecordHistoryMapper, TaskRecordHistoryDO> implements TaskRecordHistoryService {

    private final TaskRecordHistoryMapper taskRecordHistoryMapper;
    private final FileService fileService;
    private final UserService userService;

    @Override
    public List<TaskRecordHistoryResp> getTaskRecordHistoryList(TaskRecordHistoryQuery query) {
        QueryWrapper queryWrapper = QueryWrapperHelper.build(query);
        List list = this.list(queryWrapper);

        if (CollectionUtil.isNotEmpty(list)) {
            return BeanUtil.copyToList(list, TaskRecordHistoryResp.class);
        }
        return Collections.emptyList();
    }

    @Override
    public List<String> addTaskRecordHistory(TaskRecordHistoryAddReq req) {
        //先校验userId
        String userId = req.getUserId();
        if (!StpUtil.isLogin(userId) || StpUtil.getTokenValue() == null) {
            String tokenValue = StpUtil.getTokenValueByLoginId(userId);
            StpUtil.setTokenValue(tokenValue);
        }
        //先下载文件
        List<String> fileUrls = req.getFileUrl();
        List<String> res = new ArrayList<>();
        if (!fileUrls.isEmpty()) {
            fileUrls.forEach(fileUrl -> {
                if (StrUtil.isEmpty(fileUrl)) {
                    throw new RuntimeException("文件url地址为空");
                }
                FileInfo upload;
                try {
                    // 1. 构造URL格式
                    URL url = new URL(fileUrl);
                    // 2. 打开HTTP连接并配置参数
                    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                    connection.setRequestMethod("GET");
                    // 5秒连接超时
                    connection.setConnectTimeout(5000);
                    // 10秒读取超时
                    connection.setReadTimeout(10000);
                    // 设置User-Agent
                    connection.setRequestProperty("User-Agent", "Mozilla/5.0");
                    // 3. 检查HTTP响应状态码
                    int responseCode = connection.getResponseCode();
                    if (responseCode != HttpURLConnection.HTTP_OK) {
                        throw new IOException("HTTP请求失败，状态码: " + responseCode);
                    }
                    // 4. 获取输入流（注意：调用者需负责关闭此流）
                    InputStream inputStream = connection.getInputStream();
                    String fileName = extractFileName(fileUrl);
                    // 过滤非法字符
                    String safeFileName = sanitizeFileName(fileName);
                    String uniqueName = UUID.randomUUID() + "_" + safeFileName;
                    MultipartFile multipartFile = new CommonMultipartFile(uniqueName, safeFileName, MediaType.MULTIPART_FORM_DATA_VALUE, inputStream);
                    upload = fileService.upload(multipartFile);

                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("文件下载失败");
                }
                //插入记录到数据库
                TaskRecordHistoryDO entity = BeanUtil.copyProperties(req, TaskRecordHistoryDO.class);
                entity.setFileUrl(upload.getUrl());
                taskRecordHistoryMapper.insert(entity);
                res.add(upload.getUrl());
            });
        }
        return res;

    }

    /**
     * 从URL提取文件名（处理含参数的URL）
     */
    private static String extractFileName(String fileUrl) {
        try {
            URI uri = URI.create(fileUrl);
            String path = uri.getPath();
            if (path == null || path.isEmpty()) {
                return "unknown_" + System.currentTimeMillis();
            }

            // 提取最后一个斜杠后的内容
            String rawName = path.substring(path.lastIndexOf('/') + 1);

            // 去除URL参数（如?foo=bar）
            return rawName.contains("?") ? rawName.split("\\?")[0] : rawName;
        } catch (Exception e) {
            return "unknown_" + System.currentTimeMillis();
        }
    }

    // 过滤非法文件名字符（Windows/Linux兼容）
    private static String sanitizeFileName(String fileName) {
        // 替换非法字符为下划线
        return fileName.replaceAll("[\\\\/:*?\"<>|]", "_");
    }

    @Override
    public boolean editTaskRecordHistory(TaskRecordHistoryEditReq req) {
        TaskRecordHistoryDO taskRecordHistoryDO = BeanUtil.copyProperties(req, TaskRecordHistoryDO.class);
        return taskRecordHistoryMapper.updateById(taskRecordHistoryDO) > 0;

    }

    @Override
    public boolean deleteTaskRecordHistory(Long id) {
        if (id != null) {
            return taskRecordHistoryMapper.deleteById(id) > 0;
        }
        return false;
    }

    @Override
    public TaskRecordHistoryResp getTaskRecordHistory(Long id) {
        TaskRecordHistoryDO taskRecordHistoryDO = taskRecordHistoryMapper.selectById(id);
        TaskRecordHistoryResp taskRecordHistoryResp = new TaskRecordHistoryResp();
        if (taskRecordHistoryDO != null) {
            taskRecordHistoryResp = BeanUtil.copyProperties(taskRecordHistoryDO, TaskRecordHistoryResp.class);
        }
        return taskRecordHistoryResp;
    }

    @Override
    public PageResp<TaskRecordHistoryResp> getTaskRecordHistoryPage(TaskRecordHistoryQuery query, PageQuery pageQuery) {
        QueryWrapper queryWrapper = QueryWrapperHelper.build(query);
        Page page = taskRecordHistoryMapper.selectPage(new Page<>(pageQuery.getPage(), pageQuery
            .getSize()), queryWrapper);
        return PageResp.build(page);
    }

}