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

import com.xinelu.common.config.AppletPageConfig;
import com.xinelu.common.config.XinELuConfig;
import com.xinelu.common.constant.Constants;
import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.enums.NurseClassifyInfoEnum;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.AppletChatUtil;
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.FileUploadUtils;
import com.xinelu.common.utils.file.FileUtils;
import com.xinelu.common.utils.file.MimeTypeUtils;
import com.xinelu.common.utils.regex.RegexUtil;
import com.xinelu.manage.domain.nurseclassifyinfo.NurseClassifyInfo;
import com.xinelu.manage.domain.nursestation.NurseStation;
import com.xinelu.manage.domain.nursestationclassifyrelation.NurseStationClassifyRelation;
import com.xinelu.manage.domain.nursestationitem.NurseStationItem;
import com.xinelu.manage.domain.nursetype.NurseType;
import com.xinelu.manage.dto.nursestation.NurseStationDTO;
import com.xinelu.manage.dto.nursestation.NurseStationImportDTO;
import com.xinelu.manage.mapper.nursestation.NurseStationMapper;
import com.xinelu.manage.mapper.nursestationclassifyrelation.NurseStationClassifyRelationMapper;
import com.xinelu.manage.mapper.nursestationlabel.NurseStationLabelMapper;
import com.xinelu.manage.mapper.sysarea.SysAreaMapper;
import com.xinelu.manage.service.nursestation.INurseStationService;
import com.xinelu.manage.vo.nursestation.*;
import com.xinelu.manage.vo.sysarea.SysAreaVO;
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 org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 护理站信息Service业务层处理
 *
 * @author ljh
 * @date 2022-09-02
 */
@Service
public class NurseStationServiceImpl implements INurseStationService {
    @Resource
    private RegexUtil regexUtil;
    @Resource
    private NurseStationMapper nurseStationMapper;
    @Resource
    private NurseStationLabelMapper nurseStationLabelMapper;
    @Resource
    private GenerateSystemCodeUtil generateSystemCodeUtil;
    @Resource
    private XinELuConfig xinELuConfig;
    @Resource
    private SysAreaMapper sysAreaMapper;
    @Resource
    private NurseStationClassifyRelationMapper stationClassifyRelationMapper;
    @Resource
    private AppletPageConfig appletPageConfig;
    @Resource
    private XinELuConfig xinYiLuConfig;
    @Resource
    private AppletChatUtil appletChatUtil;

    /**
     * 护理站营业时间默认值
     */
    private static final String OPEN_TIME = "00:00:00";

    /**
     * 获取小程序二维码接口失败标识
     */
    private static final String FAIL = "FAIL";

    /**
     * 返回成功状态码
     */
    private static final int SUCCESS_CODE = 0;

    /**
     * 查询护理站信息
     *
     * @param id 护理站信息主键
     * @return 护理站信息
     */
    @Override
    public NurseStationAndAreaVO selectNurseStationById(Long id) {
        // 根据护理站id查询护理站所属护理机构
        NurseStationAndAreaVO nurseStation = nurseStationMapper.selectNurseStationById(id);
        //筛选护理站所属护理机构列表
        List<NurseClassifyInfo> nurseClassifyInfoList = nurseStation.getNurseClassifyInfoList().stream().filter(Objects::nonNull).filter(item -> StringUtils.isNotBlank(item.getClassifyType()) && item.getClassifyType().equals(NurseClassifyInfoEnum.NURSE_AGENCY.getInfo())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(nurseClassifyInfoList)) {
            nurseStation.setNurseClassifyInfoList(nurseClassifyInfoList);
        }
        //用逗号分割护理机构名称为字符串
        StringJoiner stringJoiner = new StringJoiner(",");
        nurseClassifyInfoList.forEach(s -> stringJoiner.add(s.getClassifyName()));
        String classifyNameList = stringJoiner.toString();
        //回显护理站所属护理机构的字符串
        nurseStation.setClassifyNameList(classifyNameList);
        if (StringUtils.isNotBlank(nurseStation.getAreaCode())) {
            SysAreaVO nurseStationAndAreaCode = sysAreaMapper.getSubordinateRegionsFindSuperiorRegions(nurseStation.getAreaCode());
            nurseStation.setProvinceCode(StringUtils.isBlank(nurseStationAndAreaCode.getProvinceCode()) ? "" : nurseStationAndAreaCode.getProvinceCode());
            nurseStation.setProvinceName(StringUtils.isBlank(nurseStationAndAreaCode.getProvinceName()) ? "" : nurseStationAndAreaCode.getProvinceName());
            nurseStation.setCityCode(StringUtils.isBlank(nurseStationAndAreaCode.getCityCode()) ? "" : nurseStationAndAreaCode.getCityCode());
            nurseStation.setCityName(StringUtils.isBlank(nurseStationAndAreaCode.getCityName()) ? "" : nurseStationAndAreaCode.getCityName());
            nurseStation.setRegionCode(StringUtils.isBlank(nurseStationAndAreaCode.getRegionCode()) ? "" : nurseStationAndAreaCode.getRegionCode());
            nurseStation.setRegionName(StringUtils.isBlank(nurseStationAndAreaCode.getRegionName()) ? "" : nurseStationAndAreaCode.getRegionName());
            nurseStation.setStreetCode(StringUtils.isBlank(nurseStationAndAreaCode.getStreetCode()) ? "" : nurseStationAndAreaCode.getStreetCode());
            nurseStation.setStreetName(StringUtils.isBlank(nurseStationAndAreaCode.getStreetName()) ? "" : nurseStationAndAreaCode.getStreetName());
        }
        return nurseStation;
    }

