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


import com.xinelu.common.config.XinELuConfig;
import com.xinelu.common.constant.Constants;
import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.core.domain.model.LoginUser;
import com.xinelu.common.enums.AppointmentTimeIntervalEnum;
import com.xinelu.common.enums.NurseStationItemShelfStatusEnum;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.SecurityUtils;
import com.xinelu.common.utils.bean.BeanUtils;
import com.xinelu.common.utils.codes.GenerateSystemCodeUtil;
import com.xinelu.common.utils.file.FileUtils;
import com.xinelu.manage.domain.nursestation.NurseStation;
import com.xinelu.manage.domain.nursestationItemconsumable.NurseStationItemConsumable;
import com.xinelu.manage.domain.nursestationitem.NurseStationItem;
import com.xinelu.manage.domain.nursestationitemprice.NurseStationItemPrice;
import com.xinelu.manage.dto.nursestationitem.NurseStationItemDTO;
import com.xinelu.manage.dto.nursestationitem.NurseStationItemImportDTO;
import com.xinelu.manage.mapper.nursestation.NurseStationMapper;
import com.xinelu.manage.mapper.nursestationItemconsumable.NurseStationItemConsumableMapper;
import com.xinelu.manage.mapper.nursestationitem.NurseStationItemMapper;
import com.xinelu.manage.mapper.nursestationitemprice.NurseStationItemPriceMapper;
import com.xinelu.manage.service.nursestationitem.INurseStationItemService;
import com.xinelu.manage.vo.nursestationitem.NurseStationItemImportVO;
import com.xinelu.manage.vo.nursestationitem.NurseStationItemInfoDetailsVO;
import com.xinelu.manage.vo.nursestationitem.NurseStationItemInfoVO;
import com.xinelu.manage.vo.nursestationitem.NurseStationItemVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.xinelu.common.utils.PageUtils.startPage;

/**
 * 护理站护理项目Service业务层处理
 *
 * @author ljh
 * @date 2022-09-02
 */
@Service
public class NurseStationItemServiceImpl implements INurseStationItemService {
    @Resource
    private NurseStationItemMapper nurseStationItemMapper;
    @Resource
    private NurseStationItemConsumableMapper nurseStationItemConsumableMapper;
    @Resource
    private NurseStationItemPriceMapper nurseStationItemPriceMapper;
    @Resource
    private GenerateSystemCodeUtil generateSystemCodeUtil;
    @Resource
    private NurseStationMapper nurseStationMapper;

    /**
     * 护理项目每个时间点的预约人数上限
     */
    private static final int APPOINTMENT_LIMIT_COUNT = 0;

