package com.ruoyi.common.service.impl;

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.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.bo.AnnexQueryBo;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.domain.Annex;
import com.ruoyi.common.domain.dto.AnnexDTO;
import com.ruoyi.common.mapper.AnnexMapper;
import com.ruoyi.common.service.IAnnexService;
import com.ruoyi.common.tool.FileDeletionService;
import com.ruoyi.common.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 附件Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-14
 */
@Service
public class AnnexServiceImpl extends ServicePlusImpl<AnnexMapper, Annex> implements IAnnexService {

	@Autowired
	private FileDeletionService fileDeletionService;

    @Override
    public Annex queryById(String id){
        return getById(id);
    }

    @Override
    public TableDataInfo<Annex> queryPageList(AnnexQueryBo bo) {
        Page<Annex> result = page(PageUtils.buildPage(), buildQueryWrapper(bo));
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<Annex> queryList(AnnexQueryBo bo) {
        return list(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<Annex> buildQueryWrapper(AnnexQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Annex> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, Annex::getUserId, bo.getUserId());
        lqw.eq(StrUtil.isNotBlank(bo.getAnnexType()), Annex::getAnnexType, bo.getAnnexType());
        lqw.like(StrUtil.isNotBlank(bo.getAnnexName()), Annex::getAnnexName, bo.getAnnexName());
        lqw.eq(StrUtil.isNotBlank(bo.getAnnexUrl()), Annex::getAnnexUrl, bo.getAnnexUrl());
        return lqw;
    }

    @Override
    public Boolean insert(Annex bo) {
        Annex add = BeanUtil.toBean(bo, Annex.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean update(Annex bo) {
        Annex update = BeanUtil.toBean(bo, Annex.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Annex entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

	@Override
	public void deleteByTypes(List<String> types) {
		baseMapper.delete(new LambdaQueryWrapper<Annex>().in(Annex::getAnnexType, types));
	}

	@Override
	public void insertBatch(List<AnnexDTO> annexList) {
		List<Annex> annexes = annexList.stream()
			.map(dto -> {
				Annex annex = new Annex();
				BeanUtil.copyProperties(dto, annex);
				return annex;
			})
			.collect(Collectors.toList());
		if(CollectionUtil.isNotEmpty(annexes)){
			super.saveAll(annexes);
		}
	}

	@Override
	@Transactional
	public Boolean deleteByIds(Long id) {
		//1、查询数据
		Annex annex = baseMapper.selectById(id);
		//2、删除对应的数据，并删除相对应的资源
		if (baseMapper.deleteById(id)>0){
			boolean b = fileDeletionService.deleteFileByPath(annex.getAnnexUrl());
			if(!b){
				throw new RuntimeException("附件删除失败！");
			}
		}else{
			throw new RuntimeException("数据删除失败！");
		}
		return true;
	}
}
