package com.diagbot.facade.str;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.diagbot.dto.RespDTO;
import com.diagbot.dto.data.ColumnZhAndChDTO;
import com.diagbot.entity.StrAdmissionNote;
import com.diagbot.enums.CacheKeyEnum;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.facade.data.AMedAbnormalInfoFacade;
import com.diagbot.facade.data.ColumnFacade;
import com.diagbot.service.impl.StrAdmissionNoteServiceImpl;
import com.diagbot.util.DateUtil;
import com.diagbot.util.EntityUtil;
import com.diagbot.util.MapUtil;
import com.diagbot.util.StringUtil;
import com.diagbot.vo.data.AStrAdmissionNoteVO;
import com.diagbot.vo.str.StrAdmissionNoteVO;
import com.diagbot.vo.str.StrContentVO;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
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.Date;
import java.util.List;
import java.util.Map;

@Component
public class BStrAdmissionNoteFacade extends StrAdmissionNoteServiceImpl {

    @Autowired
    @Qualifier("strAdmissionNoteServiceImpl")
    private StrAdmissionNoteServiceImpl strAdmissionNoteService;
    @Autowired
    private ColumnFacade columnFacade;
    @Autowired
    private AMedAbnormalInfoFacade aMedAbnormalInfoFacade;

    @Value("${log_switch.enable}")
    private boolean logSwitch;

    public void getColumnZhAndCh() {
        List<ColumnZhAndChDTO> list = this.baseMapper.getColumnZhAndCh();
        list.forEach(s -> {
            s.setEn(NamingStrategy.underlineToCamel(s.getEn()));
        });

        Map<String, String> columnMap = EntityUtil.makeMapWithKeyValue(list, "ch", "en");
        Boolean flag = columnFacade.createColumn(columnMap, "strAdmissionNote");

        //Map<String, String> map=columnFacade.getColumn("strAdmissionNote");
        if (!flag) {
            return;
        }
    }
    /**
     * @Description:不解析时入库
     * @Author:liuqq
     * @time: ${DATE} ${TIME}
     **/
    public void dealData(StrContentVO strContentVO){
        StrAdmissionNote strAdmissionNote = new StrAdmissionNote();
        strAdmissionNote.setRecId(strContentVO.getRecId());
        strAdmissionNote.setBehospitalCode(strContentVO.getBehospitalCode());
        strAdmissionNote.setHospitalId(strContentVO.getHospitalId());
        strAdmissionNote.setWholeData(strContentVO.getWholeData());
        //判断数据库中是否存在，不存在insert
        if (isExist(strAdmissionNote)) {
            strAdmissionNote.setGmtCreate(new Date());//记录创建时间
            this.save(strAdmissionNote);
        } else {
            strAdmissionNote.setGmtModified(new Date());//记录修改时间
            this.update(strAdmissionNote, new QueryWrapper<StrAdmissionNote>()
                    .eq("rec_id", strAdmissionNote.getRecId())
                    .eq("hospital_id", strAdmissionNote.getHospitalId())
                    .eq("behospital_code", strAdmissionNote.getBehospitalCode()));
        }
    }

    /**
     * @Description:解析后存储数据
     * @Author:liuqq
     * @time: ${DATE} ${TIME}
     **/
    public void dealData(String columnMap, Map<String, Object> entityMap, Long hospitalId) throws Exception {
        StrAdmissionNote strAdmissionNote = new StrAdmissionNote();
        AStrAdmissionNoteVO strAdmissionNoteVO = (AStrAdmissionNoteVO) MapUtil.mapToObject(entityMap, AStrAdmissionNoteVO.class);
        BeanUtils.copyProperties(strAdmissionNoteVO, strAdmissionNote);
        strAdmissionNote.setHospitalId(hospitalId);//医院编码

        strAdmissionNote.setAuditDate(DateUtil.parseDateTime(strAdmissionNoteVO.getAuditDate()));//审核时间
        strAdmissionNote.setRecDate(DateUtil.parseDateTime(strAdmissionNoteVO.getRecDate()));//记录时间
        strAdmissionNote.setBehospitalDate(DateUtil.parseDateTime(strAdmissionNoteVO.getBehospitalDate()));//入院日期
        strAdmissionNote.setBirthday(DateUtil.parseDate(strAdmissionNoteVO.getBirthday()));//出生日期
        strAdmissionNote.setRecordDate(DateUtil.parseDateTime(strAdmissionNoteVO.getRecordDate()));//病历日期

        strAdmissionNote.setWholeData(columnMap);
        //判断数据库中是否存在，不存在insert
        if (isExist(strAdmissionNote)) {
            strAdmissionNote.setGmtCreate(new Date());//记录创建时间
            this.save(strAdmissionNote);
        } else {
            strAdmissionNote.setGmtModified(new Date());//记录修改时间
            this.update(strAdmissionNote, new QueryWrapper<StrAdmissionNote>()
                    .eq("rec_id", strAdmissionNote.getRecId())
                    .eq("hospital_id", strAdmissionNote.getHospitalId())
                    .eq("behospital_code", strAdmissionNote.getBehospitalCode()));
        }
    }

