from configs.connections import connect_graph
from functions.solve_graph import create_job_dataList, create_enterprise_dataList, create_seeker_dataList, \
    add_seeker_dataList
import logging
from flask import current_app

logger = logging.getLogger(__name__)

# 图谱节点类型:job(招聘职位) enterprise(企业) person-seeker(求职者)  给他们打标签建立关系 label

# 针对招聘职位的操作
def operate_job(operate, dataList):
    try:
        if operate == 'sync_all':
            sync_all_jobs(dataList)
        elif operate == 'add':
            add_jobs(dataList)
        elif operate == 'update':
            update_jobs(dataList)
        elif operate == 'delete':
            delete_jobs(dataList)
        else:
            current_app.logger.error(f'operate_job: Invalid operation')
        return True
    except Exception as e:
        current_app.logger.error(f'operate_job error: {e}')

def sync_all_jobs(dataList):
    try:
        # 创建新的job数据
        create_job_dataList(dataList)
    except Exception as e:
        current_app.logger.error(f'sync_all_jobs error: {e}')

def add_jobs(dataList):
    try:
        create_job_dataList(dataList)
    except Exception as e:
        current_app.logger.error(f'add_jobs error: {e}')

def update_jobs(dataList):
    try:
        # 删除旧的job和jobLabel节点及关系
        delete_old_jobs(dataList)
        # 创建新的job数据
        create_job_dataList(dataList)
    except Exception as e:
        current_app.logger.error(f'update_jobs error: {e}')

def delete_jobs(dataList):
    try:
        # 删除指定的job节点
        query = """
        UNWIND $Ids AS id
        MATCH (n:job {uniqueId: id})
        DETACH DELETE n
        """
        ids = [item['id'] for item in dataList]
        connect_graph.run(query, Ids=ids)
    except Exception as e:
        current_app.logger.error(f'delete_jobs error: {e}')

def delete_old_jobs(dataList):
    try:
        # 删除与job节点相连的jobLabel节点和关系
        query = """
        WITH $Ids AS ids_list
        UNWIND ids_list AS Id
        MATCH (n:job {uniqueId: Id})
        WITH n
        MATCH (n)-[r:connection]-(m:jobLabel)
        WITH n, m, COUNT(r) AS connection_count, collect(r) AS relationships
        UNWIND relationships AS rel
        WITH n, m, connection_count, rel
        // 删除连接数为1的jobLabel节点
        WHERE connection_count = 1
        DETACH DELETE m
        WITH n, rel
        // 删除连接数大于1的connection关系
        WHERE connection_count > 1
        DELETE rel"""
        ids = [item['id'] for item in dataList]
        connect_graph.run(query, Ids=ids)
        cql ="""// 第二步：删除指定的job节点
            WITH $Ids AS ids_list
            UNWIND ids_list AS Id
            MATCH (n:job {uniqueId: Id})
            DETACH DELETE n
            """
        connect_graph.run(cql, Ids=ids)
    except Exception as e:
        current_app.logger.error(f'delete_old_jobs error: {e}')

# 企业
def operate_enterprise(operate, dataList):
    try:
        if operate == 'sync_all':
            sync_all_enterprise(dataList)
        elif operate == 'add':
            add_enterprise(dataList)
        elif operate == 'update':
            update_enterprise(dataList)
        elif operate == 'delete':
            delete_enterprise(dataList)
        else:
            current_app.logger.error(f'operate_enterprise: Invalid operation')

        return True

    except Exception as e:
        current_app.logger.error(f'operate_enterprise error: {e}')

def sync_all_enterprise(dataList):
    try:
        create_enterprise_dataList(dataList)
    except Exception as e:
        current_app.logger.error(f'sync_all_enterprise error:{e}')


def add_enterprise(dataList):
    try:
        create_enterprise_dataList(dataList)
    except Exception as e:
        current_app.logger.error(f'add_enterprise error:{e}')


def update_enterprise(dataList):
    try:
        delete_old_enterprise(dataList)
        create_enterprise_dataList(dataList)
    except Exception as e:
        current_app.logger.error(f'add_enterprise error:{e}')

def delete_enterprise(dataList):
    try:
        query = """
                UNWIND $Ids AS id
                MATCH (n:enterprise) WHERE n.uniqueId = id
                DETACH DELETE n"""
        # 提取所有 id
        ids = [item['id'] for item in dataList]
        connect_graph.run(query, Ids=ids)
    except Exception as e:
        current_app.logger.error(f'delete_enterprise error:{e}')

