import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12
//import QtQml 2.12

import Components 1.0

import "file:recommendations.js" as REC


/*ПК ДК. СИП. ВК " Рекомендации КДК" */

GridLayout {
    id: root

    anchors.fill: parent
    columns: 5
    rows: 4
    rowSpacing: 15
    columnSpacing: 20

    property alias combobox_as: combobox_as
    property alias combobox_au: combobox_au
    property alias stack: ldr

    property int selected_codeAS //код типа выбранной АС
    property var selected_au //id выбранного АУ

    property var list_au: [
        {id: 1, name: 'АУ 1', file: REC.au1_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: true},
        {id: 2, name: 'АУ 2', file: REC.au2_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: true},
        {id: 3, name: 'АУ 3', file: REC.au3_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: true},
        {id: 4, name: 'АУ 4', file: REC.au4_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: true},
        {id: 5, name: 'АУ 5', file: REC.au5_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: true},
        {id: 6, name: 'АУ 6', file: REC.au6_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: true},
        {id: 7, name: 'АУ 7', file: REC.au7_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: true},
        {id: 8, name: 'АУ 8', file: REC.au8_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: true},
        {id: 9, name: 'АУ 9', file: REC.au9_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: false},
        {id: 10, name: 'АУ 10', file: REC.au10_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: false},
        {id: 11, name: 'АУ 11', file: REC.au11_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: false},
        {id: 12, name: 'АУ 12', file: REC.au12_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: false},
        {id: 13, name: 'АУ 13', file: REC.au13_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: false},
        {id: 14, name: 'АУ 14', file: REC.au14_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: false},
        {id: 15, name: 'АУ 15', file: REC.au15_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: false},
        {id: 16, name: 'АУ 16', file: REC.au16_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: false},
        {id: 17, name: 'АУ 17', file: REC.au17_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: false},
        {id: 18, name: 'АУ 18', file: REC.au18_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: false},
        {id: 19, name: 'АУ 19', file: REC.au19_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: false},
        {id: 20, name: 'АУ 20', file: REC.au20_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: false},
        {id: 21, name: 'АУ 21', file: REC.au21_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: false},

        {id: -1, name: 'БО', file: REC.bo_KDK, [Enums.EmergencyType.Fire]: false, [Enums.EmergencyType.Water]: true},
        {id: 100, name: 'ДО', file: REC.do_KDK, [Enums.EmergencyType.Fire]: true, [Enums.EmergencyType.Water]: false}
    ]

    //символьное значение выбранной АС
    property string selected_typeAS: {
        if (root.selected_codeAS === Enums.EmergencyType.Fire) return 'F'
        if (root.selected_codeAS === Enums.EmergencyType.Water) return 'W'
    }
    property var firstConfirmedAlarm: SIP_Data.listmodel_confirmedAS.firstConfirmedAlarm //первая подтвержденная авария

    Connections {
        target: SIP_Data.listmodel_confirmedAS
        function onModelUpdated(num_au, index)
        {
            if (visible)
                combobox_as.currentIndex = combobox_as.indexOfValue(firstConfirmedAlarm.type) !== -1? combobox_as.indexOfValue(firstConfirmedAlarm.type): 0
            setCurrentIndex()
        }
    }

    Connections {
        target: SIP_Data.listmodel_confirmedAS
        function modelCleared()
        {
            if (visible)
                combobox_as.currentIndex = 0
            combobox_au.currentIndex = 0
        }
    }

    function setCurrentIndex ()
    {
        for (let i = 0; i < SIP_Data.listmodel_confirmedAS.count; i++) {
            const alarm = SIP_Data.listmodel_confirmedAS.get(i);
            const type = alarm.type;

            if (root.selected_codeAS === type)
            {
                let idx = combobox_au.indexOfValue(alarm.au_num)
                combobox_au.currentIndex = idx !== -1 ? idx : 0
                return
            }
        }
    }

    property string selected_btn: '#Section1' //текущая информация

    //***** Поле вывода информации
    Item {
        id: area
        Layout.columnSpan: 4
        Layout.rowSpan: 3
        Layout.fillHeight: true
        Layout.fillWidth: true

        Loader {
            id: ldr
            anchors.fill: parent
            property var current_au: combobox_au.model[combobox_au.currentIndex]
            property string current_typeAS: selected_typeAS
            property var current_key: {
                switch(selected_btn) {
                case '#Section1': return {key: 'Рекомендации КДК', ref: "#Section1"}
                case '#Section2': return {key: 'Рекомендации КДК', ref: "#Section2"}
                case '#Section3': return {key: 'Рекомендации КДК', ref: "#Section3"}
                case '#Section4': return {key: 'Проведение доковых операций', ref: "#Section4"}
                default: return {key: '', ref: ""}
                }
            }
            sourceComponent: type1
        }
    }

    //*****Кнопки
    Rectangle {
        id: rect1
        Layout.column: 4
        Layout.row: 0
        Layout.rowSpan: 3
        Layout.preferredWidth: 220
        Layout.fillHeight: true
        color: 'transparent'
        border.color: Prop.color_button_frame
        function clearSectionButtonsFocus() // сброс фокуса кнопок при перемещении текста
        {
            for (let i = 0; i < contentRect1.children.length; ++i) {
                let btn = contentRect1.children[i];
                if (btn && typeof btn.forceActiveFocus === "function") {
                    btn.forceActiveFocus(false);
                }
            }
        }
        Column {
            id: contentRect1
            anchors.fill: parent
            anchors.margins: 10
            spacing: 5
            Binding {
                target: rect1
                property: "implicitHeight"
                value: contentRect1.childrenRect.height+contentRect1.anchors.margins*2
                delayed: true
            }
            ArialText {
                anchors.horizontalCenter: parent.horizontalCenter
                bottomPadding: 5
                text: 'Рекомендации КДК'
                font.bold: true
            }
            Repeater {
                id: sectionButtons
                model: [
                    {name: 'Первичные действия', ref: '#Section1'},
                    {name: 'Борьба с аварией', ref: '#Section2'},
                    {name: 'Ликвидация \n последствий аварии', ref: '#Section3'},
                    {name: 'Проведение \n доковых операций', ref: '#Section4'},
                ]
                WindowsButton {
                    anchors.left: parent.left
                    anchors.right: parent.right
                    height: 45
                    text: modelData.name
                    label.font.pixelSize: Prop.font3_pixel_size
                    back.gradient_color: (modelData.ref === root.selected_btn) && enabled?
                                             Prop.gradient.on: Prop.gradient.off
                    enabled: root.selected_au !== 0 && root.selected_au !== -1 && !modelData.disabled
                    onClicked: {
                        root.selected_btn = modelData.ref
                    }
                }
            }
        }
    }
    Rectangle {
        Layout.column: 0
        Layout.row: 3
        Layout.alignment: Qt.AlignBottom
        Layout.preferredWidth: 150
        Layout.preferredHeight: 90
        color: 'transparent'
        border.color: Prop.color_button_frame
        Column {
            anchors.fill: parent
            anchors.margins: 10
            spacing: 10
            ArialText {
                anchors.horizontalCenter: parent.horizontalCenter
                bottomPadding: 5
                text: 'Выбор АС'
                font.bold: true
            }
            ComboBox {
                id: combobox_as
                anchors.left: parent.left
                anchors.right: parent.right
                model: [
                    {name: 'Пожар', value: Enums.EmergencyType.Fire},
                    {name: 'Вода', value: Enums.EmergencyType.Water}, ]
                textRole: 'name'
                valueRole: 'value'
                displayText: currentText
                delegate: ItemDelegate {
                    width: combobox_as.width
                    contentItem:
                        Rectangle {
                        anchors.fill: parent
                        color: highlighted? Prop.color_back: Prop.color_off
                        ArialText {
                            anchors.fill: parent
                            horizontalAlignment: Text.AlignLeft
                            padding: 10
                            text: modelData.name
                            color: Prop.color_text
                            elide: Text.ElideRight
                            verticalAlignment: Text.AlignVCenter
                        }
                        focus: true
                    }
                    highlighted: combobox_as.highlightedIndex === index
                }
                background: Rectangle {
                    implicitWidth: 120
                    implicitHeight: 30
                    border.color: Prop.color_button_frame
                    radius: 2
                }
                contentItem: ArialText {
                    padding: 10
                    color: Prop.color_text
                    text: combobox_as.displayText
                    elide: Text.ElideRight
                    verticalAlignment: Text.AlignVCenter
                    horizontalAlignment: Text.AlignLeft
                }
                onCurrentIndexChanged: {
                    // Сохраняем текущий выбранный АУ
                    let previousSelectedAU = root.selected_au;

                    root.selected_codeAS = model[currentIndex].value

                    // Получаем текущую отфильтрованную модель для ComboBox АУ
                    let filteredModel = combobox_au.model

                    // Проверяем, существует ли предыдущий выбранный АУ в новой модели
                    let newIndex = filteredModel.findIndex(au => au.id === previousSelectedAU);

                    // Если предыдущий выбранный АУ существует, восстанавливаем его, иначе выбираем первый
                    if (newIndex !== -1)
                    {
                        combobox_au.currentIndex = newIndex;
                        root.selected_au = filteredModel[newIndex].id;
                    } else {
                        combobox_au.currentIndex = 0; // Выбираем первый элемент
                    }

                    root.setCurrentIndex()
                }
                onVisibleChanged: {
                    if (visible)
                    {
                        currentIndex = indexOfValue(root.firstConfirmedAlarm.type) !== -1?
                                    indexOfValue(root.firstConfirmedAlarm.type): 0
                    }
                }
                Component.onCompleted: {
                    currentIndex = indexOfValue(root.firstConfirmedAlarm.type) !== -1?
                                indexOfValue(root.firstConfirmedAlarm.type): 0
                }
            }
        }
    }
    Rectangle {
        Layout.column: 1
        Layout.row: 3
        Layout.columnSpan: 2
        Layout.alignment: Qt.AlignBottom
        Layout.preferredWidth: 150
        Layout.preferredHeight: 90
        color: 'transparent'
        border.color: Prop.color_button_frame
        Column {
            anchors.fill: parent
            anchors.margins: 10
            spacing: 10
            ArialText {
                anchors.horizontalCenter: parent.horizontalCenter
                bottomPadding: 5
                text: 'Выбор АУ'
                font.bold: true
            }
            ComboBox {
                id: combobox_au
                anchors.left: parent.left
                anchors.right: parent.right
                model: filtered_au_list
                property var filtered_au_list: list_au.filter(function(au) {
                    return au[root.selected_codeAS];
                })
                textRole: 'name'
                valueRole: 'id'
                delegate: ItemDelegate {
                    width: combobox_au.width
                    contentItem:
                        Rectangle {
                        anchors.fill: parent
                        color: highlighted? Prop.color_back: Prop.color_off
                        ArialText {
                            anchors.fill: parent
                            horizontalAlignment: Text.AlignLeft
                            padding: 10
                            text: modelData.name
                            color: Prop.color_text
                            elide: Text.ElideRight
                            verticalAlignment: Text.AlignVCenter
                            opacity: enabled? 1: 0.6
                        }
                        focus: true
                    }
                    highlighted: combobox_au.highlightedIndex === index
                }
                background: Rectangle {
                    implicitWidth: 120
                    implicitHeight: 30
                    border.color: Prop.color_button_frame
                    radius: 2
                }
                contentItem: ArialText {
                    padding: 10
                    color: Prop.color_text
                    text: combobox_au.displayText
                    elide: Text.ElideRight
                    verticalAlignment: Text.AlignVCenter
                    horizontalAlignment: Text.AlignLeft
                }
                onCurrentValueChanged: {
                    root.selected_au = currentValue
                }
                onVisibleChanged: {
                    if (visible)
                    {
                        var idx = indexOfValue(root.firstConfirmedAlarm.au_num)
                        currentIndex = idx !== -1 ? idx : 0
                    }
                }
                Component.onCompleted: {
                    var idx = indexOfValue(root.firstConfirmedAlarm.au_num)
                    currentIndex = idx !== -1 ? idx : 0
                }
            }
        }
    }
    Item {
        Layout.column: 3
        Layout.row: 3
        Layout.fillWidth: true
    }


    //---------------------------------------
    //       Компоненты
    //---------------------------------------

    //Рекомендации КДК
    Component {
        id: type1
        Rectangle {
            id: mainRec
            color: 'transparent'
            border.color: Prop.color_button_frame

            property var au: current_au
            property var typeAS: current_typeAS
            property string key: current_key.key
            property string ref: current_key.ref
            property string prevRef: ""

            onAuChanged: flickable.loadContent()
            onTypeASChanged: flickable.loadContent()
            onRefChanged: {
                if (ref === "#Section4" || prevRef === "#Section4")
                {
                    flickable.loadContent();
                }
                prevRef = ref;

                if (!flickable.scrollingTextChange)
                    flickable.scrollToSection()
                flickable.scrollingTextChange = false;
            }

            ColumnLayout {
                anchors.fill: parent
                ArialText {
                    Layout.topMargin: 5
                    Layout.alignment: Qt.AlignHCenter | Qt.AlignTop
                    Layout.fillWidth: true
                    font.pixelSize: 20
                    font.bold: true
                    text: key !== "Проведение доковых операций"? `${key} для ${au.name}`: `${key}`
                }

                Flickable {
                    id: flickable
                    Layout.margins: 1
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    contentHeight: columnText.implicitHeight // Автоматическая высота контента
                    clip: true

                    property real lastCheckedContentY: -1
                    property int contentYDelta: 20
                    property bool scrollingTextChange: false
                    property bool scrollToSectionChange: false

                    onContentYChanged: {
                        // Вызываем только если прокручено заметно
                        if (Math.abs(contentY - lastCheckedContentY) > contentYDelta)
                        {
                            lastCheckedContentY = contentY;
                            if (!scrollToSectionChange)
                                detectSectionByTop();
                            scrollToSectionChange = false;
                        }
                    }

                    function detectSectionByTop()
                    {
                        if (root.selected_btn === "#Section4")
                            return;

                        // Верхняя граница видимой области:
                        var topY = contentY;

                        // Начала каждого TextArea в контейнере
                        var section1Top = columnText.y; // Это всегда 0 относительно Flickable
                        var section2Top = section1Top + textArea1.y + textArea1.height;
                        var section3Top = section2Top + textArea2.height;

                        var newSection = root.selected_btn;

                        // Логика: если верх прокрутки >= начала раздела и < начала следующего - это этот раздел.
                        if (topY < section2Top - 1) { // -1 чтобы избежать "дребезга" на граничных значениях
                            newSection = "#Section1";
                        } else if (topY < section3Top - 20) {
                            newSection = "#Section2";
                        } else {
                            newSection = "#Section3";
                        }

                        // Явная проверка: если прокручено до самого низа — всегда #Section3
                        if (contentY >= (contentHeight - height - 20)) {
                            newSection = "#Section3";
                        }

                        // Переключаем только если изменилось
                        if (root.selected_btn !== newSection) {
                            scrollingTextChange = true;
                            root.selected_btn = newSection;
                            rect1.clearSectionButtonsFocus();
                        }
                    }

                    function loadContent()
                    {
                        //console.log("loadContent", au.name)
                        if (au.id === -1) {
                            selected_btn = '#Section1'
                        }

                        if (selected_btn !== '#Section4') {
                            if (!flickable.scrollingTextChange)
                                scrollToSectionChange = true;
                            textArea1.text = au.file[current_typeAS][1]
                            textArea2.text = au.file[current_typeAS][2]
                            textArea3.text = au.file[current_typeAS][3]
                            if (!flickable.scrollingTextChange)
                                scrollToSection()
                        }
                        else {
                            textArea1.text = au.file[current_typeAS][4]
                            textArea2.text = '';
                            textArea3.text = '';
                            flickable.contentY = 0;
                            scrollToSectionChange = true;
                        }

                        flickable.scrollingTextChange = false;
                    }
                    function scrollToSection()
                    {
                        //console.log("scrollToSection")
                        if (!visible)
                            return;
                        switch(selected_btn) {
                        case '#Section1': flickable.contentY = 0;
                            break;
                        case '#Section2': flickable.contentY = columnText.y + textArea1.height;
                            break;
                        case '#Section3':
                            if (textArea3.height < flickable.height) {
                                flickable.contentY = textArea1.height + textArea2.height + textArea3.height - flickable.height;
                            }
                            else {
                                flickable.contentY = columnText.y + textArea1.height + textArea2.height;
                            }
                            break;
                        case '#Section4': flickable.contentY = 0;
                            break;
                        }
                    }

                    Column {
                        width: flickable.width
                        spacing: -1
                        id: columnText
                        TextArea {
                            id: textArea1
                            width: parent.width
                            wrapMode: TextArea.Wrap
                            textFormat: TextEdit.RichText
                            textMargin: 10
                            font.family: Prop.font
                            font.pixelSize: 18
                            color: Prop.color_text
                            readOnly: true
                            selectByMouse: true
                            text: ''
                            rightPadding: vbar.width + 2
                            topPadding: 0
                            bottomPadding: 0

                            onLinkActivated: function(link) {
                                root.selected_btn = link
                            }

                            MouseArea {
                                anchors.fill: parent
                                acceptedButtons: Qt.NoButton
                                cursorShape: parent.hoveredLink ? Qt.PointingHandCursor : Qt.IBeamCursor
                            }
                        }
                        TextArea {
                            id: textArea2
                            width: parent.width
                            wrapMode: TextArea.Wrap
                            textFormat: TextEdit.RichText
                            textMargin: 10
                            font.family: Prop.font
                            font.pixelSize: 18
                            color: Prop.color_text
                            readOnly: true
                            selectByMouse: true
                            text: ''
                            rightPadding: vbar.width + 2
                            topPadding: -textMargin
                            bottomPadding: 0

                            onLinkActivated: function(link) {
                                root.selected_btn = link
                            }

                            MouseArea {
                                anchors.fill: parent
                                acceptedButtons: Qt.NoButton
                                cursorShape: parent.hoveredLink ? Qt.PointingHandCursor : Qt.IBeamCursor
                            }
                        }

                        TextArea {
                            id: textArea3
                            width: parent.width
                            wrapMode: TextArea.Wrap
                            textFormat: TextEdit.RichText
                            textMargin: 10
                            font.family: Prop.font
                            font.pixelSize: 18
                            color: Prop.color_text
                            readOnly: true
                            selectByMouse: true
                            text: ''
                            rightPadding: vbar.width + 2
                            topPadding: -textMargin
                            bottomPadding: textMargin

                            onLinkActivated: function(link) {
                                root.selected_btn = link
                            }

                            MouseArea {
                                anchors.fill: parent
                                acceptedButtons: Qt.NoButton
                                cursorShape: parent.hoveredLink ? Qt.PointingHandCursor : Qt.IBeamCursor
                            }
                        }
                    }

                    ScrollBar.vertical: ScrollBarV {id: vbar}
                }
            }
        }
    }
    // Получение настроек отображения для передачи на ЭКП
    property var getSettings: () => {
                                  let obj = {}
                                  if (root.visible)
                                  {
                                      obj["Рек КДК"] = {}
                                      obj["Рек КДК"]["combobox_as-currentIndex"] = combobox_as.currentIndex
                                      obj["Рек КДК"]["combobox_au-currentIndex"] = combobox_au.currentIndex
                                      obj["Рек КДК"]["selected_btn"] = selected_btn
                                  }
                                  return obj
                              }
}
что улучшить ?