package com.lantone.daqe.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.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lantone.common.enums.IsDeleteEnum;
import com.lantone.common.exception.Asserts;
import com.lantone.common.util.BeanUtil;
import com.lantone.common.util.DateUtil;
import com.lantone.common.util.ListUtil;
import com.lantone.common.util.StringUtil;
import com.lantone.common.util.SysUserUtils;
import com.lantone.daqe.dto.GetByIdColumnResultDTO;
import com.lantone.daqe.dto.GetColumnResultNumberDTO;
import com.lantone.daqe.dto.GetColumnResultPageDTO;
import com.lantone.daqe.dto.GetRegular;
import com.lantone.daqe.dto.GetStandardvalueInfoDTO;
import com.lantone.daqe.dto.GetTableColumnInfoDTO;
import com.lantone.daqe.entity.BehospitalInfo;
import com.lantone.daqe.entity.ColumnInfo;
import com.lantone.daqe.entity.ColumnResult;
import com.lantone.daqe.entity.NonnullInfo;
import com.lantone.daqe.entity.NonnullResult;
import com.lantone.daqe.entity.RegularResult;
import com.lantone.daqe.entity.StandardvalueResult;
import com.lantone.daqe.enums.AuditStatusEnum;
import com.lantone.daqe.enums.ColumnResultTypeEnum;
import com.lantone.daqe.enums.ColumnTypeEnum;
import com.lantone.daqe.enums.ColumnVerifyTypeEnum;
import com.lantone.daqe.enums.ModeEnum;
import com.lantone.daqe.enums.NonnullStatusEnum;
import com.lantone.daqe.enums.SolvedStatusEnum;
import com.lantone.daqe.facade.base.BehospitalInfoFacade;
import com.lantone.daqe.facade.base.ColumnInfoFacade;
import com.lantone.daqe.facade.base.ColumnResultFacade;
import com.lantone.daqe.facade.base.NonnullInfoFacade;
import com.lantone.daqe.facade.base.NonnullResultFacade;
import com.lantone.daqe.facade.base.RegularMappingFacade;
import com.lantone.daqe.facade.base.RegularResultFacade;
import com.lantone.daqe.facade.base.StandardvalueInfoFacade;
import com.lantone.daqe.facade.base.StandardvalueResultFacade;
import com.lantone.daqe.vo.DataCheckVO;
import com.lantone.daqe.vo.GetColumnResultNumberVO;
import com.lantone.daqe.vo.GetColumnResultPageVO;
import com.lantone.daqe.vo.GetRegularMappingVO;
import com.lantone.daqe.vo.GetStandardvalueInfoVO;
import com.lantone.daqe.vo.GetTableColumnInfoVO;
import com.lantone.daqe.vo.UpdateColumnResultVO;
import com.lantone.daqe.vo.GetByIdColumnResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @Description: 字段校验问题明细维护API-业务处理类
 * @author： zhanghang
 * @time: 2022/3/8 14:49
 */
@Component
public class ColumnResultManagementFacade {
    @Autowired
    ColumnResultFacade columnResultFacade;
    @Autowired
    NonnullResultFacade nonnullResultFacade;
    @Autowired
    RegularResultFacade regularResultFacade;
    @Autowired
    StandardvalueResultFacade standardvalueResultFacade;
    @Autowired
    BehospitalInfoFacade behospitalInfoFacade;
    @Autowired
    NonnullInfoFacade nonnullInfoFacade;
    @Autowired
    RegularMappingFacade regularMappingFacade;
    @Autowired
    StandardvalueInfoFacade standardvalueInfoFacade;
    @Autowired
    ColumnInfoFacade columnInfoFacade;

    /**
     * 获取字段校验问题明细分页列表数据
     *
     * @param getColumnResultPageVO
     * @return: 字段校验问题明细分页列表数据
     */
    public IPage<GetColumnResultPageDTO> getColumnResultPage(GetColumnResultPageVO getColumnResultPageVO) {
        Page<GetColumnResultPageDTO> getColumnResultPageDTOPage = new Page<>();
        Long currentHospitalId = SysUserUtils.getCurrentHospitalId();
        getColumnResultPageVO.setHospitalId(currentHospitalId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startDate = null;
        String endDate = null;
        if (getColumnResultPageVO.getBehospitalStartDate() != null) {
            startDate = sdf.format(getColumnResultPageVO.getBehospitalStartDate());
        }
        if (getColumnResultPageVO.getBehospitalEndDate() != null) {
            endDate = sdf.format(getColumnResultPageVO.getBehospitalEndDate());
        }
        QueryWrapper<ColumnResult> columnResultQueryWrapper = new QueryWrapper<>();
        columnResultQueryWrapper.eq(getColumnResultPageVO.getHospitalId() != null, "hospital_id", getColumnResultPageVO.getHospitalId());
        columnResultQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey());
        columnResultQueryWrapper.eq(StringUtil.isNotBlank(getColumnResultPageVO.getType()), "type", getColumnResultPageVO.getType());
        columnResultQueryWrapper.eq(StringUtil.isNotBlank(getColumnResultPageVO.getIsSolved()), "is_solved", getColumnResultPageVO.getIsSolved());
        columnResultQueryWrapper.eq(StringUtil.isNotBlank(getColumnResultPageVO.getModeName()),"mode_name", getColumnResultPageVO.getModeName());
        columnResultQueryWrapper.ge(StringUtil.isNotBlank(startDate), "behospital_date", getColumnResultPageVO.getBehospitalStartDate());
        columnResultQueryWrapper.le(StringUtil.isNotBlank(endDate), "behospital_date", getColumnResultPageVO.getBehospitalEndDate());
        columnResultQueryWrapper.like(StringUtil.isNotBlank(getColumnResultPageVO.getBehospitalCode()), "behospital_code", getColumnResultPageVO.getBehospitalCode());
        columnResultQueryWrapper.like(StringUtil.isNotBlank(getColumnResultPageVO.getHosptialDatatmpCode()), "hosptial_datatmp_code", getColumnResultPageVO.getHosptialDatatmpCode());
        columnResultQueryWrapper.like(StringUtil.isNotBlank(getColumnResultPageVO.getHosptialDatatmpName()), "hosptial_datatmp_name", getColumnResultPageVO.getHosptialDatatmpName());

        Page<ColumnResult> columnResultPage = new Page<>(getColumnResultPageVO.getCurrent(), getColumnResultPageVO.getSize());
        columnResultFacade.page(columnResultPage, columnResultQueryWrapper);
        BeanUtil.copyProperties(columnResultPage, getColumnResultPageDTOPage);
        List<GetColumnResultPageDTO> getRecordTemplatePageDTOList = BeanUtil.listCopyTo(columnResultPage.getRecords(), GetColumnResultPageDTO.class);

        getColumnResultPageDTOPage.setRecords(getRecordTemplatePageDTOList);
        return getColumnResultPageDTOPage;
    }

