package org.dromara.business.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.Synchronized;
import org.dromara.business.domain.CaseBaseInfo;
import org.dromara.business.domain.CaseOssFile;
import org.dromara.business.domain.bo.CaseBaseInfoBo;
import org.dromara.business.domain.vo.CaseBaseInfoVo;
import org.dromara.business.domain.vo.CaseBeatifyNotice;
import org.dromara.business.domain.vo.CaseUserVo;
import org.dromara.business.domain.vo.UserCaseInfoVo;
import org.dromara.business.mapper.CaseBaseInfoMapper;
import org.dromara.business.service.ICaseBaseInfoService;
import org.dromara.common.core.constant.CaseConstants;
import org.dromara.common.core.constant.TenantConstants;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.domain.SysTenant;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.vo.SysTenantVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SysTenantMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 病例基础信息Service业务层处理
 *
 * @author wuzhigang
 * @date 2023-11-27
 */
@RequiredArgsConstructor
@Service
public class CaseBaseInfoServiceImpl implements ICaseBaseInfoService {

    private final CaseBaseInfoMapper baseMapper;
    private final SysUserMapper userMapper;
    private final SysTenantMapper tenantMapper;

    @Value("${login.address.user}")
    private String userLoginAddress;

    /**
     * 查询病例基础信息
     */
    @Override
    public CaseBaseInfoVo queryById(Long id) {
        CaseBaseInfoVo vo = baseMapper.selectVoById(id);
        // 获取病例归属用户信息
        SysUserVo sysUserVo = userMapper.selectUserById(vo.getUserId());
        // 获取点评专家用户信息
        if (vo.getCommentUserId() != null) {
            SysUserVo commentUser = userMapper.selectUserById(vo.getCommentUserId());
            vo.setCommentUseName(commentUser.getNickName());
            vo.setCommentUseCompany(commentUser.getOrganizationName());
            // 职称不为空
            if (StringUtils.isNotBlank(commentUser.getTitle())) {
                if (commentUser.getTitle().equals(UserConstants.TITLE_ONE_KEY)) {
                    vo.setCommentUseTitle(UserConstants.TITLE_ONE_VALUE);
                } else if (commentUser.getTitle().equals(UserConstants.TITLE_TWO_KEY)) {
                    vo.setCommentUseTitle(UserConstants.TITLE_TWO_VALUE);
                } else if (commentUser.getTitle().equals(UserConstants.TITLE_THREE_KEY)) {
                    vo.setCommentUseTitle(UserConstants.TITLE_THREE_VALUE);
                } else if (commentUser.getTitle().equals(UserConstants.TITLE_FOUR_KEY)) {
                    vo.setCommentUseTitle(UserConstants.TITLE_FOUR_VALUE);
                }
            }
        }
        vo.setUserName(sysUserVo.getNickName());
        if (StringUtils.isNotBlank(vo.getCaseFile())) {
            // json字符串转病例文件对象
            vo.setCaseFileList(JSONUtil.toList(vo.getCaseFile(), CaseOssFile.class));
        }

        if (StringUtils.isNotBlank(vo.getCaseBeautifyFile())) {
            // json字符串转病例美化文件对象
            vo.setCaseBeautifyFileList(JSONUtil.toList(vo.getCaseBeautifyFile(), CaseOssFile.class));
        }

        return vo;
    }

