package com.ruoyi.file.service.impl;

import java.util.List;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.file.domain.UserFile;
import com.ruoyi.file.mapper.UserFileMapper;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Objects;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.file.domain.DownloadRecordItem;
import com.ruoyi.file.mapper.DownloadRecordMapper;
import com.ruoyi.file.domain.DownloadRecord;
import com.ruoyi.file.service.IDownloadRecordService;

import javax.servlet.http.HttpServletRequest;

/**
 * 下载记录Service业务层处理
 *
 * @author liangwen
 * @date 2025-09-12
 */
@Service
public class DownloadRecordServiceImpl implements IDownloadRecordService
{
    @Autowired
    private DownloadRecordMapper downloadRecordMapper;

    @Autowired
    private UserFileMapper userFileMapper;

    /**
     * 查询下载记录
     *
     * @param recordId 下载记录主键
     * @return 下载记录
     */
    @Override
    public DownloadRecord selectDownloadRecordByRecordId(Long recordId)
    {
        return downloadRecordMapper.selectDownloadRecordByRecordId(recordId);
    }

    /**
     * 查询下载记录列表
     *
     * @param downloadRecord 下载记录
     * @return 下载记录
     */
    @Override
    public List<DownloadRecord> selectDownloadRecordList(DownloadRecord downloadRecord)
    {
        return downloadRecordMapper.selectDownloadRecordList(downloadRecord);
    }

    /**
     * 新增下载记录
     *
     * @param downloadRecord 下载记录
     * @return 结果
     */
    @Transactional
    @Override
    public int insertDownloadRecord(DownloadRecord downloadRecord)
    {
        int rows = downloadRecordMapper.insertDownloadRecord(downloadRecord);
        insertDownloadRecordItem(downloadRecord);
        return rows;
    }

    /**
     * 修改下载记录
     *
     * @param downloadRecord 下载记录
     * @return 结果
     */
    @Transactional
    @Override
    public int updateDownloadRecord(DownloadRecord downloadRecord)
    {
        downloadRecordMapper.deleteDownloadRecordItemByRecordId(downloadRecord.getRecordId());
        insertDownloadRecordItem(downloadRecord);
        return downloadRecordMapper.updateDownloadRecord(downloadRecord);
    }

    /**
     * 批量删除下载记录
     *
     * @param recordIds 需要删除的下载记录主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDownloadRecordByRecordIds(Long[] recordIds)
    {
        downloadRecordMapper.deleteDownloadRecordItemByRecordIds(recordIds);
        return downloadRecordMapper.deleteDownloadRecordByRecordIds(recordIds);
    }

    /**
     * 删除下载记录信息
     *
     * @param recordId 下载记录主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDownloadRecordByRecordId(Long recordId)
    {
        downloadRecordMapper.deleteDownloadRecordItemByRecordId(recordId);
        return downloadRecordMapper.deleteDownloadRecordByRecordId(recordId);
    }

    @Override
    public void saveDownloadRecord(List<String> userFileIds) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        String address = AddressUtils.getRealAddressByIP(ip);
        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        DownloadRecord downloadRecord = new DownloadRecord();
        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        downloadRecord.setUserId(userId);
        downloadRecord.setIpaddr(ip);
        downloadRecord.setLocation(address);
        downloadRecord.setOs(os);
        downloadRecord.setBrowser(browser);
        downloadRecord.setDownloadTime(DateUtils.getNowDate());
        List<DownloadRecordItem> itemList = new ArrayList<>();
        List<UserFile> userFileList = userFileMapper.selectByUserFileIds(userFileIds);
        String fileNames = userFileList.stream()
                .filter(Objects::nonNull)
                .map(userFile -> {
                    String name = userFile.getFileName();
                    String ext = userFile.getExtendName();
                    if (ext != null && !ext.isEmpty()) {
                        return name + "." + ext;
                    } else {
                        return name;
                    }
                })
                .filter(Objects::nonNull)
                .collect(Collectors.joining(","));
        downloadRecord.setFileNames(fileNames);
        for (String userFileId : userFileIds) {
            DownloadRecordItem downloadRecordItem = new DownloadRecordItem();
            downloadRecordItem.setUserFileId(userFileId);
            itemList.add(downloadRecordItem);
        }
        downloadRecord.setDownloadRecordItemList(itemList);
        downloadRecordMapper.insertDownloadRecord(downloadRecord);
        insertDownloadRecordItem(downloadRecord);
    }

    /**
     * 新增下载记录明显信息
     *
     * @param downloadRecord 下载记录对象
     */
    public void insertDownloadRecordItem(DownloadRecord downloadRecord)
    {
        List<DownloadRecordItem> downloadRecordItemList = downloadRecord.getDownloadRecordItemList();
        Long recordId = downloadRecord.getRecordId();
        if (StringUtils.isNotNull(downloadRecordItemList))
        {
            List<DownloadRecordItem> list = new ArrayList<DownloadRecordItem>();
            for (DownloadRecordItem downloadRecordItem : downloadRecordItemList)
            {
                downloadRecordItem.setRecordId(recordId);
                list.add(downloadRecordItem);
            }
            if (list.size() > 0)
            {
                downloadRecordMapper.batchDownloadRecordItem(list);
            }
        }
    }
}
