#复诊
import sys
import os
import time
import operator
import cx_Oracle
import numpy as np
import pandas as pd
import tensorflow as tf

uid = 6
sql = "select username,sex,age,province,area,bumen,ke,result,chufang,jianyi,yiyuaan,yisheng,jianchaxiang,zhenduanriqi from zhenduanjilutable where userid=%d" % uid
cursor.execute(sql)
rows = cursor.fetchall()
zhenduanjilu = []
for row in rows:
    temp = []
    temp.append(row[0])
    temp.append(row[1])
    temp.append(row[2])
    temp.append(row[3])
    temp.append(row[4])
    temp.append(row[5])
    temp.append(row[6])
    temp.append(row[7])
    temp.append(row[8])
    temp.append(row[9])
    temp.append(row[10])
    temp.append(row[11])
    temp.append(row[12])
    temp.append(row[13])
    zhenduanjilu.append(temp)

print("===================打印诊断历史记录=====================")
for i in range(len(zhenduanjilu)):
    print("-------------->>第:"+str(i+1)+"次诊断<<-------------------")
    print("     姓名:"+zhenduanjilu[i][0])
    print("     性别:"+zhenduanjilu[i][1])
    print("     年龄:"+str(zhenduanjilu[i][2]))
    print("     省份:"+zhenduanjilu[i][3])
    print("     市区:"+zhenduanjilu[i][4])
    print("     门诊部门:"+zhenduanjilu[i][5])
    print("     门诊科目:"+zhenduanjilu[i][6])
    print("     诊断结果:"+zhenduanjilu[i][7])
    print("     医疗处方:"+zhenduanjilu[i][8])
    print("     养生建议:"+zhenduanjilu[i][9])
    print("     推荐医院:"+zhenduanjilu[i][10])
    print("     推荐医生:"+zhenduanjilu[i][11])
    print("     建议检查项:"+zhenduanjilu[i][12])
    print("     诊断日期:"+str(zhenduanjilu[i][13]))

num = int(input("请输入需要复诊的对应第几次诊断记录编号:"))
print("===================开始复诊流程=====================")
num -= 1
username=zhenduanjilu[num][0]
sex=zhenduanjilu[num][1]
age=zhenduanjilu[num][2]
province=zhenduanjilu[num][3]
area=zhenduanjilu[num][4]
bumen=zhenduanjilu[num][5]
ke=zhenduanjilu[num][6]

sql = "select keid from hy_keid where ke='%s'" % ke
cursor.execute(sql)
rows = cursor.fetchall()
keid = []
for row in rows:
    keid.append(row[0])

sql = "select QUESTION from HY_QUESTID where QUID=%d" % keid[0]
cursor.execute(sql)
rows = cursor.fetchall()
question = []
for row in rows:
    question.append(row[0])
question = question[0].split(",")
# print(question)
answer = []
for i,j in zip(question,np.arange(len(question))):
    print("问题"+str(j+1)+":是否"+i+"")
    print("    A、正常    B、较轻    C、明显    D、非常严重")
    temp = input("请根据实际情况选择上面的一项:")
    if(temp=="A"):
        answer.append(1)
    elif(temp=="B"):
        answer.append(2)
    elif(temp=="C"):
        answer.append(3)
    else:
        answer.append(4)
        
surgery = bumen
surgeryChest = ke

#one-hot编码
def onehot(labels):
    n_sample = len(labels)
    n_class = max(labels) + 1
    onehot_labels = np.zeros((n_sample, n_class))
    onehot_labels[np.arange(n_sample), labels] = 1
    return onehot_labels

#获取数据集
def getdata(surgery,surgeryChest):
    sql = "select feature1,feature2,feature3,feature4,feature5,trainLable from menzhen where surgery='%s' and surgeryChest='%s'" % (surgery,surgeryChest)
    cursor.execute(sql)
    rows = cursor.fetchall()
    dataset = []
    lables = []
    for row in rows:
        temp = []
        temp.append(row[0])
        temp.append(row[1])
        temp.append(row[2])
        temp.append(row[3])
        temp.append(row[4])
        dataset.append(temp)
        if(row[5]==3):
            lables.append(0)
        elif(row[5]==6):
            lables.append(1)
        else:
            lables.append(2)
    dataset = np.array(dataset)
    lables = np.array(lables)
    dataset = dataset.astype(np.float32)
    labless = onehot(lables)
    return dataset,labless

