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

import com.xinelu.common.config.XinELuConfig;
import com.xinelu.common.constant.Constants;
import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.enums.SettingsTypeEnum;
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.systemsettingsinfo.SystemSettingsInfo;
import com.xinelu.manage.mapper.systemsettingsinfo.SystemSettingsInfoMapper;
import com.xinelu.manage.service.systemsettingsinfo.ISystemSettingsInfoService;
import org.apache.commons.collections4.CollectionUtils;
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.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 泉医到家平台系统业务设置信息Service业务层处理
 *
 * @author xinyilu
 * @date 2023-02-23
 */
@Service
public class SystemSettingsInfoServiceImpl implements ISystemSettingsInfoService {
    @Resource
    private SystemSettingsInfoMapper systemSettingsInfoMapper;
    @Resource
    private GenerateSystemCodeUtil generateSystemCodeUtil;

    /**
     * 查询泉医到家平台系统业务设置信息
     *
     * @param id 泉医到家平台系统业务设置信息主键
     * @return 泉医到家平台系统业务设置信息
     */
    @Override
    public SystemSettingsInfo selectSystemSettingsInfoById(Long id) {
        return systemSettingsInfoMapper.selectSystemSettingsInfoById(id);
    }

    /**
     * 查询泉医到家平台系统业务设置信息列表
     *
     * @param systemSettingsInfo 泉医到家平台系统业务设置信息
     * @return 泉医到家平台系统业务设置信息
     */
    @Override
    public List<SystemSettingsInfo> selectSystemSettingsInfoList(SystemSettingsInfo systemSettingsInfo) {
        return systemSettingsInfoMapper.selectSystemSettingsInfoList(systemSettingsInfo);
    }

    /**
     * 新增泉医到家平台系统业务设置信息
     *
     * @param systemSettingsInfo 泉医到家平台系统业务设置信息
     * @return 结果
     */
    @Override
    public AjaxResult insertSystemSettingsInfo(SystemSettingsInfo systemSettingsInfo) {
        AjaxResult ajaxResult = checkSystemSettingsInfo(systemSettingsInfo);
        if (Objects.nonNull(ajaxResult)) {
            return ajaxResult;
        }
        int systemSettingsInfoByCount = systemSettingsInfoMapper.selectSystemSettingsInfoByCount(systemSettingsInfo.getSettingsType());
        if (systemSettingsInfoByCount > 0) {
            return AjaxResult.error("系统已设置'" + systemSettingsInfo.getSettingsType() + "'类型的规则，请进行修改即可！");
        }
        systemSettingsInfo.setCreateTime(LocalDateTime.now());
        systemSettingsInfo.setCreateBy(SecurityUtils.getUsername());
        systemSettingsInfo.setSettingsCode(Constants.SETTINGS_CODE + generateSystemCodeUtil.generateSystemCode(Constants.SETTINGS_CODE));
        return AjaxResult.success(systemSettingsInfoMapper.insertSystemSettingsInfo(systemSettingsInfo));
    }

    /**
     * 修改泉医到家平台系统业务设置信息
     *
     * @param systemSettingsInfo 泉医到家平台系统业务设置信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateSystemSettingsInfo(SystemSettingsInfo systemSettingsInfo) {
        AjaxResult ajaxResult = checkSystemSettingsInfo(systemSettingsInfo);
        if (Objects.nonNull(ajaxResult)) {
            return ajaxResult;
        }
        SystemSettingsInfo settingsInfo = systemSettingsInfoMapper.selectSystemSettingsInfoById(systemSettingsInfo.getId());
        if (Objects.isNull(settingsInfo)) {
            return AjaxResult.error("当前信息不存在，请联系管理员！");
        }
        if (!StringUtils.equals(settingsInfo.getSettingsType(), systemSettingsInfo.getSettingsType())) {
            int systemSettingsInfoByCount = systemSettingsInfoMapper.selectSystemSettingsInfoByCount(systemSettingsInfo.getSettingsType());
            if (systemSettingsInfoByCount > 0) {
                return AjaxResult.error("系统已有相同的设置类型，请进行修改！");
            }
        }
        systemSettingsInfo.setUpdateTime(LocalDateTime.now());
        systemSettingsInfo.setUpdateBy(SecurityUtils.getUsername());
        int updateSystemSettingsInfo = systemSettingsInfoMapper.updateSystemSettingsInfo(systemSettingsInfo);
        if (updateSystemSettingsInfo < 0) {
            throw new ServiceException("修改信息失败，请联系管理员！");
        }
        //删除富文本图片
        this.deleteStationPictureUrl(systemSettingsInfo, settingsInfo);
        return AjaxResult.success();
    }

    /**
     * 批量删除泉医到家平台系统业务设置信息
     *
     * @param ids 需要删除的泉医到家平台系统业务设置信息主键
     * @return 结果
     */
    @Override
    public int deleteSystemSettingsInfoByIds(Long[] ids) {
        return systemSettingsInfoMapper.deleteSystemSettingsInfoByIds(ids);
    }

