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.StrIllSeriousl;
import com.diagbot.entity.StrIllSeriousl;
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.StrIllSeriouslServiceImpl;
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.AStrIllSeriouslVO;
import com.diagbot.vo.str.StrContentVO;
import com.diagbot.vo.str.StrIllSeriouslVO;
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 BStrIllSeriouslFacade extends StrIllSeriouslServiceImpl {

    @Autowired
    @Qualifier("strIllSeriouslServiceImpl")
    private StrIllSeriouslServiceImpl strIllSeriouslService;
    @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,"strIllSeriousl");

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

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

    /**
     * @Description:解析后存储数据
     * @Author:liuqq
     * @time: ${DATE} ${TIME}
     **/
    public void dealData(String columnMap,Map<String, Object> entityMap,Long hospitalId){
        StrIllSeriousl strIllSeriousl=new StrIllSeriousl();
        try {
            AStrIllSeriouslVO strIllSeriouslVO=(AStrIllSeriouslVO) MapUtil.mapToObject(entityMap, AStrIllSeriouslVO.class);
            BeanUtils.copyProperties(strIllSeriouslVO,strIllSeriousl);
            strIllSeriousl.setHospitalId(hospitalId);//医院编码
            strIllSeriousl.setPatientSignDate(DateUtil.parseDateTime(strIllSeriouslVO.getPatientSignDate()));
            strIllSeriousl.setDoctorSignDate(DateUtil.parseDateTime(strIllSeriouslVO.getDoctorSignDate()));//审核时间
            strIllSeriousl.setRecordDate(DateUtil.parseDateTime(strIllSeriouslVO.getRecordDate()));//病历日期

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

        }catch (Exception e){
            log.error(e.getMessage(),e);
            aMedAbnormalInfoFacade.saveAbnormalInfo("病重通知单", strIllSeriousl.getRecId(),JSON.toJSONString(entityMap),"",e.getMessage());
        }

    }

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

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

                if(logSwitch){
                    strIllSeriouslList.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<StrIllSeriousl> initData(List<StrIllSeriouslVO> list) throws Exception{
        List<StrIllSeriousl> tList=Lists.newArrayList();
        for (StrIllSeriouslVO s:list) {
            StrIllSeriousl t=new StrIllSeriousl();
            BeanUtils.copyProperties(s,t);
            if(StringUtil.isNotEmpty(s.getRecordDate())){
                t.setRecordDate(DateUtil.parseDateTime(s.getRecordDate()));//病历日期
            }
            if(StringUtil.isNotEmpty(s.getPatientSignDate())){
                t.setPatientSignDate(DateUtil.parseDateTime(s.getPatientSignDate()));//病人签名日期
            }
            if(StringUtil.isNotEmpty(s.getDoctorSignDate())){
                t.setDoctorSignDate(DateUtil.parseDateTime(s.getDoctorSignDate()));//医生签名日期
            }
            Map<String, String> columnMap=columnFacade.getColumn(CacheKeyEnum.ILL_SERIOUSL.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<StrIllSeriousl> list){
        List<StrIllSeriousl> addE = Lists.newLinkedList();
        List<StrIllSeriousl> updateE = Lists.newLinkedList();
        if (list != null && list.size() > 0) {
            list.stream().forEach(s -> {
                StrIllSeriousl strIllSeriousl = this.getOne(new QueryWrapper<StrIllSeriousl>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("rec_id", s.getRecId())
                        .eq("hospital_id", s.getHospitalId())
                        .eq("behospital_code",s.getBehospitalCode()), false);
                if (strIllSeriousl != null) {
                    s.setGmtModified(new Date());
                    updateE.add(s);
                } else {
                    s.setGmtCreate(new Date());
                    addE.add(s);
                }
            });
        }
        if(addE.size()>0){
            strIllSeriouslService.saveBatch(addE);
        }
        if(updateE.size()>0){
            this.baseMapper.updateBatchByKey(updateE);
        }
    }
}
