<template>
    <SecondSheet>
        <div class='tolerance-curve'>
            <el-form label-width='auto' :inline='true'>
                <el-form-item label='生产线'>
                    <el-select v-model='form.productLineId'>
                        <el-option v-for='item in productLineOptions' :key='item.id' :label='item.name'
                            :value='item.id' />
                    </el-select>
                </el-form-item>
                <el-form-item label='终端'>
                    <el-select v-model='form.machineId' placeholder='暂无终端'>
                        <el-option v-for='item in machineOptions' :key='item.id' :label='item.name' :value='item.id' />
                    </el-select>
                </el-form-item>
                <el-form-item label='敏感元器件'>
                    <el-select v-model='form.unitId' placeholder='暂无元器件' @change="changeUnit" clearable>
                        <el-option v-for='item in unitOptions' :key='item.id' :label='item.name' :value='item.id' />
                    </el-select>
                </el-form-item>
            </el-form>
            <div style='display: flex; flex: 1'>
                <el-form label-width='auto' label-position='top'>
                    <!--                    <el-form-item label='耐受曲线'>-->
                    <!--                        <el-select v-model='form.name' placeholder='Select'>-->
                    <!--                            <el-option-->
                    <!--                                v-for='item in selectOptions'-->
                    <!--                                :key='item.value'-->
                    <!--                                :label='item.label'-->
                    <!--                                :value='item.value'-->
                    <!--                            />-->
                    <!--                        </el-select>-->
                    <!--                    </el-form-item>-->
                    <!--                    <el-form-item label='耐受能力（膝点坐标）'>-->
                    <!--                        <el-select v-model='form.name' placeholder='Select'>-->
                    <!--                            <el-option-->
                    <!--                                v-for='item in selectOptions'-->
                    <!--                                :key='item.value'-->
                    <!--                                :label='item.label'-->
                    <!--                                :value='item.value'-->
                    <!--                            />-->
                    <!--                        </el-select>-->
                    <!--                    </el-form-item>-->
                    <el-form-item label='上限曲线膝点'>
                        <div>
                            <div>
                                <el-input-number v-model='unit.vtcAmpUpper' controls-position='right'
                                    @change='reDrawPic' />
                                <span class='ml10' style='color: #333'>p.u.</span>
                            </div>
                            <div class='mt10'>
                                <el-input-number v-model='unit.vtcTimeUpper' controls-position='right'
                                    @change='reDrawPic' />
                                <span class='ml10' style='color: #333'>ms</span>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label='下限曲线膝点'>
                        <div>
                            <div>
                                <el-input-number v-model='unit.vtcAmpLower' controls-position='right'
                                    @change='reDrawPic' />
                                <span class='ml10' style='color: #333'>p.u.</span>
                            </div>
                            <div class='mt10'>
                                <el-input-number v-model='unit.vtcTimeLower' controls-position='right'
                                    @change='reDrawPic' />
                                <span class='ml10' style='color: #333'>ms</span>
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
                <div style='flex: 1' class='ml10'>
                    <MyEchart :options='options' v-if='options'></MyEchart>
                </div>
            </div>
        </div>
    </SecondSheet>
</template>

<script lang='ts' setup>
import SecondSheet from '@/components/secondSheet/index.vue'
import MyEchart from '@/components/echarts/MyEchart.vue'
import { reactive, ref } from 'vue'
import { querySgProductLineByUserId } from '@/api/advance-boot/sgGroven/sgProductLine'
import { ElMessage } from 'element-plus'
import { querySgMachineByProductLineId } from '@/api/advance-boot/sgGroven/sgMachine'
import { queryUnitByMachineId } from '@/api/advance-boot/sgGroven/sgSensitiveUnit'
import { getEventDataByProductLineId } from '@/api/advance-boot/sgGroven/sgEvent'


const searchBeginTime = ref()
const searchEndTime = ref()
const userId = ref()

const form = reactive({
    num: 1,
    productLineId: '',
    machineId: '',
    unitId: ''
})
const productLineOptions = ref()
const machineOptions = ref()
const unitOptions = ref()
const unit = ref({
    'vtcTimeUpper': 0,
    'vtcAmpUpper': 0,
    'vtcTimeLower': 0,
    'vtcAmpLower': 0
})
const overEvent = ref([])
const unOverEvent = ref([])
const unKnownEvent = ref([])
const overEventColor = ref('#A52a2a')
const unOverEventColor = ref('#61a0a8')
const unKnownEventColor = ref('#d48265')
const eventData = ref()
const search = async (id: string, beginTime: string, endTime: string) => {
    // 从父组件tableStore获取参数
    searchBeginTime.value = beginTime
    searchEndTime.value = endTime
    userId.value = id
    //根据用户id获取到生产线下拉框、再根据生产线下拉框获取生产线下的终端下拉，再根据终端获取下拉的敏感元器件的下拉
    await querySgProductLineByUserId(id).then((res: any) => {
        productLineOptions.value = res.data
        form.productLineId = productLineOptions.value[0].id
    })

    //根据生产线获取终端数据
    await querySgMachineByProductLineId(form.productLineId).then((res: any) => {
        machineOptions.value = res.data
        if (machineOptions.value.length > 0) {
            form.machineId = machineOptions.value[0].id
        }
    })

    //根据终端获取元器件数据
    await queryUnitByMachineId(form.machineId).then((res: any) => {
        unitOptions.value = res.data
        if (unitOptions.value.length > 0) {
            form.unitId = unitOptions.value[0].id
            unit.value = JSON.parse(JSON.stringify(unitOptions.value[0]))
        }

    })

    const data = {
        searchBeginTime: beginTime,
        searchEndTime: endTime,
        productId: form.productLineId
    }

    await getEventDataByProductLineId(data).then((res: any) => {
        eventData.value = res.data
        reDrawPic()
    })

}
const changeUnit = (id: any) => {
    if (id == undefined) return
    let list = unitOptions.value.filter((item: any) => item.id == id)
    unit.value = JSON.parse(JSON.stringify(list[0]))
    reDrawPic()

}

