<script setup lang="ts">
import { ref, onMounted, reactive, nextTick,computed } from 'vue'
import MarkdownIt from 'markdown-it'
import DOMPurify from 'dompurify'
import Page from '@/components/Pagination/page.vue'
import { ElMessageBox, ElMessage, ElTable, FormRules, ElTree } from 'element-plus'
import { getDeviceByType } from '@/api/device'
import Eldialog from '@/components/seccmsdialog/eldialog.vue'
import { useUserStore } from '@/store/modules/user';
import * as echarts from 'echarts'
import { getAlgorithmClassTree, getAlgorithmDeviceParams, getAlgorithmDeviceCurve, getAlgorithmParamsNameList, callAlgorithmAnalyse } from '@/api/question';
import { fa } from 'element-plus/es/locale'
import axios from 'axios';
const userStore = useUserStore();//pythonUrl
//树形控件类型定义
interface Tree {
    [x: string]: any;
    label: string;
    children?: Tree[];
}
const vMove = {
    mounted(el: any) {
        el.onmousedown = function (e: any) {
            var init = e.clientX;
            var parent: any = document.getElementById("silderLeft");
            const initWidth: any = parent.offsetWidth;
            document.onmousemove = function (e) {
                var end = e.clientX;
                var newWidth = end - init + initWidth;
                parent.style.width = newWidth + "px";
            };
            document.onmouseup = function () {
                document.onmousemove = document.onmouseup = null;
            };
        };
    }
}
// 创建计算属性处理文本
const md = new MarkdownIt()
const processedActionData = computed(() => {
  return md.render(DOMPurify.sanitize(actionData.value))
})
const defaultProps = { label: "name" };
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeData: any = ref([])
const treeloading = ref(false)
onMounted(() => {
    init()
})
const algorithmClassName = ref('')
const algorithmId = ref('')
const componentId = ref('')
function init() {
    const params = {
        algorithmClassName: algorithmClassName.value,
        stationCode: userStore.stationCode
    }
    treeloading.value = true
    getAlgorithmClassTree(params).then((res: any) => {
        if (res.data.length !== 0 && res.data !== null) {
            treeData.value = res.data
            treeloading.value = false
            if (res.data.length !== 0 && res.data !== null) {
                componentId.value = res.data[0].children[0].id
                algorithmId.value = res.data[0].children[0].parentId

                nextTick(() => {
                    treeRef.value?.setCurrentKey(componentId.value);
                });
                gatdata()
                getecharts()
                getfenList()
            }
        }
    })
}
const comainName = ref('')
function handleNodeClick(data: any, node: any) {
    if (data.children.length != 0) {
        node.isCurrent = false
        nextTick(() => {
            treeRef.value?.setCurrentKey(componentId.value);
        })
    } else {
        // console.log(data)
        componentId.value = data.id
        algorithmId.value = data.parentId
    
        gatdata()
        getecharts()
        getfenList()
        canshuList.value = ''
    }
}
const parameter: any = ref([])
function gatdata() {
    fixloading.value = true
    getAlgorithmDeviceParams({ algorithmId: algorithmId.value, componentId: componentId.value }).then((res: any) => {
        parameter.value = res.data
        fixloading.value = false
    })
}
//echarts
const eacherslist: any = ref([1, 2, 3, 4])
function getecharts() {
    checloading.value = true
    getAlgorithmDeviceCurve({ algorithmId: algorithmId.value, componentId: componentId.value }).then((res: any) => {
        checloading.value = false
        eacherslist.value = res.data
        setTimeout(() => {
            eacherslist.value.forEach((item: any, index: any) => {
                drawEchart(item, index)
            })
        }, 100);

    })
}
function getRandomColor(): string {
    const hue = Math.floor(Math.random() * 360); // 色相 0~359
    const saturation = 70 + Math.floor(Math.random() * 20); // 饱和度 70~90%
    const lightness = 50 + Math.floor(Math.random() * 10); // 亮度 50~60%

    return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
}
function drawEchart(item: any, index: any) {
    // 生成随机颜色
    const randomColor = getRandomColor();

    let myChart = echarts.init(document.getElementById("deviceEachers" + index) as HTMLDivElement);
    myChart.setOption({
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: [item.series[0].name],
            textStyle: { color: randomColor, fontSize: 14 }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '18%',
            containLabel: true,
            borderColor: randomColor
        },
        xAxis: item.xAxis,
        yAxis: item.yAxis,
        series: item.series.map((series: any) => ({
            ...series,
            itemStyle: { color: randomColor }
        }))
    });
}
//fenxi
const checloading = ref(false)
const fixloading = ref(false)
const fenloading = ref(false)
const fenList: any = ref([])
function getfenList() {
    fenloading.value = true
    getAlgorithmParamsNameList({ algorithmId: algorithmId.value, componentId: componentId.value }).then((res: any) => {
        fenList.value = res.data
        fenloading.value = false
    })

}
const canshuList: any = ref()
const mapList: any = ref()
function analysis() {
    fenloading.value = true
    callAlgorithmAnalyse({ id: algorithmId.value, componentId: componentId.value }).then((res: any) => {
        fenloading.value = false
        if (res.data.code == -2) {
            ElMessage.warning(res.data.msg)
        } else {
            ElMessage.success('分析成功')
            comainName.value = res.data.desc
            mapList.value = res.data.mapList
            canshuList.value = res.data.result.description
            getovercanshu()
            getaction()
        }


    })
}
function getovercanshu() {
    mapList.value.forEach((item: any) => {
        fenList.value.forEach((items: any) => {
            if (item.paramId == items.id) {
                items.paramValue = item.paramValue
            }
        })
    })
}
//故障分析
const fault = ref(false)
function fenfault() {
    fault.value = true
    canshuList.value = ''
    actionData.value = ''
    gatdata()
    analysis()
    actionloading.value = true
}
//生成处理方案