    /**
     * 获取字段校验问题明细数量
     *
     * @param getColumnResultNumberVO
     * @return: 字段校验问题明细数量
     */
    public GetColumnResultNumberDTO getColumnResultNumber(GetColumnResultNumberVO getColumnResultNumberVO) {
        Long currentHospitalId = SysUserUtils.getCurrentHospitalId();
        getColumnResultNumberVO.setHospitalId(currentHospitalId);
        return columnResultFacade.getBaseMapper().getColumnResultNumber(getColumnResultNumberVO);
    }

    /**
     * 修改字段校验问题明细
     *
     * @param updateColumnResultVO
     * @return: 是否成功
     */
    public Boolean updateColumnResult(UpdateColumnResultVO updateColumnResultVO) {
        Long principleId = SysUserUtils.getCurrentPrincipleId();
        ColumnResult columnResultFacadeById = columnResultFacade.getById(updateColumnResultVO.getId());
        //先修改副表
        //非空校验结果表
        Long resultId = columnResultFacadeById.getResultId();
        String type = columnResultFacadeById.getType();
        if (ColumnVerifyTypeEnum.NONNULL_TYPE.getKey().equals(type)) {
            nonnullResultFacade.update(new UpdateWrapper<NonnullResult>()
                    .eq("is_deleted", IsDeleteEnum.N.getKey())
                    .eq("id", resultId)
                    .set("description", updateColumnResultVO.getDescription())
                    .set("gmt_modified", new Date())
                    .set("modifier", principleId == null ? "0" : principleId)
            );
        }
        //正则校验结果表
        if (ColumnVerifyTypeEnum.REGULAR_TYPE.getKey().equals(type)) {
            regularResultFacade.update(new UpdateWrapper<RegularResult>()
                    .eq("is_deleted", IsDeleteEnum.N.getKey())
                    .eq("id", resultId)
                    .set("description", updateColumnResultVO.getDescription())
                    .set("gmt_modified", new Date())
                    .set("modifier", principleId == null ? "0" : principleId)
            );
        }
        //关键字校验结果表
        if (ColumnVerifyTypeEnum.STANDARD_TYPE.getKey().equals(type)) {
            standardvalueResultFacade.update(new UpdateWrapper<StandardvalueResult>()
                    .eq("is_deleted", IsDeleteEnum.N.getKey())
                    .eq("id", resultId)
                    .set("description", updateColumnResultVO.getDescription())
                    .set("gmt_modified", new Date())
                    .set("modifier", principleId == null ? "0" : principleId)
            );
        }

        return columnResultFacade.update(new UpdateWrapper<ColumnResult>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("id", updateColumnResultVO.getId())
                .set("description", updateColumnResultVO.getDescription())
                .set("gmt_modified", new Date())
                .set("modifier", principleId == null ? "0" : principleId)
        );
    }

