<style lang="scss" scoped>
.layout_head {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30px;
}

.layout_card {
    display: flex;
    width: 100%;
    height: 11vh;
    margin-bottom: 30px;
    justify-content: space-between;
}

.layout_card_item {
    margin-top: 20px;
}

.el-card__body {
    display: flex;
}

.card_text {
    font-size: 12px;

    .text_num {
        font-size: 16px;
        font-weight: bold;
        padding: 5px 0;
    }
}

.card_round {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.card_head {
    width: 100%;
    height: 32px;
    display: flex;
    justify-content: space-between;
}

.echarts {
    width: 100%;
    height: calc(100% - 32px);
    margin: 10px 0;
}

.card_title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
}

.export_content {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
}

.export_subtitle {
    font-size: 14px;
    padding-bottom: 10px;
}
.layout_title {
    font-size: 18px;
    font-weight: bold;
}
</style>
<template>
    <div>
        <div class="layout_head">
            <span class="layout_title">健康数据记录</span>
            <div>
                <el-input type="hidden" />
                <el-button icon="UserFilled">何悦琳</el-button>
                <el-button style="margin-right: 10px;" round>25岁</el-button>
                <el-date-picker style="margin-right: 50px;" v-model="dateRange" type="daterange" range-separator="-"
                    :clearable="false" :disabled-date="disabledDayRange" start-placeholder="开始日期" end-placeholder="结束日期"
                    size="default" @change="handleDateChange" />
                <el-button type="primary" @click="handleBack">返回</el-button>
            </div>
        </div>
        <div class="layout_card">
            <el-card v-for="(item, index) in cardArr" :key="index" body-class="card_item"
                :style="{ background: item.background, width: '22%' }"
                body-style="display: flex; justify-content: space-between;">
                <div class="card_text">
                    <div>{{ item.title }}</div>
                    <div class="text_num">{{ item.value }}</div>
                    <div>{{ item.text }}</div>
                </div>
                <div class="card_round" :style="{ background: item.round }">
                    <img :src="item.url" alt="">
                </div>
            </el-card>
        </div>
        <el-scrollbar height="54vh" wrap-class="scrollbar">
            <el-card class="echarts_card" body-style="height: 40vh;">
                <div class="card_head">
                    <div class="card_title">健康数据趋势</div>
                    <div>
                        <el-button :type="activeTab === 1 ? 'primary' : ''" @click="handleTab(1)">血压</el-button>
                        <el-button :type="activeTab === 2 ? 'primary' : ''" @click="handleTab(2)">血氧</el-button>
                        <el-button :type="activeTab === 3 ? 'primary' : ''" @click="handleTab(3)">心率</el-button>
                        <el-button :type="activeTab === 4 ? 'primary' : ''" @click="handleTab(4)">体温</el-button>
                    </div>
                </div>
                <div class="echarts" ref="chart"></div>
            </el-card>
            <el-card class="layout_card_item" body-style="height: 40vh;">
                <div>
                    <div class="card_title">历史记录</div>
                    <el-table class="table-container" v-loading="tableLoading" ref="tableRef" :data="tableData" border
                        :height="tableHeight" width="100%">
                        <el-table-column label="序号" type="index" align="center" width="120" fixed="left" />
                        <el-table-column prop="A8" label="监测时间" align="center" min-width="120" show-overflow-tooltip />
                        <el-table-column prop="A9" label="血压(MMHG)" align="center" min-width="90" show-overflow-tooltip>
                            <template #default="scope">
                                <span v-if="isBloodPressureNormal(scope.row.A9)">{{ scope.row.A9 }}</span>
                                <span style="color: red" v-else>{{ scope.row.A9 }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="A10" label="血氧(%)" align="center" min-width="70" show-overflow-tooltip>
                            <template #default="scope">
                                <span v-if="scope.row.A10 >= 85">{{ scope.row.A10 }}</span>
                                <span style="color: red" v-else>{{ scope.row.A10 }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="A11" label="心率(BPM)" align="center" min-width="80" show-overflow-tooltip>
                            <template #default="scope">
                                <span v-if="scope.row.A11 <= 100 && scope.row.A11 >= 60">{{ scope.row.A11 }}</span>
                                <span style="color: red" v-else>{{ scope.row.A11 }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="A12" label="体温(℃)" align="center" min-width="70" show-overflow-tooltip>
                            <template #default="scope">
                                <span v-if="scope.row.A12 >= 36.1 && scope.row.A12 <= 37.2">{{ scope.row.A12 }}</span>
                                <span style="color: red" v-else>{{ scope.row.A12 }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="A13" label="健康状态" align="center" min-width="80" show-overflow-tooltip>
                            <template #default="scope">
                                <el-tag round type='success' effect="dark" v-if="scope.row.A13 === '正常'">{{
                                    scope.row.A13 }}</el-tag>
                                <el-tag round type='warning' effect="dark" v-else-if="scope.row.A13 === '轻度异常'">{{
                                    scope.row.A13 }}</el-tag>
                                <el-tag round type='danger' effect="dark" v-else-if="scope.row.A13 === '严重异常'">{{
                                    scope.row.A13 }}</el-tag>
                                <el-tag round type='info' effect="dark" v-else>{{ scope.row.A13 }}</el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination class="layout-pagination" :current-page="currentPage" :page-size="pageSize"
                        :page-sizes="pageSizes" :size="size" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next, jumper" :total="tableData.length"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
            </el-card>
            <el-card class="layout_card_item" body-style="height: 20vh;">
                <div>
                    <div class="card_title">数据导出</div>
                    <div class="export_content">
                        <div style="width: 26%;">
                            <div style="margin-bottom: 10px;">
                                <div class="export_subtitle">选择时间范围</div>
                                <el-radio-group v-model="radio" @change="radioChange">
                                    <el-radio-button label="最近一周" value="1" />
                                    <el-radio-button label="最近一月" value="2" />
                                    <el-radio-button label="自定义" value="3" />
                                </el-radio-group>
                            </div>
                            <el-input type="hidden" />
                            <el-date-picker v-if="showDateRange2" style="margin-right: 50px;" v-model="dateRange2"
                                type="daterange" range-separator="-" :clearable="false"
                                :disabled-date="disabledDayRange" start-placeholder="开始日期" end-placeholder="结束日期"
                                size="default" @change="handleDateChange2" />
                        </div>
                        <div>
                            <div class="export_subtitle">选择数据项</div>
                            <el-checkbox-group v-model="checkboxGroup">
                                <el-checkbox-button v-for="city in cities" :key="city" :value="city">
                                    {{ city }}
                                </el-checkbox-button>
                            </el-checkbox-group>
                        </div>
                        <div>
                            <div class="export_subtitle">导出格式</div>
                            <el-button type="primary" icon="Document">PDF</el-button>
                            <el-button type="success" icon="DocumentDelete">Excel</el-button>
                        </div>
                    </div>
                </div>
            </el-card>
        </el-scrollbar>
    </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, onMounted } from 'vue'
const emit = defineEmits(['close'])

const handleBack = () => {
    emit('close')
}
import { disabledDayRange } from '@/utils/disabledDate'
import formatDate from '@/utils/formatDate'
const dateRange = ref([formatDate(new Date().getTime() - 6 * 24 * 60 * 60 * 1000, 'YYYY-MM-DD'), formatDate(new Date(), 'YYYY-MM-DD')])

import BLOODPRESSURE from '@/assets/images/pages/blood_pressure.png'
import BLOODOXYGEN from '@/assets/images/pages/blood_oxygen.png'
import HEARTRATE from '@/assets/images/pages/heart_rate.png'
import BODYTEMPERATURE from '@/assets/images/pages/body_temperature.png'

const cardArr = [
    { title: '平均血压', value: '145/95 mmHG', text: '正常范围：90-140/60-90mmHG', url: BLOODPRESSURE, background: '#fff', round: '#bbc8ef' },
    { title: '平均血氧', value: '98 %', text: '正常范围：95-100%', url: BLOODOXYGEN, background: '#fff', round: '#b4e9e2' },
    { title: '平均心率', value: '72 BPM', text: '正常范围：60-100BPM', url: HEARTRATE, background: '#fff', round: '#ffcc8d' },
    { title: '平均体温', value: '36.5 ℃', text: '正常范围：36.1-37.2℃', url: BODYTEMPERATURE, background: '#fff', round: '#ccc6fb' },
]

const chart = ref(null)
const chartData1 = ref([])
const chartData12 = ref([])
const chartData2 = ref([])
const chartData3 = ref([])
const chartData4 = ref([])

const generateBloodPressure = () => {
    const low = Math.floor(Math.random() * 51) + 50
    const highMin = Math.max(80, low)
    const high = Math.floor(Math.random() * (150 - highMin + 1)) + highMin
    return `${high}`
}

const generateBloodPressure2 = () => {
    const low = Math.floor(Math.random() * 51) + 50
    return `${low}`
}

const getDate = (startTime, endTime) => {
    const start = new Date(startTime)
    const end = new Date(endTime)
    const dateArr = []
    while (start <= end) {
        dateArr.push(formatDate(start, 'YYYY-MM-DD'))
        chartData1.value.push(generateBloodPressure())
        chartData12.value.push(generateBloodPressure2())
        chartData2.value.push(Math.floor(Math.random() * 31) + 70)
        chartData3.value.push(Math.floor(Math.random() * 61) + 50)
        chartData4.value.push((Math.random() * 3 + 35).toFixed(1))
        start.setDate(start.getDate() + 1)
    }
    return dateArr
}
const initChart1 = () => {
    if (!chart.value) return false
    const myChart = echarts.init(chart.value);
    const option = {
        title: {
            text: '血压趋势',
            top: 'top',
            left: 'center'
        },
        legend: {
            data: ['收缩压', '舒张压'],
            bottom: 'bottom'
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (params) { 
                return params[0].name + '<br>' +
                    params[0].marker + params[0].seriesName + ':' + params[0].value + 'mmHg<br>' +
                    params[1].marker + params[1].seriesName + ':' + params[1].value + 'mmHg'
            }
        },
        grid: {
            top: '15%',
            left: '5%',
            right: '5%',
            bottom: '20%'
        },
        xAxis: {
            type: 'category',
            data: getDate(dateRange.value[0], dateRange.value[1]),
            boundaryGap: false
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: '{value}mmHg'
            }
        },
        series: [
            {
                name: '收缩压',
                data: chartData1.value,
                type: 'line',
                smooth: true
            },
            {
                name: '舒张压',
                data: chartData12.value,
                type: 'line',
                smooth: true
            }
        ]
    };
    myChart.setOption(option);
    window.addEventListener('resize', () => {
        myChart.resize()
    })
}

const initChart2 = () => {
    if (!chart.value) return false
    const myChart = echarts.init(chart.value);
    const option = {
        title: {
            text: '血氧趋势',
            top: 'top',
            left: 'center'
        },
        legend: {
            data: ['血氧饱和度'],
            bottom: 'bottom'
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (params) { 
                return params[0].name + '<br/>' + params[0].seriesName + '：' + params[0].value + '%'
            }
        },
        grid: {
            top: '15%',
            left: '5%',
            right: '5%',
            bottom: '20%'
        },
        xAxis: {
            type: 'category',
            data: getDate(dateRange.value[0], dateRange.value[1]),
            boundaryGap: false
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: '{value}%'
            }
        },
        series: [
            {
                name: '血氧饱和度',
                data: chartData2.value,
                type: 'line',
                smooth: true
            }
        ]
    };
    myChart.setOption(option);
    window.addEventListener('resize', () => {
        myChart.resize()
    })
}

const initChart3 = () => {
    if (!chart.value) return false
    const myChart = echarts.init(chart.value);
    const option = {
        title: {
            text: '心率趋势',
            top: 'top',
            left: 'center'
        },
        legend: {
            data: ['心率'],
            bottom: 'bottom'
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (params) { 
                return params[0].name + '<br/>' + params[0].seriesName + '：' + params[0].value + 'BPM'
            }
        },
        grid: {
            top: '15%',
            left: '5%',
            right: '5%',
            bottom: '20%'
        },
        xAxis: {
            type: 'category',
            data: getDate(dateRange.value[0], dateRange.value[1]),
            boundaryGap: false
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: '{value}bpm'
            }
        },
        series: [
            {
                name: '心率',
                data: chartData3.value,
                type: 'line',
                smooth: true
            }
        ]
    };
    myChart.setOption(option);
    window.addEventListener('resize', () => {
        myChart.resize()
    })
}

