package com.diagbot.util;

import com.diagbot.entity.BasDoctorInfo;
import com.diagbot.vo.his.FeedbackHosVO;
import com.google.common.collect.Lists;

import java.sql.*;
import java.util.List;
import java.util.ResourceBundle;

public class PushFeedbackConn {
    private static final String DRIVER = getValue("jdbc.driverClassName1");
    private static final String URL = getValue("jdbc.url1");
    private static final String USERNAME = getValue("jdbc.username1");
    private static final String PASSWORD = getValue("jdbc.password1");

    public static final Long HOSPITAL_ID=Long.valueOf("35");//1:长兴，2：邵逸夫，3：台州市立医院

    private static Connection connection = null;
    private static PreparedStatement sta = null;
    private static ResultSet rs = null;

    /**
     * 读取属性文件中的信息
     *
     * @param key
     * @return
     */
    private static String getValue(String key) {
        // 资源包绑定
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        return bundle.getString(key);
    }

    /**
     * 加载驱动程序
     */
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * @return 连接对象
     */
    public Connection getConnection() {
        try {
            connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * @param sql sql语句
     * @param obj 参数
     * @return 数据集合
     */
    public ResultSet Query(String sql,Object...obj){
        connection=getConnection();
        try {
            sta=connection.prepareStatement(sql);
            if(obj!=null){
                for(int i=0;i<obj.length;i++){
                    sta.setObject(i+1, obj[i]);
                }
            }
            rs=sta.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 关闭资源
     */
    public void close() {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (sta != null) {
                    sta.close();
                }
            } catch (SQLException e2) {
                e2.printStackTrace();
            } finally {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 关闭数据库
     * @param conn
     */
    public void closeConnection(Connection conn){
        try{
            if(conn != null){
                conn.close();
            }
        }
        catch(Exception e){
            System.out.println("数据库关闭失败");
            e.printStackTrace();
        }
    }

    /**
     * 新赠评分插入表中
     * @return
     */
    public Integer setQcMessAge(FeedbackHosVO feedbackHosVO) throws SQLException {
        try {
            String patientId=feedbackHosVO.getBehospitalCode().split("_")[0];
            String visitId=feedbackHosVO.getBehospitalCode().split("_")[1];
            int re=0;
            connection = getConnection();
            connection.setAutoCommit(false);//事物开始
            PreparedStatement state=connection.prepareStatement("insert into MEDICAL_QC_MSG " +
                    "(PATIENT_ID,VISIT_ID,DOCTOR_IN_CHARGE,QA_EVENT_TYPE,QC_MSG_CODE,MESSAGE,ISSUED_BY,ISSUED_DATE_TIME,TOPIC_ID,DEPT_STAYED,MSG_STATUS,EXPLAIN_INFO,QCRESULT_DETAI_SCORE,DETAIL_CODE)"+
                    "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            state.setString(1, patientId);
            state.setString(2, visitId);
            state.setString(3,feedbackHosVO.getSenderName());
            state.setString(4,feedbackHosVO.getModeName());
            state.setInt(5,1511);
            state.setString(6,feedbackHosVO.getQcresultDetailMsg());
            state.setString(7,"评价质控");
            state.setString(8, DateUtil.formatDateTime(DateUtil.now()));
            state.setString(9,feedbackHosVO.getModeName());
            state.setString(10,feedbackHosVO.getDeptId());
            state.setInt(11,0);
            state.setString(12,feedbackHosVO.getExplainInfo());
            state.setString(13, String.format("%.2f", feedbackHosVO.getQcresultDetaiScore()));
            state.setString(14,Long.toString(feedbackHosVO.getId()));
            re = state.executeUpdate();
            if(re < 0){               //插入失败
                connection.rollback();      //回滚
                state.close();
                closeConnection(connection);
                return re;
            }
            connection.commit();            //插入正常
            state.close();
            closeConnection(connection);
            return re;

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }finally {
            close();
        }

    }

    /**
     * 删除评分表中的对应数据
     * @return
     */
    public Integer DeleteQcMessAge(FeedbackHosVO feedbackHosVO) throws SQLException {
        try {
            String patientId=feedbackHosVO.getBehospitalCode().split("_")[0];
            String visitId=feedbackHosVO.getBehospitalCode().split("_")[1];
            int re=0;
            connection = getConnection();
            connection.setAutoCommit(false);//事物开始
            String sql ="delete from MEDICAL_QC_MSG ";
            sql+=" where PATIENT_ID = '"+patientId+"' and VISIT_ID = '"+visitId+"' and DETAIL_CODE='"+feedbackHosVO.getId()+"'";
            PreparedStatement state=connection.prepareStatement(sql);
            re = state.executeUpdate();
            if(re < 0){               //删除失败
                connection.rollback();      //回滚
                state.close();
                closeConnection(connection);
                return re;
            }
            connection.commit();            //删除正常
            state.close();
            closeConnection(connection);
            return re;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }finally {
            close();
        }

    }

    /**
     * 修改评分表中对应数据
     * @return
     */
    public Integer UpdateQcMessAge(FeedbackHosVO feedbackHosVO) throws SQLException {
        try {
            String patientId=feedbackHosVO.getBehospitalCode().split("_")[0];
            String visitId=feedbackHosVO.getBehospitalCode().split("_")[1];
            int re=0;
            connection = getConnection();
            connection.setAutoCommit(false);//事物开始
            String sql =" update MEDICAL_QC_MSG set " +
                    "MESSAGE = '"+feedbackHosVO.getQcresultDetailMsg()+"'" +
                    ",EXPLAIN_INFO='"+feedbackHosVO.getExplainInfo()+"'" +
                    ",QCRESULT_DETAI_SCORE='"+feedbackHosVO.getQcresultDetaiScore()+"'";
            sql+="where PATIENT_ID = '"+patientId+"' and VISIT_ID = '"+visitId+"' and DETAIL_CODE='"+feedbackHosVO.getId()+"'";
            PreparedStatement state=connection.prepareStatement(sql);
            re = state.executeUpdate();
            if(re < 0){               //修改失败
                connection.rollback();      //回滚
                state.close();
                closeConnection(connection);
                return re;
            }
            connection.commit();            //修改正常
            state.close();
            closeConnection(connection);
            return re;

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }finally {
            close();
        }

    }

    public List<FeedbackHosVO> statusQuery(FeedbackHosVO feedbackHosVO){
        List<FeedbackHosVO> statusList= Lists.newLinkedList();
        try {
            connection = getConnection();
            connection.setAutoCommit(false);//事物开始
            String sql =" select DETAIL_CODE,MSG_STATUS from MEDICAL_QC_MSG ";
            sql+=" where DETAIL_CODE in("+feedbackHosVO.getIds()+")";
            rs =this.Query(sql, null);
            while(rs.next()){
                FeedbackHosVO hosVO=new FeedbackHosVO();
                hosVO.setId(Long.valueOf(rs.getString("DETAIL_CODE")));
                hosVO.setMsgStatus(rs.getString("MSG_STATUS"));

                statusList.add(hosVO);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            close();
        }
        return statusList;
    }

}
