package com.xinelu.manage.service.nursestationperson.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.entity.SysRole;
import com.xinelu.common.core.domain.entity.SysUser;
import com.xinelu.common.enums.ModifyCheckStatusEnum;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.DateUtils;
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.regex.RegexUtil;
import com.xinelu.common.utils.sign.Md5Utils;
import com.xinelu.manage.domain.nursestation.NurseStation;
import com.xinelu.manage.domain.nursestationperson.NurseStationPerson;
import com.xinelu.manage.domain.nursestationpersoncertificate.NurseStationPersonCertificate;
import com.xinelu.manage.domain.nursestationpersoncheck.NurseStationPersonCheck;
import com.xinelu.manage.dto.nursestationperson.NurseStationPersonCheckDTO;
import com.xinelu.manage.dto.nursestationperson.NurseStationPersonDTO;
import com.xinelu.manage.dto.nursestationperson.NurseStationPersonImportDTO;
import com.xinelu.manage.mapper.nursestation.NurseStationMapper;
import com.xinelu.manage.mapper.nursestationperson.NurseStationPersonMapper;
import com.xinelu.manage.mapper.nursestationpersoncertificate.NurseStationPersonCertificateMapper;
import com.xinelu.manage.mapper.nursestationpersoncheck.NurseStationPersonCheckMapper;
import com.xinelu.manage.service.nursestationperson.INurseStationPersonService;
import com.xinelu.manage.vo.nursestationperson.NurseStationPersonSysUserVO;
import com.xinelu.manage.vo.nursestationperson.NurseStationPersonVO;
import com.xinelu.system.domain.SysUserRole;
import com.xinelu.system.mapper.SysRoleMapper;
import com.xinelu.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
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.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 护理站人员信息Service业务层处理
 *
 * @author ljh
 * @date 2022-09-02
 */
@Service
@Slf4j
public class NurseStationPersonServiceImpl implements INurseStationPersonService {
    @Resource
    private RegexUtil regexUtil;
    @Resource
    private NurseStationPersonMapper nurseStationPersonMapper;
    @Resource
    private GenerateSystemCodeUtil generateSystemCodeUtil;
    @Resource
    private NurseStationMapper nurseStationMapper;
    @Resource
    private NurseStationPersonCertificateMapper nurseStationPersonCertificateMapper;
    @Resource
    private NurseStationPersonCheckMapper nurseStationPersonCheckMapper;
    @Resource
    private SysUserRoleMapper userRoleMapper;
    @Resource
    private SysRoleMapper roleMapper;
    @Resource
    private XinELuConfig xinELuConfig;

    /**
     * 男性
     */
    private static final String MALE_CHINESE = "男";

    /**
     * 女性
     */
    private static final String FEMALE_CHINESE = "女";

    /**
     * 角色标识为护理人员
     */
    private static final String ROLE = "nursePersonRole";

    /**
     * 查询护理站人员信息
     *
     * @param id 护理站人员信息主键
     * @return 护理站人员信息
     */
    @Override
    public NurseStationPersonVO selectNurseStationPersonById(Long id) {
        NurseStationPersonVO nurseStationPersonVO = nurseStationPersonMapper.selectNurseStationPersonById(id);
        int avgEvaluateSatisfaction = nurseStationPersonMapper.selectAvgEvaluateSatisfaction(id);
        nurseStationPersonVO.setEvaluateStarCount(Math.round(avgEvaluateSatisfaction));
        return nurseStationPersonVO;
    }

    /**
     * 查询护理站人员信息列表
     *
     * @param nurseStationPerson 护理站人员信息
     * @return 护理站人员信息
     */
    @Override
    public List<NurseStationPerson> selectNurseStationPersonList(NurseStationPerson nurseStationPerson) {
        return nurseStationPersonMapper.selectNurseStationPersonList(nurseStationPerson);
    }

