def get_user():
    """
    获取所有活跃的用户信息
    :return: user:所有用户的信息
    """
    mongo_operator = MongoOperator(**MongoDB_CONFIG)
    user_set = mongo_operator.get_collection("user")
    user = user_set.find({"status": '1'})
    user_list = []
    for i in user:
        try:
            if len(i['charge_school']) > 0:
                str = i['charge_school'][0]
                for j in i['charge_school'][1:]:
                    str = str + "," + j
                user_list.append([
                    i['name'], i['tel_number'], i['email'], str, i['id'],
                    i['type'], i['id']
                ])
            else:
                user_list.append([
                    i['name'], i['tel_number'], i['email'], '', i['id'],
                    i['type'], i['id']
                ])
        except BaseException:
            pass
    return user_list
def search_teacher_basic_info(teacher_id):
    """
    根据教师的id从MongoDB中获取教师的基本信息
    :param teacher_id:
    :return:
    """
    print(
        "-------------------------开始搜索学者基本信息---------------------------------------"
    )
    try:
        mongo_operator = MongoOperator(**MongoDB_CONFIG)
        # 指定集合
        basic_info_col = mongo_operator.get_collection("basic_info")

        basic_info_dict = basic_info_col.find_one({"id": teacher_id}, {
            "id": 1,
            "name": 1,
            "birth_year": 1,
            "title": 1,
            "email": 1,
            "school": 1,
            "institution": 1,
            "edu_exp": 1,
            "other_title": 1,
            "position": 1,
            "phone_number": 1,
            "office_number": 1
        })
        # print(basic_info_dict)

    except Exception as e:
        print("------exception------  ", e)

    return basic_info_dict
def update_basic_info(basic_info_dict):
    """
    根据更改后的信息更新数据库中对应的教师基本信息
    :param basic_info_dict:
    :return:
    """
    mongo_operator = MongoOperator(**MongoDB_CONFIG)
    # 指定集合
    basic_info_col = mongo_operator.get_collection("basic_info")

    teacher_id = basic_info_dict["id"]

    info_in_mongo = basic_info_col.find_one({"id": teacher_id})
    #    更新信息
    info_in_mongo["name"] = basic_info_dict["name"]
    info_in_mongo["birth_year"] = basic_info_dict["birth_year"]
    info_in_mongo["title"] = basic_info_dict["title"]
    info_in_mongo["email"] = basic_info_dict["email"]
    info_in_mongo["school"] = basic_info_dict["school"]
    info_in_mongo["edu_exp"] = basic_info_dict["edu_exp"]
    info_in_mongo["other_title"] = basic_info_dict["other_title"]
    info_in_mongo["position"] = basic_info_dict["position"]
    info_in_mongo["phone_number"] = basic_info_dict["phone_number"]
    info_in_mongo["office_number"] = basic_info_dict["office_number"]

    print(info_in_mongo)

    basic_info_col.save(info_in_mongo)
def insert_basic_info(data, obj_id):
    """
    将一条记录插入basic_info表中,并根据_id将agent_feed中的那条数据status设置为0
    """
    mogo_operator = MongoOperator(**MongoDB_CONFIG)
    collection = mogo_operator.get_collection('basic_info')
    agent_feedback_collection = mogo_operator.get_collection('agent_feedback')
    try:
        collection.insert_one(data)
        # 将商务反馈的记录标注为已处理
        agent_feedback_collection.update_one({'_id': obj_id},
                                             {'$set': {
                                                 'status': 0
                                             }})
    except Exception as e:
        print(e.args)
def get_school():
    """
    获取数据库中所有学校名
    :return:
    """
    mongo_operator = MongoOperator(**MongoDB_CONFIG)
    school = mongo_operator.get_collection("basic_info")
    school_list = school.distinct("school")
    return school_list
def delete_teacher(id):
    """
    根据教师id改变教师状态为不可用,增加status为0
    :param id:教师id
    :return:
    """
    mongo_operator = MongoOperator(**MongoDB_CONFIG)
    teacher_list = mongo_operator.get_collection("basic_info")
    teacher_list.update_one({"id": id}, {"$set": {"status": 0}})
def delete_user(user_id):
    """
    根据user_id(用户id),将用户的状态修改为0
    :param :user_id:用户id
    :return:
    """

    mongo_operator = MongoOperator(**MongoDB_CONFIG)
    user = mongo_operator.get_collection("user")
    return user.update_one({"id": user_id}, {"$set": {"status": "0"}})
def get_institution(school_name):
    """
    根据学校名获取这个学校的所有学院名
    :param school_name: 学校名
    :return: institution:学院名
    """
    mongo_operator = MongoOperator(**MongoDB_CONFIG)
    school = mongo_operator.get_collection("basic_info")
    institution = school.distinct("institution", {"school": school_name})
    return institution
