#用户注册、登录模块
#数据库脚本
CREATE TABLE usertable(
  userid number(8) primary key not  null ,
  username varchar(50)  NULL,
  password varchar(50) NOT NULL,
  sex varchar(10) NOT NULL,
  age number(3) NOT NULL,
  province varchar2(50) null,
  area varchar(50) NOT NULL
  );
commit;

create sequence usertable_seq
minvalue 1
maxvalue 999
start with 1    
increment by 1
NOCYCLE
nocache;
commit;

insert into  usertable (userid, username , password, sex,age, province ,area ) values ( usertable_seq.Nextval , '小明','123','',13,'广东省', '广州市' );
insert into  usertable (userid, username , password, sex,age, province ,area ) values ( usertable_seq.Nextval , '小红','123','',14,'广东省', '广州市' );
insert into  usertable (userid, username , password, sex,age, province ,area ) values ( usertable_seq.Nextval , '小东','123','',15,'广东省', '广州市' );
commit;
insert into  usertable (userid, username , password, sex,age, province ,area ) values ( usertable_seq.Nextval , '小东东','123','',15,'广东省', '广州市' );
commit;
#注册
import cx_Oracle
import numpy as np

conn=cx_Oracle.connect('doctor/admin@localhost:1521/tszr')
cursor = conn.cursor()

username = input("请输入用户名:")
password = input("请输入密码:")
sex = input("请输入性别:")
age = int(input("请输入年龄:"))
province = input("请输入省份:")
area = input("请输入所属区:")

sql = "insert into  usertable (userid, username , password, sex,age, province ,area ) values (usertable_seq.Nextval,'%s','%s','%s',%d,'%s','%s')" % (username, password,sex,age,province,area)
cursor.execute(sql)
conn.commit()
print("注册成功!")

#登录
import cx_Oracle
import numpy as np

conn=cx_Oracle.connect('doctor/admin@localhost:1521/tszr')
cursor = conn.cursor()

username = input("请输入用户名:")
password = input("请输入密码:")

sql = "select userid from usertable where username='%s' and password='%s'" % (username,password)
cursor.execute(sql)
rows = cursor.fetchall()
uid = []
for row in rows:
    uid.append(row[0])
if(len(uid)==1):
    print("登录成功!")
else:
    print("登录失败!")

#诊断记录表
#数据库脚本

CREATE TABLE zhenduanjilutable(
  userid number(8) not  null ,
  username varchar(50)  NULL,
  sex varchar(10) NOT NULL,
  age number(3) NOT NULL,
  province varchar2(50) null,
  area varchar(50) NOT NULL,
  bumen varchar(26) NOT NULL,
  ke varchar(26) NOT NULL,
  result varchar(26) NOT NULL,
  chufang varchar2(2220),
  jianyi varchar2(1020),
  yiyuaan varchar2(100),
  yisheng varchar2(1100),
  jianchaxiang varchar2(1100),
  zhenduanriqi date default sysdate
  );
commit;

insert into zhenduanjilutable (userid,username,sex,age,province,area,bumen,ke,result,chufang,jianyi,yiuaan,yisheng,jianchaxiang)
values (%d,'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s') % (,,,,,,,,,,,,,)
#智能初诊
import cx_Oracle
import numpy as np

conn=cx_Oracle.connect('doctor/admin@localhost:1521/tszr')
cursor = conn.cursor()

uid = uid[0]
sql = "select username,sex,age,province,area from usertable where userid=%d" % uid
cursor.execute(sql)
rows = cursor.fetchall()
userinfo = []
for row in rows:
    userinfo.append(row[0])
    userinfo.append(row[1])
    userinfo.append(row[2])
    userinfo.append(row[3])
    userinfo.append(row[4])
print(userinfo)

import cx_Oracle
import numpy as np

conn=cx_Oracle.connect('doctor/admin@localhost:1521/tszr')
cursor = conn.cursor()

sql = "select mname from hy_bumen"
cursor.execute(sql)
rows = cursor.fetchall()
bumen = []
for row in rows:
    bumen.append(row[0])
# print(bumen)

bumen = "外科"
sql = "select MENZHENID from hy_bumen where MNAME='%s'" % bumen
cursor.execute(sql)
rows = cursor.fetchall()
bumenid = []
for row in rows:
    bumenid.append(row[0])

sql = "select ke from hy_keid where MENZHENID=%d" % bumenid[0]
cursor.execute(sql)
rows = cursor.fetchall()
kelist = []
for row in rows:
    kelist.append(row[0])
# print(kelist)   
ke = "胸外科"
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)
# print(answer)

#使用神经网络探索数据集
import sys
import os
import time
import operator
import cx_Oracle
import numpy as np
import pandas as pd
import tensorflow as tf

conn=cx_Oracle.connect('doctor/admin@localhost:1521/tszr')
cursor = conn.cursor()

surgery = "外科"
surgeryChest = "胸外科"

#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("姓名:"+userinfo[0])
print("性别:"+userinfo[1])
print("年龄:"+str(userinfo[2]))
print("省份:"+userinfo[3])
print("所属区:"+userinfo[4])
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'" % (userinfo[3],userinfo[4])
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,userinfo[0],userinfo[1],userinfo[2],userinfo[3],userinfo[4],bumen,ke,firstResult,chufang_str,jianyi_str,yiyuan[0],yisheng_str,jianchax)
cursor.execute(sql)
conn.commit()
print("此次智能诊断完成,欢迎你下次继续使用:天生自然健康智能医疗系统!")

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