    /**
     * 查询护理站护理项目
     *
     * @param id 护理站护理项目主键
     * @return 护理站护理项目
     */
    @Override
    public NurseStationItemInfoVO selectNurseStationItemById(Long id) {
        NurseStationItemInfoVO nurseStationItemInfo = new NurseStationItemInfoVO();
        NurseStationItemInfoDetailsVO nurseStationItem = nurseStationItemMapper.selectNurseStationItemInfoVO(id);
        if (Objects.isNull(nurseStationItem)) {
            return nurseStationItemInfo;
        }
        NurseStationItemVO nurseStationItemVO = new NurseStationItemVO();
        nurseStationItemVO.setId(Objects.isNull(nurseStationItem.getId()) ? null : nurseStationItem.getId());
        nurseStationItemVO.setNurseStationId(Objects.isNull(nurseStationItem.getNurseStationId()) ? null : nurseStationItem.getNurseStationId());
        nurseStationItemVO.setNurseItemName(StringUtils.isBlank(nurseStationItem.getNurseItemName()) ? "" : nurseStationItem.getNurseItemName());
        nurseStationItemVO.setNurseItemCode(StringUtils.isBlank(nurseStationItem.getNurseItemCode()) ? "" : nurseStationItem.getNurseItemCode());
        nurseStationItemVO.setNurseStationName(StringUtils.isBlank(nurseStationItem.getNurseStationName()) ? "" : nurseStationItem.getNurseStationName());
        nurseStationItemVO.setNurseItemContent(StringUtils.isBlank(nurseStationItem.getNurseItemContent()) ? "" : nurseStationItem.getNurseItemContent());
        nurseStationItemVO.setItemPictureUrl(StringUtils.isBlank(nurseStationItem.getItemPictureUrl()) ? "" : nurseStationItem.getItemPictureUrl());
        nurseStationItemVO.setAdvanceAppointDuration(StringUtils.isBlank(nurseStationItem.getAdvanceAppointDuration()) ? "" : nurseStationItem.getAdvanceAppointDuration());
        nurseStationItemVO.setSort(Objects.isNull(nurseStationItem.getSort()) ? null : nurseStationItem.getSort());
        nurseStationItemVO.setNurseClassifyId(Objects.isNull(nurseStationItem.getNurseClassifyId()) ? null : nurseStationItem.getNurseClassifyId());
        nurseStationItemVO.setClassifyName(StringUtils.isBlank(nurseStationItem.getClassifyName()) ? "" : nurseStationItem.getClassifyName());
        nurseStationItemVO.setAppointmentLimitCount(Objects.isNull(nurseStationItem.getAppointmentLimitCount()) ? null : nurseStationItem.getAppointmentLimitCount());
        nurseStationItemVO.setAppointmentTimeInterval(StringUtils.isBlank(nurseStationItem.getAppointmentTimeInterval()) ? "" : nurseStationItem.getAppointmentTimeInterval());
        nurseStationItemVO.setShelfStatus(StringUtils.isBlank(nurseStationItem.getShelfStatus()) ? "" : nurseStationItem.getShelfStatus());
        nurseStationItemInfo.setNurseStationItem(nurseStationItemVO);
        if (CollectionUtils.isNotEmpty(nurseStationItem.getNurseStationItemConsumables())) {
            nurseStationItemInfo.setNurseStationItemConsumables(nurseStationItem.getNurseStationItemConsumables());
        }
        if (CollectionUtils.isNotEmpty(nurseStationItem.getNurseStationItemPrices())) {
            nurseStationItemInfo.setNurseStationItemPrices(nurseStationItem.getNurseStationItemPrices());
        }
        return nurseStationItemInfo;
    }

    /**
     * 查询护理站护理项目列表
     *
     * @param nurseStationItem 护理站护理项目
     * @return 护理站护理项目
     */
    @Override
    public List<NurseStationItemVO> selectNurseStationItemList(NurseStationItem nurseStationItem) {
        //查询所有的项目进行
        startPage();
        List<NurseStationItemVO> nurseStationItemList = nurseStationItemMapper.selectNurseStationItemList(nurseStationItem);
        //获取护理站项目的id
        List<Long> idList = nurseStationItemList.stream().filter(Objects::nonNull).filter(item -> Objects.nonNull(item.getId())).map(NurseStationItemVO::getId).distinct().collect(Collectors.toList());
        //根据护理站项目的id去查找所有的项目价格表
        List<NurseStationItemPrice> nurseStationItemPriceByList = nurseStationItemPriceMapper.getNurseStationItemPriceByList(idList);
        if (CollectionUtils.isEmpty(nurseStationItemPriceByList)) {
            return nurseStationItemList;
        }
        Map<Long, List<NurseStationItemPrice>> nurseStationItemPriceMap = nurseStationItemPriceByList.stream().filter(Objects::nonNull).filter(item -> Objects.nonNull(item.getNurseStationItemId())).collect(Collectors.groupingBy(NurseStationItemPrice::getNurseStationItemId));
        nurseStationItemList.forEach(item -> item.setNurseStationItemPrices(nurseStationItemPriceMap.getOrDefault(Objects.isNull(item.getId()) ? 0L : item.getId(), Lists.newArrayList())));
        return nurseStationItemList;
    }