    /**
     * 根据ID查看字段校验问题明细
     *
     * @param getByIdColumnResultVO
     * @return: 字段校验问题明细明细
     */
    public GetByIdColumnResultDTO getByIdColumnResult(GetByIdColumnResultVO getByIdColumnResultVO) {
        ColumnResult columnResult = columnResultFacade.getBaseMapper().selectById(getByIdColumnResultVO.getId());
        String type = columnResult.getType();
        GetByIdColumnResultDTO getByIdColumnResultDTO = new GetByIdColumnResultDTO();
        //非空校验
        if (ColumnVerifyTypeEnum.NONNULL_TYPE.getKey().equals(type)) {
            getByIdColumnResultDTO.setType(type);
            Long resultId = columnResult.getResultId();
            NonnullResult nonnullResult = nonnullResultFacade.getBaseMapper().selectOne(new QueryWrapper<NonnullResult>()
                    .eq("is_deleted", IsDeleteEnum.N.getKey())
                    .eq("id", resultId)
            );
            BeanUtil.copyProperties(nonnullResult, getByIdColumnResultDTO);
            return getByIdColumnResultDTO;
        }
        //正则校验结果表
        if (ColumnVerifyTypeEnum.REGULAR_TYPE.getKey().equals(type)) {
            getByIdColumnResultDTO.setType(type);
            Long resultId = columnResult.getResultId();
            RegularResult regularResult = regularResultFacade.getBaseMapper().selectOne(new QueryWrapper<RegularResult>()
                    .eq("is_deleted", IsDeleteEnum.N.getKey())
                    .eq("id", resultId)
            );
            BeanUtil.copyProperties(regularResult, getByIdColumnResultDTO);
            return getByIdColumnResultDTO;
        }
        //关键字校验结果表
        if (ColumnVerifyTypeEnum.STANDARD_TYPE.getKey().equals(type)) {
            getByIdColumnResultDTO.setType(type);
            Long resultId = columnResult.getResultId();
            StandardvalueResult standardvalueResult = standardvalueResultFacade.getBaseMapper().selectOne(new QueryWrapper<StandardvalueResult>()
                    .eq("is_deleted", IsDeleteEnum.N.getKey())
                    .eq("id", resultId)
            );
            BeanUtil.copyProperties(standardvalueResult, getByIdColumnResultDTO);
            return getByIdColumnResultDTO;
        }
        return getByIdColumnResultDTO;
    }

    /**
     *获取枚举所有Name 也就是质控模块名称
     *
     * @param
     * @return:
     */
    public List<String> getModeName(){
        List<String> modeNameList = new ArrayList<>();
        for (ModeEnum value : ModeEnum.values()) {
            modeNameList.add(value.getName());
        }
        return modeNameList;
    }

    /**
     * 数据校验接口
     *
     * @param dataCheckVO
     * @return: 是否成功
     */
    public Boolean dataCheck(DataCheckVO dataCheckVO) {
        List<String> behospitalCodeList = new ArrayList<>();
        Long hospitalId = null;
        Long principleId = null;
        if(dataCheckVO.getHospitalId()==null){
            hospitalId=SysUserUtils.getCurrentHospitalId();
            principleId=SysUserUtils.getCurrentPrincipleId();
        }
        dataCheckVO.setHospitalId(hospitalId);
        String behospitalCode = dataCheckVO.getBehospitalCode();
        //传入BehospitalCode 只针对单个病历进行校验
        if (StringUtil.isNotEmpty(behospitalCode)) {
            List<BehospitalInfo> behospitalInfos = behospitalInfoFacade.getBaseMapper().selectList(new QueryWrapper<BehospitalInfo>()
                    .eq("is_deleted", IsDeleteEnum.N.getKey())
                    .eq("behospital_code", dataCheckVO.getBehospitalCode())
                    .eq(hospitalId!=null,"hospital_id", hospitalId)
            );
            if (ListUtil.isEmpty(behospitalInfos)) {
                Asserts.fail("该患者信息未查询到！");
            }
            behospitalCodeList.add(behospitalCode);
            //对于集合病历所有校验规则校验其表信息字段
            checkTableColumnVal(behospitalCodeList,hospitalId,principleId);
        }
        //对于只传时间不传病历的情况
        //创建一个病历集合
        if (StringUtil.isEmpty(behospitalCode)) {
            List<BehospitalInfo> behospitalInfos = getBehospitalInfos(dataCheckVO.getDateStart(), dataCheckVO.getDateEnd(), hospitalId);
            if (ListUtil.isEmpty(behospitalInfos)) {
                Asserts.fail("该时间段无病历信息！");
            }
            for (BehospitalInfo behospitalInfo : behospitalInfos) {
                //获取时间段所有病历
                behospitalCodeList.add(behospitalInfo.getBehospitalCode());
            }
            //对于集合病历所有校验规则校验其表信息字段
            checkTableColumnVal(behospitalCodeList,hospitalId,principleId);
        }
        return true;
    }


    /**
     * 对于集合病历所有校验规则校验其表信息字段
     *
     * @param behospitalCodeList
     * @return: 具体数据
     */
    public void checkTableColumnVal(List<String> behospitalCodeList,Long hospitalId,Long principleId) {
        //先获取非空的所有字段校验规则
        List<NonnullInfo> nonnullInfos = getNonnullInfo();
        if (ListUtil.isNotEmpty(nonnullInfos)) {
            //调用校验非空规则方法
            checkNonnull(nonnullInfos, behospitalCodeList, hospitalId,principleId);
        }
        //获取正则所有字段校验规则
        List<GetRegular> regularMappings = getRegularMapping();
        if (ListUtil.isNotEmpty(regularMappings)) {
            //调用校验正则规则
            checkRegular(regularMappings, behospitalCodeList, hospitalId,principleId);
        }
        //获取字段校验的标准值规则
        List<GetStandardvalueInfoDTO> standardvalueInfo = getStandardvalueInfo();
        if (ListUtil.isNotEmpty(standardvalueInfo)) {
            checkStandardvalue(standardvalueInfo, behospitalCodeList, hospitalId,principleId);
        }
    }