    /**
     * 新增护理站人员信息
     *
     * @param nurseStationPerson 护理站人员信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertNurseStationPersonList(NurseStationPersonDTO nurseStationPerson) {
        //校验数据是否为空
        if (Objects.isNull(nurseStationPerson)) {
            return AjaxResult.error("请添加护理站人员信息！");
        }
        //校验手机号是否正确
        if (StringUtils.isNotBlank(nurseStationPerson.getPhone())) {
            boolean regexPhone = regexUtil.regexPhone(nurseStationPerson.getPhone());
            if (BooleanUtils.isFalse(regexPhone)) {
                return AjaxResult.error("您输入的联系电话" + nurseStationPerson.getPhone() + "不正确，请重新输入！");
            }
            // 校验手机号是否重复
            int nurseStationPersonPhone = nurseStationPersonMapper.getNurseStationPersonPhone(nurseStationPerson.getPhone());
            if (nurseStationPersonPhone > 0) {
                log.warn("新增当前护理员手机号信息在nurse_station_person表中存在重复！！");
                return AjaxResult.error("您输入的联系电话" + nurseStationPerson.getPhone() + "重复！");
            }
            //根据手机号查询sysUser表的信息 是否重复
            int nurseStationUserCount = nurseStationPersonMapper.getNurseStationUserCount(nurseStationPerson.getPhone());
            if (nurseStationUserCount > 0) {
                return AjaxResult.error("您输入的联系电话" + nurseStationPerson.getPhone() + "在用户管理中重复！");
            }
        }
        // 设置创建人创建时间以及随机生成唯一编码
        nurseStationPerson.setModifyCheckStatus(ModifyCheckStatusEnum.CHECKED.getInfo());
        nurseStationPerson.setCreateTime(LocalDateTime.now());
        nurseStationPerson.setCreateBy(SecurityUtils.getUsername());
        nurseStationPerson.setUserId(SecurityUtils.getUserId());
        nurseStationPerson.setNursePersonCode(Constants.NURSE_PERSON_CODE + generateSystemCodeUtil.generateSystemCode(Constants.NURSE_PERSON_CODE));
        int insertCount = nurseStationPersonMapper.insertNurseStationPerson(nurseStationPerson);
        if (insertCount <= 0) {
            throw new ServiceException("新增护理人员信息失败，请联系管理员！");
        }
        //新增sys_user表信息
        this.insertSysUserInfo(nurseStationPerson);
        if (CollectionUtils.isNotEmpty(nurseStationPerson.getNurseStationPersonCertificateList())) {
            //新增护理员证书表
            for (NurseStationPersonCertificate personCertificate : nurseStationPerson.getNurseStationPersonCertificateList()) {
                personCertificate.setNurseStationPersonId(nurseStationPerson.getId());
                personCertificate.setCreateTime(LocalDateTime.now());
                personCertificate.setCreateBy(SecurityUtils.getUsername());
                personCertificate.setCertificateCode(Constants.PERSON_CERTIFICATE_CODE + generateSystemCodeUtil.generateSystemCode(Constants.PERSON_CERTIFICATE_CODE));
            }
            int nurseStationPersonCertificateList = nurseStationPersonCertificateMapper.insertNurseStationPersonCertificateList(nurseStationPerson.getNurseStationPersonCertificateList());
            if (nurseStationPersonCertificateList <= 0) {
                throw new ServiceException("新增护理员证书信息失败，请联系管理员！");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 修改护理站人员信息
     *
     * @param nurseStationPerson 护理站人员信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateNurseStationPerson(NurseStationPersonDTO nurseStationPerson) {
        //根据id查询当前人员是否存在
        NurseStationPerson existStationPerson = nurseStationPersonMapper.getNurseStationPersonInfo(nurseStationPerson.getId());
        if (Objects.isNull(existStationPerson)) {
            return AjaxResult.error("当前护理站人员信息不存在！");
        }
        if (StringUtils.isNotBlank(nurseStationPerson.getPhone())) {
            // 校验手机号是否正确
            boolean regexPhone = regexUtil.regexPhone(nurseStationPerson.getPhone());
            if (BooleanUtils.isFalse(regexPhone)) {
                return AjaxResult.error("您输入的联系电话" + nurseStationPerson.getPhone() + "不正确，请重新输入！");
            }
            // 校验手机号是否重复
            boolean existStationPhone = StringUtils.isNotBlank(existStationPerson.getPhone()) && StringUtils.isNotBlank(nurseStationPerson.getPhone()) && !existStationPerson.getPhone().equals(nurseStationPerson.getPhone());
            if (BooleanUtils.isTrue(existStationPhone)) {
                int nurseStationPersonPhone = nurseStationPersonMapper.getNurseStationPersonPhone(nurseStationPerson.getPhone());
                if (nurseStationPersonPhone > 0) {
                    return AjaxResult.error("您输入的联系电话" + nurseStationPerson.getPhone() + "重复，请重新输入！");
                }
                //根据手机号查询sysUser表的信息 是否重复
                int nurseStationUserCount = nurseStationPersonMapper.getNurseStationUserCount(nurseStationPerson.getPhone());
                if (nurseStationUserCount > 0) {
                    return AjaxResult.error("您输入的联系电话" + nurseStationPerson.getPhone() + "在用户管理中重复！");
                }
            }
        }
        //更新护理人员表信息
        nurseStationPerson.setUpdateBy(SecurityUtils.getUsername());
        nurseStationPerson.setUpdateTime(LocalDateTime.now());
        int stationPerson = nurseStationPersonMapper.updateNurseStationPerson(nurseStationPerson);
        if (stationPerson <= 0) {
            throw new ServiceException("修改护理人员失败，请联系管理员！");
        }
        //修改sys_user表信息
        this.updateSysUserInfo(nurseStationPerson, existStationPerson);
        //修改护理人员证书
        this.extracted(nurseStationPerson);
        return AjaxResult.success();
    }

    /**
     * 批量删除护理站人员信息
     *
     * @param ids 需要删除的护理站人员信息主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult deleteNurseStationPersonByIds(Long[] ids) {
        //根据护理人员id去查询对应的资质证书 使用流来获取所有的证书路径
        List<NurseStationPersonCertificate> stationPersonCertificates = nurseStationPersonCertificateMapper.selectNurseStationPersonCertificateByIds(Arrays.asList(ids));
        //删除人员资质证书表信息
        if (CollectionUtils.isNotEmpty(stationPersonCertificates)) {
            nurseStationPersonCertificateMapper.deleteNurseStationPersonCertificateByPersonIds(ids);
        }
        //删除sysUser表信息
        nurseStationPersonMapper.deleteNurseStationPersonSysUser(ids);
        //删除nurse_station_person表信息
        int stationPersonByIds = nurseStationPersonMapper.deleteNurseStationPersonByIds(ids);
        if (stationPersonByIds <= 0) {
            return AjaxResult.error("删除护理人员信息失败！");
        }
        //删除护理人员的资质证书
        if (CollectionUtils.isNotEmpty(stationPersonCertificates)) {
            List<String> personCertificateUrlList = stationPersonCertificates.stream().filter(Objects::nonNull)
                    .filter(hospitalUrl -> (StringUtils.isNotBlank(hospitalUrl.getCertificateUrl())))
                    .map(NurseStationPersonCertificate::getCertificateUrl).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(personCertificateUrlList)) {
                personCertificateUrlList.forEach(this::deletePictureUrl);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 删除护理站人员信息信息
     *
     * @param id 护理站人员信息主键
     * @return 结果
     */
    @Override
    public int deleteNurseStationPersonById(Long id) {
        return nurseStationPersonMapper.deleteNurseStationPersonById(id);
    }

