# -*- coding: utf-8 -*-
"""
@Author: HuangJianYi
@Date: 2026-03-18 18:30:00
@Description: CDP作业信息模型
"""
from seven_framework.mysql import MySQLHelper
from seven_framework.base_model import *
from seven_cloudapp_frame.models.cache_model import *
# 在文件顶部添加模块级缓存
_job_monitor_cache = {}
import threading
_job_cache_lock = threading.Lock()

class CdpJobInfoModel(CacheModel):
    def __init__(self, db_connect_key='db_cloudapp', sub_table=None, db_transaction=None, context=None, is_auto=False):
        super(CdpJobInfoModel, self).__init__(CdpJobInfo, sub_table)
        self.db = MySQLHelper(self.convert_db_config(db_connect_key, is_auto))
        self.db_connect_key = db_connect_key
        self.db_transaction = db_transaction
        self.db.context = context

    #方法扩展请继承此类

    def get_jobs(self, engineer_code=None):
        """
        获取已发布的作业列表
        
        :param engineer_code: 工程代码
        :param business_id: 商家ID
        :param store_id: 店铺ID
        :return: 作业列表
        """
        where_conditions = ["is_release=1", "progress_type in (0,1)"]
        params = []

        if engineer_code:
            where_conditions.append("engineer_code=%s")
            params.append(engineer_code)

        where_sql = " AND ".join(where_conditions)

        return self.get_dict_list(where_sql, order_by="create_date ASC", params=params)

    def monitor_job(self, job_id, run_desc='持续处理中', interval_seconds=60):
        """
        监控作业 - 为了避免数据库压力，添加1分钟间隔
        :param job_id: 作业ID
        :param run_desc: 运行描述描述
        :return: 更新结果
        """
        current_time = time.time()
        # 先判断模块级别缓存
        local_cache_key = f"cdp_job_monitor_local:{job_id}"
        with _job_cache_lock:
            last_local_time = _job_monitor_cache.get(local_cache_key, 0)
            # 如果本地时间判断通过，直接返回
            if current_time - float(last_local_time) < interval_seconds:
                return True

        update_sqls = ["run_last_date=NOW()"]
        params = []
        if run_desc:
            update_sqls.append("run_desc=%s")
            params.append(run_desc)
        params.append(job_id)
        result = self.update_table(",".join(update_sqls), "id=%s", params=params)

        # 更新缓存时间
        with _job_cache_lock:
            _job_monitor_cache[local_cache_key] = current_time

        return result

    def start_job(self, job_id, run_desc='开始处理'):
        """
        开始作业
        :param job_id: 作业ID
        :param run_desc: 运行描述描述
        :return: 更新结果
        """
        update_sqls = ["progress_type=1", "run_start_date=NOW()", "run_last_date=NOW()"]
        params = []
        if run_desc:
            update_sqls.append("run_desc=%s")
            params.append(run_desc)
        params.append(job_id)
        return self.update_table(
            ",".join(update_sqls),
            "id=%s",
            params=params
        )

    def stop_job(self, job_id, run_desc='停止处理'):
        """
        停止作业
        :param job_id: 作业ID
        :param run_desc: 运行描述描述
        :return: 更新结果
        """
        update_sqls = ["progress_type=0", "run_last_date=NOW()"]
        params = []
        if run_desc:
            update_sqls.append("run_desc=%s")
            params.append(run_desc)
        params.append(job_id)
        return self.update_table(
            ",".join(update_sqls),
            "id=%s",
            params=params
        )

    def complete_job(self, job_id, run_desc='完成处理'):
        """
        完成作业
        
        :param job_id: 作业ID
        :param run_desc: 运行结果描述
        :return: 更新结果
        """
        update_sqls = ["progress_type=2", "run_end_date=NOW()", "run_last_date=NOW()"]
        params = []
        if run_desc:
            update_sqls.append("run_desc=%s")
            params.append(run_desc)
        params.append(job_id)
        return self.update_table(
            ",".join(update_sqls),
            "id=%s",
            params=params
        )


class CdpJobInfo:
    """CDP作业信息实体类"""

    def __init__(self):
        super(CdpJobInfo, self).__init__()
        self.id = 0  # id
        self.business_id = 0  # 商家标识
        self.store_id = 0  # 店铺标识
        self.job_code = ""  # 作业代码(对应函数名)
        self.engineer_code = ""  # 工程代码
        self.is_release = 0  # 是否发布（1-是 0-否）
        self.progress_type = 0  # 进度类型(0-未开始 1-进行中 2-已完成)
        self.extend_info = {} # 扩展信息json
        self.run_desc = ""  # 运行结果描述
        self.run_start_date = "1970-01-01 00:00:00.000"  # 开始运行时间
        self.run_end_date = "1970-01-01 00:00:00.000"  # 结束运行时间
        self.run_last_date = "1970-01-01 00:00:00.000"  # 最近运行时间
        self.create_date = "1970-01-01 00:00:00.000"  # 创建时间
        self.modify_date = "1970-01-01 00:00:00.000"  # 修改时间

    @classmethod
    def get_field_list(self):
        return [
            'id', 'business_id', 'store_id', 'job_code', 'engineer_code',
            'is_release', 'progress_type', 'extend_info', 'run_desc', 'run_start_date',
            'run_end_date', 'run_last_date', 'create_date', 'modify_date'
        ]

    @classmethod
    def get_primary_key(self):
        return "id"

    def __str__(self):
        return "cdp_job_info_tb"
