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.BaseSuperviseDataDictDao;
import com.yihu.jw.dict.dao.BaseSuperviseDictDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.hospital.dict.BaseSuperviseDataDict;
import com.yihu.jw.entity.hospital.dict.BaseSuperviseDict;
import com.yihu.jw.entity.thirdUpload.*;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.internet.dao.HospitalImgDao;
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.service.ykyy.YkyyInternetService;
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.thirdUpload.UpMedicalOnlineDao;
import com.yihu.jw.thirdUpload.service.*;
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 sun.misc.BASE64Encoder;

import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * Created by wsy on 2021/9/7.
 */
@Service
public class YkyyCommonService extends BaseJpaService<InternetUpErrorLogDO, InternetUpLogDao> {

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

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

    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;
    @Autowired
    private WlyyHospitalSysDictDao dictDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private BaseSuperviseDataDictDao superviseDataDictDao;
    @Autowired
    private BaseSuperviseDictDao superviseDictDao;
    @Autowired
    private UpnsDoctorRecordService upnsDoctorRecordService;
    @Autowired
    private UpAppointmentOnlineService upAppointmentOnlineService;
    @Autowired
    private UpMedicalOnlineService upMedicalOnlineService;
    @Autowired
    private UpnsDoctorScoreService upnsDoctorScoreService;
    @Autowired
    private BaseNsOnlineAskService baseNsOnlineAskService;
    @Autowired
    private BaseNsOlineMedService baseNsOlineMedService;
    @Autowired
    private BaseNsPrescriptionAService baseNsPrescriptionAService;
    @Autowired
    private BaseNsPrescriptionDrugService baseNsPrescriptionDrugService;

    static String userName = "xmykzx";
    static String psw = "7j39c7";
    static String appId = "ws022";
    static String AesEncodeKey = "834irjf3jd39rh2m";
    //static String urlString = "http://10.120.102.202:18081/micc/wsapi/1.0?wsdl";  // 正式线路径
    static String urlString = "http://fjhlw.bsoft.com.cn:18081/micc/wsapi/1.0?wsdl";   // 测试线路径
    static String method = "execute";
    static String token = "";
    static String orgCode = "350211A5004";
    static String orgName = "厦门大学附属厦门眼科中心";
    static String orgArea = "350203000";
    static String orgSub = "350200000";
    static String imgPath =File.separator+"usr"+File.separator+"local"+File.separator+"hospital"+File.separator+"svr-internet-hospital-job"+File.separator+"img"+File.separator;