    /**
     * 对于当天有规则被修改，校验30天内所有病历中规则关联的数据
     *
     * @param
     * @return: 具体数据
     */
    public void taskCheckTableColumnVal(Long hospitalId) {
        Long principleId = null;
        List<NonnullInfo> nonnullInfoList = new ArrayList<>();
        List<GetRegular> regularList = new ArrayList<>();
        List<GetStandardvalueInfoDTO> standardvalueList = new ArrayList<>();
        List<String> behospitalCodeList = new ArrayList<>();
        Date startDate = DateUtil.addDate(DateUtil.now(), -1);
        Date endDate = DateUtil.now();
        //先获取非空的所有字段校验规则
        List<NonnullInfo> nonnullInfos = getNonnullInfo();
        if (ListUtil.isNotEmpty(nonnullInfos)) {
            //遍历所有规则
            for (NonnullInfo nonnullInfo : nonnullInfos) {
                Date gmtModified = nonnullInfo.getGmtModified();
                //判断修改时间是否为当天
                if (gmtModified.after(startDate) && endDate.after(gmtModified)) {
                    //如果是今天则将规则存入一个对象集合中待处理
                    nonnullInfoList.add(nonnullInfo);
                } else {
                    continue;
                }
            }
        }
        //获取正则所有字段校验规则
        List<GetRegular> regularMappings = getRegularMapping();
        if (ListUtil.isNotEmpty(regularMappings)) {
            //遍历所有规则
            for (GetRegular getRegular : regularMappings) {
                Date gmtModified = getRegular.getGmtModified();
                if (gmtModified.after(startDate) && endDate.after(gmtModified)) {
                    //如果是今天则将规则存入一个对象集合中待处理
                    regularList.add(getRegular);
                } else {
                    continue;
                }
            }
        }
        //获取字段校验的标准值规则
        List<GetStandardvalueInfoDTO> standardvalueInfo = getStandardvalueInfo();
        if (ListUtil.isNotEmpty(standardvalueInfo)) {
            //遍历所有规则
            for (GetStandardvalueInfoDTO standardvalueInfoDTO : standardvalueInfo) {
                Date gmtModified = standardvalueInfoDTO.getGmtModified();
                if (gmtModified.after(startDate) && endDate.after(gmtModified)) {
                    //如果是今天则将规则存入一个对象集合中待处理
                    standardvalueList.add(standardvalueInfoDTO);
                } else {
                    continue;
                }
            }
        }
        //先判断是否存在规则有修改
        if (ListUtil.isNotEmpty(nonnullInfoList) || ListUtil.isNotEmpty(standardvalueList) || ListUtil.isNotEmpty(regularList)) {
            //获取30天内所有病历
            List<BehospitalInfo> behospitalInfos = getBehospitalInfos(DateUtil.addDate(DateUtil.now(), -30), DateUtil.now(), hospitalId);
            if(ListUtil.isNotEmpty(behospitalInfos)) {
                for (BehospitalInfo behospitalInfo : behospitalInfos) {
                    behospitalCodeList.add(behospitalInfo.getBehospitalCode());
                }
            }
        }
        //非空校验规则今天有修改
        if (ListUtil.isNotEmpty(nonnullInfoList) && ListUtil.isNotEmpty(behospitalCodeList)) {
            //调用校验非空规则方法
            checkNonnull(nonnullInfos, behospitalCodeList, hospitalId,principleId);
        }
        //正则校验规则今天有修改
        if (ListUtil.isNotEmpty(regularList) && ListUtil.isNotEmpty(behospitalCodeList)) {
            //调用校验正则规则
            checkRegular(regularMappings, behospitalCodeList, hospitalId,principleId);
        }
        //标准值校验规则今天有修改
        if (ListUtil.isNotEmpty(standardvalueList) && ListUtil.isNotEmpty(behospitalCodeList)) {
            //调用校验正则规则
            checkStandardvalue(standardvalueInfo, behospitalCodeList, hospitalId,principleId);
        }
    }

    /**
     * 获取时间段内所有病历
     *
     * @param startDate
     * @param endDate
     * @return:
     */
    public List<BehospitalInfo> getBehospitalInfos(Date startDate, Date endDate, Long hospitalId) {
        return behospitalInfoFacade.getBaseMapper().selectList(new QueryWrapper<BehospitalInfo>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("hospital_id", hospitalId)
                .ge("behospital_date", startDate)
                .le("behospital_date", endDate)
        );
    }

    /**
     * 获取非空校验所有规则
     *
     * @param
     * @return:
     */
    public List<NonnullInfo> getNonnullInfo() {
        return nonnullInfoFacade.getBaseMapper().selectList(new QueryWrapper<NonnullInfo>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
        );
    }

    /**
     * 获取正则校验所有规则
     *
     * @param
     * @return:
     */
    public List<GetRegular> getRegularMapping() {
        GetRegularMappingVO getRegularMappingVO = new GetRegularMappingVO();
        return regularMappingFacade.getBaseMapper().getRegularMapping(getRegularMappingVO);
    }

    /**
     * 获取关键值校验所有规则
     *
     * @param
     * @return:
     */
    public List<GetStandardvalueInfoDTO> getStandardvalueInfo() {
        GetStandardvalueInfoVO getStandardvalueInfoVO = new GetStandardvalueInfoVO();
        return standardvalueInfoFacade.getBaseMapper().getStandardvalueInfo(getStandardvalueInfoVO);
    }

