package com.lantone.security.facade.base;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lantone.security.dto.GetDataAuthDeptDTO;
import com.lantone.security.dto.GetDataAuthDetailDTO;
import com.lantone.security.dto.GetDataAuthDoctorDTO;
import com.lantone.security.dto.GetDataAuthHospitalDTO;
import com.lantone.common.enums.DataAuthDataTypeEnum;
import com.lantone.common.enums.DataAuthDetailTypeEnum;
import com.lantone.common.enums.IsDeleteEnum;
import com.lantone.common.service.RedisService;
import com.lantone.common.util.ListUtil;
import com.lantone.security.vo.DataAuthPack;
import com.lantone.security.entity.DeptUser;
import com.lantone.security.service.impl.DataAuthServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 表名：sys_data_auth 业务类
 * </p>
 */
@Component
public class DataAuthFacade extends DataAuthServiceImpl {
    @Autowired
    private RedisService redisService;
    @Autowired
    private DeptUserFacade deptUserFacade;
    @Autowired
    private MedoupDoctorFacade medoupDoctorFacade;
    @Autowired
    private HospitalFacade hospitalFacade;
    @Autowired
    private DeptFacade deptFacade;

    /**
     * @param
     * @Description加载用户数据权限
     * @Return void
     */
    public void initUserDataAuth() {
        //获取用户的数据权限
        List<GetDataAuthDetailDTO> dataAuthDetails = this.getBaseMapper()
                .getDataAuth(null, null);
        if (ListUtil.isNotEmpty(dataAuthDetails)) {
            //通过id分组
            Map<String, List<GetDataAuthDetailDTO>> dataAuthMap = dataAuthDetails.stream()
                    .collect(Collectors.groupingBy(GetDataAuthDetailDTO::getId));
            //遍历每个医院_用户_服务id 的数据权限
            dataAuthMap.keySet().stream().forEach(id -> {
                DataAuthPack dataAuthPack = new DataAuthPack();
                if (ListUtil.isNotEmpty(dataAuthMap.get(id))) {
                    //通过数据权限类型分类
                    //1:全部组织,2:全部科室,3:全部科室除本科室外,4:本科室,5:本医疗组,6:本人,7:自定义
                    Map<Integer, List<GetDataAuthDetailDTO>> dataAuthDetailMap = dataAuthMap.get(id).stream()
                            .collect(Collectors.groupingBy(GetDataAuthDetailDTO::getDataType));
                    dataAuthDetailMap.keySet().stream().forEach(dataType -> {
                        //获取医院id和用户id
                        Long hospitalId = null;
                        Long userId = null;
                        try {
                            hospitalId = Long.parseLong(id.split("_")[0]);
                            userId = Long.parseLong(id.split("_")[1]);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //全部组织
                        if (DataAuthDataTypeEnum.ALL_HOSPITAL.getKey() == dataType) {
                            //获取当前登录用户的医院id
                            if (hospitalId != null) {
                                dataAuthPack.getHospitals().add(hospitalId);
                            }
                        }
                        //全部科室
                        if (DataAuthDataTypeEnum.ALL_DEPT.getKey() == dataType) {
                            if (hospitalId != null) {
                                dataAuthPack.getHospitals().add(hospitalId);
                            }
                            //获取所有科室
//                    depts.addAll(deptFacade.list(new QueryWrapper<Dept>()
//                            .in("hospital_id",hospitalId)
//                            .eq("is_deleted",IsDeleteEnum.N.getKey())).stream().map(Dept::getId).collect(Collectors.toList()));
                        }
                        //除了本科室外
                        if (DataAuthDataTypeEnum.ALL_DEPT_NOT_SELF.getKey() == dataType) {
                            if (userId != null) {
                                dataAuthPack.getNotDepts().addAll(deptUserFacade.list(new QueryWrapper<DeptUser>()
                                        .eq("user_id", userId)
                                        .eq("is_deleted", IsDeleteEnum.N.getKey())).stream()
                                        .map(DeptUser::getDeptId).collect(Collectors.toList()));
                            }
                        }
                        //本科室
                        if (DataAuthDataTypeEnum.ALL_SELF_DEPT.getKey() == dataType) {
                            if (userId != null) {
                                dataAuthPack.getDepts().addAll(deptUserFacade.list(new QueryWrapper<DeptUser>()
                                        .eq("user_id", userId)
                                        .eq("is_deleted", IsDeleteEnum.N.getKey())).stream()
                                        .map(DeptUser::getDeptId).collect(Collectors.toList()));
                            }
                        }
                        //本医疗组
                        if (DataAuthDataTypeEnum.SELF_MEDOUP.getKey() == dataType) {
                            if (userId != null) {
                                dataAuthPack.getDoctors().addAll(medoupDoctorFacade.getBaseMapper().getDoctorIdByMedoup(userId));
                            }
                        }
                        //本人
                        if (DataAuthDataTypeEnum.SELF_MEDOUP.getKey() == dataType) {
                            if (userId != null) {
                                dataAuthPack.getUsers().add(userId);
                            }
                        }
                        //自定义
                        if (DataAuthDataTypeEnum.CUSTOMIZE.getKey() == dataType) {
                            Map<Integer, List<GetDataAuthDetailDTO>> dataAuthDetailTypeMap = dataAuthDetailMap.get(dataType).stream()
                                    .collect(Collectors.groupingBy(GetDataAuthDetailDTO::getDetailType));
                            dataAuthDetailTypeMap.keySet().stream().forEach(detailType -> {
                                List<Long> ids = dataAuthDetailTypeMap
                                        .get(detailType).stream().map(GetDataAuthDetailDTO::getDetailId).collect(Collectors.toList());
                                //医院
                                if (DataAuthDetailTypeEnum.HOSPITAL.getKey() == detailType) {
                                    dataAuthPack.getHospitals().addAll(hospitalFacade.getBaseMapper().getHospitals(ids).stream()
                                            .map(GetDataAuthHospitalDTO::getId).collect(Collectors.toList()));
                                }
                                //科室
                                if (DataAuthDetailTypeEnum.DEPT.getKey() == detailType) {
                                    dataAuthPack.getDepts().addAll(deptFacade.getBaseMapper().getDepts(ids).stream()
                                            .map(GetDataAuthDeptDTO::getId).collect(Collectors.toList()));
                                }
                                //医生
                                if (DataAuthDetailTypeEnum.DOCTOR.getKey() == detailType) {
                                    dataAuthPack.getDoctors().addAll(deptFacade.getBaseMapper().getDoctors(ids).stream()
                                            .map(GetDataAuthDoctorDTO::getId).collect(Collectors.toList()));
                                }
                            });
                        }
                    });
                }
                redisService.set("dataAuth:" + id, dataAuthPack);
            });

        }
    }
}