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.StrOperativeFirstRecord;
import com.diagbot.entity.StrOperativeFirstRecord;
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.StrOperativeFirstRecordServiceImpl;
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.AStrOperativeFirstRecordVO;
import com.diagbot.vo.str.StrContentVO;
import com.diagbot.vo.str.StrOperativeFirstRecordVO;
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 BStrOperativeFirstRecordFacade extends StrOperativeFirstRecordServiceImpl {

    @Autowired
    @Qualifier("strOperativeFirstRecordServiceImpl")
    private StrOperativeFirstRecordServiceImpl strOperativeFirstRecordService;
    @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,"strOperativeFirstRecord");

        if(!flag){
            return;
        }
    }

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

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

            strOperativeFirstRecord.setAuditDate(DateUtil.parseDateTime(strOperativeFirstRecordVO.getAuditDate()));//审核时间
            strOperativeFirstRecord.setRecDate(DateUtil.parseDateTime(strOperativeFirstRecordVO.getRecDate()));//记录时间
            strOperativeFirstRecord.setOperationDate(DateUtil.parseDateTime(strOperativeFirstRecordVO.getOperationDate()));//手术日期
            strOperativeFirstRecord.setStartTime(DateUtil.parseDate(strOperativeFirstRecordVO.getStartTime()));//开始时间
            strOperativeFirstRecord.setEndTime(DateUtil.parseDate(strOperativeFirstRecordVO.getEndTime()));//结束时间
            strOperativeFirstRecord.setRecordDate(DateUtil.parseDateTime(strOperativeFirstRecordVO.getRecordDate()));//病历日期

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

        }catch (Exception e){
            log.error(e.getMessage(),e);
            aMedAbnormalInfoFacade.saveAbnormalInfo("术后首程",strOperativeFirstRecord.getRecId(), JSON.toJSONString(entityMap),"",e.getMessage());
        }

    }

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

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

                if(logSwitch){
                    strOperativeFirstRecordList.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<StrOperativeFirstRecord> initData(List<StrOperativeFirstRecordVO> list) throws Exception{
        List<StrOperativeFirstRecord> tList=Lists.newArrayList();
        for (StrOperativeFirstRecordVO s:list) {
            StrOperativeFirstRecord t=new StrOperativeFirstRecord();
            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()));//审核时间
            }
            if(StringUtil.isNotEmpty(s.getOperationDate())){
                t.setOperationDate(DateUtil.parseDateTime(s.getOperationDate()));//手术日期
            }
            if(StringUtil.isNotEmpty(s.getStartTime())){
                t.setEndTime(DateUtil.parseDateTime(s.getStartTime()));//开始时间
            }
            if(StringUtil.isNotEmpty(s.getEndTime())){
                t.setEndTime(DateUtil.parseDateTime(s.getEndTime()));//结束时间
            }
            Map<String, String> columnMap=columnFacade.getColumn(CacheKeyEnum.OPERATIVE_FIRST_RECORD.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<StrOperativeFirstRecord> list){
        List<StrOperativeFirstRecord> addE = Lists.newLinkedList();
        List<StrOperativeFirstRecord> updateE = Lists.newLinkedList();
        if (list != null && list.size() > 0) {
            list.stream().forEach(s -> {
                StrOperativeFirstRecord strOperativeFirstRecord = this.getOne(new QueryWrapper<StrOperativeFirstRecord>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("rec_id", s.getRecId())
                        .eq("hospital_id", s.getHospitalId())
                        .eq("behospital_code",s.getBehospitalCode()), false);
                if (strOperativeFirstRecord != null) {
                    s.setGmtModified(new Date());
                    updateE.add(s);
                } else {
                    s.setGmtCreate(new Date());
                    addE.add(s);
                }
            });
        }
        if(addE.size()>0){
            strOperativeFirstRecordService.saveBatch(addE);
        }
        if(updateE.size()>0){
            this.baseMapper.updateBatchByKey(updateE);
        }
    }
}
