package com.yihu.jw.hospital.prescription.service.entrance;

import com.yihu.jw.hospital.prescription.service.entrance.util.ConvertUtil;
import com.yihu.jw.hospital.prescription.service.entrance.util.MqSdkUtil;
import com.yihu.jw.restmodel.hospital.register.RegisterAmVO;
import com.yihu.jw.util.date.DateUtil;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * Created by Trick on 2019/10/17.
 */
@Service
@Transactional
public class RegisterService {
    private Logger logger= LoggerFactory.getLogger(RegisterService.class);

    private String orgCode="350211A1002";
    @Value("${hospital.mqUser}")
    private String mqUser;
    @Value("${hospital.mqPwd}")
    private String mqPwd;
    @Value("${hospital.SourceSysCode}")
    private String sourceSysCode;
    @Value("${hospital.TargetSysCode}")
    private String targetSysCode;
    @Value("${hospital.url}")
    private String serverUrl;

    /**
     * 预约排班号源
     * @param dept
     * @param doctor_code
     * @param special_code
     * @param startDate
     * @param endDate
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSONArray BS10045(String dept,String doctor_code,String doctor_name,String special_code,String charge_type,String startDate,String endDate, boolean demoFlag) throws Exception {
        logger.info("BS10045:");
        String fid="BS10045";
        String resp="";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>"+mqUser+"</UserName><Password>"+mqPwd+"</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>"+sourceSysCode+"</SourceSysCode><TargetSysCode>"+targetSysCode+"</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum>");
            sbs.append(" <Msg>");
            sbs.append(" and (request_day between '"+startDate+"' and '"+endDate+"') ");
            if(StringUtils.isNotBlank(dept)){
                sbs.append(" and unit_code ='"+dept+"'");
            }
            if(StringUtils.isNotBlank(doctor_code)){
                sbs.append(" and doctor_code ='"+doctor_code+"'");
            }
            if(StringUtils.isNotBlank(doctor_name)){
                sbs.append(" and doctor_name like '%"+doctor_name+"%'");
            }
            if(StringUtils.isNotBlank(charge_type)){
                sbs.append(" and charge_type ='"+charge_type+"'");
            }
            if(StringUtils.isNotBlank(special_code)){
                sbs.append(" and special_code ='"+special_code+"'");
            }
            sbs.append(" order by request_day,ampm");
            sbs.append(" </Msg>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");

            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }

    /**
     * 预约时间号源表
     * @param dept
     * @param doctor_code
     * @param date
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSONArray BS10046(String dept,String doctor_code,String date,String ampm, boolean demoFlag) throws Exception {
        String fid="BS10046";
        String resp="";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>"+mqUser+"</UserName><Password>"+mqPwd+"</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>"+sourceSysCode+"</SourceSysCode><TargetSysCode>"+targetSysCode+"</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum>");
            sbs.append(" <Msg/>");
            sbs.append(" <query compy=\"=\" item=\"unit_code\" splice=\"and\" value=\"'"+dept+"'\"/>");
            sbs.append(" <query compy=\"=\" item=\"doctor_code\" splice=\"and\" value=\"'"+doctor_code+"'\"/>");
            sbs.append(" <query compy=\"=\" item=\"CONVERT(varchar(100),yy_time,23)\" splice=\"and\" value=\"'"+date+"'\"/>");
//            sbs.append(" <query compy=\"=\" item=\"yy_status\" splice=\"and\" value=\"'0'\"/>");
            sbs.append(" <query compy=\"=\" item=\"ampm\" splice=\"and\" value=\"'"+ampm+"'\"/>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }


    /**
     * BS10047 病人预约结果表 2.00
     * @param social_no 病人ID
     * @param doctor_code   医生ID
     * @param doctor_name   医生名称支持模糊
     * @param unit_code 部门
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @param reg_type 号别
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public JSONArray BS10047(String social_no,String doctor_code,String doctor_name,String unit_code,String startDate,String endDate,String reg_type,boolean demoFlag) throws Exception {
        String fid="BS10047";
        String resp="";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>"+mqUser+"</UserName><Password>"+mqPwd+"</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>"+sourceSysCode+"</SourceSysCode><TargetSysCode>"+targetSysCode+"</TargetSysCode></MessageHeader>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum>");
            sbs.append("<Msg>");
            if(StringUtils.isNotBlank(social_no)){
                sbs.append(" and social_no = '"+social_no+"' ");
            }
            if(StringUtils.isNotBlank(doctor_code)){
                sbs.append(" and doctor_code = '"+doctor_code+"' ");
            }
            if(StringUtils.isNotBlank(doctor_name)){
                sbs.append(" and doctor_name like '%"+doctor_name+"%' ");
            }
            if(StringUtils.isNotBlank(unit_code)){
                sbs.append(" and unit_code = '"+unit_code+"' ");
            }
            if(StringUtils.isNotBlank(startDate)&&StringUtils.isNotBlank(endDate)){
                sbs.append(" and (request_day between '"+startDate+"' and '"+endDate+"' )");
            }
            if(StringUtils.isNotBlank(reg_type)){
                sbs.append(" and reg_type = '"+reg_type+"' ");
            }
            sbs.append("</Msg>");
            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            logger.info(fid+" xmlresp:"+resp);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
            logger.info(fid+" jsonresp:"+resp);
        }
        return ConvertUtil.convertListEnvelopInBodyRow(resp);
    }

    /**
     * 居民预约
     * @param registerAmVO
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public net.sf.json.JSONObject BS10048(RegisterAmVO registerAmVO, boolean demoFlag) throws Exception {
        String fid="BS10048";
        String resp="";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>"+mqUser+"</UserName><Password>"+mqPwd+"</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>"+sourceSysCode+"</SourceSysCode><TargetSysCode>"+targetSysCode+"</TargetSysCode></MessageHeader>");
            sbs.append("<Msg/>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum>");
            sbs.append(" <query item=\"DeptCode\" value=\""+registerAmVO.getDept()+"\"/>");
            sbs.append(" <query item=\"DocCode\" value=\""+registerAmVO.getDoctor()+"\"/>");
            sbs.append(" <query item=\"SectionType\" value=\""+registerAmVO.getSectionType()+"\"/>");
            sbs.append(" <query item=\"StartTime\" value=\""+registerAmVO.getStartTime()+"\"/>");
            sbs.append(" <query item=\"PatientName\" value=\""+registerAmVO.getPatientName()+"\"/>");
            sbs.append(" <query item=\"PatientID\" value=\""+registerAmVO.getIdcard()+"\"/>");
            sbs.append(" <query item=\"PatientPhone\" value=\""+registerAmVO.getPatientPhone()+"\"/>\n");
            sbs.append(" <query item=\"app_type\" value=\"XS\"/>");

            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
            logger.info(fid+" resp:"+resp);
        }
        return ConvertUtil.convertListEnvelopInRequest(resp);
    }

    /**
     * 居民取消预约
     * @param registerAmVO
     * @param demoFlag
     * @return
     * @throws Exception
     */
    public net.sf.json.JSONObject BS10049(RegisterAmVO registerAmVO, boolean demoFlag) throws Exception {
        String fid="BS10049";
        String resp="";
        if (demoFlag) {
            resp = getJosnFileResullt(fid);
        } else {
            StringBuffer sbs = new StringBuffer();
            //AccessControl ：用户、密码、服务id
            sbs.append("<ESBEntry><AccessControl><Fid>" + fid + "</Fid><UserName>"+mqUser+"</UserName><Password>"+mqPwd+"</Password></AccessControl>");
            //MessageHeader ：固定值 消费方系统编号 S60,提供方系统编号 S01
            sbs.append("<MessageHeader><Fid>" + fid + "</Fid><MsgDate>" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "</MsgDate><SourceSysCode>"+sourceSysCode+"</SourceSysCode><TargetSysCode>"+targetSysCode+"</TargetSysCode></MessageHeader>");
            sbs.append("<Msg/>");
            //查询信息拼接
            sbs.append("<MsgInfo><endNum>20000</endNum>");
            sbs.append(" <query item=\"DeptCode\" value=\""+registerAmVO.getDept()+"\"/>");
            sbs.append(" <query item=\"DocCode\" value=\""+registerAmVO.getDoctor()+"\"/>");
            sbs.append(" <query item=\"SectionType\" value=\""+registerAmVO.getSectionType()+"\"/>");
            sbs.append(" <query item=\"StartTime\" value=\""+registerAmVO.getStartTime()+"\"/>");
            sbs.append(" <query item=\"PatientName\" value=\""+registerAmVO.getPatientName()+"\"/>");
            sbs.append(" <query item=\"PatientID\" value=\""+registerAmVO.getIdcard()+"\"/>");
            sbs.append(" <query item=\"PatientPhone\" value=\""+registerAmVO.getPatientPhone()+"\"/>\n");

            sbs.append("<startNum>1</startNum></MsgInfo></ESBEntry>");
            resp = MqSdkUtil.putReqAndGetRespByQueryStr(sbs.toString(), fid);
            resp = MqSdkUtil.xml2jsonArrayRootRow(resp);
            logger.info(fid+" resp:"+resp);
        }
        return ConvertUtil.convertListEnvelopInRequest(resp);
    }


    public String getJosnFileResullt(String fid) throws Exception {
        String contentStr = null;
        Resource resource = new ClassPathResource("mqConfig/mqdata/" + fid + ".json");
        if (resource.exists()) {
            InputStream is = resource.getInputStream();
            contentStr = new BufferedReader(new InputStreamReader(is,"utf-8"))
                    .lines().collect(Collectors.joining(System.lineSeparator()));
//            contentStr =  replaceSpecialStr(contentStr);
        }else {
            throw new Exception("文件不存在");
        }
        return  contentStr;
    }
}
