#!D:/IDE/anaconda3/envs/Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@FileName：UpdateScanTemplateBusiness.py
@Description：
@Author：XSH
@Time：2025/12/2 17:49
@Department：研发部
@Copyright：©2025 乐辰生物
"""
from PyQt5 import Qt
from abc import abstractmethod, abstractclassmethod, abstractstaticmethod
from AppInterfaces.utils                    import *
from AppSettings.utils                      import *
from AppCore.Requests                       import *
from AppInterfaces.Interfaces               import *
from AppCore.Levels                         import *
from AppUtils.utils                         import *
from AppBackEnd.WebBusinessInterface import WebBusinessInterface
from AppCore.DBModels import ScanTemplate, Previewsettings, Collectsettings

class UpdateScanTemplateBusiness(Qt.QObject, WebBusinessInterface):
    def __init__(self, manager: WebReaderInterface = None, parent: Qt.QObject = None):
        super(UpdateScanTemplateBusiness, self).__init__(parent=parent)
        self.Manager = manager
        self.Initialization("UpdateScanTemplateBusiness", self, parent)

    def initWEBAPILevel(self):
        self.Level = WebAPILevel.updateTempLate



    def Done(self, handler: WebClientInterface, **args):
        isWrong: int = RECODE_FAILURE
        from AppCore.DBModels import ScanTemplate, Previewsettings, Collectsettings
        try:
            self.Handler = handler
            request = Request.APIInstance(self.Level)
            request.data['saveTemplate']    = False     #
            Preview : Previewsettings       = None      #
            Collect : Collectsettings       = None      #
            Template: ScanTemplate          = None      #
            data: dict[str, object] = kwargs.get('data', None)
            if isinstance(data, dict) and len(data) > 0:
                Template, Preview, Collect = self.saveTemplate(data)
                if isinstance(Template, ScanTemplate) and isinstance(Preview, Previewsettings) and isinstance(Collect, Collectsettings):
                    pass


            isWrong = self.WebSendFrame(request.toJson())
        except Exception as e:

            AppUtils.print_Exception(e)
        return
    def WaitDone(self, handler: WebClientInterface, **args) -> int:
        isWrong         : int = RECODE_FAILURE

        try:
            self.Handler = handler
            request     = Request.APIInstance(self.Level)
            request.data['saveTemplate']    = False     #
            Preview     : Previewsettings   = None      #
            Collect     : Collectsettings   = None      #
            Template    : ScanTemplate      = None      #
            data: dict[str, object] = args.get('data', None)
            if isinstance(data, dict) and len(data) > 0:
                Template, Preview, Collect = self.saveTemplate(data)
                if isinstance(Template, ScanTemplate) and isinstance(Preview, Previewsettings) and isinstance(Collect, Collectsettings):
                    try:
                        Preview_dict    : dict = Preview.to_field   (False)
                        Collect_dict    : dict = Collect.to_field   (False)
                        Template_dict   : dict = Template.to_field  (False)
                        Previewsettings.model_update(Preview_dict, Previewsettings.ID == Preview.ID)
                        Collectsettings.model_update(Collect_dict, Collectsettings.ID == Collect.ID)
                        ScanTemplate.model_update(Template_dict, ScanTemplate.ID == Template.ID)
                        request.data['saveTemplate'] = False
                    except Exception as e:
                        AppUtils.print_Exception(e)
                        request.data['saveTemplate'] = False


            isWrong = self.WebSendFrame(request.toJson())
        except Exception as e:
            AppUtils.print_Exception(e)
        return isWrong

    def saveTemplate(self, data: dict[str, object]) -> (ScanTemplate, Previewsettings, Collectsettings):
        """
        保存模板
        :param data:
        :return:
        """
        from AppCore.DBModels import ScanTemplate, Previewsettings, Collectsettings, TrayModel, TrayConfigModel
        Preview : Previewsettings = None
        Collect : Collectsettings = None
        Template: ScanTemplate    = None
        try:

            left                : int = AppConvert.ObjectConvert(data.get('left'                , None), int)
            top                 : int = AppConvert.ObjectConvert(data.get('top'                 , None), int)
            width               : int = AppConvert.ObjectConvert(data.get('width'               , None), int)
            height              : int = AppConvert.ObjectConvert(data.get('height'              , None), int)
            focus_point_row     : int = AppConvert.ObjectConvert(data.get('focus_point_row'     , None), int)
            focus_point_column  : int = AppConvert.ObjectConvert(data.get('focus_point_column'  , None), int)
            """如果范围错误 """
            if not isinstance(left, (int, float)) or not isinstance(top, (float, int)):
                return None, None, None
            if not isinstance(width, (int, float)) or not isinstance(height, (float, int)):
                return None, None, None
            if not isinstance(focus_point_row, (int, float)) or not isinstance(focus_point_column, (float, int)):
                return None, None, None
            Preview_fields: dict[str, object] = data.get('previewsettings', None)
            Collect_fields: dict[str, object] = data.get('collectsettings', None)
            if not isinstance(Preview_fields, dict) or not isinstance(Collect_fields, dict):
                return None, None, None
            if len(Preview_fields) <= 0 or len(Collect_fields) <= 0:
                return None, None, None
            Preview         = Previewsettings.instance(**Preview_fields)
            Collect         = Collectsettings.instance(**Collect_fields)
            """如果没有选择数据模型"""
            if not Preview.has_classifier:
                Preview.classifier = 'Aberration'
            if not Collect.has_classifier:
                Collect.classifier = 'Aberration'
            """数据模型不相同 退出"""
            if Preview.classifier != Collect.classifier:
                return None, None, None

            Template         = ScanTemplate()
            Template.as_field(data)
            Template.focus_point_column = focus_point_row       #
            Template.focus_point_row    = focus_point_column    #
            if not Template.has_ID :
                Template.collectsettings_ID = None
                Template.previewsettings_ID = None
                ScanTemplate.append_all([Template])
            if not Preview.has_ID:
                if Template.has_previewsettings_ID:
                    Preview.ID = Template.previewsettings_ID
                else:
                    Previewsettings.append_all([Preview])
                Template.previewsettings_ID = Preview.ID

            """如果没有ID字段"""
            if not Collect.has_ID:
                if Template.has_collectsettings_ID:
                    Collect.ID = Template.collectsettings_ID
                else:
                    Collectsettings.append_all([Collect])
                Template.collectsettings_ID = Collect.ID


            tray_model  : TrayModel = TrayModel.getConfig(ModuleLevel.ModuleTraySlide1)
            tray_model.UpdateMaxLocation()
            MinRowNumber: int = tray_model.MinRowNumber
            MinColNumber: int = tray_model.MinColNumber
            MaxRowNumber: int = tray_model.MaxRowNumber
            MaxColNumber: int = tray_model.MaxColNumber
            if Preview.isMicronucleus():
                MaxRowNumber: int = tray_model.MaxRowNumber20X
                MaxColNumber: int = tray_model.MaxColNumber20X
            left    = int(min(max(left, MinRowNumber), MaxRowNumber))
            top     = int(min(max(top, MinColNumber), MaxColNumber))
            width   = int(min(max(width, MinRowNumber), MaxRowNumber - left))
            height  = int(min(max(height, MinColNumber), MaxColNumber - top))
            Template.previewsettings_ID = Preview.ID
            Template.collectsettings_ID = Collect.ID
            Template.left               = left
            Template.top                = top
            Template.width              = width
            Template.height             = height
            ScanTemplate.changed(Template.to_field(False), ScanTemplate.ID == Template.ID)
        except Exception as e:
            AppUtils.print_Exception(e)
            Preview  = None
            Collect  = None
            Template = None
        return Template, Preview, Collect

    """
    
    
    
    
    """