    /**
     * 新增护理站护理项目
     *
     * @param nurseStationItemDTO 护理站护理项目
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertNurseStationItem(NurseStationItemDTO nurseStationItemDTO) {
        //判断护理站项目价额是否为负数
        AjaxResult ajaxResult = judgePriceInfo(nurseStationItemDTO);
        if (Objects.nonNull(ajaxResult)) {
            return ajaxResult;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        LocalDateTime now = LocalDateTime.now();
        //护理站项目信息
        NurseStationItem nurseStationItem = nurseStationItemDTO.getNurseStationItem();
        //判断护理项目预约时间点间隔是否为空
        if (StringUtils.isBlank(nurseStationItem.getAppointmentTimeInterval())) {
            nurseStationItem.setAppointmentTimeInterval(AppointmentTimeIntervalEnum.HALF_HOUR.getValue());
        }
        //判断护理项目每个时间点的预约人数上限是否为0
        if (Objects.nonNull(nurseStationItem.getAppointmentLimitCount()) && nurseStationItem.getAppointmentLimitCount() == APPOINTMENT_LIMIT_COUNT) {
            return AjaxResult.error("预约人数上限应该大于零，请重新输入！");
        }
        nurseStationItem.setCreateTime(now);
        nurseStationItem.setCreateBy(loginUser.getUsername());
        nurseStationItem.setUserId(loginUser.getUserId());
        nurseStationItem.setShelfStatus(NurseStationItemShelfStatusEnum.NOT_SHELF.getInfo());
        nurseStationItem.setNurseItemCode(Constants.STATION_ITEM + generateSystemCodeUtil.generateSystemCode(Constants.STATION_ITEM));
        int stationItemCount = nurseStationItemMapper.insertNurseStationItem(nurseStationItem);
        if (stationItemCount <= 0) {
            throw new ServiceException(nurseStationItem.getNurseItemName() + "-" + "护理项目新增失败!");
        }
        //绑定护理站护理项目id
        if (CollectionUtils.isNotEmpty(nurseStationItemDTO.getNurseStationItemConsumables())) {
            for (NurseStationItemConsumable nurseStationItemConsumable : nurseStationItemDTO.getNurseStationItemConsumables()) {
                nurseStationItemConsumable.setNurseStationItemId(nurseStationItem.getId());
                nurseStationItemConsumable.setCreateTime(now);
                nurseStationItemConsumable.setCreateBy(loginUser.getUsername());
            }
            int itemConsumable = nurseStationItemConsumableMapper.insertNurseStationItemConsumable(nurseStationItemDTO.getNurseStationItemConsumables());
            if (itemConsumable <= 0) {
                throw new ServiceException(nurseStationItem.getNurseItemName() + "-" + "护理项目耗材新增失败!");
            }
        }
        //绑定护理站护理项目价格
        if (CollectionUtils.isNotEmpty(nurseStationItemDTO.getNurseStationItemPrices())) {
            for (NurseStationItemPrice nurseStationItemPrice : nurseStationItemDTO.getNurseStationItemPrices()) {
                nurseStationItemPrice.setNurseStationItemId(nurseStationItem.getId());
                nurseStationItemPrice.setCreateTime(now);
                nurseStationItemPrice.setCreateBy(loginUser.getUsername());
                if (Objects.nonNull(nurseStationItemPrice.getCommissionRate())) {
                    //算出佣金比例
                    BigDecimal commissionRatePriceMultiply = nurseStationItemPrice.getCommissionRate().multiply(nurseStationItemPrice.getPrice().multiply(BigDecimal.valueOf(0.01))).setScale(2, RoundingMode.HALF_UP);
                    nurseStationItemPrice.setCommissionAmount(commissionRatePriceMultiply);
                }
            }
            int itemPrice = nurseStationItemPriceMapper.insertNurseStationItemPrice(nurseStationItemDTO.getNurseStationItemPrices());
            if (itemPrice <= 0) {
                throw new ServiceException(nurseStationItem.getNurseItemName() + "-" + "护理项目价格新增失败!");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 批量修改护理站护理项目
     *
     * @param nurseStationItemDTO 护理站护理项目
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateNurseStationItem(NurseStationItemDTO nurseStationItemDTO) {
        //判断护理站项目价额是否为负数
        AjaxResult ajaxResult = judgePriceInfo(nurseStationItemDTO);
        if (Objects.nonNull(ajaxResult)) {
            return ajaxResult;
        }
        //前端传过来的
        NurseStationItem nurseStationItem = nurseStationItemDTO.getNurseStationItem();
        //从数据库中查到的
        NurseStationItemVO nurseStationItemVO = nurseStationItemMapper.selectNurseStationItemById(nurseStationItem.getId());
        if (Objects.isNull(nurseStationItemVO)) {
            return AjaxResult.error("当前护理项目信息不存在，无法进行修改，请联系管理员！");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        LocalDateTime now = LocalDateTime.now();
        //判断护理项目预约时间点间隔是否为空
        if (StringUtils.isBlank(nurseStationItem.getAppointmentTimeInterval())) {
            nurseStationItem.setAppointmentTimeInterval(AppointmentTimeIntervalEnum.HALF_HOUR.getValue());
        }
        //判断护理项目每个时间点的预约人数上限是否为0
        if (Objects.nonNull(nurseStationItem.getAppointmentLimitCount()) && nurseStationItem.getAppointmentLimitCount() == APPOINTMENT_LIMIT_COUNT) {
            return AjaxResult.error("预约人数上限应该大于零，请重新输入！");
        }
        int item = nurseStationItemMapper.updateNurseStationItem(nurseStationItem);
        if (item <= 0) {
            throw new ServiceException(nurseStationItem.getNurseItemName() + "-" + "护理项目修改失败!");
        }
        //删除护理站护理项目耗材关系
        nurseStationItemConsumableMapper.deleteNurseStationItemConsumableByItemId(nurseStationItem.getId());
        //护理站耗材表
        if (CollectionUtils.isNotEmpty(nurseStationItemDTO.getNurseStationItemConsumables())) {
            for (NurseStationItemConsumable nurseStationItemConsumable : nurseStationItemDTO.getNurseStationItemConsumables()) {
                nurseStationItemConsumable.setNurseStationItemId(nurseStationItem.getId());
                nurseStationItemConsumable.setCreateTime(now);
                nurseStationItemConsumable.setCreateBy(loginUser.getUsername());
            }
            int itemConsumable = nurseStationItemConsumableMapper.insertNurseStationItemConsumable(nurseStationItemDTO.getNurseStationItemConsumables());
            if (itemConsumable <= 0) {
                throw new ServiceException(nurseStationItem.getNurseItemName() + "-" + "护理项目耗材修改失败!");
            }
        }
        //删除护理站护理项目绑定的价格
        nurseStationItemPriceMapper.deleteNurseStationItemPriceByItemId(nurseStationItem.getId());
        if (CollectionUtils.isNotEmpty(nurseStationItemDTO.getNurseStationItemPrices())) {
            for (NurseStationItemPrice nurseStationItemPrice : nurseStationItemDTO.getNurseStationItemPrices()) {
                nurseStationItemPrice.setNurseStationItemId(nurseStationItem.getId());
                nurseStationItemPrice.setCreateTime(now);
                nurseStationItemPrice.setCreateBy(loginUser.getUsername());
                if (Objects.nonNull(nurseStationItemPrice.getCommissionRate())) {
                    //算出佣金比例
                    BigDecimal commissionRatePriceMultiply = nurseStationItemPrice.getCommissionRate().multiply(nurseStationItemPrice.getPrice().multiply(BigDecimal.valueOf(0.01))).setScale(2, RoundingMode.HALF_UP);
                    nurseStationItemPrice.setCommissionAmount(commissionRatePriceMultiply);
                }
            }
            //绑定护理站护理项目价格
            int itemPrice = nurseStationItemPriceMapper.insertNurseStationItemPrice(nurseStationItemDTO.getNurseStationItemPrices());
            if (itemPrice <= 0) {
                throw new ServiceException(nurseStationItem.getNurseItemName() + "-" + "护理项目价格修改失败!");
            }
        }
        //删除护理站项目的图片
        if (StringUtils.isNotBlank(nurseStationItemVO.getItemPictureUrl()) && StringUtils.isNotBlank(nurseStationItem.getItemPictureUrl()) && !nurseStationItemVO.getItemPictureUrl().equals(nurseStationItem.getItemPictureUrl())) {
            this.deletePictureUrl(nurseStationItemVO.getItemPictureUrl());
        }
        //删除护理站富文本图片
        this.deleteNurseStationItemPictureUrl(nurseStationItem, nurseStationItemVO);
        return AjaxResult.success();
    }

    /**
     * 批量删除护理站护理项目
     *
     * @param ids 需要删除的护理站护理项目主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult deleteNurseStationItemByIds(Long[] ids) {
        //根据id查询护理项目的信息 删除护理站项目的图片地址
        List<NurseStationItem> nurseStationItemByIds = nurseStationItemMapper.getNurseStationItemByIds(Arrays.asList(ids));
        //获取护理项目的图片信息
        List<String> itemPictureUrlList = nurseStationItemByIds.stream().filter(Objects::nonNull).filter(item -> StringUtils.isNotBlank(item.getItemPictureUrl())).map(NurseStationItem::getItemPictureUrl).distinct().collect(Collectors.toList());
        //获取护理项目富文本信息
        List<String> nurseItemContentList = nurseStationItemByIds.stream().filter(Objects::nonNull).filter(item -> StringUtils.isNotBlank(item.getNurseItemContent())).map(NurseStationItem::getNurseItemContent).distinct().collect(Collectors.toList());
        //删除护理站相关联的项目信息
        nurseStationItemConsumableMapper.deleteNurseStationItemConsumableByItemIds(ids);
        nurseStationItemPriceMapper.deleteNurseStationItemPriceByItemIds(ids);
        nurseStationItemMapper.deleteNurseStationItemByIds(ids);
        //删除图片
        itemPictureUrlList.forEach(this::deletePictureUrl);
        //遍历删除护理站富文本图片地址
        for (String nurseItemContent : nurseItemContentList) {
            List<String> nurseStationItemImgSrc = FileUtils.getImgSrc(nurseItemContent);
            for (String pictureUrl : nurseStationItemImgSrc) {
                if (StringUtils.isBlank(pictureUrl)) {
                    continue;
                }
                //修改路径
                String substring = pictureUrl.substring(pictureUrl.indexOf("/profile"));
                //删除商品富文本图片
                deletePictureUrl(substring);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 护理站护理项目信息导入
     *
     * @param list 护理站护理项目
     * @return 导入结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult importData(List<NurseStationItemImportDTO> list) {
        NurseStationItemImportVO stationItemImport = new NurseStationItemImportVO();
        //获取当前用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (CollectionUtils.isEmpty(list)) {
            return AjaxResult.error("请添加护理项目导入数据！");
        }
        //获取所有的护理站名称,去重复以后
        List<String> stationNameList = list.stream().filter(Objects::nonNull).map(NurseStationItemImportDTO::getNurseStationName).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
        //获取数据库中已经存在的所有项目信息  +通过服务站名称查询所有的关联
        List<NurseStationItemImportDTO> allNurseStationItemList = nurseStationItemMapper.selectItemInfoList(stationNameList);
        //求出差集,进行新增
        Collection<NurseStationItemImportDTO> subtractList = CollectionUtils.subtract(list, allNurseStationItemList);
        //求出并集,重复数据
        Collection<NurseStationItemImportDTO> intersectionList = CollectionUtils.intersection(list, allNurseStationItemList);
        //如果差集为null直接返回
        if (CollectionUtils.isEmpty(subtractList)) {
            stationItemImport.setSuccessList(subtractList);
            stationItemImport.setFailList(intersectionList);
            return AjaxResult.success(stationItemImport);
        }
        //根据护理项目名称进行分组
        Map<String, List<NurseStationItemImportDTO>> itemNameMap = list.stream().filter(item -> StringUtils.isNotBlank(item.getNurseItemName())).collect(Collectors.groupingBy(NurseStationItemImportDTO::getNurseItemName));
        //获取到所有的护理站信息
        List<NurseStation> nurseStations = nurseStationMapper.selectNurseStationListByNames(stationNameList);
        //以护理站名称进行分组匹配护理站id
        Map<String, Long> nurseStationLabelMap = nurseStations.stream().filter(Objects::nonNull).filter(item -> StringUtils.isNotBlank(item.getNurseStationName())).collect(Collectors.toMap(NurseStation::getNurseStationName, NurseStation::getId));
        //设置护理站id
        subtractList.forEach(item -> item.setNurseStationId(nurseStationLabelMap.getOrDefault(item.getNurseStationName(), 0L)));
        //添加创建时间/护理站编号/判断如果没有护理站信息,添加0L
        List<NurseStationItemPrice> priceList = Lists.newArrayList();
        for (NurseStationItemImportDTO item : subtractList) {
            //判断当前护理站项目在数据库中是否已经存在
            String nurseStationName = StringUtils.isBlank(item.getNurseStationName()) ? "" : item.getNurseStationName();
            String nurseItemName = StringUtils.isBlank(item.getNurseItemName()) ? "" : item.getNurseItemName();
            NurseStationItemImportDTO nurseStationItemImport = allNurseStationItemList.stream()
                    .filter(nurse -> !StringUtils.isAnyBlank(nurse.getNurseStationName(), nurse.getNurseItemName()))
                    .filter(nurseItem -> nurseStationName.equals(nurseItem.getNurseStationName()) && nurseItemName.equals(nurseItem.getNurseItemName())).findFirst().orElse(new NurseStationItemImportDTO());
            if (Objects.nonNull(nurseStationItemImport.getNurseStationItemId())) {
                //添加项目价格信息
                item.setNurseStationItemId(nurseStationItemImport.getNurseStationItemId());
                NurseStationItemPrice nurseStationItemPrice = new NurseStationItemPrice();
                nurseStationItemPrice.setCreateTime(LocalDateTime.now());
                BeanUtils.copyProperties(item, nurseStationItemPrice);
                priceList.add(nurseStationItemPrice);
                continue;
            }
            //根据护理项目名称获取护理项目名称
            List<NurseStationItemImportDTO> itemNameList = itemNameMap.getOrDefault(item.getNurseItemName(), Lists.newArrayList());
            //添加项目信息
            NurseStationItem nurseStationItem = new NurseStationItem();
            nurseStationItem.setNurseStationId(item.getNurseStationId());
            nurseStationItem.setNurseTypeId(0L);
            nurseStationItem.setUserId(SecurityUtils.getUserId());
            nurseStationItem.setNurseItemCode(Constants.STATION_ITEM + generateSystemCodeUtil.generateSystemCode(Constants.STATION_ITEM));
            nurseStationItem.setNurseItemName(item.getNurseItemName());
            nurseStationItem.setNurseItemContent(item.getNurseItemContent());
            nurseStationItem.setAdvanceAppointDuration(item.getAdvanceAppointDuration());
            nurseStationItem.setCreateTime(LocalDateTime.now());
            nurseStationItem.setCreateBy(loginUser.getUsername());
            //保存护理项目信息
            int stationItemCount = nurseStationItemMapper.insertNurseStationItem(nurseStationItem);
            if (stationItemCount <= 0) {
                throw new ServiceException(itemNameList.get(0).getNurseItemName() + "-" + "护理项目导入失败，请联系管理员！");
            }
            //添加项目价格信息
            item.setNurseStationItemId(nurseStationItem.getId());
            NurseStationItemPrice nurseStationItemPrice = new NurseStationItemPrice();
            nurseStationItemPrice.setCreateTime(LocalDateTime.now());
            BeanUtils.copyProperties(item, nurseStationItemPrice);
            priceList.add(nurseStationItemPrice);
        }
        //保存护理项目价格信息
        if (CollectionUtils.isNotEmpty(priceList)) {
            int itemPriceCount = nurseStationItemPriceMapper.insertNurseStationItemPrice(priceList);
            if (itemPriceCount <= 0) {
                throw new ServiceException("护理项目价格信息导入失败，请联系管理员！");
            }
        }
        //新增成功的项目信息
        stationItemImport.setSuccessList(subtractList);
        //新增重复的项目信息
        stationItemImport.setFailList(intersectionList);
        return AjaxResult.success(stationItemImport);
    }


    /**
     * 删除护理站富文本图片
     *
     * @param nurseStationItem   前端传过来的
     * @param nurseStationItemVO 数据库中的
     **/
    public void deleteNurseStationItemPictureUrl(NurseStationItem nurseStationItem, NurseStationItemVO nurseStationItemVO) {
        if (StringUtils.isNotBlank(nurseStationItem.getNurseItemContent()) && StringUtils.isNotBlank(nurseStationItemVO.getNurseItemContent())
                && !nurseStationItem.getNurseItemContent().equals(nurseStationItemVO.getNurseItemContent())) {
            //数据库中的
            List<String> stationItemImgSrc = FileUtils.getImgSrc(nurseStationItemVO.getNurseItemContent());
            //前端传的
            List<String> nurseStationItemImgSrc = FileUtils.getImgSrc(nurseStationItem.getNurseItemContent());
            //差集不同的
            List<String> subtractNurseStationImgSrc = new ArrayList<>(CollectionUtils.subtract(stationItemImgSrc, nurseStationItemImgSrc));
            for (String pictureUrl : subtractNurseStationImgSrc) {
                if (StringUtils.isBlank(pictureUrl)) {
                    continue;
                }
                //修改路径
                String substring = pictureUrl.substring(pictureUrl.indexOf("/profile"));
                //删除商品富文本图片
                deletePictureUrl(substring);
            }
        }
    }


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

