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.diagbot.dto.RespDTO;
import com.diagbot.dto.data.AHomeOperationDTO;
import com.diagbot.entity.HomeOperationInfo;
import com.diagbot.entity.HomePage;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.service.impl.HomeOperationInfoServiceImpl;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.DateUtil;
import com.diagbot.util.StringUtil;
import com.diagbot.util.TZDBConn;
import com.diagbot.vo.data.ADeleteFlagVO;
import com.diagbot.vo.data.AHomeOperationVO;
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 AHomeOperationInfoFacade extends HomeOperationInfoServiceImpl{

    @Autowired
    @Qualifier("homeOperationInfoServiceImpl")
    private HomeOperationInfoServiceImpl homeOperationInfoService;
    @Autowired
    private AMedAbnormalInfoFacade aMedAbnormalInfoFacade;
    @Autowired
    private AHomePageFacade aHomePageFacade;
    @Value("${log_switch.enable}")
    private boolean logSwitch;

    private TZDBConn tzDBConn = new TZDBConn();

    /**
     * 终末质控-同步前一天数据
     */
    public void executeHomeOperation() {
        //String sql="select * from br_recoperation where cjcxrq>=dateadd(day,-2,getdate()) and cjcxrq<=getdate()";
        //前一天数据
        String sql="select * from br_recoperation where cjcxrq>=(select CONVERT(varchar,GETDATE()-2,23)) and cjcxrq<(select CONVERT(varchar,GETDATE(),23))";
        List<HomeOperationInfo> homeOperationList = tzDBConn.getHomeOperation(sql);
        execute(homeOperationList);
    }

    /**
     * 终末质控-通过接口更新病案首页手术
     * @param list
     * @return
     */
    public RespDTO executeHomeOperation(List<AHomeOperationVO> list) {
        try {
            List<HomeOperationInfo> homeOperationList=Lists.newArrayList();
            List<AHomeOperationDTO> homeOperationDtoList=Lists.newArrayList();
            if(list!=null && list.size()>0){
                list.stream().forEach(s->{
                    HomeOperationInfo homeOperationInfo=new HomeOperationInfo();
                    String behospitalCode=s.getBehospitalCode();
                    HomePage homePage = aHomePageFacade.getOne(new QueryWrapper<HomePage>()
                            .eq("behospital_code", behospitalCode), false);
                    if(homePage!=null){
                        s.setHomePageId(homePage.getHomePageId());
                    }
                    BeanUtil.copyProperties(s,homeOperationInfo);
                    homeOperationInfo.setOperationDate(DateUtil.parseDateTime(s.getOperationDate()));
                    homeOperationList.add(homeOperationInfo);
                });
                homeOperationDtoList=BeanUtil.listCopyTo(list,AHomeOperationDTO.class);
                execute(homeOperationList);
                if(logSwitch){
                    homeOperationList.forEach(s->{
                        aMedAbnormalInfoFacade.saveAbnormalInfo("病案首页手术-正常","", JSON.toJSONString(list),"","");
                    });
                }
                return RespDTO.onSuc("操作正常！");
            }else{
                return RespDTO.onError("未接收到数据!");
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            aMedAbnormalInfoFacade.saveAbnormalInfo("病案首页手术-异常","",JSON.toJSONString(list),"",e.getMessage());
            return RespDTO.onError("数据处理异常，详情查看日志表");
        }
    }

    public void execute(List<HomeOperationInfo> homeOperationList){
        List<HomeOperationInfo> addE = Lists.newLinkedList();
        List<HomeOperationInfo> updateE = Lists.newLinkedList();
        if (homeOperationList != null && homeOperationList.size() > 0) {
            homeOperationList.stream().forEach(s -> {
                if(s.getHomePageId()!=null && !"".equals(s.getOperationOrderNo())) {
                    QueryWrapper<HomeOperationInfo> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("home_page_id", s.getHomePageId());
                    queryWrapper.eq("hospital_id", s.getHospitalId());
                    queryWrapper.eq("operation_order_no", s.getOperationOrderNo());
                    HomeOperationInfo operationInfo = this.getOne(queryWrapper, false);
                    if (operationInfo != null) {
                        s.setGmtModified(new Date());
                        updateE.add(s);
                    } else {
                        s.setGmtCreate(new Date());
                        addE.add(s);
                    }
                }
            });
        }
        if(addE.size()>0){
            homeOperationInfoService.saveBatch(addE);
        }
        if(updateE.size()>0){
            homeOperationInfoService.updateBatchByKey(updateE);
        }
    }

    public RespDTO deleteFlag(ADeleteFlagVO aDeleteFlagVO){
        try {
            //验证数据是否存在
            if(StringUtil.isEmpty(aDeleteFlagVO.getHomePageId())) {
                return RespDTO.onError("住院手术未输入病案首页编号!");
            }else if(aDeleteFlagVO.getHospitalId()==null){
                return RespDTO.onError("住院手术未输入医院编码!");
            }else if(StringUtil.isEmpty(aDeleteFlagVO.getOperationOrderNo())){
                return RespDTO.onError("住院手术未输入顺序号!");
            }else {
                UpdateWrapper<HomeOperationInfo> updateWrapper=new UpdateWrapper<>();
                updateWrapper.eq("home_page_id", aDeleteFlagVO.getHomePageId())
                        .eq("hospital_id", aDeleteFlagVO.getHospitalId())
                        .eq("operation_order_no", aDeleteFlagVO.getOperationOrderNo())
                        .eq("is_deleted", IsDeleteEnum.N)
                        .set("is_deleted",IsDeleteEnum.Y)
                        .set("gmt_modified", DateUtil.now());

                Boolean flag=update(new HomeOperationInfo(),updateWrapper);
                //aMedAbnormalInfoFacade.saveAbnormalInfo("病案首页-手术-删除",JSON.toJSONString(aDeleteFlagVO),JSON.toJSONString(RespDTO.onSuc(flag)),"操作成功!");
                return RespDTO.onSuc(flag);
            }
        }catch (Exception e){
            aMedAbnormalInfoFacade.saveAbnormalInfo("病案首页-手术-删除","",JSON.toJSONString(aDeleteFlagVO),"",e.getMessage());
            return RespDTO.onError(e.getMessage());
        }
    }
}
