package com.diagbot.facade.str;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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.StrBloodTransfusion;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.facade.data.AMedAbnormalInfoFacade;
import com.diagbot.facade.data.ColumnFacade;
import com.diagbot.service.impl.StrBloodTransfusionServiceImpl;
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.AStrBloodTransfusionVO;
import com.diagbot.vo.str.StrBloodTransfusionVO;
import com.diagbot.vo.str.StrContentVO;
import com.google.common.collect.Lists;

/**
 * @Description:输血/血制品病程记录-业务类
 * @Author:liuqq
 * @time: ${DATE} ${TIME}
 **/
@Component
public class BStrBloodTransfusionFacade extends StrBloodTransfusionServiceImpl {

//    @Autowired
//    @Qualifier("strBloodTransfusionServiceImpl")
//    private StrBloodTransfusionServiceImpl strBloodTransfusionService;
    @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,"strBloodTransfusion");

        //Map<String, String> map=columnFacade.getColumn("strConsultationNote");
        if(!flag){
            return;
        }
    }

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

    /**
     * @Description:解析后存储数据
     * @Author:liuqq
     * @time: ${DATE} ${TIME}
     **/
    public void dealData(String columnMap,Map<String, Object> entityMap,Long hospitalId){
        StrBloodTransfusion strBloodTransfusion=new StrBloodTransfusion();
        try {
            AStrBloodTransfusionVO strBloodTransfusionVO=(AStrBloodTransfusionVO) MapUtil.mapToObject(entityMap, AStrBloodTransfusionVO.class);
            BeanUtils.copyProperties(strBloodTransfusionVO,strBloodTransfusion);
            strBloodTransfusion.setHospitalId(hospitalId);//医院编码
            strBloodTransfusion.setStartTime(DateUtil.parseDateTime(strBloodTransfusionVO.getStartTime()));
            strBloodTransfusion.setEndTime(DateUtil.parseDateTime(strBloodTransfusionVO.getEndTime()));
            strBloodTransfusion.setAuditDate(DateUtil.parseDateTime(strBloodTransfusionVO.getAuditDate()));//审核时间
            strBloodTransfusion.setRecDate(DateUtil.parseDateTime(strBloodTransfusionVO.getRecDate()));//记录时间
            strBloodTransfusion.setRecordDate(DateUtil.parseDateTime(strBloodTransfusionVO.getRecordDate()));//病历日期

            strBloodTransfusion.setWholeData(columnMap);

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

        }catch (Exception e){
            log.error(e.getMessage(),e);
            aMedAbnormalInfoFacade.saveAbnormalInfo("输血记录", strBloodTransfusion.getRecId(),JSON.toJSONString(entityMap),"",e.getMessage());
        }

    }

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

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

                if(logSwitch){
                    strBloodTransfusionList.forEach(s->{
                        aMedAbnormalInfoFacade.saveAbnormalInfo("结构化-输血/血制品病程记录-正常", s.getRecId(), JSON.toJSONString(s), "", "");
                    });
                }
                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("数据处理异常，详情查看日志表");
        }
    }

    private List<StrBloodTransfusion> initData(List<StrBloodTransfusionVO> list) throws Exception{
        List<StrBloodTransfusion> tList=Lists.newArrayList();
        for (StrBloodTransfusionVO s:list) {
            StrBloodTransfusion t=new StrBloodTransfusion();
            BeanUtils.copyProperties(s,t);
            if(StringUtil.isNotEmpty(s.getRecordDate())){
                t.setRecordDate(DateUtil.parseDateTime(s.getRecordDate()));//病历日期
            }
            if(StringUtil.isNotEmpty(s.getRecDate())){
                t.setRecDate(DateUtil.parseDateTime(s.getRecDate()));//记录时间
            }
            if(StringUtil.isNotEmpty(s.getStartTime())){
                t.setStartTime(DateUtil.parseDateTime(s.getStartTime()));//开始日期
            }
            if(StringUtil.isNotEmpty(s.getEndTime())){
                t.setEndTime(DateUtil.parseDateTime(s.getEndTime()));//结束日期
            }
            if(StringUtil.isNotEmpty(s.getAuditDate())){
                t.setAuditDate(DateUtil.parseDateTime(s.getAuditDate()));//审核时间
            }
//            Map<String, String> columnMap=columnFacade.getColumn(CacheKeyEnum.BLOOD_TRANSFUSION.getName());
//            Map<String, Object> entityMap=MapUtil.objectToMap(s);
//            Map<String, Object> wholeMap=MapUtil.objcetKeyConvert(columnMap,entityMap);
            //t.setWholeData(JSON.toJSONString(wholeMap));
            tList.add(t);
        }
        return tList;
    }

    public void execute(List<StrBloodTransfusion> list){
        try {
            List<StrBloodTransfusion> addE = Lists.newLinkedList();
            List<StrBloodTransfusion> updateE = Lists.newLinkedList();
            if (list != null && list.size() > 0) {
                list.stream().forEach(s -> {
                    StrBloodTransfusion strBloodTransfusion = this.getOne(new QueryWrapper<StrBloodTransfusion>()
                            .eq("is_deleted", IsDeleteEnum.N.getKey())
                            .eq("rec_id", s.getRecId())
                            .eq("hospital_id", s.getHospitalId())
                            .eq("behospital_code",s.getBehospitalCode()), false);
                    if (strBloodTransfusion != null) {
                        s.setGmtModified(new Date());
                        updateE.add(s);
                    } else {
                        s.setGmtCreate(new Date());
                        addE.add(s);
                    }
                });
            }
            if(addE.size()>0){
                saveBatch(addE);
            }
            if(updateE.size()>0){
                this.baseMapper.updateBatchByKey(updateE);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            aMedAbnormalInfoFacade.saveAbnormalInfo("结构化-入院记录","", JSON.toJSONString(list),"",e.getMessage());
        }
    }
}
