package com.diagbot.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.diagbot.dto.CheckDeptDTO;
import com.diagbot.dto.CheckMedoupDTO;
import com.diagbot.dto.DeptCheckUserDTO;
import com.diagbot.entity.*;
import com.diagbot.enums.CheckJobTypeEnum;
import com.diagbot.enums.CheckTypeEnum;
import com.diagbot.enums.CheckerRoleEnum;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.MedExamineInfoServiceImpl;
import com.diagbot.util.DateUtil;
import com.diagbot.util.ListUtil;
import com.diagbot.util.SysUserUtils;
import com.diagbot.vo.BehospitalcodeVO;
import com.diagbot.vo.MedCheckInfoAddVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * @author wangfeng
 * @Description:
 * @time: 2024-07-06 13:27
 */
@Component
public class MedExamineInfoFacade extends MedExamineInfoServiceImpl {

    @Autowired
    SysUserFacade sysUserFacade;
    @Autowired
    MedExamineInfoFacade medExamineInfoFacade;

    public boolean passAudit(BehospitalcodeVO behospitalcodeVO) {
        Long hospitalId = Long.parseLong(SysUserUtils.getCurrentHospitalID());
        Long userId = Long.parseLong(SysUserUtils.getCurrentPrincipleID());

        //获取判断是否有审核
        QueryWrapper<MedExamineInfo> medExamineInfoQueryWrapper = new QueryWrapper<>();
        medExamineInfoQueryWrapper.eq("behospital_code", behospitalcodeVO.getBehospitalCode());
        medExamineInfoQueryWrapper.eq("hospital_id", hospitalId);
//        medCheckInfoQueryWrapper.eq("check_id", userId);
//        medCheckInfoQueryWrapper.eq("check_type", CheckTypeEnum.ALL.getKey());
        MedExamineInfo medExamineInfo = medExamineInfoFacade.getOne(medExamineInfoQueryWrapper);
        SysUser user = sysUserFacade.getOne(new QueryWrapper<SysUser>()
                .eq("id", userId)
                .eq("is_deleted", IsDeleteEnum.N.getKey()));
        if (medExamineInfo == null) {
            MedExamineInfo insertCheckInfo = new MedExamineInfo();
            insertCheckInfo.setBehospitalCode(behospitalcodeVO.getBehospitalCode());
            insertCheckInfo.setCheckId(userId);
            if (user != null) {
                insertCheckInfo.setCheckName(user.getLinkman());
            }
            insertCheckInfo.setAction(CheckTypeEnum.PASSED.getKey());
            insertCheckInfo.setHospitalId(hospitalId);
            insertCheckInfo.setStatus(1);
            insertCheckInfo.setCheckTime(DateUtil.now());
            return medExamineInfoFacade.save(insertCheckInfo);
        }

        medExamineInfo.setCheckId(userId);
        if (user != null) {
            medExamineInfo.setCheckName(user.getLinkman());
        }
        medExamineInfo.setStatus(1);
        medExamineInfo.setCheckTime(DateUtil.now());
        medExamineInfoFacade.updateById(medExamineInfo);

        return true;
    }

    /**
     * @param medCheckInfoAddVO
     * @return
     */
    public Boolean addMedCheckInfos(MedCheckInfoAddVO medCheckInfoAddVO) {
        boolean res = false;
        Date now = DateUtil.now();
        //获取人员id 和 该人员的医院id
        Long hospitalId = Long.valueOf(SysUserUtils.getCurrentHospitalID());
        Long principleId = Long.valueOf(SysUserUtils.getCurrentPrincipleID());
        QueryWrapper<SysUser> userQuer = new QueryWrapper<>();
        userQuer.eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("id", principleId)
                .eq("status", 1);
        SysUser user = sysUserFacade.getOne(userQuer);
        String principleName = user.getLinkman();
        Map<String, Object> mapAll = new HashMap<String, Object>();
        mapAll.put("is_deleted", IsDeleteEnum.N.getKey());
        mapAll.put("behospital_code", medCheckInfoAddVO.getBehospitalCode());
        mapAll.put("hospital_id", hospitalId);
        mapAll.put("check_type", medCheckInfoAddVO.getCheckType());
        QueryWrapper<MedExamineInfo> medCheckInfoQuerys = new QueryWrapper<>();
        medCheckInfoQuerys.allEq(mapAll);
        MedExamineInfo data = this.getOne(medCheckInfoQuerys, false);
        if (data != null) {
            //检验核查人是否是本人
            if (data.getCheckId().equals(principleId)) {
                res = saveNew(mapAll, now, hospitalId, principleId, principleName, medCheckInfoAddVO);
            } else {
                throw new CommonException(CommonErrorCode.NOT_EXISTS, "该数据已被人核查，您暂无权限！");
            }
        } else {
            //该病历没有核查的时候， 就添加核查记录
            MedExamineInfo medCheckInfo = new MedExamineInfo();
            medCheckInfo.setGmtCreate(now);
            medCheckInfo.setGmtModified(now);
            medCheckInfo.setHospitalId(hospitalId);
            medCheckInfo.setCheckId(principleId);
            medCheckInfo.setCheckName(principleName);
            medCheckInfo.setCheckTime(now);
            medCheckInfo.setAction(medCheckInfoAddVO.getCheckType());
            medCheckInfo.setStatus(medCheckInfoAddVO.getCheckStatus());
            medCheckInfo.setBehospitalCode(medCheckInfoAddVO.getBehospitalCode());
            res = this.save(medCheckInfo);
        }

        return res;
    }