    public String imgUrl;


    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();
    }

    public String getDate(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.format(new Date());
    }

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

    // 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 {
        getBaseSurperviseDict();
        BaseSuperviseDataDict superviseDataDict = superviseDataDictDao.selectByDictName();
        String url = getUrl();
        String api = "micc.upNsOrganBase";

        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", superviseDataDict.getSecondOrganName());
        jb.put("charge_person", 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);

        jb.put("secu_level",superviseDataDict.getSecuLevel());
        jb.put("secu_level_cert","");

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

        //用户协议
        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 startDate, String endDate,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);

        //取数据
        UpnsDoctorRecordDO upnsDoctorRecordDO;
        List<UpnsDoctorRecordDO> list = upnsDoctorRecordService.findAllByDate(startDate,endDate);

        total = list.size();

        for(int i=0; i<total; i++){
            upnsDoctorRecordDO = list.get(i);
            Boolean errorFlag = false;
            JSONObject jb = new JSONObject();
            try {

                //监管平台  职务字典强转
                jb.put("organ_code", orgCode);
                jb.put("organ_name", orgName);
                jb.put("doc_name", upnsDoctorRecordDO.getDoc_name());
                jb.put("docimg", upnsDoctorRecordDO.getDocimg());
                jb.put("id_card", upnsDoctorRecordDO.getId_card());
                jb.put("sex", upnsDoctorRecordDO.getSex());
                jb.put("birthday", upnsDoctorRecordDO.getBirthday());
                jb.put("subject", upnsDoctorRecordDO.getSubject());
                jb.put("subject_name", upnsDoctorRecordDO.getSubject_name());
                jb.put("belong_dept", upnsDoctorRecordDO.getBelong_dept());
                jb.put("belong_dept_name", upnsDoctorRecordDO.getBelong_dept_name());
                jb.put("doo_tel", upnsDoctorRecordDO.getDoo_tel());
                jb.put("title_rec_date", upnsDoctorRecordDO.getTitle_rec_date());
                jb.put("prac_type", upnsDoctorRecordDO.getPrac_type());
                jb.put("title_code", upnsDoctorRecordDO.getTitle_code());
                jb.put("first_compeny_code", upnsDoctorRecordDO.getFirst_compeny_code());
                jb.put("first_compeny_name", upnsDoctorRecordDO.getFirst_compeny_name());
                jb.put("secd_compeny_code", upnsDoctorRecordDO.getSecd_compeny_code());
                jb.put("secd_compeny_name", upnsDoctorRecordDO.getSecd_compeny_name());
                jb.put("net_service", upnsDoctorRecordDO.getNet_service());
                jb.put("cert_no", upnsDoctorRecordDO.getCert_no());
                jb.put("prac_no", upnsDoctorRecordDO.getPrac_no());
                jb.put("doc_cert", upnsDoctorRecordDO.getDoc_cert());
                jb.put("cert_doc_prac", upnsDoctorRecordDO.getCert_doc_prac());
                jb.put("txt_introduction", upnsDoctorRecordDO.getTxt_introduction());

            }catch (Exception e){
                errorFlag = true;
                saveErrorLog(upid,"3",upnsDoctorRecordDO.getId(),"数据格式错误",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",upnsDoctorRecordDO.getId(),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 {
        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 {
        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);

        UpAppointmentOnlineDO upAppointmentOnlineDO;
        List<UpAppointmentOnlineDO> list = upAppointmentOnlineService.findAllByDate(startDate,endDate);
        total = list.size();

        for(int i=0; i< total; i++){
            JSONObject jb = new JSONObject();
            upAppointmentOnlineDO = list.get(i);
            Boolean errorFlag = false;
            try{
                String[] dept = depToSubject(upAppointmentOnlineDO.getReg_subject_code());
                jb.put("id", orgCode +"_"+ upAppointmentOnlineDO.getId());
                jb.put("cd_org", orgCode);
                jb.put("cd_area", orgArea);
                jb.put("cd_orgSub", orgSub);
                jb.put("reg_time", upAppointmentOnlineDO.getReg_time());
                jb.put("fg_visit",  upAppointmentOnlineDO.getFg_visit() == null?"1" : upAppointmentOnlineDO.getFg_visit());
                jb.put("reg_dep_code",  upAppointmentOnlineDO.getReg_dep_code() == null?"0":upAppointmentOnlineDO.getReg_dep_code());
                jb.put("reg_dep_name",  upAppointmentOnlineDO.getReg_dep_name() == null?"0":upAppointmentOnlineDO.getReg_dep_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",  upAppointmentOnlineDO.getReg_price());
                jb.put("pt_name", upAppointmentOnlineDO.getPt_name() == null?"0":upAppointmentOnlineDO.getPt_name());
                jb.put("ge_code", upAppointmentOnlineDO.getGe_code());
                jb.put("pt_age", upAppointmentOnlineDO.getPt_age());
                jb.put("card_type", upAppointmentOnlineDO.getCard_type());
                jb.put("id_no",  upAppointmentOnlineDO.getId_no() == null?"0": upAppointmentOnlineDO.getId_no());
                jb.put("pt_tel",  upAppointmentOnlineDO.getPt_tel());
                jb.put("crt_date",DateUtil.dateToStrLong(DateUtil.getNow()));
            }catch (Exception e){
                errorFlag = true;
                saveErrorLog(upid,"5",upAppointmentOnlineDO.getId(),"网上预约挂号数据格式错误",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",upAppointmentOnlineDO.getId(),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 {
        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;

        UpMedicalOnlineDO upMedicalOnlineDO;
        List<UpMedicalOnlineDO> list = upMedicalOnlineService.findAllByDate(startDate,endDate);

        if(list != null && list.size() > 0){
            total = list.size();
            for(int i = 0; i<total; i++){
                JSONObject jb = new JSONObject();
                upMedicalOnlineDO = list.get(i);
                Boolean errorFlag = false;
                try {
                    String docInterId = achNsDoctorRecord(upMedicalOnlineDO.getId_doctor());
                    jb.put("id",orgCode +"_"+ upMedicalOnlineDO.getId());
                    jb.put("cd_org", orgCode);
                    jb.put("cd_area", orgArea);
                    jb.put("cd_orgSub", orgSub);
                    jb.put("app_time",upMedicalOnlineDO.getApp_time());
                    jb.put("app_dep_code", upMedicalOnlineDO.getApp_dep_code());
                    jb.put("app_class_code", upMedicalOnlineDO.getApp_class_code());
                    jb.put("id_doctor", docInterId);
                    jb.put("fg_handle", upMedicalOnlineDO.getFg_handle());
                    jb.put("handle_time", upMedicalOnlineDO.getHandle_time());
                    jb.put("pt_name",upMedicalOnlineDO.getPt_name());
                    jb.put("ge_code", upMedicalOnlineDO.getGe_code());
                    jb.put("card_type", upMedicalOnlineDO.getCard_type());
                    jb.put("id_no", upMedicalOnlineDO.getId_no());
                    jb.put("pt_tel", upMedicalOnlineDO.getPt_tel());
                    jb.put("crt_date",DateUtil.dateToStrLong(DateUtil.getNow()));
                }catch (Exception e){
                    errorFlag = true;
                    saveErrorLog(upid,"6",upMedicalOnlineDO.getId(),"在线医技预约格式错误",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",upMedicalOnlineDO.getId(),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 {
        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);

        List<UpnsDoctorScoreDO> list = upnsDoctorScoreService.findAllByDate(startDate,endDate);
        UpnsDoctorScoreDO upnsDoctorScoreDO = new UpnsDoctorScoreDO();

        total = list.size();
        Boolean errorFlag = false;
        JSONObject jb = new JSONObject();
        for(int i=0; i<list.size(); i++) {
            try{
            upnsDoctorScoreDO = list.get(i);
            String docInterId = achNsDoctorRecord(upnsDoctorScoreDO.getId_doctor());
            jb.put("id",orgCode +"_"+ upnsDoctorScoreDO.getId());
            jb.put("id_doctor",docInterId);
            jb.put("organ_code",orgCode);
            jb.put("organ_name", orgName);
            jb.put("net_service", upnsDoctorScoreDO.getNet_service());
            jb.put("net_service_name", upnsDoctorScoreDO.getNet_service_name());
            jb.put("val_score", upnsDoctorScoreDO.getVal_score() ==null ? "0": upnsDoctorScoreDO.getVal_score());
            jb.put("grader", upnsDoctorScoreDO.getGrader() == null ? "0":  upnsDoctorScoreDO.getGrader());
            jb.put("dt_grade", upnsDoctorScoreDO.getDt_grade());
            jb.put("grade_content", upnsDoctorScoreDO.getGrade_content() == null ? "0": upnsDoctorScoreDO.getGrade_content());
            jb.put("crt_date", DateUtil.dateToStrLong(DateUtil.getNow()));
            }catch (Exception e){
                errorFlag = true;
                saveErrorLog(upid,"7",upnsDoctorScoreDO.getId(),"医生评价信息格式错误",2);
                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,"7",upnsDoctorScoreDO.getId(),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 url = getUrl();
        String api = "micc.upNsOnlineAsk";
        String upid = getCode();
        String token = upNsUserToken(url);
        String res = "";
        int success = 0;
        int error = 0;
        int dataError = 0;
        int total;

        List<BaseNsOnlineAskDO> list = baseNsOnlineAskService.findAllByDate(startDate,endDate);
        BaseNsOnlineAskDO baseNsOnlineAskDO;
        total = list.size();


        for(int i=0; i<total; i++) {

            JSONObject jb = new JSONObject();
            Boolean errorFlag = false;
            baseNsOnlineAskDO = list.get(i);
            try {
                //基于科室转换成国家诊疗科目代码
                String[] dept = depToSubject(baseNsOnlineAskDO.getVisitDeptCode());
                String visitDocCode = achNsDoctorRecord(baseNsOnlineAskDO.getVisitDocCode());
                jb.put("id_online_ask", orgCode+"_"+ baseNsOnlineAskDO.getIdOnlineAsk());
                jb.put("net_service_code", baseNsOnlineAskDO.getNetServiceCode());
                jb.put("med_class_code", baseNsOnlineAskDO.getMedClassCode());
                jb.put("med_pop_code", baseNsOnlineAskDO.getMedClassCode());
                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",  baseNsOnlineAskDO.getVisitDocName() == null? "0": baseNsOnlineAskDO.getVisitDocName());
                jb.put("visit_doc_id_no", baseNsOnlineAskDO.getVisitDocIdNo() == null? "0":baseNsOnlineAskDO.getVisitDocIdNo());
                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", baseNsOnlineAskDO.getPtNo() == null? "0": baseNsOnlineAskDO.getPtNo());
                jb.put("pt_age", IdCardUtil.getAgeForIdcard(baseNsOnlineAskDO.getPtAge()));
                jb.put("cost_type", baseNsOnlineAskDO.getCostType());
                jb.put("pt_birthdate", baseNsOnlineAskDO.getPtBirthdate() == null? "":baseNsOnlineAskDO.getPtBirthdate());
                jb.put("ge_code", baseNsOnlineAskDO.getGeCode() == null? "0": baseNsOnlineAskDO.getGeCode());
                jb.put("pt_tel", baseNsOnlineAskDO.getPtTel() == null ? "0": baseNsOnlineAskDO.getPtTel());
                jb.put("card_type", baseNsOnlineAskDO.getCardType());
                jb.put("id_no", baseNsOnlineAskDO.getIdNo() == null? "0": baseNsOnlineAskDO.getIdNo());
                jb.put("pt_district", baseNsOnlineAskDO.getPtDistrict() == null?"": baseNsOnlineAskDO.getPtDistrict());
                jb.put("apply_time", baseNsOnlineAskDO.getApplyTime() ==null?"1900-01-01": baseNsOnlineAskDO.getApplyTime());
                jb.put("visit_time", baseNsOnlineAskDO.getVisitTime() ==null?"1900-01-01": baseNsOnlineAskDO.getVisitTime());
                jb.put("visit_finish_time", baseNsOnlineAskDO.getVisitFinishTime() ==null?"1900-01-01": baseNsOnlineAskDO.getVisitFinishTime());
                jb.put("complaint_content", baseNsOnlineAskDO.getComplaintContent());
                jb.put("proc_file", baseNsOnlineAskDO.getProcFile());
                jb.put("price", baseNsOnlineAskDO.getPrice());
                jb.put("fg_reply", baseNsOnlineAskDO.getFgReply());
                jb.put("crt_time", DateUtil.dateToStrLong(DateUtil.getNow()));
            }catch (Exception e){
                errorFlag = true;
                saveErrorLog(upid,"8",baseNsOnlineAskDO.getId(),"网络咨询服务信息格式错误",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",baseNsOnlineAskDO.getId().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 resInfo;
    }

    // 9 网络诊疗服务信息 	micc.upNsOnlineMed
    public String upNsOnlineMed(String startDate, String endDate,String keyId) throws Exception {
        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);

        BaseNsOnlineMedDO baseNsOnlineMedDO;
        List<BaseNsOnlineMedDO> list = baseNsOlineMedService.findAllByDate(startDate,endDate);


        total = list.size();

        for(int i=0; i<list.size(); i++) {
            baseNsOnlineMedDO = list.get(i);
            JSONObject jb = new JSONObject();
            Boolean errorFlag = false;
            try {
                //基于科室转换成国家诊疗科目代码
                String[] dept = depToSubject(baseNsOnlineMedDO.getVisitDeptCode());
                String visitDocCode = achNsDoctorRecord(baseNsOnlineMedDO.getVisitDocCode());
                jb.put("id_online_med", orgCode +"_"+ baseNsOnlineMedDO.getIdOnlineMed());
                jb.put("net_service_code", baseNsOnlineMedDO.getNetServiceCode());
                jb.put("med_class_code", baseNsOnlineMedDO.getMedClassCode() == ""?"1": baseNsOnlineMedDO.getMedClassCode());
                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",  baseNsOnlineMedDO.getVisitDocName());
                jb.put("visit_doc_id_no", baseNsOnlineMedDO.getVisitDocIdNo());
                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", baseNsOnlineMedDO.getPtNo());
                jb.put("pt_age", IdCardUtil.getAgeForIdcard(baseNsOnlineMedDO.getPtAge()));
                jb.put("cost_type", baseNsOnlineMedDO.getCostType());

                jb.put("pt_birthdate", baseNsOnlineMedDO.getPtBirthdate());

                String sex = IdCardUtil.getSexForIdcard_new(baseNsOnlineMedDO.getGeCode());
                jb.put("ge_code", sex=="3"?"9":sex);

                jb.put("pt_tel", baseNsOnlineMedDO.getPtTel() ==null?"00000000000": baseNsOnlineMedDO.getPtTel());
                jb.put("card_type", baseNsOnlineMedDO.getCardType());
                jb.put("id_no", baseNsOnlineMedDO.getIdNo());
                jb.put("pt_district", baseNsOnlineMedDO.getPtDistrict());
                jb.put("pt_card_type", baseNsOnlineMedDO.getPtCardType());
                jb.put("pt_card_no", baseNsOnlineMedDO.getPtCardNo());


                jb.put("apply_time", baseNsOnlineMedDO.getApplyTime());

                jb.put("visit_time", baseNsOnlineMedDO.getVisitTime());

                jb.put("visit_finish_time", baseNsOnlineMedDO.getVisitFinishTime());

                jb.put("old_diag_code", baseNsOnlineMedDO.getOldDiagCode());
                jb.put("old_diag_name", baseNsOnlineMedDO.getOldDiagName());
                jb.put("diag_code", baseNsOnlineMedDO.getDiagCode());
                jb.put("diag_name", baseNsOnlineMedDO.getDiagName());
                jb.put("diseases_type", baseNsOnlineMedDO.getDiseasesType() == null ? "1": baseNsOnlineMedDO.getDiseasesType());
                jb.put("complaint_content", baseNsOnlineMedDO.getComplaintContent());
                jb.put("proc_file", baseNsOnlineMedDO.getProcFile());
                jb.put("price", baseNsOnlineMedDO.getPrice());
                jb.put("fg_reply", baseNsOnlineMedDO.getFgReply());
                jb.put("crt_time", DateUtil.dateToStrLong(DateUtil.getNow()));
            }catch (Exception e){
                errorFlag = true;
                saveErrorLog(upid,"9", baseNsOnlineMedDO.getId(),"网络诊疗服务信息格式错误",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", baseNsOnlineMedDO.getId(),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 {
        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);

        BaseNsPrescriptionDO baseNsPrescriptionDO;
        List<BaseNsPrescriptionDO> list = baseNsPrescriptionAService.findAllByDate(startDate,endDate);

        total = list.size();

        for(int i=0; i<total; i++) {
            baseNsPrescriptionDO = list.get(i);
            JSONObject jb = new JSONObject();
            Boolean errorFlag = false;

            try {
                //基于科室转换成国家诊疗科目代码
                String[] dept = depToSubject(baseNsPrescriptionDO.getPresDeptCode());
                String visitDocCode = achNsDoctorRecord(baseNsPrescriptionDO.getPresDocCode());
                String trialDocCode =  achNsDoctorRecord(baseNsPrescriptionDO.getTrialDocCode());
                jb.put("id_prescription", orgCode +"_"+ baseNsPrescriptionDO.getIdPrescription());
                jb.put("pres_no", baseNsPrescriptionDO.getPresNo() == null?"0": baseNsPrescriptionDO.getPresNo());
                jb.put("pres_class_code", baseNsPrescriptionDO.getPresClassCode());
                jb.put("pres_class_name", baseNsPrescriptionDO.getPresClassName());
                jb.put("pt_id", baseNsPrescriptionDO.getPtId());
                jb.put("med_rd_no", baseNsPrescriptionDO.getMedRdNo());
                jb.put("med_class_code", baseNsPrescriptionDO.getMedClassCode());
                jb.put("med_class_name", baseNsPrescriptionDO.getMedClassName());
                jb.put("pt_no", baseNsPrescriptionDO.getPtNo());
                jb.put("ge_code", baseNsPrescriptionDO.getGeCode());
                jb.put("pt_age",baseNsPrescriptionDO.getPtAge());
                jb.put("birthday", baseNsPrescriptionDO.getBirthday() == null?"": baseNsPrescriptionDO.getBirthday());
                jb.put("card_type", baseNsPrescriptionDO.getCardType());
                jb.put("id_no", baseNsPrescriptionDO.getIdNo());
                jb.put("guarder_name", baseNsPrescriptionDO.getGuarderName());
                jb.put("guarder_no", baseNsPrescriptionDO.getGuarderNo());
                jb.put("pt_tel", baseNsPrescriptionDO.getPtDistrict() == null?"": baseNsPrescriptionDO.getPtDistrict());
                jb.put("pt_district", baseNsPrescriptionDO.getPtDistrict() == null?"": baseNsPrescriptionDO.getPtDistrict());
                jb.put("allergic_history", baseNsPrescriptionDO.getAllergicHistory());
                jb.put("cost_type", baseNsPrescriptionDO.getCostType());
                jb.put("ins_class_code", baseNsPrescriptionDO.getInsClassCode());
                jb.put("ins_class_name", baseNsPrescriptionDO.getMedClassName());
                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", baseNsPrescriptionDO.getPresDeptCode() == null?"0": baseNsPrescriptionDO.getPresDeptCode());
                jb.put("pres_dept_name", baseNsPrescriptionDO.getPresDeptName() == null?"0": baseNsPrescriptionDO.getPresDeptName());
                jb.put("pres_time", baseNsPrescriptionDO.getPresTime() == null?"1900-01-01 00:00:00":baseNsPrescriptionDO.getPresTime());
                jb.put("pres_doc_code", visitDocCode);
                jb.put("pres_doc_name", baseNsPrescriptionDO.getPresDocName() == null?"0": baseNsPrescriptionDO.getPresDocName());
                jb.put("pres_doc_id_no", baseNsPrescriptionDO.getPresDocIdNo() == null?"0": baseNsPrescriptionDO.getPresDocIdNo());
                jb.put("trial_doc_code", trialDocCode);
                jb.put("trial_doc_name", baseNsPrescriptionDO.getTrialDocName() == null?"0": baseNsPrescriptionDO.getTrialDocName());
                jb.put("trial_doc_id_no", baseNsPrescriptionDO.getTrialDocIdNo() == null?"0": baseNsPrescriptionDO.getTrialDocIdNo());
                jb.put("diag_code", baseNsPrescriptionDO.getDiagCode());
                jb.put("diag_name", baseNsPrescriptionDO.getDiagName());
                jb.put("diseases_type", baseNsPrescriptionDO.getDiseasesType());
                jb.put("mobility_flag", baseNsPrescriptionDO.getMobilityFlag());
                jb.put("long_medical_flag", baseNsPrescriptionDO.getLongMedicalFlag());
                jb.put("pres_effec_days", baseNsPrescriptionDO.getPresEffecDays());
                jb.put("total_price", baseNsPrescriptionDO.getTotalPrice() == null?  0 : baseNsPrescriptionDO.getTotalPrice());
                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",baseNsPrescriptionDO.getId(),"电子处方表格式错误",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",baseNsPrescriptionDO.getId(),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 {
        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;

        BaseNsPrescriptionDrugDO baseNsPrescriptionDrugDO;
        List<BaseNsPrescriptionDrugDO> list = baseNsPrescriptionDrugService.findAllByDate(startDate,endDate);

        total = list.size();

        for(int i=0; i<total; i++) {
            baseNsPrescriptionDrugDO = list.get(i);
            JSONObject jb = new JSONObject();
            Boolean errorFlag = false;
            try {
                jb.put("id_prescription_drug",orgCode +"_"+ baseNsPrescriptionDrugDO.getIdPrescriptionDrug());
                jb.put("pres_no", baseNsPrescriptionDrugDO.getPresNo() == null? "0": baseNsPrescriptionDrugDO.getPresNo());
                jb.put("org_code",orgCode);
                jb.put("appr_drug_code", baseNsPrescriptionDrugDO.getApprDrugCode() == null? "0": baseNsPrescriptionDrugDO.getApprDrugCode());
                jb.put("appr_drug_name", baseNsPrescriptionDrugDO.getApprDrugName() == null? "0": baseNsPrescriptionDrugDO.getApprDrugName());
                jb.put("drug_code", baseNsPrescriptionDrugDO.getApprDrugCode());
                jb.put("drug_name", baseNsPrescriptionDrugDO.getApprDrugName());
                jb.put("drug_form", baseNsPrescriptionDrugDO.getDrugForm());
                jb.put("dosage", baseNsPrescriptionDrugDO.getDosage() == null? 0: baseNsPrescriptionDrugDO.getDosage());
                jb.put("dosage_unit", baseNsPrescriptionDrugDO.getDosageUnit() == null? "0": baseNsPrescriptionDrugDO.getDosageUnit());
                jb.put("total_dosage", baseNsPrescriptionDrugDO.getTotalDosage() == null? 0: baseNsPrescriptionDrugDO.getTotalDosage());
                jb.put("total_dosage_unit", baseNsPrescriptionDrugDO.getTotalDosageUnit() == null? "0": baseNsPrescriptionDrugDO.getTotalDosageUnit());
                jb.put("medicine_freq", baseNsPrescriptionDrugDO.getMedicineFreq() == null? "0": baseNsPrescriptionDrugDO.getMedicineFreq());
                jb.put("drug_use", baseNsPrescriptionDrugDO.getDrugUse() == null? "0": baseNsPrescriptionDrugDO.getDrugUse());
                jb.put("standard_desc", baseNsPrescriptionDrugDO.getStandardDesc() == null? "0": baseNsPrescriptionDrugDO.getStandardDesc());
                jb.put("single_price", baseNsPrescriptionDrugDO.getSinglePrice() == null? 0: baseNsPrescriptionDrugDO.getSinglePrice());
                jb.put("drug_total_price",baseNsPrescriptionDrugDO.getDrugTotalPrice());
                jb.put("comments", baseNsPrescriptionDrugDO.getComments());
                jb.put("anti_comments", baseNsPrescriptionDrugDO.getAntiComments());
                jb.put("dec_meth_name", baseNsPrescriptionDrugDO.getDecMethName());
            }catch (Exception e){
                errorFlag = true;
                saveErrorLog(upid,"11",baseNsPrescriptionDrugDO.getId(),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",baseNsPrescriptionDrugDO.getId(),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;
    }



    //14.数据上传汇总信息
    public String upNsInvokeTotal(String startDate, String endDate) throws Exception {
        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;


        String upAppointCount = upAppointmentOnlineService.findCount(startDate,endDate);
        String upMedicalCount = upMedicalOnlineService.findCount(startDate,endDate);
        String upnsDoctorRecordCount = upnsDoctorRecordService.findCount(startDate,endDate);
        String upnsDoctorScoreCount = upnsDoctorScoreService.findCount(startDate,endDate);
        String baseNsOnlineAskCount = baseNsOnlineAskService.findCount(startDate,endDate);
        String baseNsPrescriptionDrugCount = baseNsPrescriptionDrugService.findCount(startDate,endDate);
        String baseNsPrescriptionCount = baseNsPrescriptionAService.findCount(startDate,endDate);
        String baseNsOlineMedCount = baseNsOlineMedService.findCount(startDate,endDate);


        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("upAppoint_upload_count", upAppointCount);
            jb.put("upMedical_upload_count", upMedicalCount);
            jb.put("upnsDoctorRecord_upload_count", upnsDoctorRecordCount);
            jb.put("upnsDoctorScore_upload_count", upnsDoctorScoreCount);
            jb.put("NsOnlineAsk_upload_count", baseNsOnlineAskCount);
            jb.put("NsPrescriptionDrug_upload_count", baseNsPrescriptionDrugCount);
            jb.put("NsPrescription_upload_count",baseNsPrescriptionCount);
            jb.put("NsOlineMed_upload_count",baseNsOlineMedCount);

            jb.put("ywsj", DateUtil.dateToStr(new Date(),"yyyy-MM-dd"));
            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 static  String[]  depToSubject(String dep){
        String[] res = new String[2];
        res[0] = "10";
        res[1] = "眼科";

        if(StringUtils.isNotBlank(dep)){
            if("1010".equals(dep)){
                res[0] = "3";
                res[1] = "内科";
            }else if("1154".equals(dep)){
                res[0] = "3";
                res[1] = "内科";
            }
        }

        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;
            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 static  String[]  classToduty(String duty){
        String[] res = new String[2];
        switch (duty) {
            case "1":
                res[0] = "231";
                res[1] = "主任医师";
                break;
            case "2":
                res[0] = "232";
                res[1] = "副主任医师";
                break;
            case "3":
                res[0] = "233";
                res[1] = "主治医师";
                break;
            default:
                res[0] = "234";
                res[1] = "医师";
        }
        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);
    }

}
