package com.xinelu.manage.service.info.impl;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.xinelu.common.config.SystemBusinessConfig;
import com.xinelu.common.constant.Constants;
import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.SecurityUtils;
import com.xinelu.common.utils.codes.GenerateSystemCodeUtil;
import com.xinelu.common.utils.file.FileUploadUtils;
import com.xinelu.common.utils.file.FileUtils;
import io.netty.util.internal.ObjectUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xinelu.manage.mapper.info.InfoMapper;
import com.xinelu.manage.domain.info.Info;
import com.xinelu.manage.service.info.IInfoService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 资讯信息Service业务层处理
 *
 * @author xinelu
 * @date 2024-04-11
 */
@Service
public class InfoServiceImpl implements IInfoService {
    @Resource
    private InfoMapper infoMapper;
    @Resource
    private GenerateSystemCodeUtil generateSystemCodeUtil;
    @Resource
    private SystemBusinessConfig systemBusinessConfig;

    /**
     * 查询资讯信息
     *
     * @param id 资讯信息主键
     * @return 资讯信息
     */
    @Override
    public Info selectInfoById(Long id) {
        return infoMapper.selectInfoById(id);
    }

    /**
     * 查询资讯信息列表
     *
     * @param info 资讯信息
     * @return 资讯信息
     */
    @Override
    public List<Info> selectInfoList(Info info) {
        return infoMapper.selectInfoList(info);
    }

    /**
     * 新增资讯信息
     *
     * @param info 资讯信息
     * @return 结果
     */
    @Override
    public int insertInfo(Info info) {
        info.setInfoCreateTime(LocalDateTime.now());
        info.setInfoCreator(SecurityUtils.getUsername());
        info.setInfoCode(Constants.INFO_CODE + generateSystemCodeUtil.generateSystemCode(Constants.INFO_CODE));
        return infoMapper.insertInfo(info);
    }

    /**
     * 修改资讯信息
     *
     * @param info 资讯信息
     * @return 结果
     */
    @Override
    public AjaxResult updateInfo(Info info) {
        //根据id查询之前的数据
        Info infoByID = infoMapper.selectInfoById(info.getId());
        if (Objects.isNull(infoByID)) {
            return AjaxResult.error("当前资讯信息不存在，无法修改，请联系管理员！");
        }
        //添加修改人 修改时间
        info.setInfoReviser(SecurityUtils.getUsername());
        info.setInfoModifyTime(LocalDateTime.now());
        int count = infoMapper.updateInfo(info);
        if (count <= 0) {
            throw new ServiceException("修改资讯信息失败，请联系管理员！");
        }
        //如果两个图片不相等，删除之前的图片
        if (!info.getInfoLargePictureUrl().equals(infoByID.getInfoLargePictureUrl())) {
            deletePictureUrl(infoByID.getInfoLargePictureUrl());
        }
        //遍历修改前后内容相不相等，如果不为空且不相等，寻找遍历前后图片的差集，然后删除.
        if (StringUtils.isNotBlank(info.getInfoContent()) && StringUtils.isNotBlank(infoByID.getInfoContent())
                && !info.getInfoContent().equals(infoByID.getInfoContent())) {
            //获取图片地址
            List<String> infoImgSrc = FileUtils.getImgSrc(info.getInfoContent());
            List<String> infoByIDImgSrc = FileUtils.getImgSrc(infoByID.getInfoContent());

            //遍历删除图片
            List<String> subList = new ArrayList<>(CollectionUtils.subtract(infoImgSrc, infoByIDImgSrc));
            for (String picUrl : subList) {
                if (StringUtils.isBlank(picUrl)) {       //删除富文本图片
                    continue;
                }
                //修改路径
                String substring = picUrl.substring(picUrl.indexOf("/profile"));
                //删除富文本图片
                deletePictureUrl(substring);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 批量删除资讯信息
     *
     * @param ids 需要删除的资讯信息主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteInfoByIds(Long[] ids) {
        //查询删除之前数据
        List<Info> infoList = infoMapper.selectInfoByIds(ids);
        //删除表信息
        int count = infoMapper.deleteInfoByIds(ids);
        if (count <= 0) {
            return AjaxResult.error("删除资讯信息失败!");
        }

        //筛选资讯主缩略图
        List<String> largePicUrlList = infoList.stream().filter(Objects::nonNull).map(Info::getInfoLargePictureUrl).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        //删除主图
        for (String picUrl : largePicUrlList) {
            String substring = picUrl.substring(picUrl.indexOf("/profile"));
            //删除富文本图片
            deletePictureUrl(substring);
        }

        //筛选资讯内容
        List<String> infoContentList = infoList.stream().filter(Objects::nonNull).map(Info::getInfoLargePictureUrl).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        //遍历获取富文本内容图片地址
        for (String infoContent : infoContentList) {
            List<String> picUrlList = FileUtils.getImgSrc(infoContent);
            for (String picUrl : picUrlList) {
                if (StringUtils.isBlank(picUrl)) {
                    continue;
                }
                //修改路径
                String substring = picUrl.substring(picUrl.indexOf("/profile"));
                //删除富文本图片
                deletePictureUrl(substring);
            }
        }

        return AjaxResult.success();
    }

    /**
     * 删除资讯信息信息
     *
     * @param id 资讯信息主键
     * @return 结果
     */
    @Override
    public int deleteInfoById(Long id) {
        return infoMapper.deleteInfoById(id);
    }

    /**
     * 图片文件上传
     *
     * @param file
     * @return
     */
    public AjaxResult picUpload(MultipartFile file) {
        try {
            return AjaxResult.success(FileUploadUtils.upload(
                    systemBusinessConfig.getProfile() + systemBusinessConfig.getInfoRichTextPictureUrl(), file));
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 删除资讯站图片地址
     *
     * @param pictureUrl 资讯站图片地址
     * @return void 资讯站图片地址
     **/
    private void deletePictureUrl(String pictureUrl) {
        if (StringUtils.isBlank(pictureUrl)) {
            return;
        }
        String picture = SystemBusinessConfig.getProfile() + systemBusinessConfig.getInfoRichTextPictureUrl() + pictureUrl.replaceAll("/profile", "");
        File checkReportNameFile = new File(picture);
        if (checkReportNameFile.exists()) {
            boolean delete = checkReportNameFile.delete();
            if (BooleanUtils.isFalse(delete)) {
                throw new ServiceException("图片地址删除失败！");
            }
        }
    }

}