const options = ref()
const initOptions = () => {
    options.value = {
        legend: {
            data: ['越限事件', '未越限事件', '不确定事件'],

        },
        tooltip: {
            formatter: function (a: any) {
                if (a[0].value[3] == undefined) {
                    return
                }
                let relVal = ''
                relVal += '<font style=\'color:' + '\'>进线:' + '&nbsp' + '&nbsp' + a[0].value[3] + '</font><br/>'
                relVal += '<font style=\'color:' + '\'>发生时刻:' + '&nbsp' + '&nbsp' + a[0].value[2] + '</font><br/>'
                relVal += '<font style=\'color:' + '\'>持续时间:' + '&nbsp' + '&nbsp' + a[0].value[0].toFixed(2) + 's</font><br/>'
                relVal += '<font style=\'color:' + '\'>特征幅值:' + '&nbsp' + '&nbsp' + a[0].value[1] + 'p.u.</font>'
                return relVal
            }
        },
        xAxis: {
            name: '持续时间/s',
            type: 'log',
            min: '0.001',
            max: '1000',
            splitLine: { show: false }
        },
        yAxis: {
            name: '幅值/p.u.',
            max: 1,
            min: 0,
            splitLine: { show: false }
        },
        grid: {
            right: '78px',
        },
        series: [
            {
                type: 'line',
                color: '#ff0000',
                data: [
                    [unit.value.vtcTimeUpper / 1000, 0],
                    [unit.value.vtcTimeUpper / 1000, unit.value.vtcAmpUpper],
                    [1000, unit.value.vtcAmpUpper]
                ],
                showSymbol: false,
                tooltips: {
                    show: false
                }
            },
            {
                type: 'line',
                color: '#ff0000',
                data: [
                    [unit.value.vtcTimeLower / 1000, 0],
                    [unit.value.vtcTimeLower / 1000, unit.value.vtcAmpLower],
                    [1000, unit.value.vtcAmpLower]
                ],
                showSymbol: false,
                tooltips: {
                    show: false
                }
            },
            {
                name: '越限事件',
                type: 'scatter',
                symbol: 'circle',
                data: overEvent.value
            },
            {
                name: '未越限事件',
                type: 'scatter',
                symbol: 'circle',
                data: unOverEvent.value
            },
            {
                name: '不确定事件',
                type: 'scatter',
                symbol: 'circle',
                data: unKnownEvent.value
            }
        ],
        options: {
            dataZoom: null
        }
    }
}

const reDrawPic = () => {
    //清洗要显示的数据
    if (eventData.value.length > 0) {
        unOverEvent.value = []
        overEvent.value = []
        unKnownEvent.value = []
        for (let event of eventData.value) {
            //判断落在哪个区域内
            let eventTime = Number(event.duration) / 1000
            let eventAmplitude = Number(event.featureAmplitude)
            if (eventTime < Number(unit.value.vtcTimeUpper / 1000) || eventAmplitude > Number(unit.value.vtcAmpUpper)) {
                //未越限
                const dataTemp = {
                    value: [
                        eventTime,
                        eventAmplitude,
                        event.startTime,
                        event.incomingLineName
                    ],
                    itemStyle: {
                        normal: {
                            color: unOverEventColor.value
                        }
                    }
                }
                unOverEvent.value.push(dataTemp)
            } else if (eventTime > Number(unit.value.vtcTimeLower / 1000) && eventAmplitude < Number(unit.value.vtcAmpLower)) {
                //故障阶段
                const dataTemp = {
                    value: [
                        eventTime,
                        eventAmplitude,
                        event.startTime,
                        event.incomingLineName
                    ],
                    itemStyle: {
                        normal: {
                            color: overEventColor.value
                        }
                    }
                }
                overEvent.value.push(dataTemp)
            } else {
                //不确定事件
                const dataTemp = {
                    value: [
                        eventTime,
                        eventAmplitude,
                        event.startTime,
                        event.incomingLineName
                    ],
                    itemStyle: {
                        normal: {
                            color: unKnownEventColor.value
                        }
                    }
                }
                unKnownEvent.value.push(dataTemp)
            }


        }
    }
    //初始化图表
    initOptions()
}

defineExpose({ search })
</script>

<style lang='scss' scoped>
.tolerance-curve {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    height: 100%;
    overflow: hidden;
    padding: 10px;
    border: 1px solid var(--el-border-color);
}

.el-form-item__label-wrap {
    margin-left: 0 !important;
}

.el-form-item__content {
    width: 185px !important;
}
</style>