#获取测试数据集
def gettestdata(surgery,surgeryChest):
    sql = "select feature1,feature2,feature3,feature4,feature5,trainLable from test where surgery='%s' and surgeryChest='%s'" % (surgery,surgeryChest)
    cursor.execute(sql)
    rows = cursor.fetchall()
    testdataset = []
    testlables = []
    for row in rows:
        temp = []
        temp.append(row[0])
        temp.append(row[1])
        temp.append(row[2])
        temp.append(row[3])
        temp.append(row[4])
        testdataset.append(temp)
        if(row[5]==3):
            testlables.append(0)
        elif(row[5]==6):
            testlables.append(1)
        else:
            testlables.append(2)
    testdataset = np.array(testdataset)
    testlables = np.array(testlables)
    testdataset = testdataset.astype(np.float32)
    testlabless = onehot(testlables)
    return testdataset,testlabless

dataset,labless = getdata(surgery,surgeryChest)
# testdataset,testlables = gettestdata(surgery,surgeryChest)

# dataset = dataset[0:100]
# labless = labless[0:100]

x_data = tf.placeholder("float32", [None, 5])
y_data = tf.placeholder("float32", [None, 3])

weight = tf.Variable(tf.ones([5, 3]))
bias = tf.Variable(tf.ones([3]))

#使用softmax激活函数
y_model = tf.nn.softmax(tf.matmul(x_data, weight) + bias)

#y_model = tf.nn.relu(tf.matmul(x_data, weight) + bias)

# loss = tf.reduce_sum(tf.pow((y_model - y_data), 2))

#使用交叉熵作为损失函数
loss = -tf.reduce_sum(y_data*tf.log(y_model))

# train_step = tf.train.GradientDescentOptimizer(1e-4).minimize(loss)

#使用AdamOptimizer优化器
# train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)


train_step = tf.train.MomentumOptimizer(1e-4,0.9).minimize(loss)

