from flask import Blueprint, request, jsonify,current_app
from configs.result import success
from functions.label_number import job_label, enterprise_label, seeker_label
from functions.operate_graph import operate_job, operate_enterprise, operate_seeker
import logging
from functions.similarity_judge import similar_job, similar_seeker, draw_graph, home_job, home_person, draw_person_graph
from functions.solve_graph import llm_client1
from configs.connections import connect_graph
logger = logging.getLogger(__name__)
rocket = Blueprint('rocket', __name__)

@rocket.route('/delete/data', methods=['POST'])
def delete_data():
    try:
        receiver = request.get_json()
        type = receiver.get('type')  # job, enterprise, person

        if type == 'job':
            connect_graph.run('match (n:job) detach delete n')
            connect_graph.run('match (n:jobLabel) detach delete n')
        elif type == 'enterprise':
            connect_graph.run('match (n:enterprise) detach delete n')
            connect_graph.run('match (n:enterpriseLabel) detach delete n')
        elif type == 'person':
            connect_graph.run('match (n:seeker) detach delete n')
            connect_graph.run('match (n:seekerLabel) detach delete n')
        else:
            current_app.logger.error('delete_data Invalid type')
        return jsonify(success(True, "success"))  # 返回成功响应

    except Exception as e:
        current_app.logger.error(f'delete_data error: {e}')
        return jsonify(success(True, "success"))



@rocket.route('/receive/data', methods=['POST'])
def receive_data():
    try:
        receiver = request.get_json()
        operate = receiver.get('operate')  # sync_all, add, update, delete
        type = receiver.get('type')  # job, enterprise, person,person_all
        dataList = receiver.get('dataList', [])

        current_app.logger.info(receiver)
        if type == 'job':
            result = operate_job(operate, dataList)
        elif type == 'enterprise':
            result = operate_enterprise(operate, dataList)
        elif type == 'person':
            result = operate_seeker(operate, dataList)

        else:
            current_app.logger.error('receive_data Invalid type')
            return jsonify(success(True, "success"))  # 返回成功响应

        if result is not None:
            return jsonify(success(True, "success"))
        else:
            current_app.logger.error('operate function returned None')
            return jsonify(success(True, "success"))

    except Exception as e:
        current_app.logger.error(f'receive_data error: {e}')
        return jsonify(success(True, "success"))

# 1.人才地图
# 招聘者--->人

# 推荐类型
# 人--->职位
# 人--->企业

# 找人：通过标签去找人
@rocket.route('/query/graph',methods=['POST'])
def query_graph():
    try:
        receiver = request.get_json()
        label = receiver.get('label', [])  # 多个标签
        description = receiver.get('content', '')  # 一段描述内容
        type = receiver.get('type', '')  # 1.找人  对应类型 person

        if description:
            label_list = llm_client1(description)
        # 如果 label_list 是非空列表，则将其与现有的 label 合并
        if isinstance(label_list, list) and label_list:
            label.extend(label_list)

        if type == 'person':
            id_list = similar_seeker(label)
        else:
            current_app.logger.error('query_graph Invalid type')
            id_list = []
        return jsonify(success(id_list, "success"))

    except Exception as e:
        current_app.logger.error(f'query_graph error: {e}')
        return jsonify(success([], "success"))


# 职位详情：职位id--标签--推荐相似职位
@rocket.route('/match/job',methods=['POST'])
def match_job():
    try:
        receiver = request.get_json()
        page = int(receiver.get('current', 1))
        page_size = int(receiver.get('size', 10))
        uniqueid = receiver.get('id', [])  #职位对应的id
        type = receiver.get('type', '')  # 查找对应的job

        draw_graph()
        # 起止范围
        start = (page - 1) * page_size
        end = page * page_size
        if type == 'job':
            id_list = similar_job(uniqueid,start,end)
        else:
            current_app.logger.error('match_job Invalid type')
            id_list = []

        return jsonify(success(id_list, "success"))
    except Exception as e:
        current_app.logger.error(f'match_job error: {e}')
        return jsonify(success([], "success"))

# 人登录之后推荐的职位
@rocket.route('/recommend/job',methods=['POST'])
def recommend_job():
    try:
        receiver = request.get_json()
        page = int(receiver.get('current', 1))
        page_size = int(receiver.get('size', 10))
        uniqueid = receiver.get('userId', "")  # 职位对应的id
        type = receiver.get('type', '')  # 推荐对应的job
        # 起止范围
        start = (page-1) * page_size
        end = page * page_size

        draw_graph()
        if type == 'job':
            id_list = home_job(uniqueid,start,end)
        else:
            current_app.logger.error('recommend_job Invalid type')
            id_list = []
        return jsonify(success(id_list, "success"))

    except Exception as e:
        current_app.logger.error(f'recommend_job error: {e}')
        return jsonify(success([], "success"))

# 人登录之后推荐的职位
@rocket.route('/recommend/person',methods=['POST'])
def recommend_person():
    try:
        receiver = request.get_json()
        page = int(receiver.get('current', 1))
        page_size = int(receiver.get('size', 10))
        uniqueid = receiver.get('id', "")  # 职位对应的id
        type = receiver.get('type', '')  # 推荐对应的person
        # 起止范围
        start = (page-1) * page_size
        end = page * page_size

        draw_person_graph()
        if type == 'person':
            id_list = home_person(uniqueid,start,end)
        else:
            current_app.logger.error('match_job Invalid type')
            id_list = []
        return jsonify(success(id_list, "success"))

    except Exception as e:
        current_app.logger.error(f'recommend_job error: {e}')
        return jsonify(success([], "success"))



# 页面标签列表
@rocket.route('/label/list',methods=['POST'])
def label_list():
    try:
        receiver = request.get_json()
        page = int(receiver.get('current', 1))  # 当前页
        page_size = int(receiver.get('size', 10)) # 每页的数量
        type = receiver['type']
        # 计算跳过的记录的数量
        skip_count = (page - 1) * page_size

        if type == 'job':
            labels,total = job_label(skip_count,page_size)
        elif type == 'enterprise':
            labels,total = enterprise_label(skip_count,page_size)
        elif type == 'person':
            labels,total = seeker_label(skip_count,page_size)
        else:
            current_app.logger.error('label_list Invalid type')
            labels,total = [],0
        response_data = {'records': labels, 'total': total, 'size': page_size, 'current': page}
        return jsonify(success(response_data, "success"))
    except Exception as e:
        current_app.logger.error(f'label_list error: {e}')
        return jsonify(success(True, "success"))


