package com.shzg.project.worn.service.impl;

import java.io.File;
import java.util.*;

import com.shzg.common.utils.DateUtils;
import com.shzg.common.utils.StringUtils;
import com.shzg.project.worn.domain.FileUploadConfig;
import com.shzg.project.worn.domain.dto.FileUrlDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.shzg.project.worn.mapper.WornTechnicalAppraisalFileMapper;
import com.shzg.project.worn.domain.WornTechnicalAppraisalFile;
import com.shzg.project.worn.service.IWornTechnicalAppraisalFileService;
import com.shzg.common.exception.ServiceException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;

/**
 * 技术鉴定附件Service业务层处理
 * 
 * @author shzg
 * @date 2026-04-10
 */
@Service
public class WornTechnicalAppraisalFileServiceImpl implements IWornTechnicalAppraisalFileService 
{
    @Autowired
    private WornTechnicalAppraisalFileMapper wornTechnicalAppraisalFileMapper;

    @Autowired
    private FileUploadConfig fileUploadConfig;
    /**
     * 查询技术鉴定附件
     * 
     * @param id 技术鉴定附件主键
     * @return 技术鉴定附件
     */
    @Override
    public WornTechnicalAppraisalFile selectWornTechnicalAppraisalFileById(Long id)
    {
        return wornTechnicalAppraisalFileMapper.selectWornTechnicalAppraisalFileById(id);
    }

    /**
     * 查询技术鉴定附件列表
     * 
     * @param wornTechnicalAppraisalFile 技术鉴定附件
     * @return 技术鉴定附件
     */
    @Override
    public List<WornTechnicalAppraisalFile> selectWornTechnicalAppraisalFileList(WornTechnicalAppraisalFile wornTechnicalAppraisalFile)
    {
        return wornTechnicalAppraisalFileMapper.selectWornTechnicalAppraisalFileList(wornTechnicalAppraisalFile);
    }

    /**
     * 新增技术鉴定附件
     * 
     * @param wornTechnicalAppraisalFile 技术鉴定附件
     * @return 结果
     */
    @Override
    public int insertWornTechnicalAppraisalFile(WornTechnicalAppraisalFile wornTechnicalAppraisalFile)
    {
        wornTechnicalAppraisalFile.setCreateTime(DateUtils.getNowDate());
        return wornTechnicalAppraisalFileMapper.insertWornTechnicalAppraisalFile(wornTechnicalAppraisalFile);
    }

    /**
     * 修改技术鉴定附件
     * 
     * @param wornTechnicalAppraisalFile 技术鉴定附件
     * @return 结果
     */
    @Override
    public int updateWornTechnicalAppraisalFile(WornTechnicalAppraisalFile wornTechnicalAppraisalFile)
    {
        return wornTechnicalAppraisalFileMapper.updateWornTechnicalAppraisalFile(wornTechnicalAppraisalFile);
    }

    /**
     * 批量删除技术鉴定附件
     * 
     * @param ids 需要删除的技术鉴定附件主键
     * @return 结果
     */
    @Override
    public int deleteWornTechnicalAppraisalFileByIds(Long[] ids)
    {
        return wornTechnicalAppraisalFileMapper.deleteWornTechnicalAppraisalFileByIds(ids);
    }

    /**
     * 删除技术鉴定附件信息
     * 
     * @param id 技术鉴定附件主键
     * @return 结果
     */
    @Override
    public int deleteWornTechnicalAppraisalFileById(Long id)
    {
        return wornTechnicalAppraisalFileMapper.deleteWornTechnicalAppraisalFileById(id);
    }
    private static final Logger log = LoggerFactory.getLogger(WornTechnicalAppraisalFileServiceImpl.class);

    /**
     * 上传技术鉴定附件存放子目录
     * 最终物理路径：profile + /technical_appraisal/yyyy/MM/dd/
     * 最终访问路径：/profile/technical_appraisal/yyyy/MM/dd/xxx.jpg
     */
    private static final String BASE_PATH = "/technical_appraisal/";



    @Override
    public List<FileUrlDTO> uploadBatch(MultipartFile[] files, String scene, String bizType, HttpServletRequest request)
    {
        if (files == null || files.length == 0)
        {
            throw new ServiceException("上传文件不能为空");
        }
        if (StringUtils.isBlank(scene) || StringUtils.isBlank(bizType))
        {
            throw new ServiceException("scene 和 bizType 不能为空");
        }

        scene = scene.trim().toLowerCase(Locale.ROOT);
        bizType = bizType.trim().toLowerCase(Locale.ROOT);

        String dateFolder = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        String uploadPath = fileUploadConfig.getUploadPath();

        File dir = new File(uploadPath + "/" + scene + "/" + bizType + "/" + dateFolder);
        if (!dir.exists())
        {
            dir.mkdirs();
        }

        List<FileUrlDTO> result = new ArrayList<>();

        try
        {
            log.info("进入批量上传接口，scene={}, bizType={}, fileCount={}", scene, bizType, files.length);

            for (MultipartFile file : files)
            {
                if (file == null || file.isEmpty())
                {
                    continue;
                }

                log.info("========== 上传文件信息 ==========");
                log.info("originalFilename = {}", file.getOriginalFilename());
                log.info("contentType     = {}", file.getContentType());
                log.info("size(bytes)     = {}", file.getSize());
                log.info("=================================");

                String contentType = file.getContentType();
                if (contentType == null || !contentType.startsWith("image/"))
                {
                    throw new ServiceException("上传失败：只允许上传图片文件");
                }

                String original = file.getOriginalFilename();
                String ext = "";

                if (original != null && original.contains("."))
                {
                    ext = original.substring(original.lastIndexOf("."));
                }

                if (StringUtils.isBlank(ext))
                {
                    if ("image/jpeg".equals(contentType))
                    {
                        ext = ".jpg";
                    }
                    else if ("image/png".equals(contentType))
                    {
                        ext = ".png";
                    }
                    else if ("image/gif".equals(contentType))
                    {
                        ext = ".gif";
                    }
                    else if ("image/webp".equals(contentType))
                    {
                        ext = ".webp";
                    }
                    else
                    {
                        throw new ServiceException("无法识别图片类型");
                    }
                }

                String newName = UUID.randomUUID().toString().replace("-", "") + ext;

                File targetFile = new File(dir, newName);
                file.transferTo(targetFile);

                String baseUrl = ServletUriComponentsBuilder.fromRequestUri(request)
                        .replacePath(null)
                        .build()
                        .toUriString();

                String url = baseUrl + "/profile/" + scene + "/" + bizType + "/" + dateFolder + "/" + newName;

                FileUrlDTO dto = new FileUrlDTO();
                dto.setName(newName);
                dto.setUrl(url);
                result.add(dto);
            }

            log.info("批量上传成功，result={}", result);
            return result;
        }
        catch (Exception e)
        {
            log.error("批量上传失败", e);
            throw new ServiceException("文件上传失败：" + e.getMessage());
        }
    }
}
