package com.yihu.jw.internet.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.dict.dao.BaseDeptDictDao;
import com.yihu.jw.dict.dao.BaseSuperviseDataDictDao;
import com.yihu.jw.dict.dao.BaseSuperviseDictDao;
import com.yihu.jw.dict.dao.DictDoctorDutyDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.dict.DictDoctorDutyDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.hospital.dict.BaseDeptDict;
import com.yihu.jw.entity.hospital.dict.BaseSuperviseDataDict;
import com.yihu.jw.entity.hospital.dict.BaseSuperviseDict;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.internet.dao.HospitalImgDao;
import com.yihu.jw.internet.dao.IntUpErrorLogDao;
import com.yihu.jw.internet.dao.InternetUpLogDao;
import com.yihu.jw.internet.entity.InternetUpErrorLogDO;
import com.yihu.jw.internet.entity.InternetUpLogDO;
import com.yihu.jw.internet.wsapi.Wsapi;
import com.yihu.jw.internet.wsapi.WsapiProxy;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.ImgUtils;
import com.yihu.jw.utils.JSONUtils;
import com.yihu.jw.utils.encode.AESUtils;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedCaseInsensitiveMap;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class InternetCommonService extends BaseJpaService<InternetUpErrorLogDO, IntUpErrorLogDao> {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(InternetCommonService.class);

    @Autowired
    private InternetUpErrorLogService internetUpErrorLogService;
    @Autowired
    private InternetUpLogDao internetUpLogDao;

    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;

    @Autowired
    private HospitalImgDao hospitalImgDao;

    @Autowired
    private WlyyHospitalSysDictDao dictDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private BaseSuperviseDictDao superviseDictDao;
    @Autowired
    private BaseSuperviseDataDictDao superviseDataDictDao;
    @Autowired
    private BaseDeptDictDao deptDictDao;
    @Autowired
    private DictDoctorDutyDao dictDoctorDutyDao;

    public String userName ;
    public String psw ;
    public String appId ;
    public String AesEncodeKey ;
    public String urlString;  // 正式线路径
 //   static String urlString = "http://fjhlw.bsoft.com.cn:18081/micc/wsapi/1.0?wsdl";   // 测试线路径
    public String method;
    public String token;
    public String orgCode;
    public String orgName;
    public String orgArea;
    public String orgSub ;
    public String imgUrl;

    static String imgPath =File.separator+"data1"+File.separator+"ehr"+File.separator+"svr-internet-hospital-job"+File.separator+"img"+File.separator;


    public ObjectMapper objectMapper;

    public void getBaseSurperviseDict(){
        BaseSuperviseDict superviseDict = superviseDictDao.selectByDictName();
        userName=superviseDict.getUserName();
        psw=superviseDict.getPsw();
        appId=superviseDict.getAppId();
        AesEncodeKey = superviseDict.getAesEncodeKey();
        method = superviseDict.getMethod();
        token = superviseDict.getToken();
        orgArea=superviseDict.getOrgArea();
        orgCode = superviseDict.getOrgCode();
        orgName=superviseDict.getOrgName();
        orgSub=superviseDict.getOrgSub();
        imgUrl=superviseDict.getImgUrl();
    }

    /**
     * 监管平台上传地址
     * @return
     */
    public String getUrl(){
        return dictDao.findByDictName("dataUpload").get(0).getDictCode();
    }

    public String getImUrl(){
        return dictDao.findByDictName("imData").get(0).getDictCode();
    }

    public String getSystemUrl(){
        return dictDao.findByDictName("SYSTEM_URL").get(0).getDictCode();
    }

    // 0 调用省监管平台接口
    public String postToInter(String token, String api, JSONArray params,String url) throws Exception {
        getBaseSurperviseDict();
        WsapiProxy proxy = new WsapiProxy();
        proxy.setEndpoint(url);
        JSONObject jsonObject= new JSONObject();
        if (params!=null&&params.size()>0){
            jsonObject= params.getJSONObject(0);
            jsonObject.put("docimg","");
            jsonObject.put("doc_cert","");
            jsonObject.put("cert_doc_prac","");

        }
        logger.info("入参:"+jsonObject.toString());
        Wsapi wsapi = proxy.getWsapi();

//        logger.info("postToInter:"+JSONUtils.toString(new String[] {token, params.toString()}));

        String encryptParams = AESUtils.encrypt(JSONUtils.toString(new String[] {token, params.toString()}), AesEncodeKey);
        String result = wsapi.invoke(appId, "", api, method, encryptParams);
        String deResult = AESUtils.decrypt(result, AesEncodeKey);

        logger.info("postToInter:"+JSONUtils.toString(deResult));

        return deResult;
    }

    // 1  接口用户信息,获取TOKEN值	 micc.upNsUserToken   --- 完成
    public String upNsUserToken(String url) throws Exception {
        getBaseSurperviseDict();
        WsapiProxy proxy = new WsapiProxy();
        proxy.setEndpoint(url);
        Wsapi wsapi = proxy.getWsapi();

        String api = "micc.upNsUserToken";
        JSONObject jb = new JSONObject();
        jb.put("cd_user", userName);
        jb.put("pwd_user", psw);

        logger.info("url :"+url);
        logger.info("jb :"+jb.toString());

        String encryptParams = AESUtils.encrypt(JSONUtils.toString(new String[] { jb.toString() }), AesEncodeKey);


        String res = wsapi.invoke(appId, "", api, method, encryptParams);
        logger.info("appId :"+appId);
        logger.info("method :"+method);
        logger.info("encryptParams :"+encryptParams);
        String deResult = AESUtils.decrypt(res, AesEncodeKey);
        logger.info("AesEncodeKey :"+AesEncodeKey);

        JSONObject resJson = (JSONObject) JSONObject.parse(deResult);
        if("200".equals(resJson.get("msg").toString())) {
            token = resJson.get("token").toString();
        }
        logger.info("upNsUserToken : "+token);
        return token;
    }


    // 2  医院基本信息	micc.upNsOrganBas     --- 完成
    public String upNsOrganBas() throws Exception {
        logger.info("开始进入==============");
        getBaseSurperviseDict();
        BaseSuperviseDataDict superviseDataDict = superviseDataDictDao.selectByDictName();
        String url = getUrl();
        String api = "micc.upNsOrganBase";
        logger.info("开始进入++++++++"+superviseDataDict.getDictName());
        JSONObject jb = new JSONObject();
        jb.put("organ_code", orgCode);
        jb.put("organ_name",orgName);
        jb.put("corporation", superviseDataDict.getCorporation());
        jb.put("no_pra_lic", superviseDataDict.getNoPraLic());
        jb.put("second_organ_name", StringUtils.isNoneBlank(superviseDataDict.getSecondOrganName())?superviseDataDict.getSecondOrganName():"");
        jb.put("charge_person",StringUtils.isNoneBlank(superviseDataDict.getChargePerson())?superviseDataDict.getChargePerson():"");

        jb.put("level", superviseDataDict.getLevelCode());
        jb.put("economic_type", superviseDataDict.getEconomicType());
        jb.put("organ_type",superviseDataDict.getOrganType());
        jb.put("organ_sub", orgSub);
        jb.put("hospital_district",orgArea);
        jb.put("hospital_address", superviseDataDict.getHospitalAddress());

        jb.put("hospital_phone", superviseDataDict.getHospitalPhone());
     /*   jb.put("hospital_img","");*/
//        jb.put("bus_lic", ImgUtils.getImageStr(imgPath+"hospital"+File.separator+"yyzz.jpg"));
//        jb.put("corp_idcord_head", ImgUtils.getImageStr(imgPath+"hospital"+File.separator+"a.jpg"));
//        jb.put("corp_idcord_tail", ImgUtils.getImageStr(imgPath+"hospital"+File.separator+"b.jpg"));
//        jb.put("pra_lic", ImgUtils.getImageStr(imgPath+"hospital"+File.separator+"zyxkz.jpg"));

/*        jb.put("bus_lic", null);
        jb.put("corp_idcord_head", null);
        jb.put("corp_idcord_tail", null);
        jb.put("pra_lic", null);*/
        String hospitalImg="";
        String busLic="";
        String corpIdcardHead ="";
        String corpIdcardTail="";
        String praLic="";

        //医院图片
        jb.put("hospital_img",ImgUtils.getImageStr(imgPath+"hospital"+File.separator+"hsimg.jpg"));
        //营业执照
        jb.put("bus_lic",ImgUtils.getImageStr(imgPath+"hospital"+File.separator+"zyxkz.jpg"));
        //身份证正面
        jb.put("corp_idcord_head",ImgUtils.getImageStr(imgPath+"hospital"+File.separator+"idcardA.jpg"));
        jb.put("corp_idcord_tail", ImgUtils.getImageStr(imgPath+"hospital"+File.separator+"idcardB.jpg"));
        jb.put("pra_lic", ImgUtils.getImageStr(imgPath+"hospital"+File.separator+"zyxkz.jpg"));

        jb.put("secu_level",StringUtils.isNoneBlank(superviseDataDict.getSecuLevel())?superviseDataDict.getSecuLevel():"");
        jb.put("secu_level_cert",ImgUtils.getImageStr(imgPath+"hospital"+File.separator+"dbtp.jpg"));

        jb.put("net_service", superviseDataDict.getNetService());
        jb.put("net_service_ot", "");
        jb.put("service_dept", superviseDataDict.getServiceDept());
        jb.put("txt_introduction", "");

        //用户协议
        jb.put("protocol_type", superviseDataDict.getProtocolType());
        jb.put("protocol_content", superviseDataDict.getProtocolContent());
        jb.put("publish_date",superviseDataDict.getPublishDate());
        jb.put("protocol_name", superviseDataDict.getProtocolName());

        //其他建设信息
        jb.put("quai_mang_dept", "");
        jb.put("info_mang_dept", "");
        jb.put("medi_service_dept", "");

        jb.put("server_type", "");
        jb.put("server_total", "");
        jb.put("server_ip", "");

        jb.put("mp_system_type", "");
        jb.put("mp_system_total", "");
        jb.put("tran_link", "");

        jb.put("tran_link_band", "");
        jb.put("server_system_name", "");
        jb.put("server_system_ip", "");

        jb.put("tech_manual", "");
        jb.put("server_manual", "");

        jb.put("emr_level", "");
        jb.put("emr_level_cert", "");

        jb.put("zone_record_share", "");
        jb.put("prov_monitor", "");
        jb.put("prov_service", "");

        jb.put("server_func", "");
        jb.put("third_compeny_name", "");
        jb.put("third_compeny_code", "");

        jb.put("third_compeny_cert", "");
        jb.put("third_compeny_corp", "");
        jb.put("third_compeny_corp_id", "");

        jb.put("third_compeny_prot", "");


        JSONArray jsonArray = new JSONArray();
        jsonArray.add(jb);

        String token = upNsUserToken(url);
        String res = postToInter(token, api, jsonArray,url);

        return res;
    }

    // 3 医师基本信息	micc.upNsDoctorRecord   --- 完成
    public String upNsDoctorRecord(String keyId) throws Exception {
        getBaseSurperviseDict();
        BaseSuperviseDataDict superviseDataDict = superviseDataDictDao.selectByDictName();
        String url = getUrl();
        String api = "micc.upNsDoctorRecord";
        String upid = getCode();
        String res = "";
        int total = 0;
        int success = 0;
        int error = 0;
        int dataError = 0;
        String token = upNsUserToken(url);

        //  因为要上传的是医师信息，所以针对到注册用户且无部门信息的用户数据不上传
        String sql = "select " +
                "   a.id AS \"id\"," +
                "   a.name AS \"name\"," +
                "   a.idcard AS \"idcard\"," +
                "   a.sex AS \"sex\"," +
                "   a.birthday AS \"birthday\", " +
                "   a.cert_no AS \"cert_no\", " +
                "   a.prac_no AS \"prac_no\"," +
                "   a.mobile AS \"mobile\"," +
                "   b.dept_code AS \"dept_code\"," +
                "   b.dept_name AS \"dept_name\"," +
                "   a.job_title_code AS \"job_title_code\"," +
                "   a.fzrq AS \"fzrq\"," +
                "   a.photo as \"photo\" " +
                "  from base_doctor a " +
                "      ,base_doctor_hospital b" +
                " where a.id = b.doctor_code" +
                "   AND b.dept_code is NOT NULL " +
                "   AND a.job_title_code is NOT NULL " +
                "   AND a.fzrq IS NOT NULL " +
                "   AND a.cert_no IS NOT NULL " +
                "   AND a.prac_no IS NOT NULL " +
                "  AND b.dept_name IS NOT NULL AND a.del=1 ";

        if(StringUtils.isNotBlank(keyId)){
            sql =  sql +  "  and a.id = '" + keyId + "' ";
        }

        List list = jdbcTemplate.queryForList(sql);

        total = list.size();

        for(int i=0; i<list.size(); i++){
            LinkedCaseInsensitiveMap info = (LinkedCaseInsensitiveMap)list.get(i);

            Boolean errorFlag = false;
            JSONObject jb = new JSONObject();
            try {
                String[] dept = depToSubject(info.get("dept_code").toString());
                // 中山医院 监管平台  职务字典强转
                String[] dutyInfo = classToduty(info.get("job_title_code").toString());

                jb.put("organ_code", orgCode);
                jb.put("organ_name", orgName);
                jb.put("doc_name", info.get("name")== null ? "0":info.get("name"));
                jb.put("docimg",info.get("photo")==null ?null:getImg("https://hlwyy.xmzsh.com/fastdfs/"+info.get("photo").toString()));
                jb.put("id_card", info.get("idcard")== null ? "0":info.get("idcard"));
                jb.put("sex", info.get("sex")== null ? "0":info.get("sex"));
                jb.put("birthday", info.get("birthday")  == null?"2020-01-01": DateUtil.dateToStrShort((Date)info.get("birthday")));
                jb.put("subject", dept.length>=1?dept[0]:"");
                jb.put("subject_name",dept.length>=2?dept[1]:"");
                jb.put("belong_dept",info.get("dept_code"));
                jb.put("belong_dept_name", info.get("dept_name"));
                jb.put("doo_tel", info.get("mobile")== null ? "":info.get("mobile"));
                jb.put("title_rec_date", getDateString(info.get("fzrq").toString()));
                if (info.get("idcard").toString().equalsIgnoreCase("350104197904305425")){
                    jb.put("prac_type", "2");   // 因为上传的是医师的信息，所以该字段全部默认设置为 1 医师
                }else {
                    jb.put("prac_type", "1");   // 因为上传的是医师的信息，所以该字段全部默认设置为 1 医师
                }
                jb.put("title_code", dutyInfo.length>=1?dutyInfo[0]:"");  // 需要与监管平台的字典进行映射
                jb.put("first_compeny_code", orgCode);
                jb.put("first_compeny_name", orgName);
                jb.put("secd_compeny_code", "");
                jb.put("secd_compeny_name", "");
                jb.put("net_service", superviseDataDict.getDoctorNetService());
                jb.put("cert_no",  info.get("cert_no")== null ? "0":info.get("cert_no"));
                jb.put("prac_no",  info.get("prac_no")== null ? "0":info.get("prac_no"));
                //资格证书
                jb.put("doc_cert",ImgUtils.getImageStr(imgPath+"doctor"+ File.separator+info.get("name")+File.separator+"执业证.jpg"));
                //执业证书
                jb.put("cert_doc_prac", ImgUtils.getImageStr(imgPath+"doctor"+ File.separator+info.get("name")+File.separator+"资格证.jpg"));
                jb.put("txt_introduction",StringUtils.isNoneBlank(superviseDataDict.getTxtIntroduction())?superviseDataDict.getTxtIntroduction():"");

            }catch (Exception e){
                errorFlag = true;
                saveErrorLog(upid,"3",info.get("id").toString(),"数据格式错误",1);
                error++;
                logger.error(e.toString());
            }
            if(!errorFlag){
                //上传监管平台
                JSONArray jsonArray = new JSONArray();
                jsonArray.add(jb);
                res = postToInter(token, api, jsonArray,url);
                JSONObject resJson = (JSONObject) JSONObject.parse(res);
                if("200".equals(resJson.get("msg").toString())){
                    success++;
                }else{
                    saveErrorLog(upid,"3",info.get("id").toString(),res,2);
                    error++;
                }
            }

        }
        String resInfo = "此次共上传：" + total + "条数据，其中成功 ：" + success + "条，上传失败 ： " + error + "条。格式错误："+dataError+"条。";
        saveUpLog(upid,"3",new Date(),new Date(),success,error,dataError,resInfo);
        return resInfo;
    }


    // 4 获取监管平台医师唯一标识	micc.achNsDoctorRecord  --- 完成
    public String achNsDoctorRecord(String idCardNo) throws Exception {
        getBaseSurperviseDict();
        String url = getUrl();
        String api = "micc.achNsDoctorRecord";
        JSONObject jb = new JSONObject();
        jb.put("organ_code", orgCode);
        jb.put("organ_name", orgName);
        jb.put("id_card", idCardNo);

        JSONArray jsonArray = new JSONArray();
        jsonArray.add(jb);
        String token = upNsUserToken(url);
        String res = postToInter(token, api, jsonArray,url);
        JSONObject rs = (JSONObject) JSONObject.parse(res);
        String msg = rs.getString("msg");
        if("200".equals(msg)){
            JSONArray reqContent = rs.getJSONArray("reqContent");
            JSONObject req = (JSONObject)reqContent.get(0);
            return req.getString("miccId");
        }
        return "";
    }

    // 5 网上预约挂号	micc.upAppointmentOnline  ----完成
    public String upAppointmentOnline(String startDate, String endDate,String keyId) throws Exception {
        getBaseSurperviseDict();
        String url = getUrl();
        String api = "micc.upAppointmentOnline";
        String upid = getCode();
        String res = "";
        int total = 0;
        int success = 0;
        int dataError = 0;
        int error = 0;

        String token = upNsUserToken(url);

        String sql = "SELECT " +
                "   p.id AS \"id\"," +
                "   p.register_no AS \"register_no\", " +
                "   p.status AS \"status\", " +
                "   p.dept AS \"dept\", " +
                "   p.dept_name AS \"dept_name\"," +
                "   p.patient_name AS \"paName\"," +
                "   p.doctor_name AS \"docName\"," +
                "   p.idcard AS \"idcard\"," +
                "   p.register_date AS \"date\"" +
                "   FROM wlyy_outpatient p " +
                " WHERE 1=1" ;
        Map<String,Object> params = new HashedMap();
        if(StringUtils.isNotBlank(startDate)){
            sql =  sql + "  and p.create_time >=:startDate ";
            params.put("startDate",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(endDate)){
            sql =  sql +  "  and p.create_time <=:endDate";
            params.put("endDate",DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(keyId)){
            sql =  sql +  "  and  p.id =:keyId ";
            params.put("keyId",keyId);
        }

        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,params);
        total = list.size();

        for(int i=0; i< total; i++){
            Map<String,Object> info = list.get(i);
            JSONObject jb = new JSONObject();
            Boolean errorFlag = false;
            try{
                String[] dept = depToSubject(info.get("dept").toString());
                jb.put("id", orgCode +"_"+ (String)info.get("id"));
                jb.put("cd_org", orgCode);
                jb.put("cd_area", orgArea);
                jb.put("cd_orgSub", orgSub);
                jb.put("reg_time", info.get("date") == null?"2020-01-01": DateUtil.dateToStrLong((Date)info.get("date")));
                jb.put("fg_visit",  fgConvent(info.get("status") == null?"-1":info.get("status").toString()));
                jb.put("reg_dep_code",  info.get("dept") == null?"0":info.get("dept"));
                jb.put("reg_dep_name",  info.get("dept_name") == null?"0":info.get("dept_name"));
                jb.put("reg_subject_code",  dept.length>=1?dept[0]:"");
                jb.put("reg_subject_name", dept.length>=2?dept[1]:"");
                jb.put("reg_price",  "0");
                jb.put("pt_name", info.get("paName") == null?"0":info.get("paName"));
                jb.put("ge_code",   IdCardUtil.getSexForIdcard_new(info.get("idcard").toString()));
                jb.put("pt_age", IdCardUtil.getAgeForIdcard(info.get("idcard").toString()));
                jb.put("card_type", "1");
                jb.put("id_no",  info.get("idcard") == null?"0":info.get("idcard"));
                jb.put("pt_tel",  "00000000000");
                jb.put("crt_date",DateUtil.dateToStrLong(DateUtil.getNow()));
            }catch (Exception e){
                errorFlag = true;
                saveErrorLog(upid,"5",(String)info.get("id"),"网上预约挂号数据格式错误",1);
                dataError++;
                logger.error(e.toString());
            }

            if(!errorFlag){
                JSONArray jsonArray = new JSONArray();
                jsonArray.add(jb);
                res = postToInter(token,api, jsonArray,url);

                JSONObject resJson = (JSONObject) JSONObject.parse(res);
                if("200".equals(resJson.get("msg").toString())){
                    success++;
                }else{
                    saveErrorLog(upid,"5",(String)info.get("id"),res,2);
                    error++;
                }
            }
        }
        String resInfo = "此次共上传：" + total + "条数据，其中成功 ：" + success + "条，上传失败 ： " + error + "条。格式错误："+dataError+"条。";
        saveUpLog(upid,"5",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"),DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"),success,error,dataError,resInfo);

        return resInfo;
    }

    // 6 在线医技预约 	micc.upMedicalOnline --- 完成
    public String upMedicalOnline(String startDate, String endDate,String keyId) throws Exception {
        getBaseSurperviseDict();
        String url = getUrl();
        String api = "micc.upMedicalOnline";
        String upid = getCode();
        String token = upNsUserToken(url);
        String res = "";
        int total = 0;
        int success = 0;
        int error = 0;
        int dataError = 0;

        String sql ="SELECT " +
                " i.id AS \"id\", " +
                " i.code AS \"code\", " +
                " o.dept AS \"dept\", " +
                " o.doctor AS \"doctor\", " +
                " o.register_date AS \"register_date\", " +
                " i.create_time AS \"create_time\", " +
                " p.name AS \"name\", " +
                " p.idcard AS \"idcard\", " +
                " d.idcard AS \"doctorIdCard\"" +
                "FROM " +
                " wlyy_inspection i " +
                " JOIN wlyy_outpatient o ON o.id = i.outpatient_id  " +
                " JOIN base_patient p ON p.id = o.patient " +
                " JOIN base_doctor d ON d.id = o.doctor " +
                "WHERE " +
                " i.dept is not null" +
                " and o.register_date is not null";
        if(StringUtils.isNotBlank(keyId)){
            sql +=" and i.id = '"+keyId+"'";
        }
        if(StringUtils.isNotBlank(startDate)){
            sql +=" and i.create_time >='"+startDate+"' ";
        }
        if(StringUtils.isNotBlank(endDate)){
            sql +=" and i.create_time <='"+endDate+"' ";
        }
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);

        if(list != null && list.size() > 0){
            total = list.size();
            for(Map<String,Object> ins :list ){
                JSONObject jb = new JSONObject();
                Boolean errorFlag = false;
                try {
                    String[] dept = depToSubject(ins.get("dept").toString());
                    String docInterId = achNsDoctorRecord((String)ins.get("doctorIdCard"));
                    jb.put("id",orgCode +"_"+ (String)ins.get("id"));
                    jb.put("cd_org", orgCode);
                    jb.put("cd_area", orgArea);
                    jb.put("cd_orgSub", orgSub);
                    jb.put("app_time",DateUtil.dateToStr((Date)ins.get("register_date"),"yyyy-MM-dd HH:mm:ss"));
                    jb.put("app_dep_code", dept.length>=1?dept[0]:"");
                    jb.put("app_class_code", ins.get("code"));
                    jb.put("id_doctor", docInterId);
                    jb.put("fg_handle", "1");
                    jb.put("handle_time", DateUtil.dateToStr((Date)ins.get("create_time"),"yyyy-MM-dd HH:mm:ss"));
                    jb.put("pt_name",ins.get("name").toString());
                    String sex = IdCardUtil.getSexForIdcard_new(ins.get("idcard").toString());
                    jb.put("ge_code", sex=="3"?"9":sex);
                    jb.put("card_type", "1");
                    jb.put("id_no", ins.get("idcard").toString());
                    jb.put("pt_tel", "00000000000");
                    jb.put("crt_date",DateUtil.dateToStrLong(DateUtil.getNow()));
                }catch (Exception e){
                    errorFlag = true;
                    saveErrorLog(upid,"6",(String)ins.get("id"),"在线医技预约格式错误",1);
                    dataError++;
                    logger.error(e.toString());
                }

                if(!errorFlag){
                    JSONArray jsonArray = new JSONArray();
                    jsonArray.add(jb);
                    res = postToInter(token,api, jsonArray,url);

                    JSONObject resJson = (JSONObject) JSONObject.parse(res);
                    if("200".equals(resJson.get("msg").toString())){
                        success++;
                    }else{
                        saveErrorLog(upid,"6",(String)ins.get("id "),res,2);
                        error++;
                    }
                }

            }
        }

        String resInfo = "此次共上传：" + total + "条数据，其中成功 ：" + success + "条，上传失败 ： " + error + "条。格式错误："+dataError+"条。";
        saveUpLog(upid,"6",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"),DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"),success,error,dataError,resInfo);

        return resInfo;
    }

    // 7 医生评价信息	micc.upNsDoctorScore  --- 完成
    public String upNsDoctorScore(String startDate, String endDate,String keyId) throws Exception {
        getBaseSurperviseDict();
        String url = getUrl();
        String api = "micc.upNsDoctorScore";
        String upid = getCode();
        String res = "";
        int total = 0;
        int success = 0;
        int error = 0;
        int dataError = 0;

        String token = upNsUserToken(url);

        String sql ="SELECT " +
                " a.id AS \"id\", " +
                " a.doctor as \"doctor\","+
                " a.doctor_name AS \"name\", " +
                " a.score AS \"score\", " +
                " a.patient_name AS \"patient_name\", " +
                " a.create_time AS \"create_time\", " +
                " e.content AS \"content\", " +
                " d.idcard AS \"docIdCard\", " +
                " e.relation_code AS \"relationCode\" "+
                "FROM " +
                " base_evaluate_score a " +
                " JOIN base_evaluate e ON a.id = e.relation_code " +
                " JOIN base_doctor d ON d.id = a.doctor  " +
                " JOIN wlyy_consult m ON m.id = a.relation_code  " +
                "WHERE " +
                " e.score_type = '4' and m.id != '' and m.id is not null ";
        Map<String,Object> params = new HashedMap();

        if(StringUtils.isNotBlank(startDate)){
            sql =  sql + "  and a.create_time >=:startDate ";
            params.put("startDate",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(endDate)){
            sql =  sql +  "  and a.create_time <=:endDate";
            params.put("endDate",DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(keyId)){
            sql =  sql +  "  and  a.id =:keyId ";
            params.put("keyId",keyId);
        }

        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,params);

        total = list.size();

        for(int i=0; i<list.size(); i++) {
            Map<String,Object> info =list.get(i);
            Boolean errorFlag = false;
            JSONObject jb = new JSONObject();
            String interId = "";
            String idCard = info.get("docIdCard") == null ? "0":info.get("docIdCard").toString();
            if( info.get("docIdCard") == null){
                interId = "0";
            }else {
                interId = achNsDoctorRecord(idCard);
                try{
//                String[] dept = depToSubject(info.get("dept_code").toString());

                    jb.put("id",interId +"_"+ (String)info.get("relationCode"));
                    jb.put("id_doctor",interId == null ? "0":interId);
                    jb.put("organ_code",orgCode);
                    jb.put("organ_name", orgName);
                    jb.put("net_service", "4");
                    jb.put("net_service_name","在线复诊");
                    jb.put("val_score",info.get("score") == null ? "0": info.get("score"));
                    jb.put("grader",info.get("patient_name") == null ? "0": info.get("patient_name"));
                    jb.put("dt_grade",DateUtil.dateToStrLong((Date)info.get("create_time")));
                    jb.put("grade_content", info.get("content") == null ? "0": info.get("content"));
                    jb.put("crt_date", DateUtil.dateToStrLong(DateUtil.getNow()));
                }catch (Exception e){
                    errorFlag = true;
                    saveErrorLog(upid,"7",(String)info.get("id"),"医生评价信息格式错误",2);
                    dataError++;
                    logger.error(e.toString());
                }
                if(!errorFlag){
                    if (!interId.equalsIgnoreCase("0")&&!interId.equalsIgnoreCase("")){
                        JSONArray jsonArray = new JSONArray();
                        jsonArray.add(jb);
                        res = postToInter(token,api, jsonArray,url);
                        JSONObject resJson = (JSONObject) JSONObject.parse(res);
                        if("200".equals(resJson.get("msg").toString())){
                            success++;
                        }else{
                            saveErrorLog(upid,"7",info.get("id").toString(),res,2);
                            error++;
                        }
                    }
                }
            }

        }
        String resInfo = "此次共上传：" + total + "条数据，其中成功 ：" + success + "条，上传失败 ： " + error + "条。格式错误："+dataError+"条。";
        saveUpLog(upid,"7",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"),DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"),success,error,dataError,resInfo);

        return resInfo;
    }

    // 8 网络咨询服务信息	micc.upNsOnlineAsk  --- 完成
    public String upNsOnlineAsk(String startDate, String endDate,String keyId) throws Exception {
        String base = getImUrl();
        getBaseSurperviseDict();
        String systemUrl = getSystemUrl();
        String url = getUrl();
        String api = "micc.upNsOnlineAsk";
        String upid = getCode();
        String token = upNsUserToken(url);
        String res = "";
        int total = 0;
        int success = 0;
        int error = 0;
        int dataError = 0;


       String sql = "SELECT\n" +
               "\ta.id as \"id\",\n" +
               "\ta.type as \"type\",\n" +
               "\tc. NAME AS \"docName\",\n" +
               "\tc.idcard AS \"docIdCard\",\n" +
               "\tc.id AS \"docId\",\n" +
               "\tb.patient AS \"patient\",\n" +
               "\tb. NAME AS \"patientName\",\n" +
               "\tb.birthday as \"birthday\",\n" +
               "\tb.doctor as \"doctor\",\n" +
               "\ta.czrq as \"czrq\",\n" +
               "\ta.end_time as \"end_time\",\n" +
               "\ta.symptoms as \"symptoms\",\n" +
               "\td.sex AS \"sex\",\n" +
               "\td.mobile AS \"mobile\",\n" +
               "\td.idcard AS \"patIdCard\",\n" +
               "\td.city_code AS \"city_code\",\n" +
               "\te.dept_code AS \"dept_code\",\n" +
               "\te.dept_name AS \"dept_name\",\n" +
               "\tt.id AS \"consult\" \n" +
               "FROM\n" +
               "\twlyy_consult a ,\n" +
               "\twlyy_consult_team b \n" +
               "JOIN base_doctor c ON c.id = b.doctor \n" +
               "JOIN base_patient d ON d.id = b.patient \n" +
               "JOIN base_doctor_hospital e ON e.doctor_code = b.doctor \n" +
               "JOIN "+base+".topics t ON t.id = b.consult\n" +
               "WHERE\n" +
               "\ta.id = b.consult\n" +
               " AND a.symptoms IS NOT NULL AND b.status=1 " +
               "  and c.doctor not in ('402803816babc778016babd0dee21112')";

        Map<String,Object> params = new HashedMap();

        if(StringUtils.isNotBlank(startDate)){
            sql =  sql + "  and a.czrq >=:startDate ";
            params.put("startDate",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(endDate)){
            sql =  sql +  "  and a.czrq <=:endDate";
            params.put("endDate",DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(keyId)){
            sql =  sql +  "  and  a.id =:keyId ";
            params.put("keyId",keyId);
        }

        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,params);
        total = list.size();
        for(int i=0; i<total; i++) {
            Map<String,Object> info = list.get(i);
            String sqlMessage="SELECT\n" +
                    "\tM.sender_name AS \"sender_name\",\n" +
                    "\tM.sender_id AS \"sender_id\",\n" +
                    "\tM.timestamp AS \"timestamp\",\n" +
                    "\tM.content AS \"content\",\n" +
                    "\tM.content_type AS \"content_type\",\n" +
                    "\tT.id AS \"id\",\n" +
                    "\tM.session_id AS \"session_id\"\n" +
                    "FROM\n" +
                    "\t"+base+".topics T\n" +
                    "JOIN "+base+".muc_messages M ON M.session_id = T.session_id\n" +
                    "AND M.timestamp >= T.create_time\n" +
                    "AND M.timestamp <= T.end_time\n" +
                    "AND T.id='"+info.get("consult").toString()+"' "+
                    " ORDER BY\n" +
                    "\tM.timestamp ASC";
        /*    String sqlMessage = "SELECT m.sender_name AS \"sender_name\", m.`timestamp` AS \"timestamp\", m.content AS  \"content\", t.id AS \"id\"  FROM topics t " +
                    "JOIN muc_messages m ON m.session_id = t.session_id AND m.`timestamp` >= t.create_time AND m.`timestamp` <= t.end_time " +
                    "AND t.id = '"+info.get("consult").toString()+"' ORDER BY m.`timestamp` ASC";*/
            List<Map<String,Object>> list1 = jdbcTemplate.queryForList(sqlMessage);
            JSONArray array = new JSONArray();
            for (Map<String,Object> map:list1){
                String sql1= "SELECT\n" +
                        "\ts.participant_id as \"participant_id\" \n" +
                        "FROM\n" +
                        "\t"+base+".PARTICIPANTS s \n" +
                        "WHERE\n" +
                        "\t s.SESSION_ID = '"+map.get("session_id").toString()+"' AND S.participant_id<> '"+map.get("sender_id").toString()+"'";
                List<Map<String,Object>> list2 = jdbcTemplate.queryForList(sql1);
                JSONObject object =new JSONObject();
                if (list2!=null&&list2.size()!=0){
                    Map<String,Object> map1 = list2.get(0);
                    BaseDoctorDO doctorDO = doctorDao.findById(map1.get("participant_id").toString());
                    if (doctorDO!=null){
                        object.put("receiver",doctorDO.getName());
                    }else {
                        BasePatientDO patientDO = patientDao.findById(map1.get("participant_id").toString());
                        if (patientDO!=null){
                            object.put("receiver",patientDO.getName());
                        }
                    }
                }
                String msg = "";
                String msgType = "";
                if (map.get("content_type").toString().equalsIgnoreCase("2")){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("sender","系统");
                    jsonObject.put("msg","病情描述");
                    jsonObject.put("msg_type","0");
                    jsonObject.put("receiver","系统");
                    jsonObject.put("send_time",DateUtil.dateToStr(DateUtil.strToDate(map.get("timestamp").toString(),"yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd HH:mm:ss"));
                    array.add(jsonObject);
                    msg = consultUpNsOnlineImg(map.get("content").toString(),map.get("id").toString());
                    msgType = "1";
                }else if (map.get("content_type").toString().equalsIgnoreCase("1")){
                    msg = map.get("content").toString();
                    msgType = "0";
                }else {
                    msg = map.get("content").toString();
                    msgType = map.get("content_type").toString();
                }
                object.put("sender",map.get("sender_name"));
                object.put("msg",msg);
                object.put("msg_type",msgType);
                object.put("send_time",DateUtil.dateToStr(DateUtil.strToDate(map.get("timestamp").toString(),"yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd HH:mm:ss"));
                array.add(object);
            }
            info.put("content",array);


        }


        for(int i=0; i<total; i++) {
            Map<String,Object> info = list.get(i);
            JSONObject jb = new JSONObject();
            Boolean errorFlag = false;
            try {
                //基于科室转换成国家诊疗科目代码
                String[] dept = depToSubject(info.get("dept_code").toString());
                // 获取监管平台唯一标识
                String visitDocCode = achNsDoctorRecord((String)info.get("docIdCard"));

                jb.put("id_online_ask", orgCode+"_"+(String)info.get("id"));
                jb.put("net_service_code", "1");
                jb.put("med_class_code", info.get("type"));
                jb.put("med_pop_code", "1");
                jb.put("org_name",orgName);
                jb.put("org_code", orgCode);
                jb.put("cd_orgSub", orgSub);
                jb.put("cd_area", orgArea);
                jb.put("visit_doc_name",  info.get("docName")== null? "0":info.get("docName"));
                jb.put("visit_doc_id_no",  info.get("docIdCard")== null? "0":info.get("docIdCard"));
                jb.put("visit_doc_code",  visitDocCode);
                jb.put("visit_dept_code",  dept.length>=1?dept[0]:"");
                jb.put("visit_dept_name",  dept.length>=2?dept[1]:"");
                jb.put("pt_no", info.get("patientName")== null? "0":info.get("patientName"));
                jb.put("pt_age", IdCardUtil.getAgeForIdcard(info.get("patIdCard").toString()));
                jb.put("cost_type", "");
                jb.put("pt_birthdate", info.get("birthday") == null? "":DateUtil.dateToStrShort((Date)info.get("birthday")));
                jb.put("ge_code", info.get("sex")== null? "0":info.get("sex"));
                jb.put("pt_tel",info.get("mobile") == null ? "0":info.get("mobile"));
                jb.put("card_type", "1");
                jb.put("id_no", info.get("patIdCard")== null? "0":info.get("patIdCard"));
                jb.put("pt_district",info.get("city_code") == null?"":info.get("city_code"));
                jb.put("apply_time", info.get("czrq")==null?"2020-01-01":DateUtil.dateToStrLong((Date)info.get("czrq")));
                jb.put("visit_time", info.get("czrq")==null?"2020-01-01":DateUtil.dateToStrLong((Date)info.get("czrq")));
                jb.put("visit_finish_time", info.get("end_time")==null?"2020-01-01":DateUtil.dateToStrLong((Date)info.get("end_time")));
                jb.put("complaint_content", info.get("content"));
                logger.info("complaint_content"+info.get("content"));
               /* String procFile="";
                if (info.get("content")!=null){
                    JSONArray array = JSONArray.parseArray(info.get("content").toString());
                    for (int j=0;j<array.size();j++){
                        String type = array.getJSONObject(j).getString("content_type");
                        if (type.equalsIgnoreCase("3")||type.equalsIgnoreCase("12")){
                            procFile=imgUrl+array.getJSONObject(j).getString("content");
                            break;
                        }
                    }
                }*/
                jb.put("proc_file", systemUrl+"ims-web/#/login?type=9&doctorCode="+info.get("doctor")+"&qCode="+info.get("id"));
                jb.put("price", 0);
                jb.put("fg_reply", "1");
                jb.put("crt_time", DateUtil.dateToStrLong(DateUtil.getNow()));
            }catch (Exception e){
                errorFlag = true;
                saveErrorLog(upid,"8",(String)info.get("id"),"网络咨询服务信息格式错误",2);
                dataError++;
                logger.error(e.toString());
            }

            if(!errorFlag){
                JSONArray jsonArray = new JSONArray();
                jsonArray.add(jb);
                String str = jb.toJSONString();
                res = postToInter(token,api, jsonArray,url);

                JSONObject resJson = (JSONObject) JSONObject.parse(res);
                if("200".equals(resJson.get("msg").toString())){
                    success++;
                }else{
                    saveErrorLog(upid,"8",info.get("id").toString(),res,2);
                    error++;
                }
            }
        }

        String resInfo = "此次共上传：" + total + "条数据，其中成功 ：" + success + "条，上传失败 ： " + error + "条。格式错误："+dataError+"条。";

        saveUpLog(upid,"8",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"),DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"),success,error,dataError,resInfo);

        return null;
    }

    // 9 网络诊疗服务信息 	micc.upNsOnlineMed
    public String upNsOnlineMed(String startDate, String endDate,String keyId) throws Exception {
        getBaseSurperviseDict();
        String url = getUrl();
        String api = "micc.upNsOnlineMed";
        String upid = getCode();
        String res = "";
        int total = 0;
        int success = 0;
        int error = 0;
        int dataError = 0;

        String token = upNsUserToken(url);

        String sql = "select " +
                "       a.id AS \"id\"," +
                "       a.register_no AS \"register_no\", " +
                "       a.type AS \"type\", " +
                "       b.id AS \"docId\", " +
                "       a.doctor_name AS \"doctor_name\", " +
                "       b.idcard AS \"docIdCard\"," +
                "       a.dept AS \"dept\", " +
                "       a.dept_name AS \"dept_name\", " +
                "       c.name AS \"paName\", " +
                "       c.idcard AS \"paId\", " +
                "       c.sex AS \"sex\"," +
                "       c.mobile AS \"mobile\"," +
                "       a.create_time AS \"create_time\"," +
                "       b.charge_type AS \"charge_type\"," +
                "       a.register_date AS \"register_date\", " +
                "       a.end_time AS \"end_time\"," +
                "       a.icd10 AS \"icd10\"," +
                "       a.icd10_name AS \"icd10_name\"," +
                "       a.origin_adm_no AS \"origin_adm_no\"," +
                "       a.card_no AS \"card_no\", " +
                "       a.description AS \"description\"" +
                "  from wlyy_outpatient a " +
                "      join base_doctor b on b.id = a.doctor" +
                "      join base_patient c on c.id = a.patient" +
                " where a.register_no is NOT NULL and a.dept is not null " +
                " and a.register_date is not null " +
                " and a.doctor not in ('402803816babc778016babd0dee21112')" +
                " and a.patient not in ('2c9081aa6c2f1892016c6a26a8c102ca','39686349deff487d8f3372fc253b8417') " ;

        Map<String,Object> params = new HashedMap();

        if(StringUtils.isNotBlank(startDate)){
            sql =  sql + "  and a.create_time >=:startDate ";
            params.put("startDate",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(endDate)){
            sql =  sql +  "  and a.create_time <=:endDate";
            params.put("endDate",DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(keyId)){
            sql =  sql +  "  and  a.id =:keyId ";
            params.put("keyId",keyId);
        }
        logger.info("sql===="+sql);
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,params);
        logger.info("count===="+list.size());

        total = list.size();

        for(int i=0; i<list.size(); i++) {
            logger.info("进入循环"+list.get(i));
            Map<String,Object> info = list.get(i);
            JSONObject jb = new JSONObject();
            Boolean errorFlag = false;
            try {
                //基于科室转换成国家诊疗科目代码
                String[] dept = depToSubject(info.get("dept").toString());
                // 获取监管平台唯一标识
                String visitDocCode = achNsDoctorRecord((String)info.get("docIdCard"));
//                String visitDocCode = achNsDoctorRecord("350102198005012428");

                jb.put("id_online_med", orgCode +"_"+ (String)info.get("id"));
                jb.put("net_service_code", "4");
                jb.put("med_class_code", info.get("type")== ""?"1":info.get("type"));
                jb.put("org_name", orgName);
                jb.put("org_code", orgCode);
                jb.put("cd_orgSub",orgSub);
                jb.put("cd_area",orgArea);
                jb.put("visit_doc_name",  info.get("doctor_name"));
                jb.put("visit_doc_id_no", info.get("docIdCard"));
                jb.put("visit_doc_code", visitDocCode);
                jb.put("visit_subject_code", dept.length>=1?dept[0]:"");
                jb.put("visit_subject_name",dept.length>=2?dept[1]:"");
                jb.put("visit_dept_code",  dept.length>=1?dept[0]:"");
                jb.put("visit_dept_name",  dept.length>=2?dept[1]:"");
                jb.put("pt_no", info.get("paName"));
                jb.put("pt_age", IdCardUtil.getAgeForIdcard(info.get("paId").toString()));
//                jb.put("cost_type", info.get("charge_type").toString());
                jb.put("cost_type", "");

                jb.put("pt_birthdate", null);

                String sex = IdCardUtil.getSexForIdcard_new(info.get("paId").toString());
                jb.put("ge_code", sex=="3"?"9":sex);

                jb.put("pt_tel", info.get("moble")==null?"00000000000":info.get("moble").toString());
                jb.put("card_type", "1");
                jb.put("id_no", info.get("paId"));
                jb.put("pt_district", "");
                jb.put("pt_card_type", "");
                jb.put("pt_card_no",info.get("card_no"));

                Date createTime = (Date) info.get("create_time");
                jb.put("apply_time", DateUtil.dateToStr(createTime,"yyyy-MM-dd HH:mm:ss"));

                Date date = (Date) info.get("register_date");
                jb.put("visit_time", DateUtil.dateToStr(date,"yyyy-MM-dd HH:mm:ss"));
                String dateStr = DateUtil.dateToStr(DateUtil.getPreDays(date,1),"yyyy-MM-dd");

                jb.put("visit_finish_time", dateStr+" 00:00:00");

                jb.put("old_diag_code", info.get("icd10"));
                jb.put("old_diag_name", info.get("icd10_name"));
                jb.put("diag_code",info.get("icd10"));
                jb.put("diag_name", info.get("icd10_name"));
                jb.put("diseases_type", info.get("origin_adm_no") == null ? "1":"2");
                JSONObject object = new JSONObject();
                object.put("sender",info.get("paName").toString());
                object.put("receiver",info.get("doctor_name"));
                object.put("msg",info.get("description").toString());
                object.put("send_time",DateUtil.dateToStr(createTime,"yyyy-MM-dd HH:mm:ss"));
                object.put("msg_type",0);
                JSONArray array = new JSONArray();
                array.add(object);
                jb.put("complaint_content",array);
                jb.put("proc_file", "无");
                jb.put("price","0");
                jb.put("fg_reply", "");
                jb.put("crt_time", DateUtil.dateToStrLong(DateUtil.getNow()));
            }catch (Exception e){
                errorFlag = true;
                saveErrorLog(upid,"9",(String)info.get("id"),"网络诊疗服务信息格式错误",1);
                dataError++;
                logger.error(e.toString());
            }
            if(!errorFlag){
                JSONArray jsonArray = new JSONArray();
                jsonArray.add(jb);
                res = postToInter(token,api, jsonArray,url);

                JSONObject resJson = (JSONObject) JSONObject.parse(res);
                if("200".equals(resJson.get("msg").toString())){
                    success++;
                }else{
                    saveErrorLog(upid,"9",(String)info.get("id"),res,2);
                    error++;
                }
            }

        }
        String resInfo = "此次共上传：" + total + "条数据，其中成功 ：" + success + "条，上传失败 ： " + error + "条。格式错误："+dataError+"条。";
        saveUpLog(upid,"9",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"),DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"),success,error,dataError,resInfo);

        return resInfo;
    }

    // 10 电子处方表 micc.upPrescription    --- 完成
    public String upPrescription(String startDate, String endDate,String keyId) throws Exception {
        getBaseSurperviseDict();
        String url = getUrl();
        String api = "micc.upPrescription";
        String upid =getCode();
        String res = "";
        int total = 0;
        int success = 0;
        int error = 0;
        int dataError = 0;

        String token = upNsUserToken(url);

        String sql = "select " +
                "  a.id AS \"id\"," +
                "  a.real_order AS \"real_order\"," +
                "  a.patient_code AS \"patient_code\"," +
                "  a.outpatient_id AS \"outpatient_id\"," +
                "  a.patient_name AS \"patient_name\"," +
                "  b.idcard AS \"idcard\"," +
                "  b.city_code AS \"city_code\"," +
                "  a.hospital AS \"hospital\"," +
                "  a.hospital_name AS \"hospital_name\"," +
                "  p.icd10 AS \"icd10\"," +
                "  p.icd10_name AS \"icd10_name\"," +
                "  p.dept AS \"dept\"," +
                "  p.dept_name AS \"dept_name\"," +
                "  a.doctor AS \"doctor\"," +
                "  a.doctor_name AS \"doctor_name\"," +
                "  a.drug_fee AS \"drug_fee\"," +
                "  c.idcard AS \"docIdcard\", " +
                "  a.create_time AS \"create_time\" " +
                "  from  wlyy_prescription a" +
                "     JOIN base_patient b on a.patient_code = b.id " +
                "     JOIN base_doctor c on a.doctor = c.id " +
                "     JOIN wlyy_outpatient p on p.id = a.outpatient_id  " +
                "  where  c.idcard is not null  and a.real_order is not null and p.icd10 is not null ";

        Map<String,Object> params = new HashedMap();

        if(StringUtils.isNotBlank(startDate)){
            sql =  sql + "  and a.create_time >=:startDate ";
            params.put("startDate",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(endDate)){
            sql =  sql +  "  and a.create_time <=:endDate";
            params.put("endDate",DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(keyId)){
            sql =  sql +  "  and  a.id =:keyId ";
            params.put("keyId",keyId);
        }

        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,params);

        total = list.size();

        for(int i=0; i<total; i++) {
            Map<String,Object> info = list.get(i);
            JSONObject jb = new JSONObject();
            Boolean errorFlag = false;

            try {
                //基于科室转换成国家诊疗科目代码
                String[] dept = depToSubject(info.get("dept").toString());
                // 获取监管平台唯一标识
                String visitDocCode = achNsDoctorRecord(info.get("docIdcard").toString());

                String trialDocCode =  achNsDoctorRecord("350104197904305425");

                jb.put("id_prescription", orgCode +"_"+ (String)info.get("id"));
                jb.put("pres_no",info.get("real_order")== null?"0":info.get("real_order"));
                jb.put("pres_class_code", "1");
                jb.put("pres_class_name", "西药");
                jb.put("pt_id", info.get("patient_code"));
                jb.put("med_rd_no", info.get("outpatient_id"));
                jb.put("med_class_code", "4");
                jb.put("med_class_name", "在线复诊");
                jb.put("pt_no", info.get("patient_name"));
                jb.put("ge_code", info.get("sex")== null?"0": info.get("sex"));
                jb.put("pt_age",IdCardUtil.getAgeForIdcard(info.get("idcard").toString()));
                jb.put("birthday", info.get("birthday")  == null?"": DateUtil.dateToStrLong((Date)info.get("birthday")));
                jb.put("card_type", "1");
                jb.put("id_no", info.get("idcard"));
                jb.put("guarder_name", "");
                jb.put("guarder_no", "");
                jb.put("pt_tel",info.get("mobile") == null?"": info.get("mobile"));
                jb.put("pt_district", info.get("city_code")== null?"": info.get("city_code"));
                jb.put("allergic_history", "");
                jb.put("cost_type", "");
                jb.put("ins_class_code", "");
                jb.put("ins_class_name", "");
                jb.put("org_code", orgCode);
                jb.put("org_name",orgName);
                jb.put("pres_subject_code", dept.length>=1?dept[0]:"");
                jb.put("pres_subject_name", dept.length>=2?dept[1]:"");
                jb.put("pres_dept_code", info.get("dept")== null?"0":info.get("dept"));
                jb.put("pres_dept_name",info.get("dept_name")== null?"0":info.get("dept_name"));
                jb.put("pres_time", info.get("create_time")== null?DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"):DateUtil.dateToStrLong((Date)info.get("create_time")));
                jb.put("trial_time",info.get("create_time")== null?DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"):DateUtil.dateToStrLong(new Date(((Date)info.get("create_time")).getTime()+600000)));
                jb.put("pres_doc_code", visitDocCode);
                jb.put("pres_doc_name", info.get("doctor_name")== null?"0":info.get("doctor_name"));
                jb.put("pres_doc_id_no", info.get("docIdcard")== null?"0":info.get("docIdcard"));
                jb.put("trial_doc_code", trialDocCode);
                jb.put("trial_doc_name", "陈燕莺");
                jb.put("trial_doc_id_no","350104197904305425");
                jb.put("diag_code", info.get("icd10"));
                jb.put("diag_name", info.get("icd10_name"));
                jb.put("diseases_type", "0");
                jb.put("mobility_flag", "3");
                jb.put("long_medical_flag", "3");
                jb.put("pres_effec_days", 0);
                String realOrder = "";
                if (info.get("real_order")!= null){
                    realOrder = info.get("real_order").toString();
                }
                String priceTotal="select sum(drug_fee) AS drug_fee from wlyy_prescription where real_order='"+realOrder+"'";
                Map<String,Object> map = jdbcTemplate.queryForMap(priceTotal);
                jb.put("total_price",map.get("drug_fee")== null?  0 : map.get("drug_fee"));
                jb.put("upload_time", DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
                jb.put("pres_photo", "");
                jb.put("pres_photos_list", "");
                jb.put("pres_photos", "");
            }catch (Exception e){
                errorFlag = true;
                saveErrorLog(upid,"10",(String)info.get("id"),"电子处方表格式错误",1);
                dataError++;
                logger.error(e.toString());
            }

            if(!errorFlag){
                JSONArray jsonArray = new JSONArray();
                jsonArray.add(jb);
                res = postToInter(token,api, jsonArray,url);

                JSONObject resJson = (JSONObject) JSONObject.parse(res);
                if("200".equals(resJson.get("msg").toString())){
                    success++;
                }else{
                    saveErrorLog(upid,"10",(String)info.get("id"),res,2);
                    error++;
                }
            }
        }
        String resInfo = "此次共上传：" + total + "条数据，其中成功 ：" + success + "条，上传失败 ： " + error + "条。格式错误："+dataError+"条";
        saveUpLog(upid,"10",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"),DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"),success,error,dataError,resInfo);

        return resInfo;
    }

    // 11 电子处方_药品明细表	micc.upPrescriptionDrug     --- 完成
    public String upPrescriptionDrug(String startDate, String endDate,String keyId) throws Exception {
        getBaseSurperviseDict();
        String url = getUrl();
        String api = "micc.upPrescriptionDrug";
        String upid = getCode();
        String token = upNsUserToken(url);
        String res = "";
        int total = 0;
        int success = 0;
        int error = 0;
        int dataError = 0;

        String sql = "select " +
                "    b.real_order AS \"real_order\"," +
                "    a.id AS \"id\", " +
                "    a.prescription_id AS \"prescription_id\", " +
                "    a.drug_no AS \"drug_no\"," +
                "    a.drug_name AS \"drug_name\", " +
                "    a.dosage AS \"dosage\"," +
                "    a.unit AS \"unit\"," +
                "    a.quantity AS \"quantity\"," +
                "    a.pack_unit AS \"pack_unit\"," +
                "    a.usage_code AS \"usage_code\"," +
                "    a.supply_code AS \"supply_code\"," +
                "    a.specification AS \"specification\"," +
                "    a.pack_retprice AS \"pack_retprice\"," +
                "    a.pack_retprice AS \"drug_total_price\"," +
                "   a.days as \"days\"," +
                "   a.serial as \"serial\" "+
                "  from wlyy_prescription_info a " +
                "     JOIN wlyy_prescription b " +
                "     on b.id = a.prescription_id" +
                "  where  a.dosage is not null and b.real_order is not null and a.del=1 ";

        Map<String,Object> params = new HashedMap();

        if(StringUtils.isNotBlank(startDate)){
            sql =  sql + "  and b.create_time >=:startDate ";
            params.put("startDate",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(endDate)){
            sql =  sql +  "  and b.create_time <=:endDate";
            params.put("endDate",DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(keyId)){
            sql =  sql +  "  and  a.prescription_id =:keyId ";
            params.put("keyId",keyId);
        }

        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,params);

        total = list.size();

        for(int i=0; i<total; i++) {
            Map<String,Object> info = list.get(i);
            JSONObject jb = new JSONObject();
            Boolean errorFlag = false;
            try {
                jb.put("id_prescription_drug",orgCode +"_"+ (String)info.get("id"));
                jb.put("pres_no", info.get("real_order") == null? "0": info.get("real_order"));
                jb.put("org_code",orgCode);
                jb.put("appr_drug_code", info.get("drug_no") == null? "0": info.get("drug_no"));
                jb.put("appr_drug_name", info.get("drug_name") == null? "0": info.get("drug_name"));
                jb.put("drug_code", "");
                jb.put("drug_name", "");
                jb.put("drug_form", "");
                jb.put("approval_no",info.get("serial"));
                jb.put("dosage",info.get("dosage") == null? 0: info.get("dosage"));
                jb.put("Prescription days",Integer.parseInt(info.get("days").toString()));
                jb.put("dosage_unit", info.get("unit") == null? "0": info.get("unit"));
                jb.put("total_dosage", info.get("quantity") == null? 0: info.get("quantity"));
                jb.put("total_dosage_unit", info.get("pack_unit") == null? "0": info.get("pack_unit"));
                jb.put("medicine_freq", info.get("usage_code") == null? "0": info.get("usage_code"));
                jb.put("drug_use", info.get("supply_code") == null? "0": info.get("supply_code"));
                jb.put("standard_desc", info.get("specification") == null? "0": info.get("specification"));
                jb.put("single_price",info.get("pack_retprice") == null? 0: info.get("pack_retprice"));
                Double pack_retprice = Double.parseDouble(info.get("pack_retprice").toString());
                Long quantity = Long.parseLong((String)info.get("quantity"));
                DecimalFormat decimalFormat = new DecimalFormat("0.00");
                Double price = pack_retprice.doubleValue()*quantity;
                logger.info("price"+decimalFormat.format(price));
                jb.put("drug_total_price",decimalFormat.format(price));
                jb.put("comments", "");
                jb.put("anti_comments", "");
                jb.put("dec_meth_name", "");
            }catch (Exception e){
                errorFlag = true;
                saveErrorLog(upid,"11",(String)info.get("id"),res,1);
                dataError++;
                logger.error(e.toString());
            }

            if(!errorFlag){
                JSONArray jsonArray = new JSONArray();
                jsonArray.add(jb);
                res = postToInter(token,api, jsonArray,url);

                JSONObject resJson = (JSONObject) JSONObject.parse(res);
                if("200".equals(resJson.get("msg").toString())){
                    success++;
                }else{
                    saveErrorLog(upid,"11",(String)info.get("id"),res,2);
                    error++;
                }
            }
        }
        String resInfo = "此次共上传：" + total + "条数据，其中成功 ：" + success + "条，上传失败 ： " + error + "条。格式错误："+dataError+"条。";
        saveUpLog(upid,"11",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"),DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"),success,error,dataError,resInfo);
        return resInfo;
    }

    public static void main(String[] args) {
        String ss="";
        System.out.println(ss.split(","));
    }
    // 12.服务信息-过程图片上传     --- 完成
    public String upNsOnlineImg(String startDate, String endDate,String keyId) throws Exception {
        getBaseSurperviseDict();
        String url = getUrl();
        String api = "micc.upNsOnlineImg";
        String upid = getCode();
        String token = upNsUserToken(url);
        String res = "";
        int total = 0;
        int success = 0;
        int error = 0;
        int dataError = 0;

        String sql = "SELECT " +
                "   p.id AS \"id\"," +
                "   p.disease_img AS \"disease_img\" " +
                " FROM wlyy_outpatient p " +
                " WHERE p.disease_img is not null ";

        Map<String,Object> params = new HashedMap();

        if(StringUtils.isNotBlank(startDate)){
            sql =  sql + "  and p.create_time >=:startDate ";
            params.put("startDate",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(endDate)){
            sql =  sql +  "  and p.create_time <=:endDate";
            params.put("endDate",DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(keyId)){
            sql =  sql +  "  and  p.id =:keyId ";
            params.put("keyId",keyId);
        }

        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,params);

        total = list.size();

        for(int i=0; i<total; i++) {
            Map<String,Object> info = list.get(i);
            String pathimg[] = ((String)info.get("disease_img")).split(",");
            if(pathimg!=null&&pathimg.length>0){
                for(String img:pathimg){
                    JSONObject jb = new JSONObject();
                    Boolean errorFlag = false;
                    try {
                        jb.put("id_online_img",getCode());
                        jb.put("id_onlne_base", orgCode+"_"+info.get("id"));
                        jb.put("online_type","2");
                        String base64 =getImg(img);
                        jb.put("img_path",base64);
                        jb.put("img_sort", i);
                        jb.put("upload_time", DateUtil.dateToStr(new Date(),"yyyy-MM-dd hh:mm:ss"));
                    }catch (Exception e){
                        errorFlag = true;
                        saveErrorLog(upid,"12",(String)info.get("id"),res,1);
                        dataError++;
                        logger.error(e.toString());
                    }

                    if(!errorFlag){
                        JSONArray jsonArray = new JSONArray();
                        jsonArray.add(jb);
                        res = postToInter(token,api, jsonArray,url);

                        JSONObject resJson = (JSONObject) JSONObject.parse(res);
                        if("200".equals(resJson.get("msg").toString())){
                            success++;
                        }else{
                            saveErrorLog(upid,"12",(String)info.get("id"),res,2);
                            error++;
                        }
                    }
                }
            }
        }
        String resInfo = "此次共上传：" + total + "条数据，其中成功 ：" + success + "条，上传失败 ： " + error + "条。格式错误："+dataError+"条。";
        saveUpLog(upid,"12",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"),DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"),success,error,dataError,resInfo);
        return resInfo;
    }


    //13.用户协议信息
    public String upNsOrganProtocol(String startDate, String endDate,String keyId) throws Exception {
        getBaseSurperviseDict();
        BaseSuperviseDataDict superviseDataDict = superviseDataDictDao.selectByDictName();
        String url = getUrl();
        String api = "micc.upNsOrganProtocol";
        String upid = getCode();
        String token = upNsUserToken(url);
        String res = "";
        int total = 0;
        int success = 0;
        int error = 0;
        int dataError = 0;

        JSONObject jb = new JSONObject();
        Boolean errorFlag = false;
        try {
            jb.put("id_organ_protocol",orgCode+"_"+upid);
            jb.put("organ_code", orgCode);
            jb.put("organ_name",orgName);
            jb.put("protocol_type", superviseDataDict.getUserProtocolType());
            jb.put("protocol_content", superviseDataDict.getUserProtocolContent());
            jb.put("publish_date", superviseDataDict.getUserPublishDate());
            jb.put("protocol_name", superviseDataDict.getUserProtocolName());
            jb.put("upload_time", DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"));

        }catch (Exception e){
            errorFlag = true;
            saveErrorLog(upid,"13",upid,res,1);
            dataError++;
            logger.error(e.toString());
        }

        if(!errorFlag){
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jb);
            res = postToInter(token,api, jsonArray,url);

            JSONObject resJson = (JSONObject) JSONObject.parse(res);
            if("200".equals(resJson.get("msg").toString())){
                success++;
            }else{
                saveErrorLog(upid,"13",upid,res,2);
                error++;
            }
        }

        String resInfo = "此次共上传：" + total + "条数据，其中成功 ：" + success + "条，上传失败 ： " + error + "条。格式错误："+dataError+"条。";
        saveUpLog(upid,"13",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"),DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"),success,error,dataError,resInfo);
        return resInfo;
    }


    //14.数据上传汇总信息
    public String upNsInvokeTotal(String startDate, String endDate) throws Exception {
        String base = getImUrl();
        getBaseSurperviseDict();
        String url = getUrl();
        String api = "micc.upNsInvokeTotal";
        String upid = getCode();
        String token = upNsUserToken(url);
        String res = "";
        int total = 0;
        int success = 0;
        int error = 0;
        int dataError = 0;

        //时间参数
        Map<String,Object> params = new HashedMap();

        //5.统计预约量
        String yyghSql = "SELECT " +
                "   count(1) AS \"yyghtotal\"" +
                " FROM wlyy_outpatient p " +
                " WHERE 1=1" ;
        if(StringUtils.isNotBlank(startDate)){
            yyghSql =  yyghSql + "  and p.create_time >=:startDate ";
            params.put("startDate",DateUtil.stringToDate(startDate+" 00:00:00","yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(endDate)){
            yyghSql =  yyghSql +  "  and p.create_time <=:endDate";
            params.put("endDate",DateUtil.stringToDate(endDate+" 00:00:00","yyyy-MM-dd HH:mm:ss"));
        }

        List<Map<String,Object>> yygh = hibenateUtils.createSQLQuery(yyghSql,params);
        Long yyghtotal = 0L;
        if(yygh!=null&&yygh.size()>0){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            yyghtotal = hibenateUtils.objTransformLong(yygh.get(0).get("yyghtotal"));
        }

        //7.医生评价
        String yypjSql ="SELECT " +
                "   count(1) AS \"yypjtotal\"" +
                " FROM " +
                " base_evaluate_score a " +
                " JOIN base_evaluate e ON a.id = e.relation_code " +
                " JOIN base_doctor d ON d.id = a.doctor " +
                " JOIN wlyy_consult m ON m.id = a.relation_code  " +
                "WHERE " +
                " e.score_type = '4' and m.id != '' and m.id is not null ";

        if(StringUtils.isNotBlank(startDate)){
            yypjSql =  yypjSql + "  and a.create_time >=:startDate ";
        }
        if(StringUtils.isNotBlank(endDate)){
            yypjSql =  yypjSql +  "  and a.create_time <=:endDate";
        }

        List<Map<String,Object>> yypj = hibenateUtils.createSQLQuery(yypjSql,params);
        Long yypjtotal = 0L;
        if(yypj!=null&&yypj.size()>0){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            yypjtotal = hibenateUtils.objTransformLong(yypj.get(0).get("yypjtotal"));
        }

        //8.统计网络咨询
        String wlzxSql = "SELECT\n" +
                "   count(1) AS \"wlzxtotal\"" +
                "FROM\n" +
                "\twlyy_consult a ,\n" +
                "\twlyy_consult_team b \n" +
                "JOIN base_doctor c ON c.id = b.doctor \n" +
                "JOIN base_patient d ON d.id = b.patient \n" +
                "JOIN base_doctor_hospital e ON e.doctor_code = b.doctor \n" +
                "JOIN "+base+".topics t ON t.id = b.consult\n" +
                "WHERE\n" +
                "\ta.id = b.consult\n" +
                "AND a.symptoms IS NOT NULL AND b.status=1 " +
                " and c.id not in ('402803816babc778016babd0dee21112')";

        if(StringUtils.isNotBlank(startDate)){
            wlzxSql =  wlzxSql + "  and a.czrq >=:startDate ";
        }
        if(StringUtils.isNotBlank(endDate)){
            wlzxSql =  wlzxSql +  "  and a.czrq <=:endDate";
        }

        List<Map<String,Object>> wlzx = hibenateUtils.createSQLQuery(wlzxSql,params);
        Long wlzxtotal = 0L;
        if(wlzx!=null&&wlzx.size()>0){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            wlzxtotal = hibenateUtils.objTransformLong(wlzx.get(0).get("wlzxtotal"));
        }

        //9.网络诊疗服务
        String wlzlSql = "select " +
                "   count(1) AS \"wlzltotal\"" +
                "  from wlyy_outpatient a " +
                "      join base_doctor b on b.id = a.doctor" +
                "      join base_patient c on c.id = a.patient" +
                " where a.register_no is NOT NULL and a.dept is not null " +
                " and a.register_date is not null " +
                " and a.doctor not in ('402803816babc778016babd0dee21112')" +
                " and a.patient not in ('2c9081aa6c2f1892016c6a26a8c102ca','39686349deff487d8f3372fc253b8417') " ;
        if(StringUtils.isNotBlank(startDate)){
            wlzlSql =  wlzlSql + "  and a.create_time >=:startDate ";
        }
        if(StringUtils.isNotBlank(endDate)){
            wlzlSql =  wlzlSql +  "  and a.create_time <=:endDate";
        }

        List<Map<String,Object>> wlzl = hibenateUtils.createSQLQuery(wlzlSql,params);
        Long wlzltotal = 0L;
        if(wlzl!=null&&wlzl.size()>0){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            wlzltotal = hibenateUtils.objTransformLong(wlzl.get(0).get("wlzltotal"));
        }

        //10.电子处方
        String dzcfsql = "select " +
                "   count(1) AS \"dzcftotal\"" +
                "  from  wlyy_prescription a" +
                "     JOIN base_patient b on a.patient_code = b.id " +
                "     JOIN base_doctor c on a.doctor = c.id " +
                "     JOIN wlyy_outpatient p on p.id = a.outpatient_id  " +
                "  where  c.idcard is not null  and a.real_order is not null and p.icd10 is not null ";

        if(StringUtils.isNotBlank(startDate)){
            dzcfsql =  dzcfsql + "  and a.create_time >=:startDate ";
        }
        if(StringUtils.isNotBlank(endDate)){
            dzcfsql =  dzcfsql +  "  and a.create_time <=:endDate";
        }

        List<Map<String,Object>> dzcf = hibenateUtils.createSQLQuery(dzcfsql,params);
        Long dzcftotal = 0L;
        if(dzcf!=null&&dzcf.size()>0){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            dzcftotal = hibenateUtils.objTransformLong(dzcf.get(0).get("dzcftotal"));
        }

        //11.电子处方药品明细
        String infosql = "select " +
                "   count(1) AS \"infototal\"" +
                "  from wlyy_prescription_info a " +
                "     JOIN wlyy_prescription b " +
                "     on b.id = a.prescription_id" +
                "  where  a.dosage is not null and b.real_order is not null and a.del=1 ";

        if(StringUtils.isNotBlank(startDate)){
            infosql =  infosql + "  and b.create_time >=:startDate ";
        }
        if(StringUtils.isNotBlank(endDate)){
            infosql =  infosql +  "  and b.create_time <=:endDate";
        }
        List<Map<String,Object>> info = hibenateUtils.createSQLQuery(infosql,params);
        Long infototal = 0L;
        if(info!=null&&info.size()>0){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            infototal = hibenateUtils.objTransformLong(info.get(0).get("infototal"));
        }

        //12.过程图片
        String gctpsql = "SELECT " +
                "   count(1) AS \"gctptotal\"" +
                " FROM wlyy_outpatient p " +
                " WHERE p.disease_img is not null ";

        if(StringUtils.isNotBlank(startDate)){
            gctpsql =  gctpsql + "  and p.create_time >=:startDate ";
        }
        if(StringUtils.isNotBlank(endDate)){
            gctpsql =  gctpsql +  "  and p.create_time <=:endDate";
        }

        List<Map<String,Object>> gctp = hibenateUtils.createSQLQuery(gctpsql,params);
        Long gctptotal = 0L;
        if(gctp!=null&&gctp.size()>0){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            gctptotal = hibenateUtils.objTransformLong(gctp.get(0).get("gctptotal"));
        }

        JSONObject jb = new JSONObject();
        Boolean errorFlag = false;
        try {
            jb.put("id_ws_invoke_total",upid);
            jb.put("org_code", orgCode);
            jb.put("org_name",orgName);
            jb.put("wsyy_upload_count", yyghtotal);
            jb.put("zxyj_upload_count", 0);
            jb.put("yspj_upload_count", yypjtotal);
            jb.put("wlzx_upload_count", wlzxtotal);
            jb.put("wlzl_upload_count", wlzltotal);
            jb.put("dzcf_upload_count", dzcftotal);
            jb.put("ypmx_upload_count", infototal);
            jb.put("gctp_upload_count", gctptotal);
            jb.put("ywsj", startDate);
            jb.put("crt_time", DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"));


        }catch (Exception e){
            errorFlag = true;
            saveErrorLog(upid,"14",upid,res,1);
            dataError++;
            logger.error(e.toString());
        }
        logger.info(jb.toString());
        if(!errorFlag){
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jb);
            res = postToInter(token,api, jsonArray,url);

            JSONObject resJson = (JSONObject) JSONObject.parse(res);
            if("200".equals(resJson.get("msg").toString())){
                success++;
            }else{
                saveErrorLog(upid,"14",upid,res,2);
                error++;
            }
        }

        String resInfo = "此次共上传：" + total + "条数据，其中成功 ：" + success + "条，上传失败 ： " + error + "条。格式错误："+dataError+"条。";
        saveUpLog(upid,"14",DateUtil.stringToDate(startDate,"yyyy-MM-dd HH:mm:ss"),DateUtil.stringToDate(endDate,"yyyy-MM-dd HH:mm:ss"),success,error,dataError,resInfo);
        return resInfo;
    }

    // 基于医生所在科室，转换成国家诊疗科目代码（中山医院专用）
    // 当科室信息在列表中不存在的情况，全部配置为预防保健科
    public String[] depToSubject(String dep){
        String[] res = new String[2];
        BaseDeptDict baseDeptDict = deptDictDao.selectByDeptCode(dep);
        if (baseDeptDict!=null){
            res[0]=baseDeptDict.getSubject();
            res[1]=baseDeptDict.getSubjectName();
        }else {
            res[0]="";
            res[1]="";
        }
        logger.info("科室转换："+res.toString());
        return res;
    }

    //2.5 预约，是否到诊字典转换
    public static String fgConvent(String status){
        String res ="";
        switch (status) {
            case "-1":
                res = "0";
                break;
            case "0":
                res = "1";
                break;
            case "1":
                res = "1";
                break;
            case "2":
                res = "1";
                break;
            case "3":
                res = "1";
                break;
            default:
                res = "";
        }
        return res;
    }

    // 将上传失败的数据存储到LOG 中，便于后续补传
    public void saveErrorLog(String upId,String type, String id, String errorInfo,Integer errorType){
        InternetUpErrorLogDO internetUpErrorLogDO = new InternetUpErrorLogDO();
        internetUpErrorLogDO.setUpId(upId);
        internetUpErrorLogDO.setType(type);
        internetUpErrorLogDO.setKeyId(id);
        internetUpErrorLogDO.setErrorInfo(errorInfo);
        internetUpErrorLogDO.setErrorType(errorType);
        internetUpErrorLogService.save(internetUpErrorLogDO);
    }

    public void saveUpLog(String upid,String code,Date startDate,Date endDate,Integer suc,Integer err,Integer dataErr,String remark){

        InternetUpLogDO internetUpLogDO = new InternetUpLogDO();
        internetUpLogDO.setId(upid);
        internetUpLogDO.setCode(code);
        internetUpLogDO.setStartDate(startDate);
        internetUpLogDO.setEndDate(endDate);
        internetUpLogDO.setCreateDate(new Date());
        internetUpLogDO.setSuc(suc);
        internetUpLogDO.setErr(err);
        internetUpLogDO.setDataErr(dataErr);
        internetUpLogDO.setRemark(remark);

        internetUpLogDao.save(internetUpLogDO);
    }

    // 基于中山医院的职务字典，强转为监管平台的字典(该部分过滤掉字典与监管理无法匹配的部分)
    public  String[]  classToduty(String duty){
        String[] res = new String[2];
        DictDoctorDutyDO doctorDutyDO = dictDoctorDutyDao.findByCode(duty);
        if (doctorDutyDO!=null){
            res[0]=doctorDutyDO.getTitleCode();
            res[1]=doctorDutyDO.getName();
        }else {
            res[0]="";
            res[1]="";
        }
        logger.info("职称转换："+res.toString());
        return  res;
    }

    /**
     * 网络图片地址
     * @param path
     * @return
     * @throws Exception
     */
    public String getImg(String path)throws Exception{
        try{
            if(path.contains("http")){
                URL url = new URL(path);
                DataInputStream dataInputStream = new DataInputStream(url.openStream());
                return getBase64FromInputStream(dataInputStream);
            }
            URL url = new URL(fastdfs_file_url+path);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            return getBase64FromInputStream(dataInputStream);
        }catch (Exception e){
            logger.error("getImg:"+e.toString());
        }
        return "";
    }

    public String getDateString(String date){
        String dates[] = date.split("-");
        if(dates!=null&&dates.length>0){
            if(dates[1].length()<2){
                dates[1] = "0"+dates[1];
            }
            if(dates[2].length()<2){
                dates[2] = "0"+dates[2];
            }
            return dates[0]+"-"+dates[1]+"-"+dates[2];
        }
        return date;
    }


    private String getBase64FromInputStream(InputStream is) throws Exception {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = is.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new Exception("输入流关闭异常");
                }
            }
        }
        //转化方法1
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encodeBuffer(data).trim();
        //转化方法2
//        return new String(Base64.encodeBase64(data));
    }

    public String testImg(String path){
        return ImgUtils.getImageStr(path);
    }



    public String consultUpNsOnlineImg(String imgPath,String consult) throws Exception {
        String msgCode = "";
        getBaseSurperviseDict();
        String url = getUrl();
        String api = "micc.upNsOnlineImg";
        String upid = getCode();
        String token = upNsUserToken(url);
        String res = "";
        int total = 0;
        int success = 0;
        int error = 0;
        int dataError = 0;

        JSONObject jb = new JSONObject();
        Boolean errorFlag = false;
        String code  = getCode();
        try {
            jb.put("id_online_img",code);
            jb.put("id_onlne_base", orgCode+"_"+consult);
            jb.put("online_type","1");
            String base64 =getImg(imgPath);
            jb.put("img_path",base64);
            jb.put("img_sort", 1);
            jb.put("upload_time", DateUtil.dateToStr(new Date(),"yyyy-MM-dd hh:mm:ss"));
        }catch (Exception e){
            errorFlag = true;
            saveErrorLog(upid,"12",consult,res,1);
            dataError++;
            logger.error(e.toString());
        }

        if(!errorFlag){
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jb);
            res = postToInter(token,api, jsonArray,url);

            JSONObject resJson = (JSONObject) JSONObject.parse(res);
            if("200".equals(resJson.get("msg").toString())){
                msgCode = code;
                success++;
            }else{
                saveErrorLog(upid,"12",imgPath,res,2);
                error++;
            }
        }

        String resInfo = "此次共上传：" + total + "条数据，其中成功 ：" + success + "条，上传失败 ： " + error + "条。格式错误："+dataError+"条。";
        saveUpLog(upid,"12",new Date(),new Date(),success,error,dataError,resInfo);
        return msgCode;
    }
}