    /**
     * 查询护理站人员信息以及护理站名称集合
     *
     * @param nurseStationPerson 护理站人员信息集合
     * @return java.util.List<com.xinelu.common.vo.nursestationperson.NurseStationPersonVO>
     **/
    @Override
    public List<NurseStationPersonVO> getNurseStationPersonList(NurseStationPersonVO nurseStationPerson) {
        List<NurseStationPersonVO> nurseStationPersonList = nurseStationPersonMapper.getNurseStationPersonList(nurseStationPerson);
        if (CollectionUtils.isNotEmpty(nurseStationPersonList)) {
            nurseStationPersonList.forEach(nurse -> {
                int avgEvaluateSatisfaction = nurseStationPersonMapper.selectAvgEvaluateSatisfaction(nurse.getId());
                nurse.setEvaluateStarCount(Math.round(avgEvaluateSatisfaction));
            });
        }
        return nurseStationPersonList;
    }

    /**
     * 护理站人员导入
     *
     * @param nurseStationPerson 护理站人员信息
     * @return 导入结果信息
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertNurseStationPersonImportList(List<NurseStationPersonImportDTO> nurseStationPerson) {
        //获取当前用户 校验数据是否有值
        if (CollectionUtils.isEmpty(nurseStationPerson)) {
            return AjaxResult.error("请添加护理站人员信息！");
        }
        NurseStationPersonImportDTO nurseStationPersonImportDTO = nurseStationPerson.stream()
                .filter(item -> StringUtils.isBlank(item.getNursePersonName()) || StringUtils.isBlank(item.getSex()) || StringUtils.isBlank(item.getPhone()) || StringUtils.isBlank(item.getNurseStationName()))
                .findFirst().orElse(null);
        if (Objects.nonNull(nurseStationPersonImportDTO)) {
            return AjaxResult.error("导入数据格式不正确，单元格数据不能为空，请进行确认！");
        }
        //根据人员姓名、联系电话、所属护理站去重
        List<NurseStationPersonImportDTO> nursePersonList = nurseStationPerson.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        //校验联系电话格式是否正确
        NurseStationPersonImportDTO dto = nursePersonList.stream().filter(item -> StringUtils.isNotBlank(item.getPhone())).filter(item -> BooleanUtils.isFalse(regexUtil.regexPhone(item.getPhone()))).findFirst().orElse(new NurseStationPersonImportDTO());
        if (StringUtils.isNotBlank(dto.getPhone())) {
            return AjaxResult.error("当前联系电话：" + dto.getPhone() + " 格式不正确，请重新录入！");
        }
        //获取护理人员的手机号集合
        List<String> phoneList = nursePersonList.stream()
                .filter(Objects::nonNull)
                .filter(item -> Objects.nonNull(item.getPhone()))
                .map(NurseStationPersonImportDTO::getPhone)
                .distinct().collect(Collectors.toList());
        //根据人员手机号查询数据库已存在的人员信息和所属护理站信息
        List<NurseStationPersonImportDTO> allNurseStationPersonInfo = nurseStationPersonMapper.getAllNurseStationPersonInfo(phoneList);
        //做差集，剔除数据库中已经存在的人员信息
        List<NurseStationPersonImportDTO> subtractList = new ArrayList<>(CollectionUtils.subtract(nursePersonList, allNurseStationPersonInfo));
        if (CollectionUtils.isEmpty(subtractList)) {
            return AjaxResult.success();
        }
        //获取护理站的名称
        List<String> stationNameList = subtractList.stream()
                .filter(Objects::nonNull)
                .filter(item -> Objects.nonNull(item.getNurseStationName()))
                .map(NurseStationPersonImportDTO::getNurseStationName)
                .distinct().collect(Collectors.toList());
        //获取到所有的护理站信息
        List<NurseStation> nurseStationList = nurseStationMapper.selectNurseStationListByNames(stationNameList);
        //查询护理站相关信息
        Map<String, Long> nurseStationMap = nurseStationList.stream().filter(Objects::nonNull)
                .filter(item -> StringUtils.isNotBlank(item.getNurseStationName()))
                .collect(Collectors.toMap(NurseStation::getNurseStationName, NurseStation::getId));
        // 设置其余编号以及系统值
        List<NurseStationPerson> nurseStationPersonList = new ArrayList<>();
        for (NurseStationPersonImportDTO item : subtractList) {
            String sex = StringUtils.isBlank(item.getSex()) ? "" : item.getSex();
            if (MALE_CHINESE.equals(sex)) {
                item.setSex(Constants.MALE);
            }
            if (FEMALE_CHINESE.equals(sex)) {
                item.setSex(Constants.FEMALE);
            }
            item.setNurseStationId(nurseStationMap.getOrDefault(item.getNurseStationName(), null));
            item.setCreateBy(SecurityUtils.getUsername());
            item.setCreateTime(LocalDateTime.now());
            item.setUserId(SecurityUtils.getUserId());
            item.setNursePersonCode(Constants.NURSE_PERSON_CODE + generateSystemCodeUtil.generateSystemCode(Constants.NURSE_PERSON_CODE));
            NurseStationPerson stationPerson = new NurseStationPerson();
            BeanUtils.copyProperties(item, stationPerson);
            nurseStationPersonList.add(stationPerson);
        }
        int insertCount = nurseStationPersonMapper.insertNurseStationPersonImportList(nurseStationPersonList);
        if (insertCount <= 0) {
            throw new ServiceException("导入护理站人员信息失败，请联系管理员！");
        }
        //导入到用户表
        this.insertSysUser(subtractList);
        return AjaxResult.success();
    }

    /**
     * 审核接口根据id查询护理站人员信息以及未审核的证书
     *
     * @param id 护理站人员信息主键
     * @return 护理站人员信息
     */
    @Override
    public NurseStationPersonCheckDTO getNurseStationPersonCheck(Long id) {
        return nurseStationPersonMapper.getNurseStationPersonCheck(id);
    }