    /**
     * 根据病历及规则校验非空规则
     *
     * @param nonnullInfos
     * @param behospitalCodeList
     * @param hospitalId
     * @return:
     */
    public void checkNonnull(List<NonnullInfo> nonnullInfos, List<String> behospitalCodeList, Long hospitalId,Long principleId) {
        for (NonnullInfo nonnullInfo : nonnullInfos) {
            Long columnId = nonnullInfo.getColumnId();
            ColumnInfo columnInfo = columnInfoFacade.getBaseMapper().selectById(columnId);
            //塞入查数据需要的条件
            GetTableColumnInfoVO getTableColumnInfoVO = new GetTableColumnInfoVO();
            getTableColumnInfoVO.setColumnCname(columnInfo.getColumnCname());
            getTableColumnInfoVO.setColumnEname(columnInfo.getColumnEname());
            getTableColumnInfoVO.setTableCname(columnInfo.getTableCname());
            getTableColumnInfoVO.setTableEname(columnInfo.getTableEname());
            getTableColumnInfoVO.setBehospitalCodeList(behospitalCodeList);
            getTableColumnInfoVO.setHospitalId(hospitalId);
            String columnNumber = getColumnNumber(columnInfo.getTableCname());
            getTableColumnInfoVO.setNumberColumnCname(columnNumber);
            List<GetTableColumnInfoDTO> tableColumnVal = getTableColumnVal(getTableColumnInfoVO);
            for (GetTableColumnInfoDTO getTableColumnInfoDTO : tableColumnVal) {
                //枚举获取模块信息
                String modeId = ModeEnum.valueOf(columnInfo.getTableEname()).getKey();
                String modeName = ModeEnum.valueOf(columnInfo.getTableEname()).getName();
                getTableColumnInfoDTO.setModeId(Long.valueOf(modeId));
                getTableColumnInfoDTO.setModeName(modeName);
                String val = getTableColumnInfoDTO.getVal();
                //删除结果表所有的信息（根据type，tableId ,columnId）
                removeNonnullResultSolved(getTableColumnInfoDTO, columnId);
                removeColumnResultSolved(getTableColumnInfoDTO, columnId, ColumnResultTypeEnum.NONNULL_TYPE.getKey());
                //不是必填则直接跳过
                if (NonnullStatusEnum.NOT_NONNULL.equals(nonnullInfo.getIsRequired())) {
                    continue;
                }
                //符合非空情况直接跳过
                if (StringUtil.isNotEmpty(val)) {
                    continue;
                }
                if (StringUtil.isEmpty(val)) {
                    //为空加入非空校验结果表
                    NonnullResult nonnullResult = new NonnullResult();
                    nonnullResult.setHospitalId(getTableColumnInfoDTO.getHospitalId());
                    nonnullResult.setBehospitalCode(getTableColumnInfoDTO.getBehospitalCode());
                    nonnullResult.setModeId(getTableColumnInfoDTO.getModeId());
                    nonnullResult.setModeName(getTableColumnInfoDTO.getModeName());
                    nonnullResult.setHosptialDatatmpCode(modeId);
                    nonnullResult.setHosptialDatatmpName(modeName);
                    nonnullResult.setColumnId(nonnullInfo.getColumnId());
                    nonnullResult.setBehospitalDate(getTableColumnInfoDTO.getBehospitalDate());
                    nonnullResult.setTableCname(columnInfo.getTableCname());
                    nonnullResult.setHospitalDataCode(getTableColumnInfoDTO.getNumberId());
                    nonnullResult.setBehospitalDate(getTableColumnInfoDTO.getBehospitalDate());
                    nonnullResult.setTableEname(columnInfo.getTableEname());
                    nonnullResult.setColumnCname(columnInfo.getColumnCname());
                    nonnullResult.setColumnEname(columnInfo.getColumnEname());
                    if(principleId!=null) {
                        nonnullResult.setCreator(principleId.toString());
                    }
                    nonnullResult.setTableId(getTableColumnInfoDTO.getTableId());
                    nonnullResult.setIsSolved(SolvedStatusEnum.NOT_SOLVED.getKey());
                    nonnullResult.setSolveTime(new Date());
                    nonnullResult.setIsAudited(AuditStatusEnum.NOT_AUDIT.getKey());
                    nonnullResult.setGmtCreate(new Date());
                    nonnullResult.setGmtModified(new Date());
                    nonnullResultFacade.getBaseMapper().insert(nonnullResult);
                    Long id = nonnullResult.getId();
                    //加入总结果表
                    addColumnResult(getTableColumnInfoDTO, columnInfo, columnId, id, ColumnResultTypeEnum.NONNULL_TYPE.getKey(),principleId);
                }
            }
        }
    }