#评估模型
correct_prediction = tf.equal(tf.argmax(y_model, 1), tf.argmax(y_data, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
# start = time.time()
for _ in range(10):
    for i in range(int(len(dataset)/100)):
        sess.run(train_step, feed_dict={x_data:dataset[i:i+100,:], y_data:labless[i:i+100,:]})
        
# print("模型准确率",sess.run(accuracy, feed_dict={x_data:testdataset , y_data:testlables}))
# end = time.time()
# print("模型训练和测试公耗时:%.2f 秒" % (end-start))
        
xl_weight = sess.run(weight)
useranswer = [[1, 2, 3, 4, 4]]*3
W = np.dot(xl_weight,useranswer)
result=0
for i in range(len(W[0])):
    for j in range(len(W[0,:])):
        if(i==j):
            result += W[i][j]
result = int(result/5)
# print(result)

if(result<=3):
    result = 3
elif(result<=6):
    result = 6
else:
    result = 9

sql = "select ILL_NAME from ill_result_tbZ where FAMILY='%s' and ILL_ID=%d" % (ke,result)
cursor.execute(sql)
rows = cursor.fetchall()
ILL_NAME = []
for row in rows:
    ILL_NAME.append(row[0])

firstResult = ILL_NAME[0]
##
print("=======================系统复诊单===================")
print("姓名:"+username)
print("性别:"+sex)
print("年龄:"+str(age))
print("省份:"+province)
print("所属区:"+area)
print("初诊部门:"+bumen)
print("科目:"+ke)
##
print("系统智能诊断结果:"+firstResult)

if(firstResult[:2]=="疑似"):
    firstResult = "疑似患病"

sql = "select PRESCRIPTION_1,PRESCRIPTION_2,PRESCRIPTION_3,PRESCRIPTION_4,PRESCRIPTION_5,PRESCRIPTION_6,PRESCRIPTION_7,PRESCRIPTION_8,PRESCRIPTION_9,PRESCRIPTION_10,PRESCRIPTION_11,PRESCRIPTION_12,PRESCRIPTION_13,PRESCRIPTION_14,PRESCRIPTION_15 from PRESCRIPTION where SURGERY='%s'and SURGERYCHEST='%s' and ILLNAME='%s'" % (bumen,ke,firstResult)
cursor.execute(sql)
rows = cursor.fetchall()
chufanggrace = []
for row in rows:
    temp = []
    temp.append(row[0])
    temp.append(row[1])
    temp.append(row[2])
    temp.append(row[3])
    temp.append(row[4])
    temp.append(row[5])
    temp.append(row[6])
    temp.append(row[7])
    temp.append(row[8])
    temp.append(row[9])
    temp.append(row[10])
    temp.append(row[11])
    temp.append(row[12])
    temp.append(row[13])
    temp.append(row[14])
    chufanggrace.append(temp)
    
PRESCRIPTION_sum = []
for col in range(np.shape(chufanggrace)[1]):
    temp = 0
    for row in range(np.shape(chufanggrace)[0]):
        temp += chufanggrace[row][col]
    PRESCRIPTION_sum.append(temp)

b = sorted(enumerate(PRESCRIPTION_sum),key=lambda x:x[1],reverse=True)[:3]
index = []
for i in b:
    index.append(i[0])

sql = "select PRESCRIPTIONINFO,HEALTH from PRESCRIPTIONINFO where DEPARTMENT='%s' and FAMILY='%s' and ILL_NAME='%s'" % (bumen,ke,firstResult)
cursor.execute(sql)
rows = cursor.fetchall()
chufanglist = []
jianyilist = []
for row in rows:
    chufanglist.append(row[0])
    jianyilist.append(row[1])
best_chufang = []
best_jianyi = []
for i in index:
    best_chufang.append(chufanglist[i])
    best_jianyi.append(jianyilist[i])
chufang_str = ""
jianyi_str = ""
for i,j in zip(best_chufang,range(len(best_chufang))):
    chufang_str += "系统智能筛选优良处方"+str(j+1)+"" + i +""
    print("系统智能筛选优良处方"+str(j+1)+"" + i)
    
for i,j in zip(best_jianyi,range(len(best_jianyi))):
    jianyi_str += "系统智能筛选优良养生建议"+str(j+1)+"" + i+""
    print("系统智能筛选优良养生建议"+str(j+1)+"" + i)

sql = "select HOSTITALNAME from DOCTORHOSTITALADRREST where PROVINCE='%s' and ADMINISTRATIVE='%s'" % (province,area)
cursor.execute(sql)
rows = cursor.fetchall()
yiyuan = []
for row in rows:
    yiyuan.append(row[0])
for i in yiyuan:
    print("系统智能匹配你所在地区附件的医院:"+i)

sql = "select ADDRACTION,NAME,SUMMARY from DOCTORS where FAMILY='%s'" % (ke)
cursor.execute(sql)
rows = cursor.fetchall()
yisheng = []
for row in rows:
    yisheng.append(row[0])
    yisheng.append(row[1])
    yisheng.append(row[2])
print("系统为你推荐全国相关出色医生所在医院信息:"+yisheng[0])
print("系统为你推荐全国相关出色医生姓名信息:"+yisheng[1])
print("系统为你推荐全国相关出色医生简介信息:"+yisheng[2])
yisheng_str = ""
yisheng_str += "医生所在医院:"+yisheng[0]
yisheng_str += "医生姓名:"+yisheng[1]
yisheng_str += "医生简介:"+yisheng[2]

sql = "select CHACKPRO from CHACKPROJECT where FAMILY='%s'" % (ke)
cursor.execute(sql)
rows = cursor.fetchall()
jiancha = []
for row in rows:
    jiancha.append(row[0])
print("系统建议你到相关正规医院检查以下身体指标:"+jiancha[0])
jianchax = "" 
jianchax += "系统建议你到相关正规医院检查以下身体指标:"+jiancha[0]

sql = "insert into zhenduanjilutable (userid,username,sex,age,province,area,bumen,ke,result,chufang,jianyi,yiyuaan,yisheng,jianchaxiang) values (%d,'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" % (uid,username,sex,age,province,area,bumen,ke,firstResult,chufang_str,jianyi_str,yiyuan[0],yisheng_str,jianchax)
cursor.execute(sql)
conn.commit()
print("此次智能诊断完成,欢迎你下次继续使用:天生自然健康智能医疗系统!")

print("特别提醒、注意:该系统的所有诊断只是作为参考,有必需要的用户请到相关正规医院接受相关专家医生完成检查、治疗等流程...")
print("系统建议:保持一颗善良、沉稳、宁静和广博的平常心度过每一个清晨和夜晚...")
print("祝你们每一位人都开开心心、健健康康、平平安安...阖家安康,如意吉祥......")