    /**
     * 管理端更新护理人员主表信息与证书信息
     *
     * @param nurseStationPersonCheckDTO 护理人员主表信息与证书信息
     * @return AjaxResult
     * @throws Exception 异常信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateNurseStationPersonChecks(NurseStationPersonCheckDTO nurseStationPersonCheckDTO) throws Exception {
        //已审核才能进行修改
        if (!StringUtils.equals(ModifyCheckStatusEnum.CHECKED.getInfo(), nurseStationPersonCheckDTO.getModifyCheckStatus())) {
            return AjaxResult.success();
        }
        //更新护理人员主表信息
        nurseStationPersonCheckDTO.setModifyInfoFlag(0);
        int personWorkStatusAndCheck = nurseStationPersonMapper.updateNurseStationPerson(nurseStationPersonCheckDTO);
        if (personWorkStatusAndCheck <= 0) {
            log.error("更新护理人员主表信息失败，请联系管理员！");
            throw new ServiceException("审核护理员信息失败，请联系管理员！");
        }
        //根据护理人员id去查询已审核证书表信息，nurse_station_person_certificate
        NurseStationPersonCertificate nurseStationPersonCertificate = new NurseStationPersonCertificate();
        nurseStationPersonCertificate.setNurseStationPersonId(nurseStationPersonCheckDTO.getId());
        List<NurseStationPersonCertificate> nurseStationPersonCertificates = nurseStationPersonCertificateMapper.selectNurseStationPersonCertificateList(nurseStationPersonCertificate);
        //根据护理人员id去查询待审核证书表信息，nurse_station_person_check
        NurseStationPersonCheck nurseStationPersonCheck = new NurseStationPersonCheck();
        nurseStationPersonCheck.setNurseStationPersonId(nurseStationPersonCheckDTO.getId());
        List<NurseStationPersonCheck> nurseStationPersonChecks = nurseStationPersonCheckMapper.selectNurseStationPersonCheckList(nurseStationPersonCheck);
        //刪除已审核与待审核证书表信息，并批量新增nurse_station_person_certificate表信息
        deleteCertificate(nurseStationPersonCheckDTO, nurseStationPersonCertificates, nurseStationPersonChecks);
        //将待审核文件信息复制到已审核文件路径下，并删除多余文件
        deleteCertificateFile(nurseStationPersonCertificates, nurseStationPersonChecks);
        return AjaxResult.success();
    }

    /**
     * 刪除已审核与待审核证书表信息，并批量新增nurse_station_person_certificate表信息
     *
     * @param nurseStationPersonCheckDTO     护理人员主表信息与证书信息
     * @param nurseStationPersonCertificates 已审核证书信息
     * @param nurseStationPersonChecks       待审核证书信息
     **/
    private void deleteCertificate(NurseStationPersonCheckDTO nurseStationPersonCheckDTO, List<NurseStationPersonCertificate> nurseStationPersonCertificates, List<NurseStationPersonCheck> nurseStationPersonChecks) throws IOException {
        //删除已审核证书表信息，nurse_station_person_certificate
        if (CollectionUtils.isNotEmpty(nurseStationPersonCertificates)) {
            Long[] longList = nurseStationPersonCertificates.stream().filter(Objects::nonNull).filter(check -> (Objects.nonNull(check.getId()))).map(NurseStationPersonCertificate::getId).toArray(Long[]::new);
            int deleteNurseStationPersonCertificates = nurseStationPersonCertificateMapper.deleteNurseStationPersonCertificateByIds(longList);
            if (deleteNurseStationPersonCertificates <= 0) {
                log.error("删除护理人员信息证书信息表失败，请联系管理员！");
                throw new ServiceException("审核护理员信息失败，请联系管理员！");
            }
        }
        //删除待审核证书表信息，nurse_station_person_check
        if (CollectionUtils.isNotEmpty(nurseStationPersonChecks)) {
            Long[] longList = nurseStationPersonChecks.stream().filter(Objects::nonNull).filter(check -> (Objects.nonNull(check.getId()))).map(NurseStationPersonCheck::getId).toArray(Long[]::new);
            int deleteNurseStationPersonCheckByIds = nurseStationPersonCheckMapper.deleteNurseStationPersonCheckByIds(longList);
            if (deleteNurseStationPersonCheckByIds <= 0) {
                log.error("删除护理人员信息修改审核信息表失败，请联系管理员！");
                throw new ServiceException("审核护理员信息失败，请联系管理员！");
            }
        }
        //将nurse_station_person_check表信息同步到nurse_station_person_certificate表中
        if (CollectionUtils.isNotEmpty(nurseStationPersonCheckDTO.getNurseStationPersonCheckList())) {
            List<NurseStationPersonCertificate> nurseStationPersonCertificateList = new ArrayList<>();
            nurseStationPersonCheckDTO.getNurseStationPersonCheckList().forEach(item -> {
                NurseStationPersonCertificate stationPersonCertificate = new NurseStationPersonCertificate();
                stationPersonCertificate.setNurseStationPersonId(item.getNurseStationPersonId());
                stationPersonCertificate.setCertificateName(StringUtils.isBlank(item.getCertificateName()) ? "" : item.getCertificateName());
                //人员信息证书表的地址
                String certificate = item.getCertificateUrl().replaceAll(xinELuConfig.getPersonCertificateCheckUrl(), xinELuConfig.getPersonCertificateUrl());
                stationPersonCertificate.setCertificateUrl(certificate);
                stationPersonCertificate.setCertificateCode(StringUtils.isBlank(item.getCertificateCode()) ? "" : item.getCertificateCode());
                stationPersonCertificate.setSort(Objects.isNull(item.getSort()) ? null : item.getSort());
                stationPersonCertificate.setCreateTime(LocalDateTime.now());
                nurseStationPersonCertificateList.add(stationPersonCertificate);
            });
            if (CollectionUtils.isNotEmpty(nurseStationPersonCertificateList)) {
                //批量新增nurse_station_person_certificate表信息
                int stationPersonCheckList = nurseStationPersonCertificateMapper.insertNurseStationPersonCertificateList(nurseStationPersonCertificateList);
                if (stationPersonCheckList <= 0) {
                    log.error("更新护理人员信息证书信息表失败，请联系管理员！");
                    throw new ServiceException("审核护理员信息失败，请联系管理员！");
                }
            }
        }
    }

