#!D:/IDE/anaconda3/envs python
# -*- coding: UTF-8 -*-
"""
 @Author: Administrator
 @FileName：ChamberStatusModel.py\n
 @DateTime: 2025/7/9 12:23\n
 @Author  ：xsh
"""
from datetime import datetime
from AppSettings.Settings import *
from AppCore.AppDBModels.CoreModel import (dbController)
from sqlalchemy.orm import Session
from sqlalchemy.orm import (Mapped, mapped_column)
from sqlalchemy.types import (Text, DateTime)
from AppUtils.utils import *
from AppCore.Levels import *
from AppCore.AppDBModels.SlideModels.SlideModelInterface import SlideModelInterface

class ChamberStatusModel(SlideModelInterface):
    __tablename__ = 't_ChamberStatusModel'
    ID                  : Mapped[int            ] = mapped_column(primary_key=True                                      , nullable=False , doc='数据ＩＤ　　', comment='数据ＩＤ　　') # '数据ＩＤ　　'
    ChamberGroupNumber  : Mapped[int            ] = mapped_column(            default=1                                 , nullable=True  , doc='片仓组号　　', comment='片仓组号　　') # '片仓组号　　'
    ChamberRowNumber    : Mapped[int            ] = mapped_column(            default=1                                 , nullable=True  , doc='片仓行号　　', comment='片仓行号　　') # '片仓行号　　'
    LState              : Mapped[int            ] = mapped_column(            default=0                                 , nullable=True  , doc='左边状态　　', comment='左边状态　　') # '左边状态　　'
    RState              : Mapped[int            ] = mapped_column(            default=0                                 , nullable=True  , doc='右边状态　　', comment='右边状态　　') # '右边状态　　'
    CodeString          : Mapped[str            ] = mapped_column(Text      , default=''                                , nullable=True  , doc='二维码编号　', comment='二维码编号　') # '二维码编号　'
    SpecimenNumber      : Mapped[str            ] = mapped_column(Text      , default=''                                , nullable=True  , doc='样本编号　　', comment='样本编号　　') # '样本编号　　'
    SlideNumber         : Mapped[str            ] = mapped_column(Text      , default=''                                , nullable=True  , doc='玻片编号　　', comment='玻片编号　　') # '玻片编号　　'
    LineNumber          : Mapped[str            ] = mapped_column(Text      , default=''                                , nullable=True  , doc='样本线号　　', comment='样本线号　　') # '样本线号　　'
    CreateTime          : Mapped[datetime       ] = mapped_column(DateTime  , default=datetime.now()                    , nullable=True  , doc='创建时间　　', comment='创建时间　　') # '创建时间　　'
    TrayNumber          : Mapped[int            ] = mapped_column(            default=ModuleLevel.ModuleTraySlide1      , nullable=True  , doc='托盘编号　　', comment='托盘编号　　') # '托盘编号　　'
    RowNumber           : Mapped[int            ] = mapped_column(            default=1                                 , nullable=True  , doc='图片行号　　', comment='图片行号　　') # '图片行号　　'
    ColNumber           : Mapped[int            ] = mapped_column(            default=1                                 , nullable=True  , doc='图片列号　　', comment='图片列号　　') # '图片列号　　'
    ImageScore          : Mapped[int            ] = mapped_column(            default=0                                 , nullable=True  , doc='图片评分　　', comment='图片评分　　') # '图片评分　　'
    IsSave              : Mapped[int            ] = mapped_column(            default=0                                 , nullable=True  , doc='是否保存　　', comment='是否保存　　') # '是否保存　　'
    ImageCellX          : Mapped[int            ] = mapped_column(            default=0                                 , nullable=True  , doc='小图中心Ｘ　', comment='小图中心Ｘ　') # '小图中心Ｘ　'
    ImageCellY          : Mapped[int            ] = mapped_column(            default=0                                 , nullable=True  , doc='小图中心Ｙ　', comment='小图中心Ｙ　') # '小图中心Ｙ　'
    ImageCellWidth      : Mapped[int            ] = mapped_column(            default=0                                 , nullable=True  , doc='小图宽度　　', comment='小图宽度　　') # '小图宽度　　'
    ImageCellHeight     : Mapped[int            ] = mapped_column(            default=0                                 , nullable=True  , doc='小图高度　　', comment='小图高度　　') # '小图高度　　'
    ImageCellScore      : Mapped[int            ] = mapped_column(            default=0                                 , nullable=True  , doc='小图评分　　', comment='小图评分　　') # '小图评分　　'
    ImageCellType       : Mapped[int            ] = mapped_column(            default=0                                 , nullable=True  , doc='小图类型　　', comment='小图类型　　') # '小图类型　　'
    ScanTemplateID      : Mapped[int            ] = mapped_column(            default=1                                 , nullable=True  , doc='模板ＩＤ　　', comment='模板ＩＤ　　') # '模板ＩＤ　　'
    Index               : Mapped[int            ] = mapped_column(            default=0                                 , nullable=True  , doc='数据序号　　', comment='数据序号　　') # '数据序号　　'
    Position_X          : Mapped[float          ] = mapped_column(            default=0.0                               , nullable=True  , doc='托盘位置Ｘ　', comment='托盘位置Ｘ　') # '托盘位置Ｘ　'
    Position_Y          : Mapped[float          ] = mapped_column(            default=0.0                               , nullable=True  , doc='托盘位置Ｙ　', comment='托盘位置Ｙ　') # '托盘位置Ｙ　'
    Position_Z          : Mapped[float          ] = mapped_column(            default=0.0                               , nullable=True  , doc='托盘位置Ｚ　', comment='托盘位置Ｚ　') # '托盘位置Ｚ　'
    SavePath            : Mapped[str            ] = mapped_column(Text      , default=''                                , nullable=True  , doc='保存路径　　', comment='保存路径　　') # '保存路径　　'
    Level               : Mapped[int            ] = mapped_column(            default=ScanStatusLevel.Default_Status    , nullable=True  , doc='当前状态　　', comment='当前状态　　') # '当前状态　　'
    ObjectiveLevel      : Mapped[int            ] = mapped_column(            default=ObjectiveLevel.ObjectiveNone      , nullable=True  , doc='物镜类型　　', comment='物镜类型　　') # '物镜类型　　'
    CollectCount        : Mapped[int            ] = mapped_column(            default=0                                 , nullable=True  , doc='采集图数量　', comment='采集图数量　') # '采集图数量　'
    PreviewCount        : Mapped[int            ] = mapped_column(            default=0                                 , nullable=True  , doc='预览图数量　', comment='预览图数量　') # '采集图数量　'
    def __init__(self, **args):
        super(ChamberStatusModel, self).__init__()
        self.initialize()
        self.initParameter(**args)
    __field__ = (
        'ID'                     ,
        'ChamberGroupNumber'     ,
        'ChamberRowNumber'       ,
        'LState'                 ,
        'RState'                 ,
        'CodeString'             ,
        'SpecimenNumber'         ,
        'SlideNumber'            ,
        'LineNumber'             ,
        'CreateTime'             ,
        'TrayNumber'             ,
        'RowNumber'              ,
        'ColNumber'              ,
        'ImageScore'             ,
        'IsSave'                 ,
        'ImageCellX'             ,
        'ImageCellY'             ,
        'ImageCellWidth'         ,
        'ImageCellHeight'        ,
        'ImageCellScore'         ,
        'ImageCellType'          ,
        'ScanTemplateID'         ,
        'Index'                  ,
        'Position_X'             ,
        'Position_Y'             ,
        'Position_Z'             ,
        'SavePath'               ,
        'Level'                  ,
        'ObjectiveLevel'         ,
        'CollectCount'           ,
        'PreviewCount'           ,

    )
    __types__ = (
        int            ,
        int            ,
        int            ,
        int            ,
        int            ,
        str            ,
        str            ,
        str            ,
        str            ,
        datetime       ,
        int            ,
        int            ,
        int            ,
        int            ,
        int            ,
        int            ,
        int            ,
        int            ,
        int            ,
        int            ,
        int            ,
        int            ,
        int            ,
        float          ,
        float          ,
        float          ,
        str            ,
        int            ,
        int            ,
        int            ,
        int            ,
    )
    __header__ = (
        '数据ＩＤ　　',
        '片仓组号　　',
        '片仓行号　　',
        '左边状态　　',
        '右边状态　　',
        '二维码编号　',
        '托盘位置Ｘ　',
        '托盘位置Ｙ　',
        '托盘位置Ｚ　',
        '样本编号　　',
        '玻片编号　　',
        '样本线号　　',
        '当前状态　　',
        '物镜类型　　',
        '托盘编号　　',
        '图片行号　　',
        '图片列号　　',
        '图片评分　　',
        '是否保存　　',
        '小图中心Ｘ　',
        '小图中心Ｙ　',
        '小图宽度　　',
        '小图高度　　',
        '小图评分　　',
        '小图类型　　',
        '保存路径　　',
        '创建时间　　',
        '采集图数量　',
        '预览图数量　',
    )
    @classmethod
    def initModels(cls):
        from AppCore.AppDBModels.ConfigModels.SystemConfigModel import SystemConfigModel
        from AppSettings.SystemSetting import SystemSetting, SystemConfig
        MinRowNumber    : int
        MaxRowNumber    : int
        MinChamberNumber: int
        MaxChamberNumber: int
        RowNumber       : int
        ChamberNumber   : int
        MinChamberNumber, MaxChamberNumber  = SystemConfig.getChamberRange          ()
        items: list[cls] = []
        item: cls
        Index: int = 1
        TrayNumbers: list[int] = TrayLevel.all()
        for ChamberNumber in range(MinChamberNumber, MaxChamberNumber + 1):
            for RowNumber in TrayNumbers:
                items.append(cls.instance(ID=Index, ChamberGroupNumber=ChamberNumber, ChamberRowNumber=RowNumber, LState=0, RState=0,CoreString='', CollectCount = 0,PreviewCount = 0))
                Index += 1
        return items


    @classmethod
    def InitChamberStatus(cls, l_state: int = 0, r_state: int = 0, templateID: int = None,preview_count: int = 0, collect_count: int = 0):
        cls.changed({
            cls.CodeString              : None                                          ,
            cls.SpecimenNumber          : None                                          ,
            cls.SlideNumber             : None                                          ,
            cls.LineNumber              : None                                          ,
            cls.SavePath                : None                                          ,
            cls.LState                  : l_state                                       ,
            cls.RState                  : r_state                                       ,
            cls.Level                   : ScanStatusLevel.Default_Status                ,
            cls.ScanTemplateID          : templateID                                    ,
            cls.PreviewCount            : collect_count                                 ,
            cls.CollectCount            : preview_count                                 ,

        })

    @classmethod
    def setCustomData(cls, items: list[list[dict[str, object]]]):
        chamber_data            : list[dict[str, object]]
        row_data                : dict[str, object]
        barcode                 : str
        templateID              : int
        ChamberGroupNumber      : int
        ChamberRowNumber        : int
        CodeString              : str
        SpecimenNumber          : str
        SlideNumber             : str
        LineNumber              : str
        SavePath                : str
        uiIndex                 : str
        color                   : str
        TemplateID              : int
        models                  : list[cls] = []
        from AppSettings.AppSetting import AppConfig
        cls.InitChamberStatus()
        SavePath = AppConfig.PathConfig.RootPath
        for ChamberGroupNumber, chamber_data in enumerate(items):
            if isinstance(chamber_data, list):
                for ChamberRowNumber, row_data in enumerate(chamber_data):
                    barcode             = None
                    uiIndex             = None
                    TemplateID          = None
                    CodeString          = None
                    SpecimenNumber      = None
                    SlideNumber         = None
                    LineNumber          = None
                    if isinstance(row_data, dict):
                        barcode     = AppConvert.ObjectConvert(row_data.get('barcode'   , None), str)
                        uiIndex     = AppConvert.ObjectConvert(row_data.get('uiIndex'   , None), str)
                        TemplateID  = AppConvert.ObjectConvert(row_data.get("templateID", None), int)
                    if isinstance(barcode, str) and isinstance(uiIndex, str) and isinstance(TemplateID, int):
                        LState              = 1
                        RState              = 1
                    else:
                        LState              = 0
                        RState              = 0

                    models.append(cls.instance(
                        ChamberGroupNumber  = ChamberGroupNumber + 1            ,
                        ChamberRowNumber    = ChamberRowNumber   + 1            ,
                        LState              = LState                            ,
                        RState              = RState                            ,
                        CodeString          = CodeString                        ,
                        SpecimenNumber      = SpecimenNumber                    ,
                        SlideNumber         = SlideNumber                       ,
                        LineNumber          = LineNumber                        ,
                        SavePath            = SavePath                          ,
                        Level               = ScanStatusLevel.Default_Status    ,
                        ObjectiveLevel      = ObjectiveLevel.ObjectiveNone      ,
                        CollectCount        = 0                                 ,
                        PreviewCount        = 0                                 ,
                    ))
            pass

        try:
            dbController.initEngine()
            with Session(dbController.Engine) as session:
                for model in models:
                    session.query(cls).filter(cls.ChamberGroupNumber == model.ChamberGroupNumber,
                                              cls.ChamberRowNumber == model.ChamberRowNumber).update(
                        {
                            cls.CodeString              : model.CodeString          ,
                            cls.SpecimenNumber          : model.SpecimenNumber      ,
                            cls.SlideNumber             : model.SlideNumber         ,
                            cls.LineNumber              : model.LineNumber          ,
                            cls.SavePath                : model.SavePath            ,
                            cls.LState                  : model.LState              ,
                            cls.RState                  : model.RState              ,
                            cls.Level                   : model.Level               ,
                            cls.ObjectiveLevel          : model.ObjectiveLevel      ,
                            cls.CollectCount            : model.CollectCount        ,
                            cls.PreviewCount            : model.PreviewCount        ,
                        }
                    )
                session.commit()
                session.close()
        except Exception as e:
            AppUtils.print_Exception(e)


    @classmethod
    def setCollectCount(cls, chamber_number: int, row_number: int, tray_number: int, objective: int, collectcount: int):
        from AppSettings.SystemSetting import system_config
        ChamberNumber: int
        RowNumber: int
        ChamberNumber, RowNumber = system_config.getChamberNumbers(chamber_number, row_number)
        item: cls
        try:
            dbController.initEngine()
            with Session(dbController.Engine) as session:
                session.query(cls).filter(cls.ChamberGroupNumber == ChamberNumber,
                                          cls.ChamberRowNumber == RowNumber).update(
                    {
                        cls.CollectCount    : abs(int(collectcount)) if isinstance(collectcount, (int, float)) else 0   ,
                        cls.TrayNumber      : tray_number                                                               ,
                        cls.ObjectiveLevel  : objective                                                                 ,
                    })
                session.commit()
                session.close()
        except Exception as e:
            from AppLog.logHelper import logDB
            logDB << AppUtils.toString(e)
        return RECODE_SUCCEED

    @classmethod
    def setPreviewCount(cls, chamber_number: int, row_number: int, tray_number: int, objective: int, previewcount: int):
        from AppSettings.SystemSetting import system_config
        ChamberNumber   : int
        RowNumber       : int
        ChamberNumber, RowNumber = system_config.getChamberNumbers(chamber_number, row_number)
        item: cls
        try:
            dbController.initEngine()
            with Session(dbController.Engine) as session:
                session.query(cls).filter(cls.ChamberGroupNumber == ChamberNumber, cls.ChamberRowNumber == RowNumber).update(
                    {
                        cls.PreviewCount    : abs(int(previewcount)) if isinstance(previewcount, (int, float)) else 0   ,
                        cls.TrayNumber      : tray_number                                                               ,
                        cls.ObjectiveLevel  : objective                                                                 ,
                    })
                session.commit()
                session.close()
        except Exception as e:
            from AppLog.logHelper import logDB
            logDB << AppUtils.toString(e)
        return RECODE_SUCCEED

    @classmethod
    def setSlideStatus(cls, chamber_number: int, row_number: int, enable: (int, bool)):
        from AppSettings.SystemSetting import SystemConfig
        ChamberNumber   : int
        RowNumber       : int
        _enable: int = 1 if isinstance(enable, (bool, int)) and enable else 0
        ChamberNumber, RowNumber = SystemConfig.getChamberNumbers(chamber_number, row_number)
        cls.changed({cls.RState: _enable, cls.LState: _enable}, *[cls.ChamberGroupNumber == ChamberNumber, cls.ChamberRowNumber == RowNumber])