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.StrInformedConsent;
import com.diagbot.entity.StrInformedConsent;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.facade.data.AMedAbnormalInfoFacade;
import com.diagbot.facade.data.ColumnFacade;
import com.diagbot.service.impl.StrInformedConsentServiceImpl;
import com.diagbot.util.EntityUtil;
import com.diagbot.util.MapUtil;
import com.diagbot.vo.str.StrContentVO;
import com.diagbot.vo.str.StrInformedConsentVO;
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 BStrInformedConsentFacade extends StrInformedConsentServiceImpl {

    @Autowired
    @Qualifier("strInformedConsentServiceImpl")
    private StrInformedConsentServiceImpl strInformedConsentService;
    @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,"strInformedConsent");
        if(!flag){
            return;
        }
    }

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

    /**
     * @Description:解析后存储数据
     * @Author:liuqq
     * @time: ${DATE} ${TIME}
     **/
    public void dealData(String columnMap,Map<String, Object> entityMap,Long hospitalId){
        StrInformedConsent strInformedConsent=new StrInformedConsent();
        try {
            StrInformedConsentVO strInformedConsentVO=(StrInformedConsentVO) MapUtil.mapToObject(entityMap, StrInformedConsentVO.class);
            BeanUtils.copyProperties(strInformedConsentVO,strInformedConsent);
            strInformedConsent.setHospitalId(hospitalId);//医院编码
            //判断数据库中是否存在，不存在insert
            if(isExist(strInformedConsent)){
                strInformedConsent.setGmtCreate(new Date());//记录创建时间
                this.save(strInformedConsent);
            }else{
                strInformedConsent.setGmtModified(new Date());//记录修改时间
                this.update(strInformedConsent,new QueryWrapper<StrInformedConsent>()
                        .eq("rec_id", strInformedConsent.getRecId())
                        .eq("hospital_id", strInformedConsent.getHospitalId())
                        .eq("behospital_code", strInformedConsent.getBehospitalCode()));
            }

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

    }

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

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

                if(logSwitch){
                    strInformedConsentList.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<StrInformedConsent> initData(List<StrInformedConsentVO> list) throws Exception{
        List<StrInformedConsent> tList= Lists.newArrayList();
        for (StrInformedConsentVO s:list) {
            StrInformedConsent t=new StrInformedConsent();
            BeanUtils.copyProperties(s,t);
            tList.add(t);
        }
        return tList;
    }

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