package com.corewing.app.service.impl;

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 com.corewing.app.common.page.PageContext;
import com.corewing.app.entity.Firmware;
import com.corewing.app.mapper.FirmwareMapper;
import com.corewing.app.service.FirmwareService;
import com.corewing.app.util.OSSUploadUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 固件 Service 实现类
 */
@Service
public class FirmwareServiceImpl extends ServiceImpl<FirmwareMapper, Firmware> implements FirmwareService {

    @Override
    public Page<Firmware> page(Firmware firmware) {
        Page<Firmware> page = PageContext.getDefaultPage(Firmware.class);
        LambdaQueryWrapper<Firmware> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(firmware.getFirmwareName()), Firmware::getFirmwareName, firmware.getFirmwareName());
        queryWrapper.eq(firmware.getFirmwareType() != null, Firmware::getFirmwareType, firmware.getFirmwareType());
        return page(page, queryWrapper);
    }

    @Override
    public Firmware getByFirmwareName(String firmwareName) {
        LambdaQueryWrapper<Firmware> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Firmware::getFirmwareName, firmwareName);
        return this.getOne(wrapper);
    }

    @Override
    public boolean uploadFile(MultipartFile file, Long id) {
        try {
            String downloadUrl = OSSUploadUtil.uploadFile(file.getInputStream(), file.getOriginalFilename());
            Firmware firmware = getById(id);
            firmware.setFirmwareSize(file.getSize());
            firmware.setDownloadUrl(downloadUrl);
            return updateById(firmware);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeData(Long id) {
        Firmware firmware = getById(id);
        if(firmware != null ){
            if(firmware.getDownloadUrl() != null) {
                OSSUploadUtil.deleteFile(getUrlLastSegment(firmware.getDownloadUrl()));
            }
            return removeById(id);
        }
        return false;
    }

    /**
     * 获取 URL 路径的最后一节（忽略查询参数 ? 和锚点 #）
     * @param urlStr URL字符串
     * @return 最后一节（如文件名、资源ID），异常/无路径时返回空字符串
     */
    public static String getUrlLastSegment(String urlStr) {
        // 1. 空值判断
        if (urlStr == null || urlStr.trim().isEmpty()) {
            return "";
        }

        // 2. 移除查询参数（? 及后面的内容）
        int queryIndex = urlStr.indexOf('?');
        if (queryIndex != -1) {
            urlStr = urlStr.substring(0, queryIndex);
        }

        // 3. 移除锚点（# 及后面的内容）
        int anchorIndex = urlStr.indexOf('#');
        if (anchorIndex != -1) {
            urlStr = urlStr.substring(0, anchorIndex);
        }

        // 4. 找到最后一个 "/" 的位置
        int lastSlashIndex = urlStr.lastIndexOf('/');

        // 5. 处理特殊情况：无 "/" 或 "/" 在末尾
        if (lastSlashIndex == -1) {
            // 无路径（如 "https://example.com" 或 "example.com"）
            return "";
        }
        if (lastSlashIndex == urlStr.length() - 1) {
            // 路径以 "/" 结尾（如 "https://example.com/folder/"），需找倒数第二个 "/"
            urlStr = urlStr.substring(0, lastSlashIndex);
            lastSlashIndex = urlStr.lastIndexOf('/');
            // 若倒数第二个 "/" 不存在（如 "https://example.com/"），返回空
            if (lastSlashIndex == -1) {
                return "";
            }
        }

        // 6. 截取最后一个 "/" 后面的内容
        return urlStr.substring(lastSlashIndex + 1);
    }

}