def delete_old_enterprise(dataList):
    try:
        # 先删除后新建
        query = """
              // 第一步：删除与enterprise节点相连的enterpriseLabel节点和关系
              WITH $Ids AS ids_list
              UNWIND ids_list AS Id
              MATCH (n:enterprise {uniqueId: Id})
              WITH n
              MATCH (n)-[r:connection]-(m:enterpriseLabel)
              WITH n, m, COUNT(r) AS connection_count, collect(r) AS relationships
              UNWIND relationships AS rel
              WITH n, m, connection_count, rel
              // 删除连接数为1的enterpriseLabel节点
              WHERE connection_count = 1
              DETACH DELETE m
              WITH n, rel
              // 删除连接数大于1的connection关系
              WHERE connection_count > 1
              DELETE rel"""
        # 提取所有 id (批量删除多个)
        ids = [item['id'] for item in dataList]
        connect_graph.run(query, Ids=ids)
        cql ="""// 第二步：删除指定的enterprise节点
               WITH $Ids AS ids_list
              UNWIND ids_list AS Id
              MATCH (n:enterprise {uniqueId: Id})
              DETACH DELETE n"""
        connect_graph.run(cql, Ids=ids)
    except Exception as e:
        current_app.logger.error(f'delete_old_enterprise error:{e}')



# 针对求职者的操作
def operate_seeker(operate, dataList):
    try:
        if operate == 'sync_all':
            create_seeker_dataList(dataList)
        # 新增 修改基本信息 (单个新增）
        elif operate == 'add':
            add_seeker_dataList(dataList)
            # part_seeker_dataList(dataList)
            # create_seeker_dataList(dataList) # 第一次同步大量数据
        elif operate == 'update':
            # 先删除后新建
            query = """
                  // 第一步：删除与seeker节点相连的seekerLabel节点和关系
                  WITH $Ids AS ids_list
                  UNWIND ids_list AS Id
                  MATCH (n:seeker {uniqueId: Id})
                  WITH n
                  MATCH (n)-[r:connection]-(m:seekerLabel)
                  WITH n, m, COUNT(r) AS connection_count, collect(r) AS relationships
                  UNWIND relationships AS rel
                  WITH n, m, connection_count, rel
                  // 删除连接数为1的seekerLabel节点
                  WHERE connection_count = 1
                  DETACH DELETE m
                  WITH n, rel
                  // 删除连接数大于1的connection关系
                  WHERE connection_count > 1
                  DELETE rel"""
            # 提取所有 id (批量删除多个)
            ids = [item['id'] for item in dataList]
            connect_graph.run(query, Ids=ids)
            cql = """
                  // 第二步：删除指定的seeker节点
                   WITH $Ids AS ids_list
                   UNWIND ids_list AS Id
                  MATCH (n:seeker {uniqueId: Id})
                  DETACH DELETE n"""
            connect_graph.run(cql, Ids=ids)
            add_seeker_dataList(dataList)
        elif operate == 'delete':
            # 删除
            query = """
                      // 第一步：删除与seeker节点相连的seekerLabel节点和关系
                      WITH $Ids AS ids_list
                      UNWIND ids_list AS Id
                      MATCH (n:seeker {uniqueId: Id})
                      WITH n
                      MATCH (n)-[r:connection]-(m:seekerLabel)
                      WITH n, m, COUNT(r) AS connection_count, collect(r) AS relationships
                      UNWIND relationships AS rel
                      WITH n, m, connection_count, rel
                      // 删除连接数为1的seekerLabel节点
                      WHERE connection_count = 1
                      DETACH DELETE m
                      WITH n, rel
                      // 删除连接数大于1的connection关系
                      WHERE connection_count > 1
                      DELETE rel"""
            connect_graph.run(query, Id=dataList[0]['id'])
            cql = """
                      // 第二步：删除指定的seeker节点
                       WITH $Ids AS ids_list
                       UNWIND ids_list AS Id
                      MATCH (n:seeker {uniqueId: Id})
                      DETACH DELETE n"""
            connect_graph.run(cql, Id=dataList[0]['id'])
        else:
            current_app.logger.error(f'operate_seeker: Invalid operation')
            current_app.logger.error(f'operate_seeker:', dataList)
        return True
    except Exception as e:
        current_app.logger.error(f'operate_seeker error: {e}')