package com.xinelu.manage.service.hospitalinfo.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.common.utils.regex.RegexUtil;
import com.xinelu.manage.domain.hospitalinfo.HospitalInfo;
import com.xinelu.manage.mapper.hospitalinfo.HospitalInfoMapper;
import com.xinelu.manage.service.hospitalinfo.IHospitalInfoService;
import com.xinelu.manage.service.nursestationitem.INurseStationItemService;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Resource;
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;

/**
 * 医院信息管理Service业务层处理
 *
 * @author xinyilu
 * @date 2023-02-13
 */
@Service
public class HospitalInfoServiceImpl implements IHospitalInfoService {
    @Resource
    private HospitalInfoMapper hospitalInfoMapper;
    @Resource
    private GenerateSystemCodeUtil generateSystemCodeUtil;
    @Resource
    private RegexUtil regexUtil;
    @Resource
    private INurseStationItemService nurseStationItemService;

    /**
     * 查询医院信息管理
     *
     * @param id 医院信息管理主键
     * @return 医院信息管理
     */
    @Override
    public HospitalInfo selectHospitalInfoById(Long id) {
        return hospitalInfoMapper.selectHospitalInfoById(id);
    }

    /**
     * 查询医院信息管理列表
     *
     * @param hospitalInfo 医院信息管理
     * @return 医院信息管理
     */
    @Override
    public List<HospitalInfo> selectHospitalInfoList(HospitalInfo hospitalInfo) {
        return hospitalInfoMapper.selectHospitalInfoList(hospitalInfo);
    }

    /**
     * 新增医院信息管理
     *
     * @param hospitalInfo 医院信息管理
     * @return 结果
     */
    @Override
    public AjaxResult insertHospitalInfo(HospitalInfo hospitalInfo) {
        //校验联系电话是否正确
        if (StringUtils.isNotBlank(hospitalInfo.getPhone())) {
            boolean phone = regexUtil.regexSeatNumber(hospitalInfo.getPhone());
            if (BooleanUtils.isFalse(phone)) {
                return AjaxResult.error("您输入的联系电话" + hospitalInfo.getPhone() + "不正确，请重新输入！");
            }
        }
        //校验名称是否重复
        int nameCount = hospitalInfoMapper.selectHospitalNameCount(hospitalInfo.getHospitalName());
        if (nameCount > 0) {
            return AjaxResult.error("您输入的医院名称" + hospitalInfo.getHospitalName() + "重复，请重新添加！");
        }
        hospitalInfo.setHospitalCode(Constants.HOSPITAL_CODE + generateSystemCodeUtil.generateSystemCode(Constants.HOSPITAL_CODE));
        hospitalInfo.setCreateBy(SecurityUtils.getUsername());
        hospitalInfo.setCreateTime(LocalDateTime.now());
        return AjaxResult.success(hospitalInfoMapper.insertHospitalInfo(hospitalInfo));
    }

    /**
     * 修改医院信息管理
     *
     * @param hospitalInfo 医院信息管理
     * @return 结果
     */
    @Override
    public AjaxResult updateHospitalInfo(HospitalInfo hospitalInfo) {
        HospitalInfo getHospitalInfo = hospitalInfoMapper.selectHospitalInfoById(hospitalInfo.getId());
        if (Objects.isNull(getHospitalInfo)) {
            return AjaxResult.error("当前医院信息不存在，无法修改，请联系管理员！");
        }
        //校验联系电话是否正确
        if (StringUtils.isNotBlank(hospitalInfo.getPhone())) {
            boolean phone = regexUtil.regexSeatNumber(hospitalInfo.getPhone());
            if (BooleanUtils.isFalse(phone)) {
                return AjaxResult.error("您输入的联系电话" + hospitalInfo.getPhone() + "不正确，请重新输入！");
            }
        }
        //校验名称是否重复
        if (!hospitalInfo.getHospitalName().equals(getHospitalInfo.getHospitalName())) {
            int nameCount = hospitalInfoMapper.selectHospitalNameCount(hospitalInfo.getHospitalName());
            if (nameCount > 0) {
                return AjaxResult.error("您输入的医院名称" + hospitalInfo.getHospitalName() + "重复，请重新添加！");
            }
        }
        hospitalInfo.setUpdateBy(SecurityUtils.getUsername());
        hospitalInfo.setUpdateTime(LocalDateTime.now());
        //修改医院信息
        hospitalInfoMapper.updateHospitalInfo(hospitalInfo);
        //修改富文本图片
        this.deleteHospitalPictureUrl(hospitalInfo, getHospitalInfo);
        return AjaxResult.success();
    }

    /**
     * 批量删除医院信息管理
     *
     * @param ids 需要删除的医院信息管理主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult deleteHospitalInfoByIds(Long[] ids) {
        //查询医院信息
        List<HospitalInfo> hospitalInfoList = hospitalInfoMapper.selectHospitalList(ids);
        if (CollectionUtils.isEmpty(hospitalInfoList)) {
            return AjaxResult.error("医院信息不存在，无法删除！");
        }
        //删除医院信息
        int count = hospitalInfoMapper.deleteHospitalInfoByIds(ids);
        if (count <= 0) {
            throw new ServiceException("删除医院信息失败，请联系管理员！");
        }
        //筛选医院简介
        List<String> hospitalIntroduceList = hospitalInfoList.stream().filter(Objects::nonNull).filter(item -> StringUtils.isNotBlank(item.getHospitalIntroduce())).map(HospitalInfo::getHospitalIntroduce).collect(Collectors.toList());
        //遍历获取简介图片地址
        for (String hospitalIntroduce : hospitalIntroduceList) {
            List<String> pictureUrlList = FileUtils.getImgSrc(hospitalIntroduce);
            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 deleteHospitalInfoById(Long id) {
        return hospitalInfoMapper.deleteHospitalInfoById(id);
    }

    /**
     * 删除医院富文本图片
     *
     * @param hospitalInfo 修改后
     * @param getHospital  修改先
     **/
    public void deleteHospitalPictureUrl(HospitalInfo hospitalInfo, HospitalInfo getHospital) {
        if (StringUtils.isNotBlank(hospitalInfo.getHospitalIntroduce()) && StringUtils.isNotBlank(getHospital.getHospitalIntroduce())
                && !hospitalInfo.getHospitalIntroduce().equals(getHospital.getHospitalIntroduce())) {
            //修改先
            List<String> getHospitalImgSrc = FileUtils.getImgSrc(getHospital.getHospitalIntroduce());
            //修改后
            List<String> hospitalImgSrc = FileUtils.getImgSrc(hospitalInfo.getHospitalIntroduce());
            //差集不同的
            List<String> subtractNurseStationImgSrc = new ArrayList<>(CollectionUtils.subtract(getHospitalImgSrc, hospitalImgSrc));
            //删除商品富文本图片
            for (String pictureUrl : subtractNurseStationImgSrc) {
                if (StringUtils.isBlank(pictureUrl)) {
                    continue;
                }
                //修改路径
                String substring = pictureUrl.substring(pictureUrl.indexOf("/profile"));
                //删除富文本图片
                nurseStationItemService.deletePictureUrl(substring);
            }
        }
    }

    /**
     * @Author mengkuiliang
     * @Description 根据家医机构编码查询医院
     * @Date 2023-10-09 009 15:47
     * @Param [orgCode]
     * @return com.xinelu.manage.domain.hospitalinfo.HospitalInfo
     **/
    @Override
    public HospitalInfo getHosptalByOrgCode(String orgCode) {
        return hospitalInfoMapper.getHosptalByOrgCode(orgCode);
    }
}