const actionData = ref('')
const actionloading = ref(false)
function getaction() {
    
    axios.get(userStore.pythonUrl + '/application/' + userStore.application_id + '/chat/open', {
        headers: {
            'AUTHORIZATION': 'application-2f942bee58ee12591b4a47deebd5b71b'
        }
    }).then((res: any) => {
        const object = ref(
            {
                message: comainName.value  + canshuList.value,
                re_chat: false,
                stream: false,
            }
        )
        axios.post(userStore.pythonUrl + '/application/chat_message/' + res.data.data, object.value, {
            headers: {
                'AUTHORIZATION': 'application-2f942bee58ee12591b4a47deebd5b71b'
            }
        }).then((res: any) => {
            actionloading.value = false
            actionData.value = res.data.data.content
            // console.log(res.data)
        })
    })
}
</script>
<template>
    <div class="faulttemplate-box">
        <aside id="silderLeft">
            <div class="tree_title">
                <img src="@/assets/navigation/ty_bq.png" alt="">
                <div>算法分类</div>
            </div>
            <el-input v-model="algorithmClassName" clearable placeholder="请输入名称" @change="init"
                style="width:100%;margin-top: 10px;" class="videomonitor-input">
                <template #suffix>
                    <img src="@/assets/videoimg/u2937.png" style="cursor:pointer ;" @click="init">
                </template>
            </el-input>
            <el-tree v-loading="treeloading" ref="treeRef" node-key="id" :data="treeData" :highlight-current="true"
                :props="defaultProps" :expand-on-click-node="false" @node-click="handleNodeClick"
                style="height: calc(80vh); overflow: auto;margin-top: 10px;">
            </el-tree>
            <div class="moveBtn" v-move>
                <div class="moveBtn-line"></div>
            </div>
        </aside>
        <section class="silderRight1">
            <div class="right_center" v-loading="checloading"
                :style="parameter.length > 0 ? 'height: 77vh;' : 'height: 90vh;margin-bottom:0px;'">
                <div style="display: flex;justify-content: space-between;align-items: center;">
                    <div class="tree_title">
                        <img src="@/assets/navigation/ty_bq.png" alt="">
                        <div>信号/点位折线图</div>
                    </div>
                    <el-button style="margin-left: 10px;" @click="fenfault()" class="searchButton">故障分析</el-button>
                </div>

                <el-scrollbar :height="parameter.length > 0 ? '70vh' : '85vh'">
                    <div class="echarts_box">
                        <div v-for="(item, index) in eacherslist" :id="'deviceEachers' + index"
                            :style="{ width: '100%', height: '160px' }"></div>
                    </div>
                </el-scrollbar>
            </div>
            <div class="right_yop" v-loading="fixloading" v-if="parameter.length > 0">
                <div class="tree_title">
                    <img src="@/assets/navigation/ty_bq.png" alt="">
                    <div>固定参数</div>
                </div>
                <el-scrollbar height="60px">
                    <div class="fixed_params">
                        <div v-for="item in parameter" class="fixed_params_item">
                            <div>{{ item.paramName }}：<span>{{ item.paramValue }}</span></div>
                        </div>
                    </div>
                </el-scrollbar>
            </div>
        </section>
        <Eldialog v-model="fault" :close-on-click-modal="false" @before-close="fault = false" :title="'故障分析'"
            append-to-body width="1100px" draggable>
            <template v-slot:PopFrameContent>
                <div class="tree_title" style="padding: 5px 0px ;">
                    <img src="@/assets/navigation/ty_bq.png" alt="">
                    <div>参数详情</div>
                </div>
                <div class="fixed_params" style="margin-bottom: 15px;">
                    <div v-for="item in fenList" class="fixed_params_item">
                        <div>{{ item.paramName }}：<span>{{ item.paramValue ? item.paramValue : '--' }}</span></div>
                    </div>
                </div>
                <div class="tree_title" style="padding: 5px 0px ;">
                    <img src="@/assets/navigation/ty_bq.png" alt="">
                    <div>分析结果</div>
                </div>
                <div class="fixed_params right_botom" style="margin-bottom: 15px;">{{ comainName  }}<span>{{
                    canshuList ? canshuList : '--' }}</span></div>
                <div class="tree_title" style="padding: 5px 0px ;">
                    <img src="@/assets/navigation/ty_bq.png" alt="">
                    <div>处理方案</div>
                </div>
                <div>
                    <el-scrollbar height="400px" v-loading="actionloading" style="margin-top: 10px;">
                        <div v-if="actionData" v-html="processedActionData" ></div>
                    </el-scrollbar>
                </div>
            </template>
        </Eldialog>
    </div>