    /**
     * 将待审核文件信息复制到已审核文件路径下，并删除多余文件
     *
     * @param nurseStationPersonCertificates 已审核证书信息
     * @param nurseStationPersonChecks       待审核证书信息
     **/
    private void deleteCertificateFile(List<NurseStationPersonCertificate> nurseStationPersonCertificates, List<NurseStationPersonCheck> nurseStationPersonChecks) throws IOException {
        //筛选已审核人员信息证书表的地址，例如：[1,2]
        List<String> certificateUrlList = nurseStationPersonCertificates.stream().filter(Objects::nonNull).map(NurseStationPersonCertificate::getCertificateUrl).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        //筛选出待审核人员信息证书表的地址，例如：[1,3]
        List<String> certificateCheckUrlList = nurseStationPersonChecks.stream().filter(Objects::nonNull).map(NurseStationPersonCheck::getCertificateUrl).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        //交集，筛选已审核表中已存在的并且未删除的证书路径，交集：[1]
        List<String> intersectionCertificateUrlList = new ArrayList<>(CollectionUtils.intersection(certificateUrlList, certificateCheckUrlList));
        //差集，筛选出需要删除的已审核路径下的文件地址，差集：[2]
        List<String> subtractCertificateList = new ArrayList<>(CollectionUtils.subtract(certificateUrlList, intersectionCertificateUrlList));
        //差集，筛选出需要删除的待审核路径下的文件地址，差集：[3]
        List<String> certificateCheckList = new ArrayList<>(CollectionUtils.subtract(certificateCheckUrlList, certificateUrlList));
        //删除已审核证书路径下图片信息
        if (subtractCertificateList.size() > 0) {
            for (String certificateUrl : subtractCertificateList) {
                com.xinelu.common.utils.file.FileUtils.deleteSystemFile(certificateUrl);
            }
        }
        //将待审核文件信息复制到已审核文件路径下，并且删除待审核的图片信息
        for (String certificateCheckUrl : certificateCheckList) {
            //待审核信息证书文件地址
            String certificateCheck = XinELuConfig.getProfile() + certificateCheckUrl.replaceAll("/profile", "");
            //已审核人员信息证书文件地址
            String certificate = certificateCheck.replaceAll(xinELuConfig.getPersonCertificateCheckUrl(), xinELuConfig.getPersonCertificateUrl());
            File certificateCheckFile = new File(certificateCheck);
            File certificateFile = new File(certificate);
            //存在则复制
            if (certificateCheckFile.exists()) {
                FileUtils.copyFile(certificateCheckFile, certificateFile);
            }
            //刪除待审核路径下证书图片
            com.xinelu.common.utils.file.FileUtils.deleteSystemFile(certificateCheckUrl);
        }
    }


