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.StrDeathDiscussion;
import com.diagbot.entity.StrDeathDiscussion;
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.StrDeathDiscussionServiceImpl;
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.AStrDeathDiscussionVO;
import com.diagbot.vo.str.StrContentVO;
import com.diagbot.vo.str.StrDeathDiscussionVO;
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 BStrDeathDiscussionFacade extends StrDeathDiscussionServiceImpl {
    @Autowired
    @Qualifier("strDeathDiscussionServiceImpl")
    private StrDeathDiscussionServiceImpl strDeathDiscussionService;
    @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,"strDeathDiscussion");

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

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

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

            strDeathDiscussion.setAuditDate(DateUtil.parseDateTime(strDeathDiscussionVO.getAuditDate()));//审核时间
            strDeathDiscussion.setRecDate(DateUtil.parseDateTime(strDeathDiscussionVO.getRecDate()));//记录时间
            strDeathDiscussion.setDeathDate(DateUtil.parseDateTime(strDeathDiscussionVO.getDeathDate()));//死亡时间
            strDeathDiscussion.setDiscussDate(DateUtil.parseDate(strDeathDiscussionVO.getDiscussDate()));//讨论时间
            strDeathDiscussion.setRecordDate(DateUtil.parseDateTime(strDeathDiscussionVO.getRecordDate()));//病历日期

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

        }catch (Exception e){
            log.error(e.getMessage(),e);
            aMedAbnormalInfoFacade.saveAbnormalInfo("死亡病例讨论记录",strDeathDiscussion.getRecId(), JSON.toJSONString(entityMap),"",e.getMessage());
        }

    }

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

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

                if(logSwitch){
                    strDeathDiscussionList.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<StrDeathDiscussion> initData(List<StrDeathDiscussionVO> list) throws Exception{
        List<StrDeathDiscussion> tList=Lists.newArrayList();
        for (StrDeathDiscussionVO s:list) {
            StrDeathDiscussion t=new StrDeathDiscussion();
            BeanUtils.copyProperties(s,t);
            if(StringUtil.isNotEmpty(s.getRecordDate())){
                t.setRecordDate(DateUtil.parseDateTime(s.getRecordDate()));//病历日期
            }
            if(StringUtil.isNotEmpty(s.getDeathDate())){
                t.setDeathDate(DateUtil.parseDateTime(s.getDeathDate()));//死亡日期
            }
            if(StringUtil.isNotEmpty(s.getDiscussDate())){
                t.setDiscussDate(DateUtil.parseDateTime(s.getDiscussDate()));//讨论时间
            }
            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.DEATH_DISCUSSION.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<StrDeathDiscussion> list){
        List<StrDeathDiscussion> addE = Lists.newLinkedList();
        List<StrDeathDiscussion> updateE = Lists.newLinkedList();
        if (list != null && list.size() > 0) {
            list.stream().forEach(s -> {
                StrDeathDiscussion strDeathDiscussion = this.getOne(new QueryWrapper<StrDeathDiscussion>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("rec_id", s.getRecId())
                        .eq("hospital_id", s.getHospitalId())
                        .eq("behospital_code",s.getBehospitalCode()), false);
                if (strDeathDiscussion != null) {
                    s.setGmtModified(new Date());
                    updateE.add(s);
                } else {
                    s.setGmtCreate(new Date());
                    addE.add(s);
                }
            });
        }
        if(addE.size()>0){
            strDeathDiscussionService.saveBatch(addE);
        }
        if(updateE.size()>0){
            this.baseMapper.updateBatchByKey(updateE);
        }
    }
}