def get_max_teacher_id():
    """
    获取basci_info中的id最大值,即mysql中的teacher_id的最大值
    :return 当前最大的id值
    """
    mogo_operator = MongoOperator(**MongoDB_CONFIG)
    collection = mogo_operator.get_collection('basic_info')
    max_id_cursor = collection.find({}).sort([('id', -1)]).limit(1)
    max_id = list(max_id_cursor)[0].get('id')
    return max_id
def update_teacher(id, teacher_info):
    """
    根据教师id和教师消息更新教师的消息
    :param id:教师id
    :param teacher_info:教师消息(教师名,学校,学院,头衔,出生年月,邮箱,办公电话,手机号码,教育经历)
    :return:
    """
    mongo_operator = MongoOperator(**MongoDB_CONFIG)
    teacher_list = mongo_operator.get_collection("basic_info")
    teacher_list.update_one({"id": id}, {"$set": teacher_info})
def insert_project_info(data, _id):
    """
    :param data:要保存的项目信息
    :param _id: 已处理的项目信息的_id
    将项目信息保存到数据库,并将project_feedback中的那条信息status置为0
    """
    mogo_operator = MongoOperator(**MongoDB_CONFIG)
    collection = mogo_operator.get_collection('project_info')
    project_feedback_collection = mogo_operator.get_collection(
        'project_feedback')
    try:
        # 将商务反馈的记录标注为已处理
        _id = ObjectId(_id)
        project_feedback_collection.update_one({'_id': _id},
                                               {'$set': {
                                                   'status': 0
                                               }})
        result_insert = collection.insert_one(data)
    except Exception as e:
        print(e.args)
def add_teacher(teacher_info):
    """
    增加教师的消息
    :param teacher_info:(教师名,学校,学院,头衔,出生年月,邮箱,办公电话,手机号码,教育经历)
    :return:
    """
    mongo_operator = MongoOperator(**MongoDB_CONFIG)
    teacher_list = mongo_operator.get_collection("basic_info")
    max_id = get_max_teacher_id() + 1
    teacher_info['id'] = max_id
    teacher_list.insert_one(teacher_info)
def get_info_from_db(teacher_id, _id):
    """
    将处理中的教师的信息从basic_info表中取出,以便于和商务提交的修改信息做对比
    :return: 该教师再basic_info表中的基本信息
    """
    mogo_operator = MongoOperator(**MongoDB_CONFIG)
    collection = mogo_operator.get_collection('basic_info')
    teacher_info_from_basic = collection.find_one({"id": teacher_id}, {
        '_id': 0,
        'funds_id': 0,
        'patent_id': 0,
        'paper_id': 0,
        'project_id': 0,
        'award_id': 0,
        'research_plan_id': 0
    })
    agent_feedback = mogo_operator.get_collection('agent_feedback')
    teacher_info_from_feedback = agent_feedback.find_one({"_id": _id})
    teacher_info_from_db = data_treate(teacher_info_from_basic,
                                       teacher_info_from_feedback)
    return teacher_info_from_db
def update_status(obj_id):
    """
    根据_id将agent_feed中的那条数据status设置为0
    """
    mogo_operator = MongoOperator(**MongoDB_CONFIG)
    agent_feedback_collection = mogo_operator.get_collection('agent_feedback')
    try:
        agent_feedback_collection.update_one({'_id': obj_id},
                                             {'$set': {
                                                 'status': 0
                                             }})
    except Exception as e:
        print(e.args)
def update_basic_info(teacher_id, obj_id, data):
    """
    修改basic_info中的一条记录,并根据_id将agent_feed中的那条数据status设置为0
    :return:
    """
    mogo_operator = MongoOperator(**MongoDB_CONFIG)
    collection = mogo_operator.get_collection('basic_info')
    try:
        agent_feedback_collection = mogo_operator.get_collection(
            'agent_feedback')
        collection.update_one({'id': int(teacher_id)}, {
            '$set': {
                'name': data.get('name'),
                'gender': data.get('gender'),
                'school': data.get('school'),
                'institution': data.get('institution'),
                'department': data.get('department'),
                'birth_year': data.get('birth_year'),
                'title': data.get('title'),
                'position': data.get('position'),
                'domain': data.get('domain'),
                'honor_title': data.get('honor_title'),
                'email': data.get('email'),
                'office_number': data.get('office_number'),
                'phone_number': data.get('phone_number'),
                'edu_exp': data.get('edu_exp'),
                'work_exp': data.get('work_exp')
            }
        })
        # 将商务反馈的记录标注为已处理
        agent_feedback_collection.update_one({'_id': obj_id},
                                             {'$set': {
                                                 'status': 0
                                             }})
    except Exception as e:
        print(e.args)
