package com.ruoyi.project.business.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.enums.FileBuzType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.business.domain.TbFile;
import com.ruoyi.project.business.domain.vo.quotation.DescFileVO;
import com.ruoyi.project.business.enums.DelFlagEnum;
import com.ruoyi.project.business.mapper.TbFileMapper;
import com.ruoyi.project.business.service.ITbFileService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * 附件Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-19
 */
@Service
public class TbFileServiceImpl extends ServiceImpl<TbFileMapper, TbFile> implements ITbFileService {

    @Resource
    private TbFileMapper tbFileMapper;

    /**
     * 查询附件
     *
     * @param id 附件主键
     * @return 附件
     */
    @Override
    public TbFile selectTbFileById(Long id) {
        return tbFileMapper.selectTbFileById(id);
    }

    /**
     * 查询附件列表
     *
     * @param tbFile 附件
     * @return 附件
     */
    @Override
    public List<TbFile> selectTbFileList(TbFile tbFile) {
        return tbFileMapper.selectTbFileList(tbFile);
    }

    /**
     * 新增附件
     *
     * @param tbFile 附件
     * @return 结果
     */
    @Override
    public int insertTbFile(TbFile tbFile) {
        tbFile.setCreateTime(DateUtils.getNowDate());
        return tbFileMapper.insertTbFile(tbFile);
    }

    /**
     * 修改附件
     *
     * @param tbFile 附件
     * @return 结果
     */
    @Override
    public int updateTbFile(TbFile tbFile) {
        tbFile.setUpdateTime(DateUtils.getNowDate());
        return tbFileMapper.updateTbFile(tbFile);
    }

    /**
     * 批量删除附件
     *
     * @param ids 需要删除的附件主键
     * @return 结果
     */
    @Override
    public int deleteTbFileByIds(Long[] ids) {
        return tbFileMapper.deleteTbFileByIds(ids);
    }

    /**
     * 删除附件信息
     *
     * @param id 附件主键
     * @return 结果
     */
    @Override
    public int deleteTbFileById(Long id) {
        return tbFileMapper.deleteTbFileById(id);
    }

    @Override
    public List<TbFile> selectTbFileListByBuzIdAndBuzType(Long leadId, String type) {
        return tbFileMapper.selectTbFileListByBuzIdAndBuzType(leadId, type);
    }

    @Override
    public Map<Long, List<DescFileVO>> getDescFileVOMap(List<Long> nonStandardDescIdList) {
        Map<Long, List<DescFileVO>> descFileMap = new HashMap<>();
        if (CollUtil.isNotEmpty(nonStandardDescIdList)) {
            List<TbFile> list = this.list(Wrappers.<TbFile>lambdaQuery()
                .eq(TbFile::getBusinessType, FileBuzType.NON_STANDARD_DESC.getType())
                .eq(TbFile::getDelFlag, DelFlagEnum.NORMAL.getValue())
                .in(TbFile::getBusinessId, nonStandardDescIdList));
            descFileMap = list.stream().map(item -> {
                DescFileVO descFileVO = new DescFileVO();
                descFileVO.setNonStandardDescId(item.getBusinessId());
                descFileVO.setFilePath(item.getFilePath());
                descFileVO.setName(item.getRealFileName());
                descFileVO.setRealFileName(item.getRealFileName());
                descFileVO.setServerFileName(item.getServerFileName());
                descFileVO.setShowFlag(true);
                return descFileVO;
            }).collect(Collectors.groupingBy(DescFileVO::getNonStandardDescId));
        }
        return descFileMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateFile(String annex, Long buzId, String type) {
        Assert.notNull(buzId, "业务ID不能为空");
        Assert.isTrue(StringUtils.isNotBlank(type), "业务类型不能为空");
        // TODO MD5判断是否有变更
        // 删除附件
        this.remove(Wrappers.<TbFile>lambdaQuery()
            .eq(TbFile::getBusinessId, buzId)
            .eq(TbFile::getBusinessType, type));
        
        // 保存附件
        if (StringUtils.isNotBlank(annex)) {
            List<TbFile> files = new ArrayList<>();
            for (String fileUrl : annex.split(",")) {
                // 获取文件名：
                // 处理空格
                fileUrl = fileUrl.replaceAll(" ", "%20");
                // 解析URL
                String path = URLUtil.getPath(fileUrl);
                // 从路径中获取文件名
                String fileName = FileUtil.getName(path);
                TbFile tbFile = new TbFile(buzId, type, fileName, fileName, fileUrl);
                files.add(tbFile);
            }
            return this.saveBatch(files);
        }
        return true;
    }
}
