package com.diagbot.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diagbot.client.AuthServiceClient;
import com.diagbot.entity.BehospitalInfo;
import com.diagbot.entity.DoctorAdvice;
import com.diagbot.entity.HomeDiagnoseInfo;
import com.diagbot.entity.HomeOperationInfo;
import com.diagbot.entity.HomePage;
import com.diagbot.entity.MedCrisisInfo;
import com.diagbot.entity.MedicalRecord;
import com.diagbot.entity.MedicalRecordContent;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.BehospitalInfoService;
import com.diagbot.service.DoctorAdviceService;
import com.diagbot.service.HomeDiagnoseInfoService;
import com.diagbot.service.HomeOperationInfoService;
import com.diagbot.service.HomePageService;
import com.diagbot.service.MedCrisisInfoService;
import com.diagbot.service.MedicalRecordContentService;
import com.diagbot.service.MedicalRecordService;
import com.diagbot.util.EncrypDES;
import com.diagbot.util.ListUtil;
import com.diagbot.util.StringUtil;
import com.diagbot.vo.DataImportVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

/**
 * @Description:
 * @Author:zhoutg
 * @time: 2018/11/23 11:37
 */
@Component
public class DataImportFacade {

    @Autowired
    @Qualifier("behospitalInfoServiceImpl")
    BehospitalInfoService behospitalInfoService;
    @Autowired
    @Qualifier("medCrisisInfoServiceImpl")
    MedCrisisInfoService medCrisisInfoService;
    @Autowired
    @Qualifier("doctorAdviceServiceImpl")
    DoctorAdviceService doctorAdviceService;
    @Autowired
    @Qualifier("homeDiagnoseInfoServiceImpl")
    HomeDiagnoseInfoService homeDiagnoseInfoService;
    @Autowired
    @Qualifier("homePageServiceImpl")
    HomePageService homePageService;
    @Autowired
    @Qualifier("homeOperationInfoServiceImpl")
    HomeOperationInfoService homeOperationInfoService;
    @Autowired
    @Qualifier("medicalRecordServiceImpl")
    MedicalRecordService medicalRecordService;
    @Autowired
    @Qualifier("medicalRecordContentServiceImpl")
    MedicalRecordContentService medicalRecordContentService;
    @Autowired
    AuthServiceClient authServiceClient;
    @Value("${encrypt.enable}")
    Boolean encryptFlag;