    /**
     * 根据病历及规则校验正则规则
     *
     * @param regularMappings
     * @param behospitalCodeList
     * @param hospitalId
     * @return:
     */
    public void checkRegular(List<GetRegular> regularMappings, List<String> behospitalCodeList, Long hospitalId,Long principleId) {
        for (GetRegular getRegular : regularMappings) {
            Long columnId = getRegular.getColumnId();
            ColumnInfo columnInfo = columnInfoFacade.getBaseMapper().selectById(columnId);
            GetTableColumnInfoVO getTableColumnInfoVO = new GetTableColumnInfoVO();
            getTableColumnInfoVO.setColumnCname(columnInfo.getColumnCname());
            getTableColumnInfoVO.setColumnEname(columnInfo.getColumnEname());
            getTableColumnInfoVO.setTableCname(columnInfo.getTableCname());
            getTableColumnInfoVO.setTableEname(columnInfo.getTableEname());
            getTableColumnInfoVO.setBehospitalCodeList(behospitalCodeList);
            getTableColumnInfoVO.setHospitalId(hospitalId);
            String columnNumber = getColumnNumber(columnInfo.getTableCname());
            getTableColumnInfoVO.setNumberColumnCname(columnNumber);
            List<GetTableColumnInfoDTO> tableColumnVal = getTableColumnVal(getTableColumnInfoVO);
            String regular = getRegular.getVal();
            for (GetTableColumnInfoDTO getTableColumnInfoDTO : tableColumnVal) {
                String modeId = ModeEnum.valueOf(columnInfo.getTableEname()).getKey();
                String modeName = ModeEnum.valueOf(columnInfo.getTableEname()).getName();
                getTableColumnInfoDTO.setModeId(Long.valueOf(modeId));
                getTableColumnInfoDTO.setModeName(modeName);
                String val = getTableColumnInfoDTO.getVal();
                Boolean matches = judgeRegular(regular, val);
                //删除结果表所有的信息（根据type，tableId ,columnId）
                removeRegularResultSolved(getTableColumnInfoDTO, columnId);
                removeColumnResultSolved(getTableColumnInfoDTO, columnId, ColumnResultTypeEnum.REGULAR_TYPE.getKey());
                //符合正则  跳过
                if (matches) {
                    continue;
                }
                //不符合正则
                if (!matches) {
                    //加入校验结果表
                    RegularResult regularResult = new RegularResult();
                    regularResult.setHospitalId(getTableColumnInfoDTO.getHospitalId());
                    regularResult.setBehospitalCode(getTableColumnInfoDTO.getBehospitalCode());
                    regularResult.setModeId(getTableColumnInfoDTO.getModeId());
                    regularResult.setModeName(getTableColumnInfoDTO.getModeName());
                    regularResult.setColumnId(columnId);
                    regularResult.setTableCname(columnInfo.getTableCname());
                    regularResult.setTableEname(columnInfo.getTableEname());
                    regularResult.setColumnCname(columnInfo.getColumnCname());
                    regularResult.setColumnEname(columnInfo.getColumnEname());
                    regularResult.setHosptialDatatmpCode(modeId);
                    regularResult.setHosptialDatatmpName(modeName);
                    regularResult.setBehospitalDate(getTableColumnInfoDTO.getBehospitalDate());
                    regularResult.setHospitalDataCode(getTableColumnInfoDTO.getNumberId());
                    regularResult.setRegularId(getRegular.getId());
                    if(principleId!=null) {
                        regularResult.setCreator(principleId.toString());
                    }
                    regularResult.setRegularName(getRegular.getName());
                    regularResult.setBehospitalDate(getTableColumnInfoDTO.getBehospitalDate());
                    regularResult.setRegularVal(getRegular.getVal());
                    regularResult.setRegularDes(getRegular.getDes());
                    regularResult.setTableId(getTableColumnInfoDTO.getTableId());
                    regularResult.setIsSolved(SolvedStatusEnum.NOT_SOLVED.getKey());
                    regularResult.setSolveTime(new Date());
                    regularResult.setIsAudited(AuditStatusEnum.NOT_AUDIT.getKey());
                    regularResult.setGmtCreate(new Date());
                    regularResult.setGmtModified(new Date());
                    regularResultFacade.getBaseMapper().insert(regularResult);
                    Long id = regularResult.getId();
                    //加入总结果表
                    addColumnResult(getTableColumnInfoDTO, columnInfo, columnId, id, ColumnResultTypeEnum.REGULAR_TYPE.getKey(),principleId);
                }
            }
        }
    }

