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

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.FileUtils;
import com.xinelu.manage.domain.information.Information;
import com.xinelu.manage.mapper.information.InformationMapper;
import com.xinelu.manage.service.information.IInformationService;
import com.xinelu.manage.service.nursestationitem.INurseStationItemService;
import com.xinelu.manage.service.patientinfo.IPatientInfoService;
import com.xinelu.manage.vo.information.InformationVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 资讯信息管理Service业务层处理
 *
 * @author xinyilu
 * @date 2023-02-14
 */
@Service
public class InformationServiceImpl implements IInformationService {
    @Resource
    private InformationMapper informationMapper;
    @Resource
    private GenerateSystemCodeUtil generateSystemCodeUtil;
    @Resource
    private INurseStationItemService nurseStationItemService;
    @Resource
    private IPatientInfoService patientInfoService;

    /**
     * 查询资讯信息管理
     *
     * @param id 资讯信息管理主键
     * @return 资讯信息管理
     */
    @Override
    public Information selectInformationById(Long id) {
        return informationMapper.getInformationById(id);
    }

    /**
     * 查询资讯信息管理列表
     *
     * @param information 资讯信息管理
     * @return 资讯信息管理
     */
    @Override
    public List<InformationVO> selectInformationList(Information information) {
        return informationMapper.selectInformationVoList(information);
    }

    /**
     * 新增资讯信息管理
     *
     * @param information 资讯信息管理
     * @return 结果
     */
    @Override
    public int insertInformation(Information information) {
        information.setCreateTime(LocalDateTime.now());
        information.setCreateBy(SecurityUtils.getUsername());
        information.setInformationCode(Constants.INFORMATION_CODE + generateSystemCodeUtil.generateSystemCode(Constants.INFORMATION_CODE));
        return informationMapper.insertInformation(information);
    }

    /**
     * 修改资讯信息管理
     *
     * @param information 资讯信息管理
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateInformation(Information information) {
        //根据id查询原数据库信息
        Information existInformation = informationMapper.selectInformationById(information.getId());
        if (Objects.isNull(existInformation)) {
            return AjaxResult.error("当前资讯信息不存在，无法修改，请联系管理员！");
        }
        //添加修改人，修改时间
        information.setUpdateTime(LocalDateTime.now());
        information.setUpdateBy(SecurityUtils.getUsername());
        //修改
        int count = informationMapper.updateInformation(information);
        if (count <= 0) {
            throw new ServiceException("修改资讯信息失败，请联系管理员！");
        }
        //删除缩略图
        if (!information.getLeadThumbnailUrl().equals(existInformation.getLeadThumbnailUrl())) {
            nurseStationItemService.deletePictureUrl(existInformation.getLeadThumbnailUrl());
        }
        if (StringUtils.isNotBlank(information.getInformationContent())
                && StringUtils.isNotBlank(existInformation.getInformationContent())
                && !information.getInformationContent().equals(existInformation.getInformationContent())) {
            List<String> informationImgSrc = FileUtils.getImgSrc(information.getInformationContent());
            List<String> getInformationImgSrc = FileUtils.getImgSrc(existInformation.getInformationContent());
            //差集不同的
            List<String> subtractNurseStationImgSrc = new ArrayList<>(CollectionUtils.subtract(getInformationImgSrc, informationImgSrc));
            //删除富文本图片
            for (String pictureUrl : subtractNurseStationImgSrc) {
                if (StringUtils.isBlank(pictureUrl)) {
                    continue;
                }
                //修改路径
                String substring = pictureUrl.substring(pictureUrl.indexOf("/profile"));
                //删除富文本图片
                nurseStationItemService.deletePictureUrl(substring);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 批量删除资讯信息管理
     *
     * @param ids 需要删除的资讯信息管理主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult deleteInformationByIds(Long[] ids) {
        //查询删除之前数据
        List<Information> informationList = informationMapper.selectInformationByIds(ids);
        //删除表信息
        int count = informationMapper.deleteInformationByIds(ids);
        if (count <= 0) {
            return AjaxResult.error("删除资讯信息失败!");
        }
        //筛选资讯主缩略图
        List<String> leadThumbnailUrlList = informationList.stream().filter(Objects::nonNull).map(Information::getLeadThumbnailUrl).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        //删除图片
        patientInfoService.updatePicture(leadThumbnailUrlList);
        //筛选资讯内容
        List<String> informationContentList = informationList.stream().filter(Objects::nonNull).map(Information::getInformationContent).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        //遍历获取内容图片地址
        for (String informationContent : informationContentList) {
            List<String> pictureUrlList = FileUtils.getImgSrc(informationContent);
            for (String pictureUrl : pictureUrlList) {
                if (StringUtils.isBlank(pictureUrl)) {
                    continue;
                }
                //修改路径
                String substring = pictureUrl.substring(pictureUrl.indexOf("/profile"));
                //删除富文本图片
                nurseStationItemService.deletePictureUrl(substring);
            }
        }
        return AjaxResult.success();
    }

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