const initChart4 = () => {
    if (!chart.value) return false
    const myChart = echarts.init(chart.value);
    const option = {
        title: {
            text: '体温趋势',
            top: 'top',
            left: 'center'
        },
        legend: {
            data: ['体温'],
            bottom: 'bottom'
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (params) { 
                return params[0].name + '<br/>' + params[0].seriesName + '：' + params[0].value + '℃'
            }
        },
        grid: {
            top: '15%',
            left: '5%',
            right: '5%',
            bottom: '20%'
        },
        xAxis: {
            type: 'category',
            data: getDate(dateRange.value[0], dateRange.value[1]),
            boundaryGap: false
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: '{value}℃'
            }
        },
        series: [
            {
                name: '体温',
                data: chartData4.value,
                type: 'line',
                smooth: true
            }
        ]
    };
    myChart.setOption(option);
    window.addEventListener('resize', () => {
        myChart.resize()
    })
}

const activeTab = ref(1)
const handleTab = (val) => {
    activeTab.value = val
    if (chart.value) {
        echarts.dispose(chart.value)
    }
    switch (val) {
        case 1: initChart1(); break;
        case 2: initChart2(); break;
        case 3: initChart3(); break;
        case 4: initChart4(); break;
    }
}

const handleDateChange = () => {
    handleTab(activeTab.value)
}