</template>

<style scoped lang="scss">
.silderLeft-default {
    :deep(.el-tree-node__label) {
        font-size: 16px !important;
    }
}

.faulttemplate-box {
    height: 100%;
    display: flex;
    display: -webkit-flex;
    background-color: #f2f4f900;
    padding: 15px 15px 0px 15px;

}

.tree_title {
    width: 100%;
    display: flex;
    align-items: center;
    font-size: 16px;
    color: #fff;
    font-weight: bold;


    img {
        margin-right: 10px;
    }
}

#silderLeft {
    width: 300px;
    padding: 10px;
    box-sizing: border-box;
    border-radius: 3px;
    position: relative;
    background: url(@/assets/navigation/ty_260x988.png);
    background-size: 100% 100%;

    &:hover {
        .moveBtn {
            opacity: 1;
        }
    }


}
:deep(.el-scrollbar__view) {
  color: #e6e6e6;
  line-height: 1.8;
  padding: 15px;
  
  h3 {
    color: #409EFF;
    margin: 20px 0 10px;
    font-size: 18px;
    border-left: 4px solid #67C23A;
    padding-left: 10px;
  }

  strong {
    color: #E6A23C;
  }

  ul {
    list-style: square inside;
    margin: 10px 0;
    
    li {
      margin: 8px 0;
    }
  }

  hr {
    margin: 20px 0;
    border: 0;
    border-top: 1px solid #606266;
  }
}
/* 拖动条 */
.moveBtn {
    height: 100%;
    width: 15px;
    padding: 0 6px;
    opacity: 0;
    position: absolute;
    right: -15px;
    top: 0;
}

.moveBtn-line {
    width: 100%;
    height: 100%;
    cursor: col-resize;
    user-select: none;
    background-color: #60bfff;
}

.fixed_params {
    width: 100%;
    display: flex;
    align-items: center;
    font-family: 'Arial Normal', 'Arial';
    font-weight: 400;
    color: #FFFFFF;
    font-size: 14px;

    .fixed_params_item {
        margin-right: 10px;

        span {
            font-family: 'Arial Negreta', 'Arial Normal', 'Arial';
            font-weight: 700;
            font-size: 18px;
            color: #00FFFF
        }
    }
}

.right_botom {
    width: 100%;
    font-family: 'Arial Normal', 'Arial';
    font-weight: 700;
    font-style: normal;
    font-size: 24px;
    color: #FFFFFF;

    span {
        font-family: 'Arial Negreta', 'Arial Normal', 'Arial';
        font-weight: 700;
        font-style: normal;
        font-size: 24px;
        letter-spacing: normal;
        color: #009900;
    }
}

.silderRight1 {
    flex: 1;
    width: 100%;
    height: calc(90vh);
    overflow: auto;
    border-radius: 3px;
    box-sizing: border-box;
    margin-left: 15px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;

    .right_yop {
        width: 100%;
        height: 110px;
        box-sizing: border-box;
        padding: 15px;
        background: url(@/assets/navigation/110tu.png);
        background-size: 100% 100%;

        // margin-bottom: 15px;
        :deep(.el-scrollbar) {
            height: auto !important;
        }


    }

    .right_center {
        width: 100%;
        height: calc(77vh);
        margin-bottom: 15px;
        box-sizing: border-box;
        padding: 15px;
        background: url(@/assets/navigation/sw1.png);
        background-size: 100% 100%;

        :deep(.el-scrollbar) {
            height: auto !important;
        }

        .echarts_box {
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-top: 10px;
        }
    }

    .right_bottom {
        width: 100%;
        height: 220px;
        box-sizing: border-box;
        padding: 15px;
        background: url(@/assets/navigation/sw.png);
        background-size: 100% 100%;





        :deep(.el-scrollbar) {
            height: 80px !important;
        }
    }

}
</style>