package com.diagbot.facade.data;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.diagbot.dto.RespDTO;
import com.diagbot.dto.data.AMedicalRecordContentDTO;
import com.diagbot.entity.MedicalRecordContent;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.service.impl.MedicalRecordContentServiceImpl;
import com.diagbot.util.*;
import com.diagbot.vo.data.ADeleteFlagVO;
import com.diagbot.vo.data.AMedicalRecordContentVO;
import com.google.common.collect.Lists;
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;

@Component
public class AMedicalRecordContentFacade extends MedicalRecordContentServiceImpl{

    @Qualifier("medicalRecordContentServiceImpl")
    @Autowired
    private MedicalRecordContentServiceImpl medicalRecordContentService;
    @Autowired
    private AMedAbnormalInfoFacade aMedAbnormalInfoFacade;
    @Value("${log_switch.enable}")
    private boolean logSwitch;

    private TZDBConn tzDBConn = new TZDBConn();

    /**
     * 终末质控-同步前一天的病历详细记录
     */
    public void executeMrRecordContent() {
        //String sql="select * from mr_mrcontent  where cjcxrq>=dateadd(day,-2,getdate()) and cjcxrq<=getdate()";
        String sql="select BLJLID,BLJLNR from mr_mrcontent  where cjcxrq>=(select CONVERT(varchar,GETDATE()-2,23)) and cjcxrq<(select CONVERT(varchar,GETDATE(),23)) ORDER BY cjcxrq DESC";
        List<MedicalRecordContent> mrContentList = tzDBConn.getMedicalRecordContent(sql);
        execute(mrContentList);
    }

    /**
     * 数据引擎-通过接口更新病历内容
     * @param list
     * @return
     */
    public RespDTO<List<AMedicalRecordContentDTO>> executeMrRecordContent(List<AMedicalRecordContentVO> list) {
        if(list!=null && list.size()>0) {
            List<MedicalRecordContent> mrContentList=BeanUtil.listCopyTo(list,MedicalRecordContent.class);
            List<AMedicalRecordContentDTO> mrContentDtoList=BeanUtil.listCopyTo(list,AMedicalRecordContentDTO.class);
            execute(mrContentList);
            return RespDTO.onSuc(mrContentDtoList);
        }else{
            return RespDTO.onError("未接收到数据!");
        }
    }

    public void execute(List<MedicalRecordContent> mrContentList){
        try {
            List<MedicalRecordContent> addE = Lists.newLinkedList();
            List<MedicalRecordContent> updateE = Lists.newLinkedList();
            if (mrContentList != null && mrContentList.size() > 0) {
                mrContentList.forEach(s -> {
                    try {
                    QueryWrapper<MedicalRecordContent> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("rec_id", s.getRecId());
                    queryWrapper.eq("hospital_id", s.getHospitalId());
                    MedicalRecordContent mrContent = this.getOne(queryWrapper, false);
                    if (mrContent != null) {
                        s.setGmtModified(new Date());
                        updateE.add(s);
                    } else {
                        s.setGmtCreate(new Date());
                        addE.add(s);
                    }
                    }catch (Exception e){
                        log.error(e.getMessage(),e);
                        aMedAbnormalInfoFacade.saveAbnormalInfo("文书内容",s.getRecId(), JSON.toJSONString(mrContentList),"",e.getMessage());
                    }
                });
            }
            if(addE.size()>0){
                medicalRecordContentService.saveBatch(addE);
            }
            if(updateE.size()>0){
                medicalRecordContentService.updateBatchByKey(updateE);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public RespDTO deleteFlag(ADeleteFlagVO aDeleteFlagVO){
        try {
            //验证数据是否存在
            if (StringUtil.isEmpty(aDeleteFlagVO.getRecId())) {
                return RespDTO.onError("请输入文书序号!");
            } else if (aDeleteFlagVO.getHospitalId() == null) {
                return RespDTO.onError("请输入医院编码!");
            }else {
                UpdateWrapper<MedicalRecordContent> updateWrapper=new UpdateWrapper<>();
                updateWrapper.eq("rec_id", aDeleteFlagVO.getRecId())
                        .eq("hospital_id", aDeleteFlagVO.getHospitalId())
                        .eq("is_deleted", IsDeleteEnum.N)
                        .set("is_deleted",IsDeleteEnum.Y)
                        .set("gmt_modified", DateUtil.now());

                Boolean flag=update(new MedicalRecordContent(),updateWrapper);
                //aMedAbnormalInfoFacade.saveAbnormalInfo("文书内容",JSON.toJSONString(aDeleteFlagVO),JSON.toJSONString(RespDTO.onSuc(flag)),"操作成功!");
                return RespDTO.onSuc(flag);
            }
        }catch (Exception e){
            aMedAbnormalInfoFacade.saveAbnormalInfo("文书内容",aDeleteFlagVO.getRecId(),JSON.toJSONString(aDeleteFlagVO),"",e.getMessage());
            return RespDTO.onError(e.getMessage());
        }
    }

    /**
     * 文书加密
     */

    public  void documentEncryption(){
        for (int i = 1; i < 1000; i++) {
            QueryWrapper<MedicalRecordContent> queryWrapper= Wrappers.query();
            queryWrapper.eq("creator","0").last("LIMIT 500, "+i+" ");
            List<MedicalRecordContent>medicalRecordContents =medicalRecordContentService.list(queryWrapper);
            medicalRecordContents.forEach(s->{
                try {
                    EncrypDES encrypDES =new EncrypDES();
                    s.setXmlText(encrypDES.encrytor(s.getXmlText()));
                    s.setCreator("1");
                    QueryWrapper<MedicalRecordContent> updateQueryWrapper = new QueryWrapper<>();
                    updateQueryWrapper.eq("rec_id", s.getRecId());
                    updateQueryWrapper.eq("hospital_id", s.getHospitalId());
                    updateQueryWrapper.eq("creator",String.valueOf(0));
                    medicalRecordContentService.update(s,updateQueryWrapper);
                } catch (Exception e) {
                    e.printStackTrace();

                }
            });
        }

    }
}