    /**
     * 导入Sys_user表
     *
     * @param subtractList 手机号列表
     */
    private void insertSysUser(List<NurseStationPersonImportDTO> subtractList) {
        //获取护理人员的手机号集合
        List<String> personPhoneList = subtractList.stream().filter(item -> StringUtils.isNotBlank(item.getPhone())).map(NurseStationPersonImportDTO::getPhone).collect(Collectors.toList());
        //查询新增护理员信息
        List<SysUser> sysUsers = new ArrayList<>();
        List<NurseStationPersonVO> allNurseStationPerson = nurseStationPersonMapper.getAllNurseStationPersonIdByPhone(personPhoneList);
        //查询SysUser表信息
        List<NurseStationPersonVO> sysUserPhoneList = nurseStationPersonMapper.selectSysUserIdByPhone(personPhoneList);
        //做差集，剔除数据库中已经存在的人员信息
        List<NurseStationPersonVO> sysUserSubtractList = new ArrayList<>(CollectionUtils.subtract(allNurseStationPerson, sysUserPhoneList));
        if (CollectionUtils.isEmpty(sysUserSubtractList)) {
            return;
        }
        //新增用户信息
        for (NurseStationPersonVO stationPerson : sysUserSubtractList) {
            SysUser sysUser = new SysUser();
            String sex = StringUtils.isBlank(stationPerson.getSex()) ? "" : stationPerson.getSex();
            if (Constants.MALE.equals(sex)) {
                sysUser.setSex(Constants.SYS_USER_MALE);
            }
            if (Constants.FEMALE.equals(sex)) {
                sysUser.setSex(Constants.SYS_USER_FEMALE);
            }
            sysUser.setUserName(stationPerson.getNursePersonName());
            sysUser.setNickName(stationPerson.getNursePersonName());
            sysUser.setPhonenumber(stationPerson.getPhone());
            sysUser.setNurseStationPersonId(stationPerson.getId());
            sysUser.setPassword(SecurityUtils.encryptPassword(Constants.PASS_WORD));
            sysUser.setStationPersonPassword(Md5Utils.hash(Constants.PASS_WORD));
            sysUser.setDelFlag("0");
            sysUser.setStatus("0");
            sysUser.setNurseStationIds(Objects.isNull(stationPerson.getNurseStationId()) ? null : stationPerson.getNurseStationId().toString());
            sysUser.setCreateTime(DateUtils.getNowDate());
            sysUser.setCreateBy(SecurityUtils.getUsername());
            sysUsers.add(sysUser);
        }
        int insert = nurseStationPersonMapper.insertSysUserList(sysUsers);
        if (insert <= 0) {
            throw new ServiceException("导入用户信息失败，请联系管理员！");
        }
    }