    /**
     * 删除富文本图片
     *
     * @param systemSettingsInfo 前端传的
     * @param settingsInfo       数据库查的
     **/
    public void deleteStationPictureUrl(SystemSettingsInfo systemSettingsInfo, SystemSettingsInfo settingsInfo) {
        if (StringUtils.isNotBlank(systemSettingsInfo.getSettingsContent()) && StringUtils.isNotBlank(settingsInfo.getSettingsContent())
                && !systemSettingsInfo.getSettingsContent().equals(settingsInfo.getSettingsContent())) {
            //数据库中的
            List<String> stationImgSrc = FileUtils.getImgSrc(settingsInfo.getSettingsContent());
            //前端传的
            List<String> nurseStationImgSrc = FileUtils.getImgSrc(systemSettingsInfo.getSettingsContent());
            //差集不同的
            List<String> subtractImgSrc = new ArrayList<>(CollectionUtils.subtract(stationImgSrc, nurseStationImgSrc));
            for (String pictureUrl : subtractImgSrc) {
                if (StringUtils.isBlank(pictureUrl)) {
                    continue;
                }
                //修改路径
                String substring = pictureUrl.substring(pictureUrl.indexOf("/profile"));
                //删除商品富文本图片
                deletePictureUrl(substring);
            }
        }
    }


    /**
     * 删除图片地址
     *
     * @param pictureUrl 护理站图片地址
     **/
    private 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 systemSettingsInfo 规则参数
     * @return 校验结果
     */
    private AjaxResult checkSystemSettingsInfo(SystemSettingsInfo systemSettingsInfo) {
        if (SettingsTypeEnum.SIGN_IN_RULE.getInfo().equals(systemSettingsInfo.getSettingsType())) {
            if (Objects.nonNull(systemSettingsInfo.getTotalSignInDays()) && systemSettingsInfo.getTotalSignInDays() <= 0) {
                return AjaxResult.error("累计签到天数应大于零，请重新填写！");
            }
            if (Objects.nonNull(systemSettingsInfo.getIntegralCount()) && systemSettingsInfo.getIntegralCount() <= 0) {
                return AjaxResult.error("赠送积分数量应大于零，请重新填写！");
            }
        }
        if (SettingsTypeEnum.INVITE_FRIENDS.getInfo().equals(systemSettingsInfo.getSettingsType())) {
            if (Objects.nonNull(systemSettingsInfo.getIntegralCount()) && systemSettingsInfo.getIntegralCount() <= 0) {
                return AjaxResult.error("赠送积分数量应大于零，请重新填写！");
            }
        }
        if (SettingsTypeEnum.INTEGRAL_DEDUCTION.getInfo().equals(systemSettingsInfo.getSettingsType())) {
            if (Objects.nonNull(systemSettingsInfo.getIntegralCount()) && systemSettingsInfo.getIntegralCount() <= 0) {
                return AjaxResult.error("赠送积分数量应大于零，请重新填写！");
            }
            if (Objects.nonNull(systemSettingsInfo.getCreditAmount()) && systemSettingsInfo.getCreditAmount().compareTo(BigDecimal.ZERO) <= 0) {
                return AjaxResult.error("积分抵扣金额应大于零，请重新填写！");
            }
        }
        return null;
    }
}