const currentPage = ref(1)
const pageSize = ref(30)
const pageSizes = ref([30, 50, 100])
// const total = ref(0)
const background = ref(true)
const disabled = ref(false)
const size = ref('default')
const tableHeight = ref('26vh')
const tableLoading = ref(false)

const tableData = ref([
    { A8: '2025-07-01 08:30', A9: '145/95', A10: '70', A11: '101', A12: '37.5', A13: '正常' },
    { A8: '2025-07-01 12:00', A9: '120/80', A10: '95', A11: '70', A12: '36.5', A13: '轻度异常' },
    { A8: '2025-07-01 16:00', A9: '120/80', A10: '95', A11: '59', A12: '36.5', A13: '正常' },
    { A8: '2025-07-01 20:00', A9: '120/80', A10: '95', A11: '59', A12: '36.5', A13: '严重异常' },
    { A8: '2025-07-02 08:00', A9: '120/80', A10: '95', A11: '59', A12: '36.5', A13: '正常' },
])

const isBloodPressureNormal = (pressure) => {
    if (!pressure) return false;

    const [systolic, diastolic] = pressure.split('/').map(Number);
    return systolic >= 90 && systolic <= 139 &&
        diastolic >= 60 && diastolic <= 89;
};
const handleCurrentChange = () => { }
const handleSizeChange = () => { }

const radio = ref('1')

const showDateRange2 = ref(false)
const radioChange = (val) => {
    if (val === '3') {
        showDateRange2.value = true
    } else {
        showDateRange2.value = false
    }
}

const dateRange2 = ref([])
const handleDateChange2 = (val) => {
    console.log(val);
}

const checkboxGroup = ref(['血压', '血氧', '心率', '体温'])
const cities = ['血压', '血氧', '心率', '体温']

onMounted(() => {
    initChart1()
})
</script>