    /**
     * 根据病历及规则校验关键值规则
     *
     * @param standardvalueInfos
     * @param behospitalCodeList
     * @param hospitalId
     * @return:
     */
    public void checkStandardvalue(List<GetStandardvalueInfoDTO> standardvalueInfos, List<String> behospitalCodeList, Long hospitalId,Long principleId) {
        for (GetStandardvalueInfoDTO standardvalueInfo : standardvalueInfos) {
            Long columnId = standardvalueInfo.getColumnId();
            ColumnInfo columnInfo = columnInfoFacade.getBaseMapper().selectById(columnId);
            GetTableColumnInfoVO getTableColumnInfoVO = new GetTableColumnInfoVO();
            getTableColumnInfoVO.setColumnCname(columnInfo.getColumnCname());
            getTableColumnInfoVO.setColumnEname(columnInfo.getColumnEname());
            getTableColumnInfoVO.setTableCname(columnInfo.getTableCname());
            getTableColumnInfoVO.setTableEname(columnInfo.getTableEname());
            getTableColumnInfoVO.setBehospitalCodeList(behospitalCodeList);
            getTableColumnInfoVO.setHospitalId(hospitalId);
            String columnNumber = getColumnNumber(columnInfo.getTableCname());
            getTableColumnInfoVO.setNumberColumnCname(columnNumber);
            List<GetTableColumnInfoDTO> tableColumnVal = getTableColumnVal(getTableColumnInfoVO);
            String standardvalue = standardvalueInfo.getStandardvalue();
            for (GetTableColumnInfoDTO getTableColumnInfoDTO : tableColumnVal) {
                String modeId = ModeEnum.valueOf(columnInfo.getTableEname()).getKey();
                String modeName = ModeEnum.valueOf(columnInfo.getTableEname()).getName();
                getTableColumnInfoDTO.setModeId(Long.valueOf(modeId));
                getTableColumnInfoDTO.setModeName(modeName);
                String val = getTableColumnInfoDTO.getVal();
                //删除结果表所有的信息（根据type，tableId ,columnId）
                removeStandardvalueResultSolved(getTableColumnInfoDTO, columnId);
                removeColumnResultSolved(getTableColumnInfoDTO, columnId, ColumnResultTypeEnum.STANDARD_TYPE.getKey());
                //判断是否符合标准值
                Boolean contains = judgeStandardvalue(standardvalue, val);
                String standardvalueMapping = getStandardvalueMapping(standardvalue, hospitalId);
                //符合标准值，直接跳过
                if (contains) {
                    continue;
                }
                //不符合标准值  若原表存在则修改，若不存在则新增
                if (!contains) {
                    //加入校验结果表
                    StandardvalueResult standardvalueResult = new StandardvalueResult();
                    standardvalueResult.setHospitalId(getTableColumnInfoDTO.getHospitalId());
                    standardvalueResult.setBehospitalCode(getTableColumnInfoDTO.getBehospitalCode());
                    standardvalueResult.setModeId(getTableColumnInfoDTO.getModeId());
                    standardvalueResult.setModeName(getTableColumnInfoDTO.getModeName());
                    standardvalueResult.setColumnId(columnId);
                    standardvalueResult.setMappings(standardvalueMapping);
                    standardvalueResult.setHosptialDatatmpCode(modeId);
                    standardvalueResult.setBehospitalDate(getTableColumnInfoDTO.getBehospitalDate());
                    standardvalueResult.setHosptialDatatmpName(modeName);
                    standardvalueResult.setTableCname(columnInfo.getTableCname());
                    standardvalueResult.setBehospitalDate(getTableColumnInfoDTO.getBehospitalDate());
                    standardvalueResult.setTableEname(columnInfo.getTableEname());
                    standardvalueResult.setColumnCname(columnInfo.getColumnCname());
                    standardvalueResult.setColumnEname(columnInfo.getColumnEname());
                    standardvalueResult.setHospitalDataCode(getTableColumnInfoDTO.getNumberId());
                    if(principleId!=null) {
                        standardvalueResult.setCreator(principleId.toString());
                    }
                    standardvalueResult.setTableId(getTableColumnInfoDTO.getTableId());
                    standardvalueResult.setIsSolved(SolvedStatusEnum.NOT_SOLVED.getKey());
                    standardvalueResult.setSolveTime(new Date());
                    standardvalueResult.setIsAudited(AuditStatusEnum.NOT_AUDIT.getKey());
                    standardvalueResult.setGmtCreate(new Date());
                    standardvalueResult.setGmtModified(new Date());
                    standardvalueResultFacade.getBaseMapper().insert(standardvalueResult);
                    Long id = standardvalueResult.getId();
                    //加入总结果表
                    addColumnResult(getTableColumnInfoDTO, columnInfo, columnId, id, ColumnResultTypeEnum.STANDARD_TYPE.getKey(),principleId);
                }
            }
        }
    }

    /**
     * 根据表名称字段名称获取具体数据
     *
     * @param getTableColumnInfoVO
     * @return: 具体数据
     */
    public List<GetTableColumnInfoDTO> getTableColumnVal(GetTableColumnInfoVO getTableColumnInfoVO) {
        List<GetTableColumnInfoDTO> tableColumnVal = columnResultFacade.getBaseMapper().getSpecialTableColumnVal(getTableColumnInfoVO);
        return tableColumnVal;
    }

