package com.yihu.jw.internet.service.ykyy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
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.dao.MedicalSkillOrdersDao;
import com.yihu.jw.internet.entity.InternetUpErrorLogDO;
import com.yihu.jw.internet.entity.InternetUpLogDO;
import com.yihu.jw.internet.service.InternetUpErrorLogService;
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.rm.base.BaseRequestMapping;
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.StringUtil;
import com.yihu.jw.utils.encode.AESUtils;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import com.ylzinfo.ehc.common.utils.DateUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
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.math.BigDecimal;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;

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

    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 HospitalImgDao hospitalImgDao;

            @Autowired
            private WlyyHospitalSysDictDao dictDao;
            @Autowired
            private HibenateUtils hibenateUtils;
            @Autowired
            private BaseDoctorDao doctorDao;
            @Autowired
            private BasePatientDao patientDao;

            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 ObjectMapper objectMapper;

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

            // 0 调用省监管平台接口
            public String postToInter(String token, String api, JSONArray params,String url) throws Exception {
                WsapiProxy proxy = new WsapiProxy();
                proxy.setEndpoint(url);
                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 {
                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 {
                String url = getUrl();
                String api = "micc.upNsOrganBase";

                JSONObject jb = new JSONObject();
                jb.put("organ_code", orgCode);
                jb.put("organ_name",orgName);
                jb.put("corporation", "苏庆灿");
                jb.put("no_pra_lic", "42660991-335020016A5122");
                jb.put("second_organ_name", "厦门眼科中心");
                jb.put("charge_person", "");

                jb.put("level", "1");
                jb.put("economic_type", "150");
                jb.put("organ_type", "2");
                jb.put("organ_sub", orgSub);
                jb.put("hospital_district",orgArea);
                jb.put("hospital_address", "厦门市思明区厦禾路336号");

                jb.put("hospital_phone", "0592-2112111");
                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","3");
                jb.put("secu_level_cert",ImgUtils.getImageStr(imgPath+"hospital"+File.separator+"dbtp.jpg"));

                jb.put("net_service", "1,3,4,5,7");
                jb.put("net_service_ot", "");
                jb.put("service_dept", "10");
                jb.put("txt_introduction", "");

                //用户协议
                jb.put("protocol_type", "1");
                jb.put("protocol_content", "声明\n" +
                        "根据国家卫生计生委的《关于推进医疗机构远程医疗服务的意见》文件中的指导意见，厦门大学附属厦门眼科中心互联网医院是医疗机构利用信息化技术向患者直接提供医疗服务，这些服务只允许医疗机构开展，厦门大学附属厦门眼科中心开展远程医疗服务的类别及专科均具有相应的资质，开展远程医疗服务的医生亦具有相应的执业资质，厦门大学附属厦门眼科中心在开展远程医疗服务过程中严格遵守相关的法律法规和行为规范，保证质量与安全，同时充分保障患者的隐私及知情权。互联网医院适用业务范围：常见病、轻病和慢性病的预诊及复诊（注：如果病人患病情况紧急、病情严重，请立即到线下医院治疗）；适用人群：常见病、轻病和慢性病患者（注：由厦门大学附属厦门眼科中心互联网医院提供的医生建议只做参考，不作为诊断。）\n" +
                        "(一)服务条款确认和接纳\n" +
                        "    1、本平台按照本协议的规定及不定期发布的操作规则提供基于互联网的医疗服务（以下称互联网医疗服务）。为获得互联网医疗服务，服务使用人（以下称用户）应当同意本协议的全部条款并按照页面上的提示完成注册程序。用户在进行注册程序过程中点击我同意按钮即表示完全接受本协议项下的全部条款。\n" +
                        "    2、用户点击同意本协议的，即视为用户确认自己具有享受本客户端服务、选用有偿服务、支付服务费用等相应的权利能力和行为能力，能够独立承担法律责任。\n" +
                        "    3、 限制行为能力人和无民事行为能力人，需要在监护人的监护参与下才能使用本平台。\n" +
                        "    4、医疗服务的具体内容由平台根据实际情况提供，平台保留随时变更、中断或终止部分或全部互联网医疗服务的权利。\n" +
                        "5、本平台提供的线上咨询服务，如即时问诊、电话咨询、图文咨询业务，发票由平台运营方福建眼界科技有限公司负责开具；若有涉及到医院线下的检查、检验及治疗项目的发票由厦门大学附属厦门眼科中心负责开具。\n" +
                        "（二）版权说明\n" +
                        "    1、本平台提供的相关服务内容可能包括：文字、软件、声音、图片、视频、录象、图表等。所有这些内容受版权、商标和其它财产所有权法律的保护。\n" +
                        "    2、本平台所登载的专有信息，未经本平台或其他相关权利人的书面授权，任何人不得以任何形式侵犯其著作权，包括擅自复制、非法使用或转载。\n" +
                        "（三）服务简介\n" +
                        "    1、互联网医院由网站所有人及其关联医院共同运营（以下合称平台运营方）。平台运营方运用自己的操作系统通过国际互联网为您提供本网站的网络服务，并承担本协议和其它服务协议中对您的责任和义务。为使用本服务，您必须能够自行通过有法律资格的第三方对您提供互联网接入服务，并自行承担以下内容：\n" +
                        "     \t(1) 自行配备上网所需的设备，包括个人电脑，调制解调器及其他必要的设备装置。 \n" +
                        "        (2) 自行承担上网所需的相关必要费用，如：电话费用、网络费用等。\n" +
                        "        (3) 本协议中规定的您的其他责任和义务。\n" +
                        "    2、健康之路无边界（厦门）医疗科技有限公司负责本平台正常运行，将协助医生或顾问与用户之间进行合法的交流，并提供必要的网络技术支持，确保提供优质的健康咨询服务通道。\n" +
                        "    3、本平台有权对相关数据、所有的申请行为以及与健康信息互通交流有关的其它事项进行审核，并在不符合平台要求的情况下给予拒绝或屏蔽。\n" +
                        "    4、用户在本平台发生不当行为，经本平台核实认为应当终止服务的，本平台有权随时删除该用户信息及终止服务，且无需征得用户的同意。\n" +
                        "（四）免责声明\n" +
                        "    1、本平台所有咨询、回答、相关评论仅代表作者本人的观点或基本判断，不代表本平台的观点和看法，与本平台立场无关。\n" +
                        "    2、本平台所刊载的各类形式(包括但不仅限于文字、图片、图表)的作品（包括广告等）仅供参考使用，并不代表本平台同意其说法或描述，也不构成任何方面建议。对于用户根据本平台提供的信息所做出的一切行为，除非另有明确的书面承诺文件，否则本平台不承担任何形式的责任。\n" +
                        "    3、凡在本平台登记注册的用户，须自行负责对您的账户和密码保密，且须对您的账户和密码下发生的所有活动承担全部责任。\n" +
                        "    4、用户自愿同意不做任何妨碍或者破坏服务（或与服务连接的服务器及网络）的任何活动。若因散布谣言、造假、谩骂等原因而被禁止本平台对其服务的，本平台均免责。\n" +
                        "    5、当政府部门、司法机关等依照法定程序要求本平台披露个人资料时，本平台将根据执法单位之要求或为公共安全之目的提供个人资料。在此情况下之任何披露，本平台均免责。\n" +
                        "    6、由于与本平台链接的其他软件或网页所造成的个人资料泄露及由此而导致的任何法律争议和后果，本平台均免责。\n" +
                        "    7、由于用户将个人密码告知他人或与他人共享注册帐户，由此导致的任何个人资料泄露，本平台均免责。\n" +
                        "    8、任何由于黑客攻击、计算机病毒侵入或发作、因政府管制而造成的暂时性关闭等影响网络正常运营的不可抗力造成的个人资料泄露、丢失、被盗用或被窜改等，本平台均免责。\n" +
                        "    9、除本平台注明的服务条款外，其他一切因使用本软件导致的任何意外、疏忽、诽谤、版权或知识产权侵犯及其所造成的损失(包括因下载而感染手机病毒)，本平台不承担任何法律责任。\n" +
                        "    10、用户自行同意本平台可自行更新、升级或关闭，而无需经过用户的同意。用户可以在任何时候停止使用本平台，而无需特别通知。\n" +
                        "（五）用户的权利和义务\n" +
                        "    1、用户应自行诚信向本客户端提供注册资料，用户保证提供的注册资料真实、准确、完整、合法有效，用户注册资料如有变动的，应及时更新其注册资料。如果用户提供的注册资料不合法、不真实、不准确、不详尽的，用户需承担因此引起的相应责任及后果，并且本平台保留终止用户使用平台各项服务的权利。\n" +
                        "    2、用户注册成功后，将产生用户名和密码等账户信息，您可以根据本平台规定改变您的密码。用户应谨慎合理的保存、使用其用户名和密码。用户若发现任何非法使用用户账号或存在安全漏洞的情况，请立即通知本平台并向公安机关报案。\n" +
                        "    3、用户有权通过本平台发布、获取信息，进行健康信息互通交流等，本平台另一端的医生或顾问将完全根据用户提供的信息做出指导和建议，如果用户提供的信息有误，造成的任何后果自行承担。\n" +
                        "    4、用户不得利用本平台各项服务在本平台或相关网站上进行销售或其他商业行为。用户违反此约定，本平台将依法追究其法律责任，由此给本平台造成损失的，本平台有权进行追偿。\n" +
                        "    5、用户同意，本平台拥有通过邮件、短信电话等形式，向在本平台注册、购买的用户发送订单信息、促销活动等告知信息的权利。\n" +
                        "    6、用户不得将在本平台注册获得的账户借给他人使用，否则用户应承担由此产生的全部责任，并与实际使用人承担连带责任。\n" +
                        "    7、用户明确同意：使用本平台相关服务所存在的风险将完全由用户自己承担；因其使用互联网医院服务而产生的一切后果也由自己承担，互联网医院对用户不承担任何责任。\n" +
                        "    8、用户同意，本平台有权使用用户的注册信息、用户名、密码等信息，登陆进入用户的注册账户，进行证据保全，包括但不限于公证、见证等。\n" +
                        "    9、用户在使用互联网医院相关服务过程中，必须遵循以下原则：\n" +
                        "        （1）遵守中国有关的法律和法规；\n" +
                        "        （2）不得为任何非法目的而使用互联网医院服务系统；\n" +
                        "        （3）遵守所有与互联网医院服务有关的网络协议、规定和程序；\n" +
                        "（4）不得利用互联网医院服务系统进行任何可能对互联网的正常运转造成不利影响的行为；\n" +
                        "        （5）不得利用互联网医院服务系统进行任何不利于医院的行为；\n" +
                        "        （6）如发现非法使用用户帐号或帐号出现安全漏洞的情况，应立即通告平台系统管理员或者客服人员。\n" +
                        "（六）隐私\n" +
                        "    1、保护用户隐私是互联网医院的一项基本政策，本平台保证不对外公开或向第三方提供用户注册资料及用户在使用互联网医院相关服务时存储的非公开内容，但下列情况除外：\n" +
                        "        （1）事先获得用户的明确授权；\n" +
                        "        （2）根据有关的法律法规要求；\n" +
                        "        （3）按照相关政府主管部门的要求；\n" +
                        "        （4）为维护社会公众的利益；\n" +
                        "        （5）为维护互联网医院的合法权益。\n" +
                        "    2、平台可能会与第三方合作向您提供相关的网络服务，在此情况下，如该第三方同意承担与平台同等的保护您隐私的责任，您同意并授权平台将您的注册资料等提供给该第三方。\n" +
                        "    3、在不透露单个用户隐私资料的前提下，本平台有权对整个用户数据库进行分析并对用户数据库进行商业上的利用。\n" +
                        "（七）互联网医疗服务变更、中断或终止\n" +
                        "    1、如因系统维护或升级的需要而需暂停互联网医疗服务，平台将尽可能事先进行通告。如发生下列任何一种情形，平台有权随时中断或终止向用户提供本协议项下相关的互联网医疗服务而无需通知用户：\n" +
                        "        （1）用户提供的个人资料不真实；\n" +
                        "        （2）用户违反本协议中规定的使用规则。\n" +
                        "    2、除前款所述情形外，系统因下列状况无法正常运作，使用户无法使用视频语音咨询服务时，平台不承担损害赔偿责任，该状况包括但不限于：\n" +
                        "        （1）互联网医院在本网站公告之系统停机维护期间；\n" +
                        "        （2）电信设备出现故障不能进行数据传输的；\n" +
                        "        （3）因台风、地震、海啸、洪水、停电、战争、恐怖袭击等不可抗力之因素，造成系统障碍不能执行业务的；\n" +
                        "        （4）由于黑客攻击、电信部门技术调整或故障、银行方面的问题等原因而造成的服务中断或者延迟。\n" +
                        "（八）其他\n" +
                        "    1、本协议构成双方对本协议之约定事项及其他有关事宜的完整协议，除本协议规定的之外，未赋予本协议各方其他权利。\n" +
                        "    2、如本协议中的任何条款无论因何种原因完全或部分无效或不具有执行力，本协议的其余条款仍应有效并且有约束力。\n" +
                        "    3、本协议中的标题仅为方便而设，在解释本协议时应被忽略。");
                jb.put("publish_date", "2019-08-24");
                jb.put("protocol_name", "用户使用协议");

                //其他建设信息
                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 {
                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\"" +
                        "  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 ";

                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", "");
                        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?"1900-01-01": DateUtil.dateToStrLong((Date)info.get("birthday")));
                        jb.put("subject", dept[0].toString());
                        jb.put("subject_name", dept[1].toString());
                        jb.put("belong_dept",jb.getString("dept_code"));
                        jb.put("belong_dept_name", jb.getString("dept_name"));
                        jb.put("doo_tel", info.get("mobile")== null ? "":info.get("mobile"));
                        jb.put("title_rec_date", getDateString(info.get("fzrq").toString()));
                        jb.put("prac_type", "1");   // 因为上传的是医师的信息，所以该字段全部默认设置为 1 医师
                        jb.put("title_code", dutyInfo[0].toString());  // 需要与监管平台的字典进行映射
                        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", "1,3,4,5,7,9,10");
                        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+"zg.jpg"));
                        //执业证书
                        jb.put("cert_doc_prac", ImgUtils.getImageStr(imgPath+"doctor"+ File.separator+info.get("name")+File.separator+"zy.jpg"));
                        jb.put("txt_introduction", "厦门大学附属厦门眼科中心成立于1997年11月8日，是集医疗、教学、科研、防盲为一体的三级甲等眼科医院、国家临床重点专科、国家药物临床试验机构。设有国家博士后科研工作站、院士专家工作站、全国住院医师规培基地、转化医学研究所等。");

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

                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?"1900-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[0].toString());
                        jb.put("reg_subject_name", dept[1].toString());
                        jb.put("reg_price",  "0");
                        jb.put("pt_name", info.get("name") == null?"0":info.get("name"));
                        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 {
                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[0].toString());
                            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 {
                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_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\" " +
                        "FROM " +
                        " base_evaluate_score a " +
                        "JOIN base_evaluate e ON a.id = e.relation_code " +
                        "JOIN base_doctor d ON d.id = a.doctor " +
                        "WHERE " +
                        " e.score_type = '4'";
                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();

            try{
                String interId = "";
                String idCard = info.get("docIdCard") == null ? "0":info.get("docIdCard").toString();
                if( info.get("docIdCard") == null){
                    interId = "0";
                }else {
                    interId = achNsDoctorRecord(idCard);
                }

//                String[] dept = depToSubject(info.get("dept_code").toString());

                jb.put("id",orgCode +"_"+ (String)info.get("id"));
                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){
                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 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" +
               "\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 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 ";

        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" +
                    "\tTOPICS T \n" +
                    "JOIN 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()+"'\n" +
                    "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);
            String content="";
            JSONArray array = new JSONArray();
            for (Map<String,Object> map:list1){
                String sql1= "SELECT\n" +
                        "\ts.participant_id as \"participant_id\" \n" +
                        "FROM\n" +
                        "\tPARTICIPANTS 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());
                        object.put("receiver",patientDO.getName());
                    }
                }
                object.put("sender",map.get("sender_name"));
                object.put("msg",map.get("content"));
                object.put("msg_type",map.get("content_type"));
                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.toJSONString());
        }


        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", info.get("dept_code") == null?"0":info.get("dept_code"));
                jb.put("visit_dept_name", info.get("dept_name") == null?"0":info.get("dept_name"));
                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?"1900-01-01":DateUtil.dateToStrLong((Date)info.get("czrq")));
                jb.put("visit_time", info.get("czrq")==null?"1900-01-01":DateUtil.dateToStrLong((Date)info.get("czrq")));
                jb.put("visit_finish_time", info.get("end_time")==null?"1900-01-01":DateUtil.dateToStrLong((Date)info.get("end_time")));
                jb.put("complaint_content", info.get("content"));
                jb.put("proc_file", "");
                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 {
        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 " ;

        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);
            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[0].toString());
                jb.put("visit_ subject _name",dept[1].toString());
                jb.put("visit_dept_code", info.get("dept"));
                jb.put("visit_dept_name", info.get("dept_name"));
                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", "");
                jb.put("old_diag_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");
                jb.put("complaint_content", info.get("paName").toString()+DateUtil.dateToStr(date,"yyyy-MM-dd HH:mm:ss")+info.get("description").toString()+"\n");
                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 {
        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.his_register_fee AS \"his_register_fee\"," +
                "  c.idcard AS \"docIdcard\"" +
                "  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());

                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[0].toString());
                jb.put("pres_subject_name", dept[1].toString());
                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?"1900-01-01 00:00:00":DateUtil.dateToStrLong((Date)info.get("create_time")));
                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", visitDocCode);
                jb.put("trial_doc_name", info.get("doctor_name")== null?"0":info.get("doctor_name"));
                jb.put("trial_doc_id_no",info.get("docIdcard")== null?"0":info.get("docIdcard"));
                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);
                jb.put("total_price",info.get("his_register_fee")== null?  0 : info.get("his_register_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 {
        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\"" +
                "  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";

        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.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("dosage",info.get("dosage") == null? 0: info.get("dosage"));
                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"));
                BigDecimal pack_retprice = (BigDecimal)info.get("pack_retprice");
                Long quantity = Long.parseLong((String)info.get("quantity"));

                Double price = pack_retprice.doubleValue()*quantity;
                jb.put("drug_total_price",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;
    }

    // 12.在线诊疗服务信息-过程图片上传     --- 完成
    public String upNsOnlineImg(String startDate, String endDate,String keyId) throws Exception {
        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 {
        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", "1");
            jb.put("protocol_content", "根据国家卫生计生委的《关于推进医疗机构远程医疗服务的意见》文件中的指导意见，厦门大学附属厦门眼科中心互联网医院是医疗机构利用信息化技术向患者直接提供医疗服务，这些服务只允许医疗机构开展，厦门大学附属厦门眼科中心开展远程医疗服务的类别及专科均具有相应的资质，开展远程医疗服务的医生亦具有相应的执业资质，厦门大学附属厦门眼科中心在开展远程医疗服务过程中严格遵守相关的法律法规和行为规范，保证质量与安全，同时充分保障患者的隐私及知情权。互联网医院适用业务范围：常见病、轻病和慢性病的预诊及复诊（注：如果病人患病情况紧急、病情严重，请立即到线下医院治疗）；适用人群：常见病、轻病和慢性病患者（注：由厦门大学附属厦门眼科中心互联网医院提供的医生建议只做参考，不作为诊断。）\n" +
                    "(一)服务条款确认和接纳\n" +
                    "    1、本平台按照本协议的规定及不定期发布的操作规则提供基于互联网的医疗服务（以下称互联网医疗服务）。为获得互联网医疗服务，服务使用人（以下称用户）应当同意本协议的全部条款并按照页面上的提示完成注册程序。用户在进行注册程序过程中点击我同意按钮即表示完全接受本协议项下的全部条款。\n" +
                    "    2、用户点击同意本协议的，即视为用户确认自己具有享受本客户端服务、选用有偿服务、支付服务费用等相应的权利能力和行为能力，能够独立承担法律责任。\n" +
                    "    3、 限制行为能力人和无民事行为能力人，需要在监护人的监护参与下才能使用本平台。\n" +
                    "    4、医疗服务的具体内容由平台根据实际情况提供，平台保留随时变更、中断或终止部分或全部互联网医疗服务的权利。\n" +
                    "5、本平台提供的线上咨询服务，如即时问诊、电话咨询、图文咨询业务，发票由平台运营方福建眼界科技有限公司负责开具；若有涉及到医院线下的检查、检验及治疗项目的发票由厦门大学附属厦门眼科中心负责开具。\n" +
                    "（二）版权说明\n" +
                    "    1、本平台提供的相关服务内容可能包括：文字、软件、声音、图片、视频、录象、图表等。所有这些内容受版权、商标和其它财产所有权法律的保护。\n" +
                    "    2、本平台所登载的专有信息，未经本平台或其他相关权利人的书面授权，任何人不得以任何形式侵犯其著作权，包括擅自复制、非法使用或转载。\n" +
                    "（三）服务简介\n" +
                    "    1、互联网医院由网站所有人及其关联医院共同运营（以下合称平台运营方）。平台运营方运用自己的操作系统通过国际互联网为您提供本网站的网络服务，并承担本协议和其它服务协议中对您的责任和义务。为使用本服务，您必须能够自行通过有法律资格的第三方对您提供互联网接入服务，并自行承担以下内容：\n" +
                    "     \t(1) 自行配备上网所需的设备，包括个人电脑，调制解调器及其他必要的设备装置。 \n" +
                    "        (2) 自行承担上网所需的相关必要费用，如：电话费用、网络费用等。\n" +
                    "        (3) 本协议中规定的您的其他责任和义务。\n" +
                    "    2、健康之路无边界（厦门）医疗科技有限公司负责本平台正常运行，将协助医生或顾问与用户之间进行合法的交流，并提供必要的网络技术支持，确保提供优质的健康咨询服务通道。\n" +
                    "    3、本平台有权对相关数据、所有的申请行为以及与健康信息互通交流有关的其它事项进行审核，并在不符合平台要求的情况下给予拒绝或屏蔽。\n" +
                    "    4、用户在本平台发生不当行为，经本平台核实认为应当终止服务的，本平台有权随时删除该用户信息及终止服务，且无需征得用户的同意。\n" +
                    "（四）免责声明\n" +
                    "    1、本平台所有咨询、回答、相关评论仅代表作者本人的观点或基本判断，不代表本平台的观点和看法，与本平台立场无关。\n" +
                    "    2、本平台所刊载的各类形式(包括但不仅限于文字、图片、图表)的作品（包括广告等）仅供参考使用，并不代表本平台同意其说法或描述，也不构成任何方面建议。对于用户根据本平台提供的信息所做出的一切行为，除非另有明确的书面承诺文件，否则本平台不承担任何形式的责任。\n" +
                    "    3、凡在本平台登记注册的用户，须自行负责对您的账户和密码保密，且须对您的账户和密码下发生的所有活动承担全部责任。\n" +
                    "    4、用户自愿同意不做任何妨碍或者破坏服务（或与服务连接的服务器及网络）的任何活动。若因散布谣言、造假、谩骂等原因而被禁止本平台对其服务的，本平台均免责。\n" +
                    "    5、当政府部门、司法机关等依照法定程序要求本平台披露个人资料时，本平台将根据执法单位之要求或为公共安全之目的提供个人资料。在此情况下之任何披露，本平台均免责。\n" +
                    "    6、由于与本平台链接的其他软件或网页所造成的个人资料泄露及由此而导致的任何法律争议和后果，本平台均免责。\n" +
                    "    7、由于用户将个人密码告知他人或与他人共享注册帐户，由此导致的任何个人资料泄露，本平台均免责。\n" +
                    "    8、任何由于黑客攻击、计算机病毒侵入或发作、因政府管制而造成的暂时性关闭等影响网络正常运营的不可抗力造成的个人资料泄露、丢失、被盗用或被窜改等，本平台均免责。\n" +
                    "    9、除本平台注明的服务条款外，其他一切因使用本软件导致的任何意外、疏忽、诽谤、版权或知识产权侵犯及其所造成的损失(包括因下载而感染手机病毒)，本平台不承担任何法律责任。\n" +
                    "    10、用户自行同意本平台可自行更新、升级或关闭，而无需经过用户的同意。用户可以在任何时候停止使用本平台，而无需特别通知。\n" +
                    "（五）用户的权利和义务\n" +
                    "    1、用户应自行诚信向本客户端提供注册资料，用户保证提供的注册资料真实、准确、完整、合法有效，用户注册资料如有变动的，应及时更新其注册资料。如果用户提供的注册资料不合法、不真实、不准确、不详尽的，用户需承担因此引起的相应责任及后果，并且本平台保留终止用户使用平台各项服务的权利。\n" +
                    "    2、用户注册成功后，将产生用户名和密码等账户信息，您可以根据本平台规定改变您的密码。用户应谨慎合理的保存、使用其用户名和密码。用户若发现任何非法使用用户账号或存在安全漏洞的情况，请立即通知本平台并向公安机关报案。\n" +
                    "    3、用户有权通过本平台发布、获取信息，进行健康信息互通交流等，本平台另一端的医生或顾问将完全根据用户提供的信息做出指导和建议，如果用户提供的信息有误，造成的任何后果自行承担。\n" +
                    "    4、用户不得利用本平台各项服务在本平台或相关网站上进行销售或其他商业行为。用户违反此约定，本平台将依法追究其法律责任，由此给本平台造成损失的，本平台有权进行追偿。\n" +
                    "    5、用户同意，本平台拥有通过邮件、短信电话等形式，向在本平台注册、购买的用户发送订单信息、促销活动等告知信息的权利。\n" +
                    "    6、用户不得将在本平台注册获得的账户借给他人使用，否则用户应承担由此产生的全部责任，并与实际使用人承担连带责任。\n" +
                    "    7、用户明确同意：使用本平台相关服务所存在的风险将完全由用户自己承担；因其使用互联网医院服务而产生的一切后果也由自己承担，互联网医院对用户不承担任何责任。\n" +
                    "    8、用户同意，本平台有权使用用户的注册信息、用户名、密码等信息，登陆进入用户的注册账户，进行证据保全，包括但不限于公证、见证等。\n" +
                    "    9、用户在使用互联网医院相关服务过程中，必须遵循以下原则：\n" +
                    "        （1）遵守中国有关的法律和法规；\n" +
                    "        （2）不得为任何非法目的而使用互联网医院服务系统；\n" +
                    "        （3）遵守所有与互联网医院服务有关的网络协议、规定和程序；\n" +
                    "（4）不得利用互联网医院服务系统进行任何可能对互联网的正常运转造成不利影响的行为；\n" +
                    "        （5）不得利用互联网医院服务系统进行任何不利于医院的行为；\n" +
                    "        （6）如发现非法使用用户帐号或帐号出现安全漏洞的情况，应立即通告平台系统管理员或者客服人员。\n" +
                    "（六）隐私\n" +
                    "    1、保护用户隐私是互联网医院的一项基本政策，本平台保证不对外公开或向第三方提供用户注册资料及用户在使用互联网医院相关服务时存储的非公开内容，但下列情况除外：\n" +
                    "        （1）事先获得用户的明确授权；\n" +
                    "        （2）根据有关的法律法规要求；\n" +
                    "        （3）按照相关政府主管部门的要求；\n" +
                    "        （4）为维护社会公众的利益；\n" +
                    "        （5）为维护互联网医院的合法权益。\n" +
                    "    2、平台可能会与第三方合作向您提供相关的网络服务，在此情况下，如该第三方同意承担与平台同等的保护您隐私的责任，您同意并授权平台将您的注册资料等提供给该第三方。\n" +
                    "    3、在不透露单个用户隐私资料的前提下，本平台有权对整个用户数据库进行分析并对用户数据库进行商业上的利用。\n" +
                    "（七）互联网医疗服务变更、中断或终止\n" +
                    "    1、如因系统维护或升级的需要而需暂停互联网医疗服务，平台将尽可能事先进行通告。如发生下列任何一种情形，平台有权随时中断或终止向用户提供本协议项下相关的互联网医疗服务而无需通知用户：\n" +
                    "        （1）用户提供的个人资料不真实；\n" +
                    "        （2）用户违反本协议中规定的使用规则。\n" +
                    "    2、除前款所述情形外，系统因下列状况无法正常运作，使用户无法使用视频语音咨询服务时，平台不承担损害赔偿责任，该状况包括但不限于：\n" +
                    "        （1）互联网医院在本网站公告之系统停机维护期间；\n" +
                    "        （2）电信设备出现故障不能进行数据传输的；\n" +
                    "        （3）因台风、地震、海啸、洪水、停电、战争、恐怖袭击等不可抗力之因素，造成系统障碍不能执行业务的；\n" +
                    "        （4）由于黑客攻击、电信部门技术调整或故障、银行方面的问题等原因而造成的服务中断或者延迟。\n" +
                    "（八）其他\n" +
                    "    1、本协议构成双方对本协议之约定事项及其他有关事宜的完整协议，除本协议规定的之外，未赋予本协议各方其他权利。\n" +
                    "    2、如本协议中的任何条款无论因何种原因完全或部分无效或不具有执行力，本协议的其余条款仍应有效并且有约束力。\n" +
                    "    3、本协议中的标题仅为方便而设，在解释本协议时应被忽略。");
            jb.put("publish_date", "2019-12-20");
            jb.put("protocol_name", "用户协议信息");
            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 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,"yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtils.isNotBlank(endDate)){
            yyghSql =  yyghSql +  "  and p.create_time <=:endDate";
            params.put("endDate",DateUtil.stringToDate(endDate,"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 " +
                " WHERE " +
                " e.score_type = '4'";

        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 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";

        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 " ;
        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";

        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", 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);
    }
}