    /**
     * 数据导入
     *
     * @param dataImportVO
     * @return
     */
    public Boolean dataImportFacade(DataImportVO dataImportVO) {
        Long hospitalId = dataImportVO.getHospitalId();
        // 病历信息导入
        List<BehospitalInfo> behospitalInfoList = dataImportVO.getBehospitalInfoList();
        if (ListUtil.isNotEmpty(behospitalInfoList)) {
            List<String> behospitalCodeList = behospitalInfoList.stream().map(r -> r.getBehospitalCode()).collect(Collectors.toList());
            if (ListUtil.isNotEmpty(behospitalCodeList)) {
                // 先删除
                behospitalInfoService.remove(new QueryWrapper<BehospitalInfo>()
                        .eq("hospital_id", hospitalId)
                        .in("behospital_code", behospitalCodeList)
                );
                // 加密
                for (BehospitalInfo behospitalInfo : behospitalInfoList) {
                    // 姓名
                    if (StringUtil.isNotBlank(behospitalInfo.getName())) {
                        behospitalInfo.setName(behospitalInfo.getName().substring(0, 1) + "**");
                    }
                }
                behospitalInfoService.saveBatch(behospitalInfoList);
            }
        }

        // 危急值信息
        List<MedCrisisInfo> medCrisisInfoList = dataImportVO.getMedCrisisInfoList();
        if (ListUtil.isNotEmpty(medCrisisInfoList)) {
            List<String> recIdList = medCrisisInfoList.stream().map(r -> r.getRecId()).collect(Collectors.toList());
            if (ListUtil.isNotEmpty(recIdList)) {
                // 先删除
                medCrisisInfoService.remove(new QueryWrapper<MedCrisisInfo>()
                        .eq("hospital_id", hospitalId)
                        .in("rec_id", recIdList)
                );
                medCrisisInfoService.saveBatch(medCrisisInfoList);
            }
        }

        // 病人医嘱
        List<DoctorAdvice> doctorAdviceList = dataImportVO.getDoctorAdviceList();
        if (ListUtil.isNotEmpty(doctorAdviceList)) {
            List<String> doctorAdviceIdList = doctorAdviceList.stream().map(r -> r.getDoctorAdviceId()).collect(Collectors.toList());
            if (ListUtil.isNotEmpty(doctorAdviceIdList)) {
                // 先删除
                doctorAdviceService.remove(new QueryWrapper<DoctorAdvice>()
                        .eq("hospital_id", hospitalId)
                        .in("doctor_advice_id", doctorAdviceIdList)
                );
                doctorAdviceService.saveBatch(doctorAdviceList);
            }
        }

        // 病案首页诊断
        List<HomeDiagnoseInfo> homeDiagnoseInfoList = dataImportVO.getHomeDiagnoseInfoList();
        if (ListUtil.isNotEmpty(homeDiagnoseInfoList)) {
            StringBuffer sb = new StringBuffer();
            sb.append(" ( ");
            for (int i = 0; i < homeDiagnoseInfoList.size(); i++) {
                HomeDiagnoseInfo s = homeDiagnoseInfoList.get(i);
                if (i == 0) {
                    sb.append(" (home_page_id = '" + s.getHomePageId() + "'"
                            + " and diagnose_order_no = '" + s.getDiagnoseOrderNo() + "'"
                            + ") " );
                } else {
                    sb.append(" or ( home_page_id = '" + s.getHomePageId() + "'"
                            + " and diagnose_order_no = '" + s.getDiagnoseOrderNo() + "'"
                            + ") " );
                }
            }
            sb.append(")");

            // 先删除
            homeDiagnoseInfoService.remove(new QueryWrapper<HomeDiagnoseInfo>()
                    .eq("hospital_id", hospitalId)
                    .apply(sb.toString())
            );
            homeDiagnoseInfoService.saveBatch(homeDiagnoseInfoList);
        }

        // 病案首页
        List<HomePage> homePageList = dataImportVO.getHomePageList();
        if (ListUtil.isNotEmpty(homePageList)) {
            List<String> homePageIdList = homePageList.stream().map(r -> r.getHomePageId()).collect(Collectors.toList());
            if (ListUtil.isNotEmpty(homePageIdList)) {
                // 先删除
                homePageService.remove(new QueryWrapper<HomePage>()
                        .eq("hospital_id", hospitalId)
                        .in("home_page_id", homePageIdList)
                );
                // 加密
                for (HomePage homePage : dataImportVO.getHomePageList()) {
                    // 姓名
                    if (StringUtil.isNotBlank(homePage.getName())) {
                        homePage.setName(homePage.getName().substring(0, 1) + "**");
                    }
                    // 身份证
                    if (StringUtil.isNotBlank(homePage.getIdentityCardNo())) {
                        homePage.setIdentityCardNo(homePage.getIdentityCardNo().substring(0, 1) + "*****************");
                    }
                    // 现住址电话
                    if (StringUtil.isNotBlank(homePage.getCurPhone())) {
                        homePage.setCurPhone(homePage.getCurPhone().substring(0, 1) + "**");
                    }
                    // 工作单位电话
                    if (StringUtil.isNotBlank(homePage.getWorkPhone())) {
                        homePage.setWorkPhone(homePage.getWorkPhone().substring(0, 1) + "**");
                    }
                    // 联系人姓名
                    if (StringUtil.isNotBlank(homePage.getContactName())) {
                        homePage.setContactName(homePage.getContactName().substring(0, 1) + "**");
                    }
                    // 联系人电话
                    if (StringUtil.isNotBlank(homePage.getContactPhone())) {
                        homePage.setContactPhone(homePage.getContactPhone().substring(0, 1) + "**");
                    }
                }
                homePageService.saveBatch(homePageList);
            }
        }

        // 病案首页手术信息
        List<HomeOperationInfo> homeOperationInfoList = dataImportVO.getHomeOperationInfoList();
        if (ListUtil.isNotEmpty(homeOperationInfoList)) {
            StringBuffer sb = new StringBuffer();
            sb.append(" ( ");
            for (int i = 0; i < homeOperationInfoList.size(); i++) {
                HomeOperationInfo s = homeOperationInfoList.get(i);
                if (i == 0) {
                    sb.append(" (home_page_id = '" + s.getHomePageId() + "'"
                            + " and operation_order_no = '" + s.getOperationOrderNo() + "'"
                            + ") " );
                } else {
                    sb.append(" or ( home_page_id = '" + s.getHomePageId() + "'"
                            + " and operation_order_no = '" + s.getOperationOrderNo() + "'"
                            + ") " );
                }
            }
            sb.append(")");
            // 先删除
            homeOperationInfoService.remove(new QueryWrapper<HomeOperationInfo>()
                    .eq("hospital_id", hospitalId)
                    .apply(sb.toString())
            );
            homeOperationInfoService.saveBatch(homeOperationInfoList);
        }

        // 文书信息
        List<MedicalRecord> medicalRecordList = dataImportVO.getMedicalRecordList();
        if (ListUtil.isNotEmpty(medicalRecordList)) {
            List<String> recIdList = medicalRecordList.stream().map(r -> r.getRecId()).collect(Collectors.toList());
            if (ListUtil.isNotEmpty(recIdList)) {
                // 先删除
                medicalRecordService.remove(new QueryWrapper<MedicalRecord>()
                        .eq("hospital_id", hospitalId)
                        .in("rec_id", recIdList)
                );
                medicalRecordService.saveBatch(medicalRecordList);
            }
        }

        // 文书明细信息
        List<MedicalRecordContent> medicalRecordContentList = dataImportVO.getMedicalRecordContentList();
        if (ListUtil.isNotEmpty(medicalRecordContentList)) {
            List<String> recIdList = medicalRecordContentList.stream().map(r -> r.getRecId()).collect(Collectors.toList());
            if (ListUtil.isNotEmpty(recIdList)) {
                // 先删除
                medicalRecordContentService.remove(new QueryWrapper<MedicalRecordContent>()
                        .eq("hospital_id", hospitalId)
                        .in("rec_id", recIdList));

                // 加密数据
                if (encryptFlag) {
                    String recId = "";
                    try {
                        EncrypDES encrypDES = new EncrypDES();
                        for (MedicalRecordContent medicalRecordContent : medicalRecordContentList) {
                            recId = medicalRecordContent.getRecId();
                            if (StringUtil.isNotBlank(medicalRecordContent.getXmlText())) {
                                medicalRecordContent.setXmlText(encrypDES.encrytor(medicalRecordContent.getXmlText()));
                            }
                        }
                    } catch (Exception e) {
                        throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "加密xml错误!recId=【" + recId + "】");
                    }
                }
                medicalRecordContentService.saveBatch(medicalRecordContentList, 100);
            }
        }
        return true;
    }


    /**
     * 数据导入【效率低，备用】
     *
     * @param dataImportVO
     * @return
     */
    public Boolean dataImportPrepareFacade(DataImportVO dataImportVO) {
        Long hospitalId = dataImportVO.getHospitalId();
        // 病历信息导入
        List<BehospitalInfo> behospitalInfoList = dataImportVO.getBehospitalInfoList();
        if (ListUtil.isNotEmpty(behospitalInfoList)) {
            behospitalInfoList.forEach(s -> {
                QueryWrapper<BehospitalInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("behospital_code", s.getBehospitalCode());
                queryWrapper.eq("hospital_id", s.getHospitalId());
                queryWrapper.eq("is_deleted", IsDeleteEnum.N);
                // 姓名加密
                if (StringUtil.isNotBlank(s.getName())) {
                    s.setName(s.getName().substring(0, 1) + "**");
                }
                int count = behospitalInfoService.count(queryWrapper);
                if (count > 0) {
                    behospitalInfoService.update(s, queryWrapper);
                } else {
                    behospitalInfoService.save(s);
                }
            });
        }

        // 危急值信息
        List<MedCrisisInfo> medCrisisInfoList = dataImportVO.getMedCrisisInfoList();
        if (ListUtil.isNotEmpty(medCrisisInfoList)) {
            medCrisisInfoList.forEach(s -> {
                QueryWrapper<MedCrisisInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("rec_id", s.getRecId());
                queryWrapper.eq("hospital_id", s.getHospitalId());
                queryWrapper.eq("behospital_code", s.getBehospitalCode());
                queryWrapper.eq("rec_type", s.getRecType());
                int count = medCrisisInfoService.count(queryWrapper);
                if (count > 0) {
                    medCrisisInfoService.update(s, queryWrapper);
                } else {
                    medCrisisInfoService.save(s);
                }
            });
        }

        // 病人医嘱
        List<DoctorAdvice> doctorAdviceList = dataImportVO.getDoctorAdviceList();
        if (ListUtil.isNotEmpty(doctorAdviceList)) {
            doctorAdviceList.forEach(s -> {
                QueryWrapper<DoctorAdvice> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("doctor_advice_id", s.getDoctorAdviceId());
                queryWrapper.eq("hospital_id", s.getHospitalId());
                queryWrapper.eq("is_deleted",IsDeleteEnum.N);
                int count = doctorAdviceService.count(queryWrapper);
                if (count > 0) {
                    doctorAdviceService.update(s, queryWrapper);
                } else {
                    doctorAdviceService.save(s);
                }
            });
        }

        // 病案首页诊断
        List<HomeDiagnoseInfo> homeDiagnoseInfoList = dataImportVO.getHomeDiagnoseInfoList();
        if (ListUtil.isNotEmpty(homeDiagnoseInfoList)) {
            homeDiagnoseInfoList.forEach(s -> {
                QueryWrapper<HomeDiagnoseInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("home_page_id", s.getHomePageId());
                queryWrapper.eq("hospital_id", s.getHospitalId());
                queryWrapper.eq("diagnose_order_no", s.getDiagnoseOrderNo());
                int count = homeDiagnoseInfoService.count(queryWrapper);
                if (count > 0) {
                    homeDiagnoseInfoService.update(s, queryWrapper);
                } else {
                    homeDiagnoseInfoService.save(s);
                }
            });
        }

        // 病案首页
        List<HomePage> homePageList = dataImportVO.getHomePageList();
        if (ListUtil.isNotEmpty(homePageList)) {
            homePageList.stream().forEach(s -> {
                // 姓名
                if (StringUtil.isNotBlank(s.getName())) {
                    s.setName(s.getName().substring(0, 1) + "**");
                }
                // 身份证
                if (StringUtil.isNotBlank(s.getIdentityCardNo())) {
                    s.setIdentityCardNo(s.getIdentityCardNo().substring(0, 1) + "*****************");
                }
                // 现住址电话
                if (StringUtil.isNotBlank(s.getCurPhone())) {
                    s.setCurPhone(s.getCurPhone().substring(0, 1) + "**");
                }
                // 工作单位电话
                if (StringUtil.isNotBlank(s.getWorkPhone())) {
                    s.setWorkPhone(s.getWorkPhone().substring(0, 1) + "**");
                }
                // 联系人姓名
                if (StringUtil.isNotBlank(s.getContactName())) {
                    s.setContactName(s.getContactName().substring(0, 1) + "**");
                }
                // 联系人电话
                if (StringUtil.isNotBlank(s.getContactPhone())) {
                    s.setContactPhone(s.getContactPhone().substring(0, 1) + "**");
                }

                QueryWrapper<HomePage> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("home_page_id", s.getHomePageId());
                queryWrapper.eq("hospital_id", s.getHospitalId());
                queryWrapper.eq("behospital_code", s.getBehospitalCode());
                queryWrapper.eq("is_deleted",IsDeleteEnum.N);
                int count = homePageService.count(queryWrapper);
                if (count > 0) {
                    homePageService.update(s, queryWrapper);
                } else {
                    homePageService.save(s);
                }
            });
        }

        // 病案首页手术信息
        List<HomeOperationInfo> homeOperationInfoList = dataImportVO.getHomeOperationInfoList();
        if (ListUtil.isNotEmpty(homeOperationInfoList)) {
            homeOperationInfoList.forEach(s -> {
                if(s.getHomePageId()!=null && !"".equals(s.getOperationOrderNo())) {
                    QueryWrapper<HomeOperationInfo> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("home_page_id", s.getHomePageId());
                    queryWrapper.eq("hospital_id", s.getHospitalId());
                    queryWrapper.eq("operation_order_no", s.getOperationOrderNo());
                    int count = homeOperationInfoService.count(queryWrapper);
                    if (count > 0) {
                        homeOperationInfoService.update(s, queryWrapper);
                    } else {
                        homeOperationInfoService.save(s);
                    }
                }
            });
        }

        // 文书信息
        List<MedicalRecord> medicalRecordList = dataImportVO.getMedicalRecordList();
        if (ListUtil.isNotEmpty(medicalRecordList)) {
            medicalRecordList.forEach(s -> {
                QueryWrapper<MedicalRecord> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("rec_id", s.getRecId());
                queryWrapper.eq("hospital_id", s.getHospitalId());
                queryWrapper.eq("is_deleted",IsDeleteEnum.N);
                int count = medicalRecordService.count(queryWrapper);
                if (count > 0) {
                    medicalRecordService.update(s, queryWrapper);
                } else {
                    medicalRecordService.save(s);
                }
            });
        }

        // 文书明细信息
        List<MedicalRecordContent> medicalRecordContentList = dataImportVO.getMedicalRecordContentList();
        if (ListUtil.isNotEmpty(medicalRecordContentList)) {
            // 加密数据
            if (encryptFlag) {
                String recId = "";
                try {
                    EncrypDES encrypDES = new EncrypDES();
                    for (MedicalRecordContent s : medicalRecordContentList) {
                        recId = s.getRecId();
                        if (StringUtil.isNotBlank(s.getXmlText())) {
                            s.setXmlText(encrypDES.encrytor(s.getXmlText()));
                        }
                        QueryWrapper<MedicalRecordContent> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("rec_id", s.getRecId());
                        queryWrapper.eq("hospital_id", s.getHospitalId());
                        queryWrapper.eq("is_deleted",IsDeleteEnum.N);
                        int count = medicalRecordContentService.count(queryWrapper);
                        if (count > 0) {
                            medicalRecordContentService.update(s, queryWrapper);
                        } else {
                            medicalRecordContentService.save(s);
                        }
                    }
                } catch (Exception e) {
                    throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "加密xml错误!recId=【" + recId + "】");
                }
            }
        }
        return true;
    }


    /**
     * 模拟测试数据
     *
     * @return
     */
    public Boolean test() {
        int size = 5;
        Long hospitalId = 8L;
        int random = (int)(Math.random() * 100);

        DataImportVO dataImportVO = new DataImportVO();
        dataImportVO.setHospitalId(hospitalId);

        // // 病历信息
        // List<BehospitalInfo> behospitalInfoList = behospitalInfoService.list(new QueryWrapper<BehospitalInfo>()
        //         .ne("hospital_id", hospitalId)
        //         .last(" limit " + size)
        // );
        // behospitalInfoList.forEach(r -> { r.setHospitalId(hospitalId); r.setBehospitalCode(r.getBehospitalCode() + random); });
        // dataImportVO.setBehospitalInfoList(behospitalInfoList);
        //
        // // 医嘱信息
        // List<DoctorAdvice> doctorAdviceList = doctorAdviceService.list(new QueryWrapper<DoctorAdvice>()
        //         .ne("hospital_id", hospitalId)
        //         .last(" limit " + size)
        // );
        // doctorAdviceList.forEach(r -> {r.setHospitalId(hospitalId); r.setBehospitalCode(r.getBehospitalCode() + random);});
        // dataImportVO.setDoctorAdviceList(doctorAdviceList);
        //
        // // 病案首页诊断
        // List<HomeDiagnoseInfo> homeDiagnoseInfoList = homeDiagnoseInfoService.list(new QueryWrapper<HomeDiagnoseInfo>()
        //         .ne("hospital_id", hospitalId)
        //         .last(" limit " + size)
        // );
        // homeDiagnoseInfoList.forEach(r -> {r.setHospitalId(hospitalId); r.setHomePageId(r.getHomePageId() + random);});
        // dataImportVO.setHomeDiagnoseInfoList(homeDiagnoseInfoList);
        //
        // // 病案首页
        // List<HomePage> homePageList = homePageService.list(new QueryWrapper<HomePage>()
        //         .ne("hospital_id", hospitalId)
        //         .last(" limit " + size)
        // );
        // homePageList.forEach(r -> {r.setHospitalId(hospitalId); r.setBehospitalCode(r.getBehospitalCode() + random);});
        // dataImportVO.setHomePageList(homePageList);

        // // 病案首页手术信息
        // List<HomeOperationInfo> homeOperationInfoList = homeOperationInfoService.list(new QueryWrapper<HomeOperationInfo>()
        //         .eq("hospital_id", hospitalId)
        //         .last(" limit " + size)
        // );
        // homeOperationInfoList.forEach(r -> {r.setHospitalId(hospitalId); r.setHomePageId(r.getHomePageId() );});
        // dataImportVO.setHomeOperationInfoList(homeOperationInfoList);
        //
        // // 文书信息
        // List<MedicalRecord> medicalRecordList = medicalRecordService.list(new QueryWrapper<MedicalRecord>()
        //         .ne("hospital_id", hospitalId)
        //         .last(" limit " + size)
        // );
        // medicalRecordList.forEach(r -> {r.setHospitalId(hospitalId); r.setBehospitalCode(r.getBehospitalCode() + random);});
        // dataImportVO.setMedicalRecordList(medicalRecordList);

        // // 文书明细信息
        // List<MedicalRecordContent> medicalRecordContentList = medicalRecordContentService.list(new QueryWrapper<MedicalRecordContent>()
        //         .ne("hospital_id", hospitalId)
        //         .last(" limit " + size)
        // );
        // medicalRecordContentList.forEach(r -> {r.setHospitalId(hospitalId); r.setRecId(r.getRecId() + random);});
        // dataImportVO.setMedicalRecordContentList(medicalRecordContentList);

        authServiceClient.dataimport(dataImportVO);
        return true;
    }
}