    /**
     * @param mapAll
     * @param now
     * @param hospitalId
     * @param principleId
     * @param principleName
     * @param medCheckInfoAddVO
     * @return
     */
    public boolean saveNew(Map<String, Object> mapAll, Date now, Long hospitalId, Long principleId, String principleName, MedCheckInfoAddVO medCheckInfoAddVO) {
        boolean res = false;
        UpdateWrapper<MedExamineInfo> medCheckInfoUpdate = new UpdateWrapper<>();
        medCheckInfoUpdate.allEq(mapAll).set("is_deleted", IsDeleteEnum.Y.getKey()).set("gmt_modified", now);
        res = this.update(medCheckInfoUpdate);
        //删除原来的成功后， 再新建一条核查数据
        if (res) {
            MedExamineInfo medCheckInfo = new MedExamineInfo();
            medCheckInfo.setGmtCreate(now);
            medCheckInfo.setGmtModified(now);
            medCheckInfo.setHospitalId(hospitalId);
            medCheckInfo.setCheckId(principleId);
            medCheckInfo.setCheckName(principleName);
            medCheckInfo.setCheckTime(now);
            medCheckInfo.setAction(medCheckInfoAddVO.getCheckType());
            medCheckInfo.setStatus(medCheckInfoAddVO.getCheckStatus());
            medCheckInfo.setBehospitalCode(medCheckInfoAddVO.getBehospitalCode());
            res = this.save(medCheckInfo);
        }
        return res;
    }

