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.StrBloodResult;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.facade.data.AMedAbnormalInfoFacade;
import com.diagbot.facade.data.ColumnFacade;
import com.diagbot.service.impl.StrBloodResultServiceImpl;
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.AStrBloodResultVO;
import com.diagbot.vo.str.StrBloodResultVO;
import com.diagbot.vo.str.StrContentVO;
import com.google.common.collect.Lists;

/**
 * @Description:输血后效果评价-业务类
 * @Author:liuqq
 * @time: ${DATE} ${TIME}
 **/
@Component
public class BStrBloodResultFacade extends StrBloodResultServiceImpl {

//    @Autowired
//    @Qualifier("strBloodResultServiceImpl")
//    private StrBloodResultServiceImpl strBloodResultService;
    @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,"strBloodResult");
        if(!flag){
            return;
        }
        //Map<String, String> map=columnFacade.getColumn("strBloodResult");
    }

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

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

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

        }catch (Exception e){
            log.error(e.getMessage(),e);
            aMedAbnormalInfoFacade.saveAbnormalInfo("输血效果评价",strBloodResult.getRecId(), JSON.toJSONString(entityMap),"",e.getMessage());
        }

    }

    /**
     * @Description: 是否存在
     * @Author:liuqq
     * @time: ${DATE} ${TIME}
     **/
    public Boolean isExist(StrBloodResult strBloodResult){
        Boolean flag=true;
        int count = this.baseMapper.selectCount(new QueryWrapper<StrBloodResult>()
                .eq("rec_id", strBloodResult.getRecId())
                .eq("hospital_id", strBloodResult.getHospitalId())
                .eq("behospital_code", strBloodResult.getBehospitalCode()));
        if(count>0){
            flag=false;
        }
        return flag;
    }

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

                if(logSwitch){
                    strBloodResultList.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("数据处理异常，详情查看日志表");
        }
    }

    private List<StrBloodResult> initData(List<StrBloodResultVO> list) throws Exception{
        List<StrBloodResult> tList=Lists.newArrayList();
        for (StrBloodResultVO s:list) {
            StrBloodResult t=new StrBloodResult();
            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.getAuditDate())){
                t.setAuditDate(DateUtil.parseDateTime(s.getAuditDate()));//审核时间
            }
//            Map<String, String> columnMap=columnFacade.getColumn(CacheKeyEnum.BLOOD_RESULT.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<StrBloodResult> list) throws Exception{
        List<StrBloodResult> addE = Lists.newLinkedList();
        List<StrBloodResult> updateE = Lists.newLinkedList();
        if (list != null && list.size() > 0) {
            list.stream().forEach(s -> {
                StrBloodResult strBloodResult = this.getOne(new QueryWrapper<StrBloodResult>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("rec_id", s.getRecId())
                        .eq("hospital_id", s.getHospitalId())
                        .eq("behospital_code",s.getBehospitalCode()), false);
                if (strBloodResult != 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);
        }
    }
}