    /**
     * 新增sys_user表信息
     *
     * @param object 参数
     */
    private void insertSysUserInfo(NurseStationPerson object) {
        NurseStationPersonSysUserVO nurseStationPersonSysUser = new NurseStationPersonSysUserVO();
        nurseStationPersonSysUser.setUserName(object.getPhone());
        nurseStationPersonSysUser.setPhonenumber(object.getPhone());
        nurseStationPersonSysUser.setNickName(object.getNursePersonName());
        if (object.getSex().equals(Constants.MALE)) {
            nurseStationPersonSysUser.setSex("0");
        } else {
            nurseStationPersonSysUser.setSex("1");
        }
        nurseStationPersonSysUser.setPassword(SecurityUtils.encryptPassword(Constants.PASS_WORD));
        nurseStationPersonSysUser.setStationPersonPassword(Md5Utils.hash((Constants.PASS_WORD)));
        nurseStationPersonSysUser.setStatus("0");
        nurseStationPersonSysUser.setDelFlag("0");
        nurseStationPersonSysUser.setCreateTime(LocalDateTime.now());
        nurseStationPersonSysUser.setCreateBy(SecurityUtils.getUsername());
        nurseStationPersonSysUser.setNurseStationIds(String.valueOf(object.getNurseStationId()));
        nurseStationPersonSysUser.setNurseStationPersonId(object.getId());
        int stationPersonSysUser = nurseStationPersonMapper.insertNurseStationPersonSysUser(nurseStationPersonSysUser);
        if (stationPersonSysUser <= 0) {
            throw new ServiceException("新增护理人员用户信息失败，请联系管理员！");
        }
        //新增角色信息
        SysRole sysRole = roleMapper.checkRoleKeyUnique(ROLE);
        if (Objects.nonNull(sysRole)) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(nurseStationPersonSysUser.getUserId());
            sysUserRole.setRoleId(sysRole.getRoleId());
            int userRole = userRoleMapper.insertSysUserRole(sysUserRole);
            if (userRole <= 0) {
                throw new ServiceException("新增角色信息失败，请联系管理员！");
            }
        }
    }

    /**
     * 修改护理人员证书
     *
     * @param nurseStationPerson 人员信息
     **/
    private void extracted(NurseStationPersonDTO nurseStationPerson) {
        //查询原有的证书信息
        List<NurseStationPersonCertificate> stationPersonCertificates = nurseStationPersonCertificateMapper.selectNurseStationPersonCertificateByIds(Collections.singletonList(nurseStationPerson.getId()));
        //删除原有证书信息
        if (CollectionUtils.isNotEmpty(stationPersonCertificates)) {
            Long[] longs = stationPersonCertificates.stream().filter(Objects::nonNull).filter(item -> Objects.nonNull(item.getId())).collect(Collectors.toList()).stream().map(NurseStationPersonCertificate::getId).toArray(Long[]::new);
            int deleteCount = nurseStationPersonCertificateMapper.deleteNurseStationPersonCertificateByIds(longs);
            if (deleteCount <= 0) {
                throw new ServiceException("修改护理人员证书信息失败，请联系管理员！");
            }
        }
        //页面传值
        List<NurseStationPersonCertificate> personCertificateListVO = nurseStationPerson.getNurseStationPersonCertificateList();
        //新增护理人员资质证书表
        if (CollectionUtils.isNotEmpty(personCertificateListVO)) {
            for (NurseStationPersonCertificate nurseStationPersonCertificate : personCertificateListVO) {
                nurseStationPersonCertificate.setNurseStationPersonId(nurseStationPerson.getId());
                nurseStationPersonCertificate.setUpdateTime(LocalDateTime.now());
                nurseStationPersonCertificate.setUpdateBy(SecurityUtils.getUsername());
                nurseStationPersonCertificate.setCertificateCode(Constants.PERSON_CERTIFICATE_CODE + generateSystemCodeUtil.generateSystemCode(Constants.PERSON_CERTIFICATE_CODE));
            }
            int hospitalPersonCertificates = nurseStationPersonCertificateMapper.insertNurseStationPersonCertificateList(nurseStationPerson.getNurseStationPersonCertificateList());
            if (hospitalPersonCertificates <= 0) {
                throw new ServiceException("修改护理人员资质证书信息失败，请联系管理员！");
            }
        }
        //删除护理人员的资质证书地址
        List<NurseStationPersonCertificate> deletePersonCertificateList = new ArrayList<>(CollectionUtils.subtract(stationPersonCertificates, personCertificateListVO));
        if (CollectionUtils.isNotEmpty(deletePersonCertificateList)) {
            List<String> certificateUrlList = deletePersonCertificateList.stream().filter(Objects::nonNull)
                    .filter(item -> (StringUtils.isNotBlank(item.getCertificateUrl())))
                    .map(NurseStationPersonCertificate::getCertificateUrl).collect(Collectors.toList());
            certificateUrlList.forEach(this::deletePictureUrl);
        }
    }


    /**
     * 修改sys_user表信息
     *
     * @param nurseStationPerson 前端输入参数
     * @param existStationPerson 数据库参数
     */
    private void updateSysUserInfo(NurseStationPerson nurseStationPerson, NurseStationPerson existStationPerson) {
        //根据手机号查询sysUser表中的id 判断是否存在
        NurseStationPersonSysUserVO sysUserAndPerson = nurseStationPersonMapper.getSysUserAndPerson(existStationPerson.getPhone());
        if (Objects.nonNull(sysUserAndPerson) && Objects.nonNull(sysUserAndPerson.getUserId())) {
            boolean existPhone = StringUtils.isNotBlank(nurseStationPerson.getPhone()) && StringUtils.isNotBlank(sysUserAndPerson.getPhonenumber()) && !sysUserAndPerson.getPhonenumber().equals(nurseStationPerson.getPhone());
            if (BooleanUtils.isTrue(existPhone)) {
                //根据手机号查询sysUser表的信息 是否重复
                int nurseStationUserCount = nurseStationPersonMapper.getNurseStationUserCount(nurseStationPerson.getPhone());
                if (nurseStationUserCount > 0) {
                    log.warn("修改当前护理员手机号信息在sys_user表中存在重复！");
                    throw new ServiceException("您输入的联系电话" + nurseStationPerson.getPhone() + "重复，请重新输入！");
                }
            }
            //修改sys_user表信息
            NurseStationPersonSysUserVO nurseStationPersonSysUser = new NurseStationPersonSysUserVO();
            nurseStationPersonSysUser.setUserName(nurseStationPerson.getPhone());
            nurseStationPersonSysUser.setPhonenumber(nurseStationPerson.getPhone());
            nurseStationPersonSysUser.setNickName(nurseStationPerson.getNursePersonName());
            if (nurseStationPerson.getSex().equals(Constants.MALE)) {
                nurseStationPersonSysUser.setSex("0");
            } else {
                nurseStationPersonSysUser.setSex("1");
            }
            nurseStationPersonSysUser.setUpdateTime(LocalDateTime.now());
            nurseStationPersonSysUser.setUpdateBy(SecurityUtils.getUsername());
            nurseStationPersonSysUser.setNurseStationIds(String.valueOf(nurseStationPerson.getNurseStationId()));
            nurseStationPersonSysUser.setNurseStationPersonId(nurseStationPerson.getId());
            nurseStationPersonSysUser.setUserId(sysUserAndPerson.getUserId());
            int stationPersonSysUser = nurseStationPersonMapper.updateNurseStationPersonSysUser(nurseStationPersonSysUser);
            if (stationPersonSysUser <= 0) {
                throw new ServiceException("修改护理人员用户信息失败，请联系管理员！");
            }
        }
    }

    /**
     * 删除图片地址
     *
     * @param pictureUrl 图片地址
     **/
    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("图片地址删除失败！");
            }
        }
    }
}