    /**
     * @Author songxl
     * @Description 院区人员用户科室合并
     * @time: 2024/6/1
     * @Param [checkRoleMap, checkUserDTOS, s]
     * @Return void
     * @MethodName margeDept
     */
    private void margeDept(Map<String, List<CheckDeptDTO>> checkRoleMap, List<DeptCheckUserDTO> checkUserDTOS, String roleId) {
        if (ListUtil.isEmpty(checkUserDTOS)) {
            return;
        }
        Set<String> userIds = checkUserDTOS.stream().map(DeptCheckUserDTO::getDoctorId).collect(Collectors.toSet());
        try {
            List<CheckDeptDTO> tempDepts = new ArrayList<>();
            //全部
            CheckDeptDTO allCheckDept = new CheckDeptDTO();
            allCheckDept.setDeptId("-1");
            allCheckDept.setDeptName("全部");
            userIds.stream().forEach(userId -> {
                //获取该用户的科室拼接
                StringBuilder deptIdBuilder = new StringBuilder();
                StringBuilder deptNameBuilder = new StringBuilder();
                StringBuilder userName = new StringBuilder();
                checkUserDTOS.stream().forEach(checkUserDTO -> {
                    if (userId.equals(checkUserDTO.getDoctorId())) {
                        deptIdBuilder.append(checkUserDTO.getDeptId()).append(",");
                        deptNameBuilder.append(checkUserDTO.getDeptName()).append(",");
                        if (userName.length() == 0) {
                            userName.append(checkUserDTO.getDoctorName());
                        }
                        //除了全部以外添加科室信息
                        if (!tempDepts.stream().map(CheckDeptDTO::getDeptId).collect(Collectors.toList())
                                .contains(checkUserDTO.getDeptId())) {
                            CheckDeptDTO oneCheckUser = new CheckDeptDTO();
                            oneCheckUser.setDeptId(checkUserDTO.getDeptId());
                            oneCheckUser.setDeptName(checkUserDTO.getDeptName());
                            tempDepts.add(oneCheckUser);
                        }
                    }
                });

                //合并科室
                String deptId = deptIdBuilder.substring(0, deptIdBuilder.length() - 1);
                String deptName = deptNameBuilder.substring(0, deptNameBuilder.length() - 1);
                //科室用户
                DeptCheckUserDTO deptCheckUserDTO = new DeptCheckUserDTO();
                deptCheckUserDTO.setDoctorId(userId);
                deptCheckUserDTO.setDoctorName(userName.toString());
                deptCheckUserDTO.setDeptId(deptId);
                deptCheckUserDTO.setDeptName(deptName);
                AtomicBoolean hasFlag = new AtomicBoolean(false);
                //全部处理
//                if (ListUtil.isEmpty(allCheckDept.getDeptcheckUsers())) {
//                    allCheckDept.getDeptcheckUsers().add(deptCheckUserDTO);
//                }
//                allCheckDept.getDeptcheckUsers().forEach(oneDeptCheckUser -> {
//                    if (!userId.equals(oneDeptCheckUser.getDoctorId())) {
//                        hasFlag.set(true);
//                    }
//                });
//                if (hasFlag.get()) {
//                    allCheckDept.getDeptcheckUsers().add(deptCheckUserDTO);
//                }
//
//                tempDepts.stream().forEach(checkDeptDTO -> {
//                    if (deptId.contains(checkDeptDTO.getDeptId())) {
//                        checkDeptDTO.getDeptcheckUsers().add(deptCheckUserDTO);
//                    }
//                });
            });
            tempDepts.add(0, allCheckDept);
            checkRoleMap.put(roleId + "", tempDepts);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * @Author songxl
     * @Description 拼装科室、核查人员、任务数对象
     * @time: 2024/5/17
     * @Param [checkRoleMap, doctorInfos, userJobs, deptInfos, roleId]
     * @Return void
     * @MethodName addCheckInfoMap
     */
    private void addCheckInfoMaps(Map<String, List<CheckDeptDTO>> checkRoleMap, Map<String, String> deptMap,
                                  List<DeptCheckUserDTO> userJobs, List<DeptCheckUserDTO> checkUserDTOS, int roleId, int jobType) {
        //非院区任务
        if (CheckJobTypeEnum.HOSP_SUPERVISOR.getKey() != jobType) {
            if (deptMap.isEmpty() || checkUserDTOS.isEmpty()) {
                return;
            }
            checkRoleMap.put(roleId + "", new ArrayList<>());
            //遍历科室
            for (String deptId : deptMap.keySet()) {
                //科室对象
                CheckDeptDTO checkDeptDTO = new CheckDeptDTO();
                checkDeptDTO.setDeptId(deptId);
                checkDeptDTO.setDeptName(deptMap.get(deptId));
//                checkDeptDTO.setDeptcheckUsers(new ArrayList<DeptCheckUserDTO>());
                //遍历医生
                for (DeptCheckUserDTO checkUserDTO : checkUserDTOS) {
                    //同一科室
                    if (checkDeptDTO.getDeptId().equals(checkUserDTO.getDeptId())) {
                        DeptCheckUserDTO deptCheckUserDTO = new DeptCheckUserDTO();
                        deptCheckUserDTO.setDeptId(checkUserDTO.getDeptId());
                        deptCheckUserDTO.setDeptName(checkUserDTO.getDeptName());
                        deptCheckUserDTO.setDoctorId(checkUserDTO.getDoctorId());
                        deptCheckUserDTO.setDoctorName(checkUserDTO.getDoctorName());
//                        checkDeptDTO.getDeptcheckUsers().add(deptCheckUserDTO);
                    }
                }
//                for (DeptCheckUserDTO deptCheckUserDTO : checkDeptDTO.getDeptcheckUsers()) {
//                    //遍历数量
//                    for (DeptCheckUserDTO jobNumDto : userJobs) {
//                        //这个科室有这个人
//                        if (deptCheckUserDTO.getDeptId().equals(jobNumDto.getDeptId())) {
//                            if (deptCheckUserDTO.getDoctorId().equals(jobNumDto.getDoctorId())) {
//                                if (jobNumDto.getStatus() == 0) {
//                                    deptCheckUserDTO.setJobNum(jobNumDto.getJobNum());
//                                }
//                                if (jobNumDto.getStatus() == 1) {
//
//                                    deptCheckUserDTO.setCheckNum(jobNumDto.getJobNum());
//                                }
//                            }
//
//                        }
//                    }
//                }
                checkRoleMap.get(roleId + "").add(checkDeptDTO);
            }
        }
        //院区任务不是同一科室的人员数量增加
//        else if (CheckJobTypeEnum.HOSP_SUPERVISOR.getKey() == jobType) {
//            checkRoleMap.get(roleId + "").stream().forEach(checkDeptDTO -> {
//                if (!ListUtil.isEmpty(checkDeptDTO.getDeptcheckUsers())) {
//                    checkDeptDTO.getDeptcheckUsers().stream().forEach(deptCheckUser -> {
//                        userJobs.stream().forEach(userJob -> {
//                            if (deptCheckUser.getDoctorId().equals(userJob.getDoctorId())) {
//                                if (userJob.getStatus() == 0) {
//                                    deptCheckUser.setJobNum(userJob.getJobNum());
//                                }
//                                if (userJob.getStatus() == 1) {
//                                    deptCheckUser.setCheckNum(userJob.getJobNum());
//                                }
//                            }
//                        });
//                    });
//                }
//            });
//        }
    }
}