    /**
     * 护理项目修改上架状态
     *
     * @param id          护理项目id
     * @param shelfStatus 上架状态
     * @return AjaxResult
     */
    @Override
    public AjaxResult updateShelfStatus(Long id, String shelfStatus) {
        if (!NurseStationItemShelfStatusEnum.SHELF.getInfo().equals(shelfStatus) && !NurseStationItemShelfStatusEnum.NOT_SHELF.getInfo().equals(shelfStatus)) {
            return AjaxResult.error("上架状态不存在！");
        }
        NurseStationItem nurseStationItem = nurseStationItemMapper.getNurseStationItemById(id);
        if (Objects.isNull(nurseStationItem)) {
            return AjaxResult.error("该护理项目不存在！");
        }
        nurseStationItemMapper.updateShelfStatusById(id, shelfStatus);
        return AjaxResult.success();
    }

    /**
     * 校验护理站项目价格和耗材包单价是否为负数
     *
     * @param nurseStationItemDTO 输入参数
     * @return 返回结果信息
     */
    private AjaxResult judgePriceInfo(NurseStationItemDTO nurseStationItemDTO) {
        //判断护理站项目价额是否为负数
        if (CollectionUtils.isNotEmpty(nurseStationItemDTO.getNurseStationItemPrices())) {
            NurseStationItemPrice nurseStationItemPrice = nurseStationItemDTO.getNurseStationItemPrices().stream().filter(item -> Objects.nonNull(item.getPrice()) && item.getPrice().compareTo(BigDecimal.ZERO) < 0).findFirst().orElse(null);
            if (Objects.nonNull(nurseStationItemPrice)) {
                return AjaxResult.error("护理项目价格不能为负数，请重新输入！");
            }
            NurseStationItemPrice itemPrice = nurseStationItemDTO.getNurseStationItemPrices().stream().filter(item -> Objects.nonNull(item.getCommissionAmount()) && item.getCommissionAmount().compareTo(BigDecimal.ZERO) < 0).findFirst().orElse(null);
            if (Objects.nonNull(itemPrice)) {
                return AjaxResult.error("护理项目佣金金额不能为负数，请重新输入！");
            }
            NurseStationItemPrice stationItemPrice = nurseStationItemDTO.getNurseStationItemPrices().stream().filter(item -> Objects.nonNull(item.getPrice()) && Objects.nonNull(item.getCommissionAmount())).filter(item -> item.getPrice().compareTo(item.getCommissionAmount()) <= 0).findFirst().orElse(null);
            if (Objects.nonNull(stationItemPrice)) {
                return AjaxResult.error("护理项目佣金金额不能大于或等于护理项目价格，请重新输入！");
            }
            NurseStationItemPrice commissionRatePrice = nurseStationItemDTO.getNurseStationItemPrices().stream().filter(item -> Objects.nonNull(item.getCommissionRate()) && (item.getCommissionRate().compareTo(BigDecimal.ZERO) < 0 || item.getCommissionRate().compareTo(BigDecimal.valueOf(100)) > 0)).findFirst().orElse(null);
            if (Objects.nonNull(commissionRatePrice)) {
                return AjaxResult.error("护理项目佣金比例只能在0-100之间，请重新输入！");
            }
        }
        //判断护理项目耗材包价格是否为负数
        if (CollectionUtils.isNotEmpty(nurseStationItemDTO.getNurseStationItemConsumables())) {
            NurseStationItemConsumable nurseStationItemConsumable = nurseStationItemDTO.getNurseStationItemConsumables().stream().filter(item -> Objects.nonNull(item.getConsumablePrice()) && item.getConsumablePrice().compareTo(BigDecimal.ZERO) < 0).findFirst().orElse(null);
            if (Objects.nonNull(nurseStationItemConsumable)) {
                return AjaxResult.error("护理项目耗材包单价不能为负数，请重新输入！");
            }
            NurseStationItemConsumable consumableCountInfoTwo = nurseStationItemDTO.getNurseStationItemConsumables().stream().filter(item -> Objects.isNull(item.getConsumableCount())).findFirst().orElse(null);
            if (Objects.nonNull(consumableCountInfoTwo)) {
                return AjaxResult.error("护理项目耗材包数量不能为空，请重新输入！");
            }
            NurseStationItemConsumable consumableCountInfo = nurseStationItemDTO.getNurseStationItemConsumables().stream().filter(item -> Objects.nonNull(item.getConsumableCount()) && item.getConsumableCount() < 0).findFirst().orElse(null);
            if (Objects.nonNull(consumableCountInfo)) {
                return AjaxResult.error("护理项目耗材包数量不能为负数，请重新输入！");
            }
        }
        return null;
    }
}