    /**
     * 查询护理站信息列表
     *
     * @param nurseStation 护理站信息
     * @return 护理站信息
     */
    @Override
    public List<NurseStationVO> selectNurseStationList(NurseStationVO nurseStation) {
        // 查询护理站的信息
        List<NurseStationVO> nurseStationList = nurseStationMapper.selectNurseStationList(nurseStation);
        //获取所有的护理站的区域编码
        List<String> areaCodeList = nurseStationList
                .stream().filter(Objects::nonNull)
                .map(NurseStationVO::getAreaCode)
                .filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(areaCodeList)) {
            return nurseStationList;
        }
        // 获取本护理站的区域信息
        List<SysAreaVO> nurseStationAreaByList = sysAreaMapper.getNurseStationAreaByList(areaCodeList);
        if (CollectionUtils.isEmpty(nurseStationAreaByList)) {
            return nurseStationList;
        }
        Map<String, SysAreaVO> collect = nurseStationAreaByList.stream().filter(item -> Objects.nonNull(item.getStreetCode())).collect(Collectors.toMap(SysAreaVO::getStreetCode, item -> item));
        nurseStationList.forEach(item -> {
            SysAreaVO orDefault = collect.getOrDefault(item.getAreaCode(), new SysAreaVO());
            item.setAreaName(orDefault.getProvinceName() + "-" + orDefault.getCityName() + "-" + orDefault.getRegionName() + "-" + orDefault.getStreetName());
        });
        return nurseStationList;
    }

    /**
     * 查询所有护理站列列表信息
     *
     * @param nurseStation 查询参数
     * @return 护理站列表信息
     */
    @Override
    public List<NurseStationByUserVO> selectNurseStationListByUser(NurseStation nurseStation) {
        return nurseStationMapper.selectNurseStationListByUser(nurseStation);
    }

    /**
     * 查询用户绑定的护理站列表信息
     *
     * @param nurseStationIdList 护理站id集合
     * @param nurseStation       查询参数
     * @return 护理站列表信息
     */
    @Override
    public List<NurseStationByUserVO> selectNurseStationListByIds(List<String> nurseStationIdList, NurseStation nurseStation) {
        //护理站名称
        String nurseStationName = StringUtils.isBlank(nurseStation.getNurseStationName()) ? "" : nurseStation.getNurseStationName();
        //护理站编码
        String nurseStationCode = StringUtils.isBlank(nurseStation.getNurseStationCode()) ? "" : nurseStation.getNurseStationCode();
        return nurseStationMapper.selectNurseStationListByIds(nurseStationIdList, nurseStationCode, nurseStationName);
    }

    /**
     * 新增护理站信息
     *
     * @param nurseStation 护理站信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertNurseStation(NurseStationDTO nurseStation) {
        //校验电话
        AjaxResult checkPhone = checkPhone(nurseStation);
        if (Objects.nonNull(checkPhone)) {
            return checkPhone;
        }
        //校验营业时间
        AjaxResult checkOpenTime = checkOpenTime(nurseStation);
        if (Objects.nonNull(checkOpenTime)) {
            return checkOpenTime;
        }
        // 查询判断护理站名称是否重复
        int nurseStationName = nurseStationMapper.getNurseStationName(nurseStation.getAreaCode(), nurseStation.getNurseStationName());
        if (nurseStationName > 0) {
            throw new ServiceException("此区域已有相同的护理站名称：" + nurseStation.getNurseStationName() + "，请重新输入！");
        }
        // 设置创建人与创建时间
        nurseStation.setUserId(SecurityUtils.getUserId());
        nurseStation.setCreateBy(SecurityUtils.getUsername());
        nurseStation.setCreateTime(LocalDateTime.now());
        //设置营业时间
        this.setBusinessHours(nurseStation);
        //护理站编码 生成有效唯一的编码
        nurseStation.setNurseStationCode(Constants.PATIENT_PREFIX + generateSystemCodeUtil.generateSystemCode(Constants.PATIENT_PREFIX));
        // 新增护理站信息
        int insertNurseStation = nurseStationMapper.insertNurseStation(nurseStation);
        if (insertNurseStation <= 0) {
            throw new ServiceException("新增护理站信息失败，请联系管理员！");
        }
        if (Objects.isNull(nurseStation.getId())) {
            throw new ServiceException("新增护理站信息失败，请联系管理员！");
        }
        // 新增护理站标签信息
        if (CollectionUtils.isEmpty(nurseStation.getNurseStationLabelList())) {
            return AjaxResult.success();
        }
        this.insertNurseStationLabelLists(nurseStation.getNurseStationLabelList(), nurseStation.getId());
        //新增护理机构分类关系表
        if (nurseStation.getNurseStationClassifyIds().length == 0 || nurseStation.getNurseStationClassifyIds() == null) {
            return AjaxResult.success();
        }
        this.insertNurseStationClassifyRelation(nurseStation.getNurseStationClassifyIds(), nurseStation.getId());
        return AjaxResult.success();
    }


    /**
     * 修改护理站信息
     *
     * @param nurseStation 护理站信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateNurseStation(NurseStationDTO nurseStation) {
        //校验电话
        AjaxResult checkPhone = checkPhone(nurseStation);
        if (Objects.nonNull(checkPhone)) {
            return checkPhone;
        }
        //校验营业时间
        AjaxResult checkOpenTime = checkOpenTime(nurseStation);
        if (Objects.nonNull(checkOpenTime)) {
            return checkOpenTime;
        }
        // 根据修改护理站的id查询所有信息
        NurseStationAndAreaVO station = nurseStationMapper.selectNurseStationById(nurseStation.getId());
        if (Objects.isNull(station)) {
            return AjaxResult.error("当前护理站信息不存在，无法修改，请联系管理员！");
        }
        boolean nurseName = (StringUtils.isNotBlank(station.getAreaCode()) && !nurseStation.getAreaCode().equals(station.getAreaCode()))
                || (StringUtils.isNotBlank(station.getNurseStationName()) && !nurseStation.getNurseStationName().equals(station.getNurseStationName()));
        if (nurseName) {
            int nurseStationName = nurseStationMapper.getNurseStationName(nurseStation.getAreaCode(), nurseStation.getNurseStationName());
            if (nurseStationName > 0) {
                throw new ServiceException("此区域已有相同的护理站名称：" + nurseStation.getNurseStationName() + "，请重新输入！");
            }
        }
        // 设置修改人人与修改时间
        nurseStation.setUpdateBy(SecurityUtils.getUsername());
        nurseStation.setUpdateTime(LocalDateTime.now());
        //设置营业时间
        this.setBusinessHours(nurseStation);
        // 修改护理站信息
        int insertNurseStation = nurseStationMapper.updateNurseStation(nurseStation);
        if (insertNurseStation <= 0) {
            throw new ServiceException("修改护理站信息失败，请联系管理员！");
        }
        if (Objects.isNull(nurseStation.getId())) {
            throw new ServiceException("修改护理站信息失败，请联系管理员！");
        }
        //全增全删护理站标签及护理机构分类
        this.updateStationLabelAndClassifyRelation(nurseStation);
        if (StringUtils.isNotBlank(nurseStation.getStationPictureUrl()) && StringUtils.isNotBlank(station.getStationPictureUrl()) && !nurseStation.getStationPictureUrl().equals(station.getStationPictureUrl())) {
            //删除护理站图片地址
            this.deletePictureUrl(station.getStationPictureUrl());
        }
        if (StringUtils.isNotBlank(nurseStation.getStationIntroducePictureUrl()) && StringUtils.isNotBlank(station.getStationIntroducePictureUrl()) && !nurseStation.getStationIntroducePictureUrl().equals(station.getStationIntroducePictureUrl())) {
            //删除护理站简介图片地址
            this.deletePictureUrl(station.getStationIntroducePictureUrl());
        }
        //删除护理站富文本图片
        this.deleteNurseStationPictureUrl(nurseStation, station);
        return AjaxResult.success();
    }

    /**
     * 批量删除护理站信息
     *
     * @param ids 需要删除的护理站信息主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult deleteNurseStationByIds(Long[] ids) {
        //根据护理站id查询
        List<NurseStationSysUserVO> nurseStationIds = nurseStationMapper.getNurseStationIds(Arrays.asList(ids));
        //获取护理站图片地址
        List<String> stationPictureUrlList = nurseStationIds.stream().filter(Objects::nonNull).filter(item -> StringUtils.isNotBlank(item.getStationPictureUrl())).map(NurseStationSysUserVO::getStationPictureUrl).distinct().collect(Collectors.toList());
        //获取护理站简介图片地址
        List<String> stationIntroducePictureUrlList = nurseStationIds.stream().filter(Objects::nonNull).filter(item -> StringUtils.isNotBlank(item.getStationIntroducePictureUrl())).map(NurseStationSysUserVO::getStationIntroducePictureUrl).distinct().collect(Collectors.toList());
        //获取护理站富文本的内容
        List<String> nurseStationAgencyIntroduceList = nurseStationIds.stream().filter(Objects::nonNull).filter(item -> StringUtils.isNotBlank(item.getAgencyIntroduce())).map(NurseStationSysUserVO::getAgencyIntroduce).distinct().collect(Collectors.toList());
        // 删除护理站信息
        int nurseStationByIds = nurseStationMapper.deleteNurseStationByIds(ids);
        if (nurseStationByIds <= 0) {
            throw new ServiceException("删除护理站信息失败!");
        }
        int stationLabelByIds = nurseStationMapper.selectNurseStationLabelByIds(ids);
        if (stationLabelByIds > 0) {
            int nurseStationLabelByIds = nurseStationMapper.deleteNurseStationLabelByIds(ids);
            if (nurseStationLabelByIds <= 0) {
                throw new ServiceException("删除护理站信息标签配置失败!");
            }
        }
        //删除护理机构所属分类关系表 - 查询护理机构所属分类关系是否存在
        int relationCount = stationClassifyRelationMapper.selectNurseStationClassifyRelationByStationIds(ids);
        if (relationCount > 0) {
            //删除关系表
            int deleteRelationCount = stationClassifyRelationMapper.deleteStationClassifyRelationByStationIds(ids);
            if (deleteRelationCount <= 0) {
                throw new ServiceException("删除护理机构所属分类关系失败!");
            }
        }
        //遍历删除护理站图片地址
        stationPictureUrlList.forEach(this::deletePictureUrl);
        //遍历删除护理站简介图片地址
        stationIntroducePictureUrlList.forEach(this::deletePictureUrl);
        //遍历删除护理站富文本图片地址
        for (String nurseStationAgencyIntroduce : nurseStationAgencyIntroduceList) {
            List<String> nurseStationImgSrc = FileUtils.getImgSrc(nurseStationAgencyIntroduce);
            for (String pictureUrl : nurseStationImgSrc) {
                if (StringUtils.isBlank(pictureUrl)) {
                    continue;
                }
                //修改路径
                String substring = pictureUrl.substring(pictureUrl.indexOf("/profile"));
                //删除商品富文本图片
                deletePictureUrl(substring);
            }
        }
        return AjaxResult.success();
    }

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


    /**
     * 根据护理项目编号查询护理站信息
     *
     * @param nurseItemCode 护理项目编号
     * @return com.xinelu.applet.domain.nursestationitem.NurseStationItem
     **/
    @Override
    public NurseStationItem getNurseItemCode(String nurseItemCode) {
        return nurseStationMapper.getNurseItemCode(nurseItemCode);
    }


    /**
     * 根据护理站编号查询所有信息
     *
     * @param nurseStationCode 护理站编号
     * @return com.xinelu.applet.domain.nursestation.NurseStation
     **/
    @Override
    public NurseStation getNurseStationCode(String nurseStationCode) {
        return nurseStationMapper.getNurseStationCode(nurseStationCode);
    }


    /**
     * 头像图片上传接口
     *
     * @param multipartFile 文件
     * @return com.xinelu.common.core.domain.AjaxResult
     **/
    @Override
    public AjaxResult updateNurseStationHeads(MultipartFile multipartFile, String type) throws Exception {
        //获取不同的文件路径
        String uploadPathUrl = "";
        switch (type) {
            //护理站图片路径上传
            case Constants.NURSE_STATION_TYPE:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getNurserStationPictureUrl();
                break;
            //护理站简介附近图片路径上传
            case Constants.NURSE_STATION_INTRODUCE_TYPE:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getNurserStationIntroducePictureUrl();
                break;
            //护理站项目图片路径上传
            case Constants.NURSE_STATION_ITEM_TYPE:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getNurserStationItemPictureUrl();
                break;
            //商品图片路径上传
            case Constants.GOODS_PICTURE_URL:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getGoodsPictureUrl();
                break;
            //用户头像上传
            case Constants.HEAD_PICTURE_URL:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getHeadPictureUrl();
                break;
            //商品属性图片地址
            case Constants.ATTRIBUTE_PICTURE_URL:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getAttributePitureUrl();
                break;
            //商品分类图片地址
            case Constants.GOODS_CATEGORY_PICTURE:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getGoodsCategoryPicture();
                break;
            //护理项目分类图标存放地址
            case Constants.NURSE_ITEM_CLASSIFY_URL:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getNurseItemClassifyUrl();
                break;
            //护理机构分类图片识别标识
            case Constants.NURSE_STATION_CLASSIFY_URL:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getNurseStationClassifyUrl();
                break;
            //海报图片存放路径地址
            case Constants.POSTER_PICTURE_URL:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getPosterPictureUrl();
                break;
            //资讯主缩略图地址
            case Constants.LEAD_THUMBNAIL_URL:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getLeadThumbnailUrl();
                break;
            //客服图片地址
            case Constants.GROUP_QR_CODE_URL:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getGroupQrCodeUrl();
                break;
            //科室人员证书图片存放路径
            case Constants.CERTIFICATE_URL:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getCertificateUrl();
                break;
            //健康咨询科室人员头像地址
            case Constants.PERSON_PICTURE_URL:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getPersonPictureUrl();
                break;
            //护理人员证书地址
            case Constants.PERSON_CERTIFICATE_URL:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getPersonCertificateUrl();
                break;
            case Constants.PLATELET_PICTURE_URL:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getPlateletPitureUrl();
                break;
            case Constants.LEFT_EYE_PICTURE_URL:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getLeftEyePitureUrl();
                break;
            case Constants.RIGHT_EYE_PICTURE_URL:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getRightEyePitureUrl();
                break;
            case Constants.ALZHEIMER_FILE_URL:
                uploadPathUrl = XinELuConfig.getProfile() + xinELuConfig.getAlzheimerFileUrl();
                break;
            default:
                break;
        }
        if (StringUtils.isBlank(uploadPathUrl)) {
            return AjaxResult.success();
        }
        //上传
        String pictureName = "";
        if (StringUtils.isNotBlank(type) && StringUtils.equals(type, Constants.ALZHEIMER_FILE_URL)) {
            pictureName = FileUploadUtils.uploadNurseStationPath(uploadPathUrl, multipartFile, MimeTypeUtils.FILE_EXTENSION);
        } else {
            pictureName = FileUploadUtils.uploadNurseStationPath(uploadPathUrl, multipartFile, MimeTypeUtils.IMAGE_EXTENSION);
        }

        if (StringUtils.isBlank(pictureName)) {
            throw new ServiceException("图片上传失败，请联系管理员！");
        }
        AjaxResult ajax = AjaxResult.success("上传成功！");
        ajax.put("imgUrl", pictureName);
        return ajax;
    }


    /**
     * 护理站信息导入
     *
     * @param nurseStation 护理站信息
     * @return 导入结果
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertNurseStationImportList(List<NurseStationImportDTO> nurseStation) {
        //判断添加的数据是否为空
        if (CollectionUtils.isEmpty(nurseStation)) {
            return AjaxResult.error("请添加护理站导入信息！");
        }
        //根据护理站名称做去除处理
        List<NurseStationImportDTO> importDataList = nurseStation.stream().filter(item -> StringUtils.isNotBlank(item.getNurseStationName())).distinct().collect(Collectors.toList());
        //校验联系电话格式是否正确
        NurseStationImportDTO dto = importDataList.stream().filter(item -> StringUtils.isNotBlank(item.getPhone())).filter(item -> BooleanUtils.isFalse(regexUtil.regexPhone(item.getPhone()))).findFirst().orElse(new NurseStationImportDTO());
        if (StringUtils.isNotBlank(dto.getPhone())) {
            return AjaxResult.error("当前护理站电话：" + dto.getPhone() + " 格式不正确，请重新录入！");
        }
        //校验负责人联系电话格式是否正确
        NurseStationImportDTO dtoTwo = importDataList.stream().filter(item -> StringUtils.isNotBlank(item.getDutyPhone())).filter(item -> BooleanUtils.isFalse(regexUtil.regexPhone(item.getDutyPhone()))).findFirst().orElse(new NurseStationImportDTO());
        if (StringUtils.isNotBlank(dtoTwo.getDutyPhone())) {
            return AjaxResult.error("当前负责人电话：" + dtoTwo.getDutyPhone() + " 格式不正确，请重新录入！");
        }
        List<String> nurseStationNames = importDataList.stream().filter(item -> StringUtils.isNotBlank(item.getNurseStationName())).map(NurseStationImportDTO::getNurseStationName).distinct().collect(Collectors.toList());
        //根据名称查询护理站基本信息
        List<NurseStationImportDTO> allNurseStationInfo = nurseStationMapper.getAllNurseStationInfo(nurseStationNames);
        //做差集，去除数据库中已经存在的护理站信息
        List<NurseStationImportDTO> subtractList = new ArrayList<>(CollectionUtils.subtract(importDataList, allNurseStationInfo));
        if (CollectionUtils.isEmpty(subtractList)) {
            return AjaxResult.success();
        }
        List<NurseStation> nurseStationList = new ArrayList<>();
        for (NurseStationImportDTO item : subtractList) {
            item.setUserId(SecurityUtils.getUserId());
            item.setCreateTime(LocalDateTime.now());
            item.setNurseStationCode(Constants.PATIENT_PREFIX + generateSystemCodeUtil.generateSystemCode(Constants.PATIENT_PREFIX));
            NurseStation nurseStations = new NurseStation();
            BeanUtils.copyProperties(item, nurseStations);
            nurseStationList.add(nurseStations);
        }
        int insertCount = nurseStationMapper.insertNurseStationImportList(nurseStationList);
        if (insertCount <= 0) {
            throw new ServiceException("导入护理站信息失败，请联系管理员！");
        }
        return AjaxResult.success();
    }

    /**
     * 获取字典中的护理类型编码
     *
     * @param nurseStation 护理站字典信息
     * @return com.xinelu.applet.vo.nursestation.NurseStationVO
     **/
    @Override
    public List<NurseStationVO> getSysDictNurseTypeCode(NurseStationVO nurseStation) {
        return nurseStationMapper.getSysDictNurseTypeCode(nurseStation);
    }

    /**
     * 根据护理站类型编码查询护理站类型名称
     *
     * @param nurseTypeCode 护理站类型编码
     * @return java.util.List<com.xinelu.applet.domain.nursetype.NurseType>
     **/
    @Override
    public AjaxResult getNurseStationType(String nurseTypeCode) {
        // 得到的编码如果是多个进行分割
        List<String> nurseTypeCodeList = Arrays.asList(StringUtils.split(nurseTypeCode, ","));
        // 去重 查询值
        List<NurseType> nurseStationType = nurseStationMapper.getNurseStationType(nurseTypeCodeList).stream().distinct().collect(Collectors.toList());
        return AjaxResult.success(nurseStationType);
    }


    /**
     * 根据用户id查询护理站
     *
     * @param sysUser 用户信息
     * @return java.util.List<com.xinelu.applet.domain.nursestation.NurseStation>
     **/
    @Override
    public AjaxResult getNurseStationByUserId(NurseStationSysUserVO sysUser) {
        sysUser.setUserId(SecurityUtils.getUserId());
        NurseStationSysUserVO nurseStationByUserId = nurseStationMapper.getNurseStationByUserId(sysUser);

        String nurseStationIds = nurseStationByUserId.getNurseStationIds();
        List<String> nurseTypeCodeList = Arrays.asList(StringUtils.split(nurseStationIds, ","));
        //List<String> 转 List<Long>
        List<Long> cdids = nurseTypeCodeList.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        List<NurseStationSysUserVO> stationIds = nurseStationMapper.getNurseStationIds(cdids).stream().distinct().collect(Collectors.toList());
        return AjaxResult.success(stationIds);
    }

    /**
     * 根据护理站id查询护理站信息是否存在
     *
     * @param idList 护理站信息主键
     * @return 护理站信息
     */
    @Override
    public int getNurseStationById(List<Long> idList) {
        return nurseStationMapper.getNurseStationCount(idList);
    }

    /**
     * 护理站生成二维码
     *
     * @param nurseStationId 护理站id
     * @return 邀请码图片地址
     */
    @Override
    public AjaxResult nurseStationCode(Long nurseStationId) {
        //获取微信小程序AccessToken的值
        NurseStation nurseStationById = nurseStationMapper.getNurseStationById(nurseStationId);
        if (Objects.isNull(nurseStationById)) {
            return AjaxResult.error("当前护理机构信息不存在，请联系管理员！");
        }
        if (StringUtils.isBlank(nurseStationById.getStationWechatCodeUrl())) {
            String fileName = String.valueOf(System.nanoTime()) + nurseStationId + ".png";
            //小程序跳转路径
            String appletPageUrl = appletPageConfig.getNurseStationDetailsPageUrl();
            //机构二维码存放路径
            String filePathWeChatCodeUrl = xinYiLuConfig.getStationWechatCodeUrl();
            String appletCodePicture = appletChatUtil.createAppletCode(nurseStationId, false, fileName, appletPageUrl, filePathWeChatCodeUrl);
            if (StringUtils.isNotBlank(appletCodePicture) && StringUtils.equals(FAIL, appletCodePicture)) {
                //第一次调用获取小程序二维码信息失败，重新递归调用一次，第二次失败直接返回提示信息
                appletCodePicture = appletChatUtil.createAppletCode(nurseStationId, true, fileName, appletPageUrl, filePathWeChatCodeUrl);
                if (StringUtils.isNotBlank(appletCodePicture) && StringUtils.equals(FAIL, appletCodePicture)) {
                    return AjaxResult.error("获取小程序二维码信息失败，请联系管理员！");
                }
            }
            String pictureUrl = "";
            if (StringUtils.isNotBlank(appletCodePicture)) {
                pictureUrl = "/profile" + xinYiLuConfig.getStationWechatCodeUrl() + "/" + nurseStationId + "/" + fileName;
                int updateCount = nurseStationMapper.updateStationWeChatCodeUrl(nurseStationId, pictureUrl);
                if (updateCount <= 0) {
                    throw new ServiceException("生成机构二维码失败，请联系管理员！");
                }
            }
            return AjaxResult.success(pictureUrl);
        }
        //直接返回二维码图片信息
        return AjaxResult.success(nurseStationById.getStationWechatCodeUrl());
    }


    /**
     * 新增护理站标签信息
     *
     * @param nurseStationLabels 护理站标签集合
     * @param nurseStationId     护理站id
     **/
    private void insertNurseStationLabelLists(List<NurseStationLabelVO> nurseStationLabels, Long nurseStationId) {
        // 判断护理站标签信息是否为空
        for (NurseStationLabelVO nurseStationLabel : nurseStationLabels) {
            //判断项目成绩级别是否为空
            nurseStationLabel.setNurseStationId(nurseStationId);
            nurseStationLabel.setCreateBy(SecurityUtils.getUsername());
            nurseStationLabel.setCreateTime(LocalDateTime.now());
            // 护理站标签编码 生成有效唯一的编码
            nurseStationLabel.setLabelCode(Constants.LABEL_CODE + generateSystemCodeUtil.generateSystemCode(Constants.LABEL_CODE));
            nurseStationLabel.setUserId(SecurityUtils.getUserId());
        }
        // 新增护理站标签信息
        int nurseStationLabel = nurseStationLabelMapper.insertBatchNurseStationLabel(nurseStationLabels);
        if (nurseStationLabel <= 0) {
            throw new ServiceException("新增护理站标签信息失败，请联系管理员！");
        }
    }

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

    /**
     * 删除护理站图片地址
     *
     * @param pictureUrl 护理站图片地址
     * @return void 护理站图片地址
     **/
    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 nurseStationClassifyIds 护理机构ids
     * @param stationId               护理站id
     */
    private void insertNurseStationClassifyRelation(Long[] nurseStationClassifyIds, Long stationId) {
        List<NurseStationClassifyRelation> nurseStationClassifyRelations = new ArrayList<>();
        //遍历塞值
        for (Long nurseStationClassifyId : nurseStationClassifyIds) {
            NurseStationClassifyRelation stationClassifyRelation = new NurseStationClassifyRelation();
            stationClassifyRelation.setNurseStationId(stationId);
            stationClassifyRelation.setNurseClassifyId(nurseStationClassifyId);
            stationClassifyRelation.setCreateBy(SecurityUtils.getUsername());
            stationClassifyRelation.setCreateTime(LocalDateTime.now());
            nurseStationClassifyRelations.add(stationClassifyRelation);
        }
        //新增护理机构分类关系表
        int insertCount = stationClassifyRelationMapper.insertNurseStationClassifyRelationList(nurseStationClassifyRelations);
        if (insertCount <= 0) {
            throw new ServiceException("护理机构类型新增失败,请联系管理员！");
        }
    }

    /**
     * 全增全删护理站标签及护理机构分类
     *
     * @param nurseStation 护理站修改信息
     */
    private void updateStationLabelAndClassifyRelation(NurseStationDTO nurseStation) {
        //删除护理站标签信息
        int nurseStationLabelStationId = nurseStationLabelMapper.getNurseStationLabelStationId(nurseStation.getId());
        if (nurseStationLabelStationId > 0) {
            int deleteNurseStationLabelStationId = nurseStationLabelMapper.deleteNurseStationLabelStationId(nurseStation.getId());
            if (deleteNurseStationLabelStationId <= 0) {
                throw new ServiceException("删除护理站标签信息失败");
            }
        }
        //修改护理站标签信息
        if (CollectionUtils.isNotEmpty(nurseStation.getNurseStationLabelList())) {
            this.insertNurseStationLabelLists(nurseStation.getNurseStationLabelList(), nurseStation.getId());
        }
        //删除护理机构所属分类关系表
        int count = stationClassifyRelationMapper.selectNurseStationClassifyRelationByStationId(nurseStation.getId());
        if (count > 0) {
            int deleteCount = stationClassifyRelationMapper.deleteStationClassifyRelationByStationId(nurseStation.getId());
            if (deleteCount <= 0) {
                throw new ServiceException("删除护理机构所属分类关系失败");
            }
        }
        //重新增加护理机构所属分类关系表
        if (nurseStation.getNurseStationClassifyIds() != null && nurseStation.getNurseStationClassifyIds().length != 0) {
            this.insertNurseStationClassifyRelation(nurseStation.getNurseStationClassifyIds(), nurseStation.getId());
        }
    }

    /**
     * 校验护理站营业时间
     *
     * @param nurseStation 输入参数
     * @return 校验结果
     */
    private AjaxResult checkOpenTime(NurseStationDTO nurseStation) {
        if (StringUtils.isBlank(nurseStation.getMorningOpenStartTimeStr())
                || StringUtils.isBlank(nurseStation.getMorningOpenEndTimeStr())
                || OPEN_TIME.equals(nurseStation.getMorningOpenStartTimeStr())
                || OPEN_TIME.equals(nurseStation.getMorningOpenEndTimeStr())) {
            return AjaxResult.error("上午营业时间不能为空！");
        }
        if (StringUtils.isBlank(nurseStation.getAfternoonOpenStartTimeStr())
                || StringUtils.isBlank(nurseStation.getAfternoonOpenEndTimeStr())
                || OPEN_TIME.equals(nurseStation.getAfternoonOpenStartTimeStr())
                || OPEN_TIME.equals(nurseStation.getAfternoonOpenEndTimeStr())) {
            return AjaxResult.error("下午营业时间不能为空！");
        }
        //格式化日期
        LocalTime morningStartTime = LocalTime.parse(DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.parse(nurseStation.getMorningOpenStartTimeStr())));
        LocalTime morningEndTime = LocalTime.parse(DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.parse(nurseStation.getMorningOpenEndTimeStr())));
        LocalTime afterStartTime = LocalTime.parse(DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.parse(nurseStation.getAfternoonOpenStartTimeStr())));
        LocalTime afterEndTime = LocalTime.parse(DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.parse(nurseStation.getAfternoonOpenEndTimeStr())));
        if (morningStartTime.isAfter(morningEndTime) || morningStartTime.equals(morningEndTime)) {
            return AjaxResult.error("上午营业开始时间不能大于等于上午营业结束时间！");
        }
        if (afterStartTime.isAfter(afterEndTime) || afterStartTime.equals(afterEndTime)) {
            return AjaxResult.error("下午营业开始时间不能大于等于下午营业结束时间！");
        }
        if (morningEndTime.isAfter(afterStartTime)) {
            return AjaxResult.error("上午营业结束时间不能大于下午营业开始时间！");
        }
        return null;
    }

    /**
     * 校点电话
     *
     * @param nurseStation 输入参数
     * @return 结果
     */
    private AjaxResult checkPhone(NurseStationDTO nurseStation) {
        if (StringUtils.isNotBlank(nurseStation.getPhone())) {
            // 校验手机号是否正确
            boolean phone = regexUtil.regexSeatNumber(nurseStation.getPhone());
            if (BooleanUtils.isFalse(phone)) {
                return AjaxResult.error("您输入的联系电话" + nurseStation.getPhone() + "不正确，请重新输入！");
            }
        }
        if (StringUtils.isNotBlank(nurseStation.getDutyPhone())) {
            // 校验负责人手机号是否正确
            boolean dutyPhone = regexUtil.regexSeatNumber(nurseStation.getDutyPhone());
            if (BooleanUtils.isFalse(dutyPhone)) {
                return AjaxResult.error("您输入的联系电话" + nurseStation.getDutyPhone() + "不正确，请重新输入！");
            }
        }
        return null;
    }

    /**
     * 设置营业时间
     *
     * @param nurseStation 护理站信息
     */
    private void setBusinessHours(NurseStationDTO nurseStation) {
        //格式化日期
        LocalTime morningStartTime = LocalTime.parse(DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.parse(nurseStation.getMorningOpenStartTimeStr())));
        LocalTime morningEndTime = LocalTime.parse(DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.parse(nurseStation.getMorningOpenEndTimeStr())));
        LocalTime afterStartTime = LocalTime.parse(DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.parse(nurseStation.getAfternoonOpenStartTimeStr())));
        LocalTime afterEndTime = LocalTime.parse(DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.parse(nurseStation.getAfternoonOpenEndTimeStr())));
        //塞值
        nurseStation.setMorningOpenStartTime(morningStartTime);
        nurseStation.setMorningOpenEndTime(morningEndTime);
        nurseStation.setAfternoonOpenStartTime(afterStartTime);
        nurseStation.setAfternoonOpenEndTime(afterEndTime);
    }
}