    public Boolean isExist(StrAdmissionNote strAdmissionNote) {
        Boolean flag = true;
        int count = this.baseMapper.selectCount(new QueryWrapper<StrAdmissionNote>()
                .eq("rec_id", strAdmissionNote.getRecId())
                .eq("hospital_id", strAdmissionNote.getHospitalId())
                .eq("behospital_code", strAdmissionNote.getBehospitalCode()));
        if (count > 0) {
            flag = false;
        }
        return flag;
    }

    /**
     * @Description:入院记录-结构化-独立入口
     * @Author:liuqq
     * @time: ${DATE} ${TIME}
     **/
    public RespDTO execDealData(List<StrAdmissionNoteVO> list) {
        try{
            if(list!=null && list.size()>0){
                //循环验证数据有效性
                for (StrAdmissionNoteVO strAdmissionNoteVO:list) {
                    if("".equals(strAdmissionNoteVO.getRecId())) {
                        return RespDTO.onError("请输入记录编号!");
                    }else if(strAdmissionNoteVO.getHospitalId()==null){
                        return RespDTO.onError("请输入医院编码!");
                    }else if("".equals(strAdmissionNoteVO.getBehospitalCode())){
                        return RespDTO.onError("请输入病人住院编码!");
                    }
                }
                //初始、格式化数据
                List<StrAdmissionNote> strAdmissionNoteList=initData(list);
                execute(strAdmissionNoteList);

                if(logSwitch){
                    strAdmissionNoteList.forEach(s->{
                        aMedAbnormalInfoFacade.saveAbnormalInfo("结构化-入院记录-正常", s.getRecId(), JSON.toJSONString(list), "", "");
                    });
                }
                return RespDTO.onSuc("操作正常！");
            }else{
                return RespDTO.onError("未接收到数据!");
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            if(list!=null && list.size()>0) {
                list.forEach(s->{
                    aMedAbnormalInfoFacade.saveAbnormalInfo("结构化-入院记录-异常", s.getRecId(), JSON.toJSONString(list), "", e.getMessage());
                });
            }
            return RespDTO.onError("数据处理异常，详情查看日志表");
        }

    }

    /**
     * @Description:入库前，初始化数据库
     * @Author:liuqq
     * @time: ${DATE} ${TIME}
     **/
    private List<StrAdmissionNote> initData(List<StrAdmissionNoteVO> list) throws Exception{
        List<StrAdmissionNote> strAdmissionNoteList=Lists.newArrayList();
        for (StrAdmissionNoteVO s:list) {
            StrAdmissionNote t=new StrAdmissionNote();
            BeanUtils.copyProperties(s,t);
            if(StringUtil.isNotEmpty(s.getRecordDate())){
                t.setRecordDate(DateUtil.parseDateTime(s.getRecordDate()));//病历日期
            }
            if(StringUtil.isNotEmpty(s.getBirthday())){
                t.setBirthday(DateUtil.parseDate(s.getBirthday()));//出生日期
            }
            if(StringUtil.isNotEmpty(s.getBehospitalDate())){
                t.setBehospitalDate(DateUtil.parseDateTime(s.getBehospitalDate()));//入院日期
            }
            if(StringUtil.isNotEmpty(s.getRecDate())){
                t.setRecDate(DateUtil.parseDateTime(s.getRecDate()));//记录时间
            }
            if(StringUtil.isNotEmpty(s.getAuditDate())){
                t.setAuditDate(DateUtil.parseDateTime(s.getAuditDate()));//审核时间
            }
            Map<String, String> columnMap=columnFacade.getColumn(CacheKeyEnum.BEHOSPITAL_INFO.getName());
            Map<String, Object> entityMap=MapUtil.objectToMap(s);
            Map<String, Object> wholeMap=MapUtil.objcetKeyConvert(columnMap,entityMap);
            t.setWholeData(JSON.toJSONString(wholeMap));
            strAdmissionNoteList.add(t);
        }
        return strAdmissionNoteList;
    }

    public void execute(List<StrAdmissionNote> list) throws Exception{
        List<StrAdmissionNote> addE = Lists.newLinkedList();
        List<StrAdmissionNote> updateE = Lists.newLinkedList();
        if (list != null && list.size() > 0) {
            list.forEach(s -> {
                StrAdmissionNote strAdmissionNote = this.getOne(new QueryWrapper<StrAdmissionNote>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("rec_id", s.getRecId())
                        .eq("hospital_id", s.getHospitalId())
                        .eq("behospital_code",s.getBehospitalCode()), false);
                if (strAdmissionNote != null) {
                    s.setGmtModified(new Date());
                    updateE.add(s);
                } else {
                    s.setGmtCreate(new Date());
                    addE.add(s);
                }
            });
        }
        if(addE.size()>0){
            strAdmissionNoteService.saveBatch(addE);
        }
        if(updateE.size()>0){
            this.baseMapper.updateBatchByKey(updateE);
        }
    }

}