    /**
     * 查询病例基础信息列表
     */
    @Override
    public TableDataInfo<CaseBaseInfoVo> queryPageList(CaseBaseInfoBo bo, PageQuery pageQuery) {

        // 构建查询条件
        LambdaQueryWrapper<CaseBaseInfo> caseLqw = buildQueryWrapper(bo);
        // 排序
        caseLqw.orderByDesc(CaseBaseInfo::getCreateTime);
        Page<CaseBaseInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), caseLqw);
        // 分页数据列表
        List<CaseBaseInfoVo> voList = result.getRecords();

        if (voList.size() > 0) {
            // 病例所属人用户ID列表
            List<Long> userIdList = voList.stream().map(CaseBaseInfoVo::getUserId).collect(Collectors.toList());
            // 病例上传用户ID列表
            List<Long> uploadUserIdList = voList.stream().map(CaseBaseInfoVo::getUploadUserId).collect(Collectors.toList());
            // 病例点评用户ID列表
            List<Long> commentUserIdList = voList.stream().map(CaseBaseInfoVo::getCommentUserId).collect(Collectors.toList());

            // 合并多个list并去重
            List<Long> allList = Stream.of(userIdList, uploadUserIdList, commentUserIdList)
                .flatMap(List::stream)
                .distinct()
                .collect(Collectors.toList());

            // 获取用户名称
            LambdaQueryWrapper<SysUser> userLqw = Wrappers.lambdaQuery();
            userLqw.in(SysUser::getUserId, allList);
            List<SysUser> userList = userMapper.selectList(userLqw);

            // 抽取userId,nickName组成Map
            Map<Long, String> nameMap = userList.stream()
                .collect(Collectors.toMap(SysUser::getUserId, SysUser::getNickName));

            for (CaseBaseInfoVo vo : voList
            ) {

                if (StringUtils.isNotBlank(vo.getCaseFile())) {
                    // json字符串转病例文件对象
                    vo.setCaseFileList(JSONUtil.toList(vo.getCaseFile(), CaseOssFile.class));
                }

                if (StringUtils.isNotBlank(vo.getCaseBeautifyFile())) {
                    // json字符串转病例美化文件对象
                    vo.setCaseBeautifyFileList(JSONUtil.toList(vo.getCaseBeautifyFile(), CaseOssFile.class));
                }

                if (vo.getUserId() != null) {
                    vo.setUserName(nameMap.get(vo.getUserId()));
                }
                if (vo.getUploadUserId() != null) {
                    vo.setUploadUserName(nameMap.get(vo.getUploadUserId()));
                }
                if (vo.getCommentUserId() != null) {
                    vo.setCommentUseName(nameMap.get(vo.getCommentUserId()));
                }
            }
            result.setRecords(voList);
        }

        return TableDataInfo.build(result);
    }

    /**
     * 查询病例基础信息列表
     */
    @Override
    public List<CaseBaseInfoVo> queryList(CaseBaseInfoBo bo) {
        LambdaQueryWrapper<CaseBaseInfo> lqw = buildQueryWrapper(bo);
        // 排序
        lqw.orderByDesc(CaseBaseInfo::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CaseBaseInfo> buildQueryWrapper(CaseBaseInfoBo bo) {
        Map<String, Object> params = bo.getParams();

        LambdaQueryWrapper<CaseBaseInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, CaseBaseInfo::getUserId, bo.getUserId());
        if (StringUtils.isNotBlank(bo.getUserIds()) && bo.getUserIds() != null) {
            String[] userIds = bo.getUserIds().split(",");
            lqw.in(StringUtils.isNotBlank(bo.getUserIds()), CaseBaseInfo::getUserId, userIds);
        }
        lqw.eq(StringUtils.isNotBlank(bo.getTenantId()), CaseBaseInfo::getTenantId, bo.getTenantId());
        lqw.eq(bo.getUploadUserId() != null, CaseBaseInfo::getUploadUserId, bo.getUploadUserId());
        lqw.like(StringUtils.isNotBlank(bo.getProjectName()), CaseBaseInfo::getProjectName, bo.getProjectName());
        lqw.like(StringUtils.isNotBlank(bo.getCaseName()), CaseBaseInfo::getCaseName, bo.getCaseName());
        lqw.eq(StringUtils.isNotBlank(bo.getCheckStatus()), CaseBaseInfo::getCheckStatus, bo.getCheckStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getCaseDescription()), CaseBaseInfo::getCaseDescription, bo.getCaseDescription());
        lqw.eq(StringUtils.isNotBlank(bo.getBeautifyStatus()), CaseBaseInfo::getBeautifyStatus, bo.getBeautifyStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getUploadType()), CaseBaseInfo::getUploadType, bo.getUploadType());
        lqw.eq(bo.getCommentUserId() != null, CaseBaseInfo::getCommentUserId, bo.getCommentUserId());
        if (StringUtils.isNotBlank(bo.getCommentUserIds()) && bo.getCommentUserIds() != null) {
            String[] commentUserIds = bo.getCommentUserIds().split(",");
            lqw.in(StringUtils.isNotBlank(bo.getCommentUserIds()), CaseBaseInfo::getCommentUserId, commentUserIds);
        }
        return lqw;
    }

    private Wrapper<CaseBaseInfo> buildQueryWrapperOld(CaseBaseInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<CaseBaseInfo> wrapper = Wrappers.query();
        if (StringUtils.isNotBlank(bo.getUserIds()) && bo.getUserIds() != null) {
            String[] userIds = bo.getUserIds().split(",");
            wrapper.in(StringUtils.isNotBlank(bo.getUserIds()), "t.user_id", userIds);
        }
        if (StringUtils.isNotBlank(bo.getCommentUserIds()) && bo.getCommentUserIds() != null) {
            String[] commentUserIds = bo.getCommentUserIds().split(",");
            wrapper.in(StringUtils.isNotBlank(bo.getCommentUserIds()), "t.comment_user_id", commentUserIds);
        }
        wrapper.eq("t.del_flag", "0")
            .eq(bo.getUserId() != null, "t.user_id", bo.getUserId())
            .eq(bo.getCommentUserId() != null, "t.comment_user_id", bo.getCommentUserId())
            .like(ObjectUtil.isNotNull(bo.getCaseName()), "t.case_name", bo.getCaseName())
            .eq(StringUtils.isNotBlank(bo.getCheckStatus()), "t.check_status", bo.getCheckStatus())
            .eq(StringUtils.isNotBlank(bo.getCommentStatus()), "t.comment_status", bo.getCommentStatus())
            .eq(StringUtils.isNotBlank(bo.getCommentAuditStatus()), "t.comment_audit_status", bo.getCommentAuditStatus())
            .eq(StringUtils.isNotBlank(bo.getCaseAnalysisStatus()), "t.case_analysis_status", bo.getCaseAnalysisStatus());
        return wrapper;
    }

    /**
     * 新增病例基础信息
     */
    @Override
    @Synchronized
    public Boolean insertByBo(CaseBaseInfoBo bo) {
        // 获取已有病例
        List<CaseBaseInfo> caseList = baseMapper.selectList();
        // 获取病例编码列表
        List<String> caseIdList = caseList.stream().map(CaseBaseInfo::getCaseId).collect(Collectors.toList());

        // 生成新编号
        String caseId = "";
        for (int i = 1; i < 100000; i++) {
            // 编号补0
            String countStr = String.format("%05d", i);
            // 生成病例编号
            caseId = "H0UID" + DateUtil.format(new DateTime(), "yyyyMMddHHmmss") + countStr;
            // 已有编号不包含新编号，跳出循环
            if (!caseIdList.contains(caseId)) {
                bo.setCaseId(caseId);
                break;
            }
        }
        // 上传用户ID
        bo.setUploadUserId(LoginHelper.getUserId());
        CaseBaseInfo add = MapstructUtils.convert(bo, CaseBaseInfo.class);
        if (bo.getCaseFileList() != null && bo.getCaseFileList().size() > 0) {
            // 病例文件列表转json字符串
            String jsonStr = JSONUtil.toJsonStr(bo.getCaseFileList());
            add.setCaseFile(jsonStr);
        }
        // 美化状态
        add.setBeautifyStatus(CaseConstants.NO_BEAUTIFY_STATUS);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改病例基础信息
     */
    @Override
    public Boolean updateByBo(CaseBaseInfoBo bo) {
        CaseBaseInfo update = MapstructUtils.convert(bo, CaseBaseInfo.class);
        if (bo.getCaseFileList() != null && bo.getCaseFileList().size() > 0) {
            // 病例文件列表转json字符串
            String jsonStr = JSONUtil.toJsonStr(bo.getCaseFileList());
            update.setCaseFile(jsonStr);
        }
        if (bo.getCaseBeautifyFileList() != null && bo.getCaseBeautifyFileList().size() > 0) {
            // 病例美化文件列表转json字符串
            String BeautifyJsonStr = JSONUtil.toJsonStr(bo.getCaseBeautifyFileList());
            update.setCaseBeautifyFile(BeautifyJsonStr);
            // 已美化
            update.setBeautifyStatus(CaseConstants.BEAUTIFY_STATUS);
            // 美化未下载
            update.setBeautifyFileDownload("0");
        } else {
            // 未美化
            update.setBeautifyStatus(CaseConstants.NO_BEAUTIFY_STATUS);
        }

        // 病例审核
        if (StringUtils.isNotBlank(bo.getCheckStatus())) {
            update.setCheckTime(DateTime.now());
            // 审核通过
            if (bo.getCheckStatus().equals(CaseConstants.CASE_PASS)) {
                // 获取当前租户信息
                SysTenantVo vo = tenantMapper.selectVoOne(new LambdaQueryWrapper<SysTenant>().eq(SysTenant::getTenantId, TenantHelper.getTenantId()));
                // 租户点评开启
                if (TenantConstants.CASE_COMMENT_OPEN.equals(vo.getCaseComment())) {
                    //待点评
                    update.setCommentStatus(CaseConstants.NO_COMMENT);
                    // 自动分配
                    if (TenantConstants.CASE_COMMENT_DISTRIBUTION_AUTOMATIC.equals(vo.getCaseCommentDistribution())) {
                        // 按规则获取分配专家
                        SysUser user = baseMapper.commentDistributionExpert();
                        if (user != null) {
                            // 分配点评专家
                            update.setCommentUserId(user.getUserId());
                        }
                    }
                }
            }

        }
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CaseBaseInfo entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除病例基础信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 修改病例状态
     *
     * @param bo
     */
    @Override
    public int updateCaseStatus(CaseBaseInfoBo bo) {
        CaseBaseInfo caseBaseInfo = MapstructUtils.convert(bo, CaseBaseInfo.class);
        return baseMapper.updateById(caseBaseInfo);
    }

    /**
     * 根据用户ID获取用户病例信息列表
     *
     * @param doctorUserId
     * @param volunteerUserId
     * @return
     */
    @Override
    public UserCaseInfoVo selectCaseListByUserId(Long doctorUserId, Long volunteerUserId) {

        // 构建查询条件
        LambdaQueryWrapper<CaseBaseInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(doctorUserId != null, CaseBaseInfo::getUserId, doctorUserId);
        lqw.eq(volunteerUserId != null, CaseBaseInfo::getUploadUserId, volunteerUserId);
        // 正常状态
        lqw.eq(CaseBaseInfo::getCaseStatus, CaseConstants.CASE_NORMAL);
        // 创建时间降序
        lqw.orderByDesc(CaseBaseInfo::getCreateTime);
        UserCaseInfoVo userCaseInfoVo = new UserCaseInfoVo();

        // 全部数据列表
        List<CaseBaseInfoVo> voList = baseMapper.selectVoList(lqw);


        if (voList.size() > 0) {
            // 病例所属人用户ID列表
            List<Long> userIdList = voList.stream().map(CaseBaseInfoVo::getUserId).collect(Collectors.toList());
            // 病例上传用户ID列表
            List<Long> uploadUserIdList = voList.stream().map(CaseBaseInfoVo::getUploadUserId).collect(Collectors.toList());
            // 病例点评用户ID列表
            List<Long> commentUserIdList = voList.stream().map(CaseBaseInfoVo::getCommentUserId).collect(Collectors.toList());

            // 合并多个list并去重
            List<Long> allList = Stream.of(userIdList, uploadUserIdList, commentUserIdList)
                .flatMap(List::stream)
                .distinct()
                .collect(Collectors.toList());

            // 获取用户名称
            LambdaQueryWrapper<SysUser> userLqw = Wrappers.lambdaQuery();
            userLqw.in(SysUser::getUserId, allList);
            List<SysUser> userList = userMapper.selectList(userLqw);

            // 抽取userId,nickName组成Map
            Map<Long, String> nameMap = userList.stream()
                .collect(Collectors.toMap(SysUser::getUserId, SysUser::getNickName));

            for (CaseBaseInfoVo vo : voList
            ) {

                if (StringUtils.isNotBlank(vo.getCaseFile())) {
                    // json字符串转病例文件对象
                    vo.setCaseFileList(JSONUtil.toList(vo.getCaseFile(), CaseOssFile.class));
                }

                if (StringUtils.isNotBlank(vo.getCaseBeautifyFile())) {
                    // json字符串转病例美化文件对象
                    vo.setCaseBeautifyFileList(JSONUtil.toList(vo.getCaseBeautifyFile(), CaseOssFile.class));
                }

                if (vo.getUserId() != null) {
                    vo.setUserName(nameMap.get(vo.getUserId()));
                }
                if (vo.getUploadUserId() != null) {
                    vo.setUploadUserName(nameMap.get(vo.getUploadUserId()));
                }
                if (vo.getCommentUserId() != null) {
                    vo.setCommentUseName(nameMap.get(vo.getCommentUserId()));
                }
            }
        }

        // 审核通过数量
        long passTotal = voList.stream().filter(vo -> vo.getCheckStatus().equals(CaseConstants.CASE_PASS)).count();

        // 审核不通过数量
        long noPassTotal = voList.stream().filter(vo -> vo.getCheckStatus().equals(CaseConstants.CASE_NO_PASS)).count();

        userCaseInfoVo.setCaseList(voList);
        userCaseInfoVo.setTotal(voList.size());
        userCaseInfoVo.setPassTotal(passTotal);
        userCaseInfoVo.setNoPassTotal(noPassTotal);

        return userCaseInfoVo;
    }

    /**
     * 获取医生用户列表
     *
     * @return
     */
    @Override
    public List<CaseUserVo> doctorList() {

        LambdaQueryWrapper<SysUser> lqw = Wrappers.lambdaQuery();
        // 医生
        lqw.eq(SysUser::getLoginIdentity, UserConstants.LOGIN_IDENTITY_DOCTOR);
        lqw.orderByAsc(SysUser::getUserId);
        // 医生用户列表
        List<SysUser> userList = userMapper.selectList(lqw);
        List<CaseUserVo> caseUserVoList = new ArrayList<>();
        for (SysUser user : userList
        ) {
            CaseUserVo caseUserVo = new CaseUserVo();
            // 用户Id
            caseUserVo.setUserId(user.getUserId());
            // 用户姓名
            caseUserVo.setUserName(user.getNickName());

            caseUserVoList.add(caseUserVo);
        }

        return caseUserVoList;
    }

    /**
     * 获取专家用户分配列表
     *
     * @return
     */
    @Override
    public List<CaseUserVo> expertList() {

        LambdaQueryWrapper<SysUser> lqw = Wrappers.lambdaQuery();
        // 专家
        lqw.eq(SysUser::getLoginIdentity, UserConstants.LOGIN_IDENTITY_EXPERT);
        lqw.orderByAsc(SysUser::getUserId);
        // 专家用户列表
        List<SysUser> userList = userMapper.selectList(lqw);
        List<CaseUserVo> caseUserVoList = new ArrayList<>();
        for (SysUser user : userList
        ) {
            CaseUserVo caseUserVo = new CaseUserVo();
            // 用户Id
            caseUserVo.setUserId(user.getUserId());
            // 用户姓名
            caseUserVo.setUserName(user.getNickName());

            caseUserVoList.add(caseUserVo);
        }

        return caseUserVoList;
    }

    /**
     * 获取专家用户下拉列表
     *
     * @return
     */
    @Override
    public List<CaseUserVo> expertSelectList() {

        QueryWrapper<SysUser> wrapper = Wrappers.query();
        wrapper.eq("u.login_identity", UserConstants.LOGIN_IDENTITY_EXPERT);
        // 专家用户列表
        List<SysUserVo> userList = userMapper.selectUserList(wrapper);
        List<CaseUserVo> caseUserVoList = new ArrayList<>();
        for (SysUserVo user : userList
        ) {
            CaseUserVo caseUserVo = new CaseUserVo();
            // 用户Id
            caseUserVo.setUserId(user.getUserId());
            // 用户姓名
            caseUserVo.setUserName(user.getNickName());

            caseUserVoList.add(caseUserVo);
        }

        return caseUserVoList;
    }

    /**
     * 获取志愿者用户列表
     *
     * @return
     */
    @Override
    public List<CaseUserVo> volunteerList() {
        LambdaQueryWrapper<SysUser> lqw = Wrappers.lambdaQuery();
        // 志愿者
        lqw.eq(SysUser::getLoginIdentity, UserConstants.LOGIN_IDENTITY_VOLUNTEER);
        lqw.orderByAsc(SysUser::getUserId);
        // 医生用户列表
        List<SysUser> userList = userMapper.selectList(lqw);
        List<CaseUserVo> caseUserVoList = new ArrayList<>();
        for (SysUser user : userList
        ) {
            CaseUserVo caseUserVo = new CaseUserVo();
            // 用户Id
            caseUserVo.setUserId(user.getUserId());
            // 用户姓名
            caseUserVo.setUserName(user.getNickName());

            caseUserVoList.add(caseUserVo);
        }

        return caseUserVoList;
    }

    /**
     * 查询病例审核列表
     *
     * @param bo
     * @param pageQuery
     */
    @Override
    public TableDataInfo<CaseBaseInfoVo> queryCheckPageList(CaseBaseInfoBo bo, PageQuery pageQuery) {
        // 构建查询条件
        Wrapper<CaseBaseInfo> caseCheckLqw = buildQueryWrapperOld(bo);

        // 获取当前租户信息
        SysTenantVo sysTenantVo = tenantMapper.selectVoOne(new LambdaQueryWrapper<SysTenant>().eq(SysTenant::getTenantId, TenantHelper.getTenantId()));

        Page<CaseBaseInfoVo> result = new Page<>();

        // 病例审核开启
        if (sysTenantVo.getCaseReview().equals(TenantConstants.CASE_REVIEW_OPEN)) {
            result = baseMapper.queryCheckPageList(pageQuery.build(), caseCheckLqw);
            // 分页数据列表
            List<CaseBaseInfoVo> voList = result.getRecords();

            if (voList.size() > 0) {

                for (CaseBaseInfoVo vo : voList
                ) {

                    if (StringUtils.isNotBlank(vo.getCaseFile())) {
                        // json字符串转病例文件对象
                        vo.setCaseFileList(JSONUtil.toList(vo.getCaseFile(), CaseOssFile.class));
                    }

                    if (StringUtils.isNotBlank(vo.getCaseBeautifyFile())) {
                        // json字符串转病例美化文件对象
                        vo.setCaseBeautifyFileList(JSONUtil.toList(vo.getCaseBeautifyFile(), CaseOssFile.class));
                    }

                }
                result.setRecords(voList);
            }
        }

        return TableDataInfo.build(result);
    }

    /**
     * 获取病例数据中审核状态
     *
     * @return
     */
    @Override
    public List<String> selectCaseReviewStatus() {
        return baseMapper.selectCaseReviewStatus();
    }

    /**
     * 查询病例点评列表
     *
     * @param bo
     * @param pageQuery
     */
    @Override
    public TableDataInfo<CaseBaseInfoVo> queryCommentList(CaseBaseInfoBo bo, PageQuery pageQuery) {

        // 超管和租户管理员看全部点评数据
        if (!LoginHelper.isSuperAdmin() && !LoginHelper.isTenantAdmin()) {
            // 登录用户信息
            SysUserVo sysUserVo = userMapper.selectUserById(LoginHelper.getUserId());

            // 用户身份为专家
            if (sysUserVo.getLoginIdentity().equals(UserConstants.LOGIN_IDENTITY_EXPERT)) {
                // 当前用户只能看到分配给自己的病例
                bo.setCommentUserId(LoginHelper.getUserId());
            }


        }

        // 构建查询条件
        Wrapper<CaseBaseInfo> caseCommentLqw = buildQueryWrapperOld(bo);

        Page<CaseBaseInfoVo> result = baseMapper.queryCommentPageList(pageQuery.build(), caseCommentLqw);

        // 分页数据列表
        List<CaseBaseInfoVo> voList = result.getRecords();

        if (voList.size() > 0) {

            for (CaseBaseInfoVo vo : voList
            ) {

                if (StringUtils.isNotBlank(vo.getCaseFile())) {
                    // json字符串转病例文件对象
                    vo.setCaseFileList(JSONUtil.toList(vo.getCaseFile(), CaseOssFile.class));
                }

                if (StringUtils.isNotBlank(vo.getCaseBeautifyFile())) {
                    // json字符串转病例美化文件对象
                    vo.setCaseBeautifyFileList(JSONUtil.toList(vo.getCaseBeautifyFile(), CaseOssFile.class));
                }

            }
            result.setRecords(voList);
        }

        return TableDataInfo.build(result);
    }

    /**
     * 点评专家分配
     *
     * @param bo
     * @return
     */
    @Override
    public int expertAllocation(CaseBaseInfoBo bo) {
        CaseBaseInfo update = MapstructUtils.convert(bo, CaseBaseInfo.class);

        return baseMapper.updateById(update);
    }

    /**
     * 专家点评
     *
     * @param bo
     * @return
     */
    @Override
    public boolean comment(CaseBaseInfoBo bo) {
        CaseBaseInfo update = MapstructUtils.convert(bo, CaseBaseInfo.class);
        // 点评
        if (StringUtils.isNotBlank(bo.getCommentContent())) {
            CaseBaseInfo caseBaseInfo = baseMapper.selectById(bo.getId());
            // 未分配点评人
            if (caseBaseInfo.getCommentUserId() == null) {
                // 点评人ID
                update.setCommentUserId(LoginHelper.getUserId());
            }

            // 点评时间
            update.setCommentTime(DateTime.now());
            // 已点评状态
            update.setCommentStatus(CaseConstants.COMMENTED);
            // 点评审核状态 -未审核
            update.setCommentAuditStatus(CaseConstants.COMMNET_UNCHECK);
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 查询病例点评审核列表
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<CaseBaseInfoVo> queryCommentAuditList(CaseBaseInfoBo bo, PageQuery pageQuery) {
        // 构建查询条件
        Wrapper<CaseBaseInfo> caseCommentLqw = buildQueryWrapperOld(bo);

        Page<CaseBaseInfoVo> result = baseMapper.queryCommentAuditList(pageQuery.build(), caseCommentLqw);
        // 分页数据列表
        List<CaseBaseInfoVo> voList = result.getRecords();

        if (voList.size() > 0) {

            for (CaseBaseInfoVo vo : voList
            ) {

                if (StringUtils.isNotBlank(vo.getCaseFile())) {
                    // json字符串转病例文件对象
                    vo.setCaseFileList(JSONUtil.toList(vo.getCaseFile(), CaseOssFile.class));
                }

                if (StringUtils.isNotBlank(vo.getCaseBeautifyFile())) {
                    // json字符串转病例美化文件对象
                    vo.setCaseBeautifyFileList(JSONUtil.toList(vo.getCaseBeautifyFile(), CaseOssFile.class));
                }

            }
            result.setRecords(voList);
        }

        return TableDataInfo.build(result);
    }

    /**
     * 专家点评审核
     *
     * @param bo
     * @return
     */
    @Override
    public int commentAudit(CaseBaseInfoBo bo) {
        CaseBaseInfo update = MapstructUtils.convert(bo, CaseBaseInfo.class);
        // 点评审核未通过
        if (bo.getCommentAuditStatus().equals(CaseConstants.COMMNET_NO_PASS)) {
            // 点评状态变更-重新点评
            update.setCommentStatus(CaseConstants.RECOMMENT);
        }
        return baseMapper.updateById(update);
    }

    /**
     * 病例解析审核分页列表查询
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<CaseBaseInfoVo> queryAnalysisList(CaseBaseInfoBo bo, PageQuery pageQuery) {
        // 构建查询条件
        Wrapper<CaseBaseInfo> caseAnalysisLqw = buildQueryWrapperOld(bo);

        Page<CaseBaseInfoVo> result = baseMapper.queryAnalysisList(pageQuery.build(), caseAnalysisLqw);
        // 分页数据列表
        List<CaseBaseInfoVo> voList = result.getRecords();

        if (voList.size() > 0) {

            for (CaseBaseInfoVo vo : voList
            ) {

                if (StringUtils.isNotBlank(vo.getCaseFile())) {
                    // json字符串转病例文件对象
                    vo.setCaseFileList(JSONUtil.toList(vo.getCaseFile(), CaseOssFile.class));
                }

                if (StringUtils.isNotBlank(vo.getCaseBeautifyFile())) {
                    // json字符串转病例美化文件对象
                    vo.setCaseBeautifyFileList(JSONUtil.toList(vo.getCaseBeautifyFile(), CaseOssFile.class));
                }

            }
            result.setRecords(voList);
        }

        return TableDataInfo.build(result);
    }

    /**
     * 病例解析审核
     *
     * @param bo
     * @return
     */
    @Transactional
    @Override
    public int analysisAudit(CaseBaseInfoBo bo) {

        CaseBaseInfo update = MapstructUtils.convert(bo, CaseBaseInfo.class);
        // 申请解析
        if (update.getCaseAnalysisStatus().equals("0")) {
            // 登录用户信息
            SysUser sysUser = userMapper.selectById(LoginHelper.getUserId());
            if (sysUser.getCaseAnalysisTimes() == 0) {
                throw new ServiceException("权限不足");
            }
            // 解析次数更新
            Integer caseAnalysisTimes = sysUser.getCaseAnalysisTimes() - 1;
            sysUser.setCaseAnalysisTimes(caseAnalysisTimes);
            userMapper.updateById(sysUser);
        }
        return baseMapper.updateById(update);
    }

    /**
     * 根据志愿者userIds查询志愿者上传病例列表
     *
     * @param volunteerUserIds
     * @param userId
     * @return
     */
    @Override
    public List<CaseBaseInfoVo> selectCaseListByVolunteerUserIds(List<Long> volunteerUserIds, Long userId) {
        // 构建查询条件
        LambdaQueryWrapper<CaseBaseInfo> lqw = Wrappers.lambdaQuery();
        lqw.in(CaseBaseInfo::getUploadUserId, volunteerUserIds);
        lqw.eq(CaseBaseInfo::getUserId, userId);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据医生userIds查询志愿者上传病例列表
     *
     * @param doctorUserIds
     * @param volunteerUserId
     * @return
     */
    @Override
    public List<CaseBaseInfoVo> selectCaseListByDoctorUserIds(List<Long> doctorUserIds, Long volunteerUserId) {
        // 构建查询条件
        LambdaQueryWrapper<CaseBaseInfo> lqw = Wrappers.lambdaQuery();
        // 志愿者
        lqw.eq(CaseBaseInfo::getUploadUserId, volunteerUserId);
        // 绑定医生列表
        lqw.in(CaseBaseInfo::getUserId, doctorUserIds);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 获取病例数据中点评审核状态
     *
     * @return
     */
    @Override
    public List<String> commentAuditStatus() {
        return baseMapper.commentAuditStatus();
    }

    /**
     * 获取病例数据中解析审核状态
     *
     * @return
     */
    @Override
    public List<String> caseAnalysisStatus() {
        return baseMapper.caseAnalysisStatus();
    }

    /**
     * 获取病例数据中点评状态
     *
     * @return
     */
    @Override
    public List<String> commentStatus() {
        return baseMapper.commentStatus();
    }

    /**
     * 点评自动分配专家
     *
     * @return
     */
    @Override
    public SysUser commentDistributionExpert() {
        return baseMapper.commentDistributionExpert();
    }

    /**
     * 下载病例美化文件状态记录
     *
     * @param bo
     * @return
     */
    @Override
    public int beautifyDownloadStatus(CaseBaseInfoBo bo) {
        CaseBaseInfo update = MapstructUtils.convert(bo, CaseBaseInfo.class);

        return baseMapper.updateById(update);
    }

    /**
     * 获取病例美化通知信息
     *
     * @param id
     * @return
     */
    @Override
    public CaseBeatifyNotice caseBeatifyNotice(Long id) {
        // 病例信息
        CaseBaseInfo caseBaseInfo = baseMapper.selectById(id);
        // 获取病例归属用户信息
        SysUserVo sysUserVo = userMapper.selectUserById(caseBaseInfo.getUserId());

        // 构建查询条件
        LambdaQueryWrapper<CaseBaseInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(CaseBaseInfo::getProjectName, caseBaseInfo.getProjectName());
        // 项目病例列表
        List<CaseBaseInfoVo> caseList = baseMapper.selectVoList(lqw);
        // 已美化病例列表
        List<CaseBaseInfoVo> beatifyCaseList = caseList.stream().filter(o -> o.getBeautifyStatus().equals(CaseConstants.BEAUTIFY_STATUS)).collect(Collectors.toList());

        // 租户移动端地址
        String appAccessPath = userLoginAddress + "pages/phone/detail/index?id=" + id + "&tenantId=" + caseBaseInfo.getTenantId();

        // 租户移动端地址
        String pcAccessPath = userLoginAddress + "pages/pc/index/index?id=" + id + "&tenantId=" + caseBaseInfo.getTenantId();

        CaseBeatifyNotice caseBeatifyNotice = new CaseBeatifyNotice();
        // 项目
        caseBeatifyNotice.setProjectName(caseBaseInfo.getProjectName());
        // 病例医生ID
        caseBeatifyNotice.setUserId(sysUserVo.getUserId());
        // 病例医生姓名
        caseBeatifyNotice.setUserName(sysUserVo.getNickName());
        // 病例数量
        caseBeatifyNotice.setCaseNumber(caseList.size());
        // 美化病例数量
        caseBeatifyNotice.setBeatifyCaseNumber(beatifyCaseList.size());
        // 手机下载地址
        caseBeatifyNotice.setAppUrl(appAccessPath);
        // 电脑下载地址
        caseBeatifyNotice.setPcUrl(pcAccessPath);
        // 美化下载状态
        caseBeatifyNotice.setBeautifyFileDownload(caseBaseInfo.getBeautifyFileDownload());

        return caseBeatifyNotice;
    }


}