def get_project_info():
    """
    从数据库project_feedback中取得所有未处理的project信息
    :return:
    """
    mogo_operator = MongoOperator(**MongoDB_CONFIG)
    # 从数据库中取出商务提交的所有信息
    project_feedback = mogo_operator.get_collection('project_feedback')
    #status表示未处理的信息
    project_info = list(project_feedback.find({'status': 1}))
    #按商务提交时间排序,先提交的排在前面
    project_info.sort(key=lambda x: x['timestamp'])
    for info in project_info:
        info['timestamp'] = info['timestamp'].strftime("%Y-%m-%d")
        # info['start_time'] = info['start_time'].strftime("%Y-%m-%d")
        # info['end_time'] = info['end_time'].strftime("%Y-%m-%d")
    return project_info
def update_user(user_dict):
    """
    根据用户id修改用户的信息
    :param user_dict:用户的信息(用户id,用户名,联系电话,邮箱,所在学校,用户类型)
    :return:
    """
    mongo_operator = MongoOperator(**MongoDB_CONFIG)
    user = mongo_operator.get_collection("user")
    user.update_many({"id": user_dict['id']}, {
        "$set": {
            "name": user_dict['name'],
            "tel_number": user_dict['tel_number'],
            "email": user_dict['email'],
            "type": user_dict['type'],
            "charge_school": user_dict['charge_school']
        }
    })
def add_user(user_dict):
    """
    将新建用户的信息入库
    :param user_dict:
    :return:
    """
    try:
        mongo_operator = MongoOperator(**MongoDB_CONFIG)
        user = mongo_operator.get_collection("user")
        user.insert_one(user_dict)

        # 添加商务数据到图图数据库
        # return ==> {success: True / False}
        NeoOperator(**NEO4J_CONFIG).create_agent(user_dict['id'],
                                                 user_dict['name'],
                                                 user_dict['type'])

    except Exception:
        raise Exception
def update_dept(dept_info):
    """
    更新系的信息
    by zhang
    :param dept_info: [
                        {teacher_id: **, department: **}
                        {}
                        ...
                        ]
    :return:
    """
    mongo = MongoOperator(**MongoDB_CONFIG)
    basic_info_col = mongo.get_collection("basic_info")

    for dict in dept_info:
        basic_info_col.update(
            {"id": int(dict["teacher_id"])},
            {"$set": {
                "department": dict["department"].strip()
            }})
def get_teacher_info(school, institution, teacher):
    """
    根据学校名,学院名和教师名获取教师信息
    :param school:学校名
    :param institution: 学院名
    :param teacher: 教师名
    :return: teacher_dict:教师名、学校名、学院名、头衔、出生年月、邮箱、办公电话、手机号码、教育经历
    """
    mongo_operator = MongoOperator(**MongoDB_CONFIG)
    teacher_list = mongo_operator.get_collection("basic_info")
    if institution != "":
        teacher_dict = teacher_list.find_one({
            "school": school,
            "institution": institution,
            "name": teacher
        })
    else:
        teacher_dict = teacher_list.find_one({
            "school": school,
            "name": teacher
        })
    return teacher_dict
def get_teacher(school, institution):
    """
    根据学校名和学院名获取其下的所有教师
    by zhang
    :param school:
    :param teacher:
    :return: 教师列表:[]
    """
    mongo = MongoOperator(**MongoDB_CONFIG)
    basic_info_col = mongo.get_collection("basic_info")
    teacher_list = list(
        basic_info_col.find({
            "school": school,
            "institution": institution
        }, {
            "_id": 0,
            "name": 1,
            "id": 1,
            "department": 1
        }))

    return teacher_list
def get_modify_info():
    """
    从数据库中将商务提交的待处理的教师信息修改信息取出
    :return: agent_feedback表中所有未处理的信息
    """
    mogo_operator = MongoOperator(**MongoDB_CONFIG)
    # 从数据库中取出商务提交的所有信息
    agent_feedback = mogo_operator.get_collection('agent_feedback')
    # status=1表示未处理的信息
    modify_info = list(agent_feedback.find({'status': 1}))
    # 商务先提交的排在前面
    modify_info.sort(key=lambda x: x['timestamp'])
    # 处理数据
    for info in modify_info:
        info['timestamp'] = info['timestamp'].strftime("%Y-%m-%d")
        if 'honor_title' in info:
            honor_title_list = []
            if info['honor_title'] != []:
                for title in info['honor_title']:
                    honor_title_list.append({'type': title, 'year': ''})
            info['honor_title'] = honor_title_list
        data_pretreate(info)
    return modify_info