    /**
     * 判断值是否属于标准值
     *
     * @param standardvalue
     * @param value
     * @return:
     */
    public Boolean judgeStandardvalue(String standardvalue, String value) {
        if (StringUtil.isEmpty(value)) {
            return false;
        } else {
            if (standardvalue.contains(value)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断值是否属于正则
     *
     * @param regular
     * @param value
     * @return:
     */
    public Boolean judgeRegular(String regular, String value) {
        if (StringUtil.isEmpty(value)) {
            return false;
        } else {
            if (value.matches(regular)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 删除非空校验结果表信息
     *
     * @param getTableColumnInfoDTO
     * @param columnId
     * @return:
     */
    public void removeNonnullResultSolved(GetTableColumnInfoDTO getTableColumnInfoDTO, Long columnId) {
        nonnullResultFacade.remove(new UpdateWrapper<NonnullResult>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("hospital_id", getTableColumnInfoDTO.getHospitalId())
                .eq("behospital_code", getTableColumnInfoDTO.getBehospitalCode())
                .eq("column_id", columnId)
                .eq("table_id", getTableColumnInfoDTO.getTableId())
        );
    }

    /**
     * 删除正则校验结果表信息
     *
     * @param getTableColumnInfoDTO
     * @param columnId
     * @return:
     */
    public void removeRegularResultSolved(GetTableColumnInfoDTO getTableColumnInfoDTO, Long columnId) {
        regularResultFacade.remove(new UpdateWrapper<RegularResult>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("hospital_id", getTableColumnInfoDTO.getHospitalId())
                .eq("behospital_code", getTableColumnInfoDTO.getBehospitalCode())
                .eq("column_id", columnId)
                .eq("table_id", getTableColumnInfoDTO.getTableId())
        );
    }

    /**
     * 删除关键字校验结果表信息
     *
     * @param getTableColumnInfoDTO
     * @param columnId
     * @return:
     */
    public void removeStandardvalueResultSolved(GetTableColumnInfoDTO getTableColumnInfoDTO, Long columnId) {
        standardvalueResultFacade.remove(new UpdateWrapper<StandardvalueResult>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("hospital_id", getTableColumnInfoDTO.getHospitalId())
                .eq("behospital_code", getTableColumnInfoDTO.getBehospitalCode())
                .eq("column_id", columnId)
                .eq("table_id", getTableColumnInfoDTO.getTableId())
        );
    }

    /**
     * 删除结果总表
     *
     * @param getTableColumnInfoDTO
     * @param columnId
     * @param type
     * @return:
     */
    public void removeColumnResultSolved(GetTableColumnInfoDTO getTableColumnInfoDTO, Long columnId, String type) {
        //未解决修改
        columnResultFacade.remove(new UpdateWrapper<ColumnResult>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("hospital_id", getTableColumnInfoDTO.getHospitalId())
                .eq("behospital_code", getTableColumnInfoDTO.getBehospitalCode())
                .eq("column_id", columnId)
                .eq("table_id", getTableColumnInfoDTO.getTableId())
                .eq("type", type)
        );
    }

    /**
     * 新增校验结果总表信息
     *
     * @param getTableColumnInfoDTO
     * @param columnInfo
     * @param columnId
     * @param id
     * @param type
     * @return:
     */
    public void addColumnResult(GetTableColumnInfoDTO getTableColumnInfoDTO, ColumnInfo columnInfo, Long columnId, Long id, String type,Long principleId) {
        ColumnResult columnResult = new ColumnResult();
        columnResult.setHospitalId(getTableColumnInfoDTO.getHospitalId());
        columnResult.setBehospitalCode(getTableColumnInfoDTO.getBehospitalCode());
        columnResult.setModeId(getTableColumnInfoDTO.getModeId());
        columnResult.setModeName(getTableColumnInfoDTO.getModeName());
        columnResult.setHosptialDatatmpCode(getTableColumnInfoDTO.getModeId().toString());
        columnResult.setHosptialDatatmpName(getTableColumnInfoDTO.getModeName());
        columnResult.setHospitalDataCode(getTableColumnInfoDTO.getNumberId());
        columnResult.setColumnId(columnId);
        if(principleId!=null) {
            columnResult.setCreator(principleId.toString());
        }
        columnResult.setBehospitalDate(getTableColumnInfoDTO.getBehospitalDate());
        columnResult.setTableCname(columnInfo.getTableCname());
        columnResult.setTableEname(columnInfo.getTableEname());
        columnResult.setColumnCname(columnInfo.getColumnCname());
        columnResult.setColumnEname(columnInfo.getColumnEname());
        columnResult.setTableId(getTableColumnInfoDTO.getTableId());
        //数据缺失
        if (ColumnResultTypeEnum.NONNULL_TYPE.getKey().equals(type)) {
            columnResult.setType(ColumnResultTypeEnum.NONNULL_TYPE.getKey());
        }
        //关键值
        if (ColumnResultTypeEnum.STANDARD_TYPE.getKey().equals(type)) {
            columnResult.setType(ColumnResultTypeEnum.STANDARD_TYPE.getKey());
        }
        //正则
        if (ColumnResultTypeEnum.REGULAR_TYPE.getKey().equals(type)) {
            columnResult.setType(ColumnResultTypeEnum.REGULAR_TYPE.getKey());
        }
        columnResult.setResultId(id);
        columnResult.setIsSolved(SolvedStatusEnum.NOT_SOLVED.getKey());
        columnResult.setSolveTime(new Date());
        columnResult.setIsAudited(AuditStatusEnum.NOT_AUDIT.getKey());
        columnResult.setGmtCreate(new Date());
        columnResult.setGmtModified(new Date());
        columnResultFacade.getBaseMapper().insert(columnResult);
    }


    /**
     * 根据表明获取该表的编号字段
     *
     * @param tableCname
     * @return:
     */
    public String getColumnNumber(String tableCname) {
        String columnEname = null;
        List<ColumnInfo> columnInfoList = columnInfoFacade.getBaseMapper().selectList(new QueryWrapper<ColumnInfo>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("type", ColumnTypeEnum.FIELD_NUMBER.getKey())
        );
        for (ColumnInfo columnInfo : columnInfoList) {
            String tableCname1 = columnInfo.getTableCname();
            if (tableCname.equals(tableCname1)) {
                columnEname = columnInfo.getColumnEname();
            }
        }
        return columnEname;
    }

    /**
     * 获取关键值映射
     *
     * @param standardvalue
     * @param hospitalId
     * @return:
     */
    public String getStandardvalueMapping(String standardvalue, Long hospitalId) {
        String[] split = standardvalue.split(";");
        StringBuffer stringBuffer = new StringBuffer();
        for (String s : split) {
            stringBuffer = stringBuffer.append(hospitalId).append("-").append(s).append(",");
        }
        String toString = stringBuffer.deleteCharAt(stringBuffer.length() - 1).toString();
        return toString;
    }

}
