<template>
    <nav-bar :navbar-data="navbarData"></nav-bar>
    <view class="report-detail-container" :style="{ marginTop: height +'px', minHeight: 'calc(100vh - '+ height +'px)' }">
        <view v-if="pageLoading">
            <view class="skeleton-box">
                <van-skeleton title row="4" />
                <van-skeleton title avatar avatar-size="50px" row="4" />
                <van-skeleton title row="4" />
                <van-skeleton title avatar avatar-size="50px" row="4" />
            </view>
        </view>
        <view v-else>
            <view class="card">
                <view class="title">{{ inspectionData.itemDesc }}</view>
                <view class="card-content patient-info" v-if="inspectionData">
                    <view class="text">患者姓名：{{ inspectionData.patName }}</view>
                    <!-- <view class="text">科室：{{ inspectionData.locDesc }}</view> -->
                    <view class="text">报告周期：{{ reportInterval }}</view>
                </view>
            </view>
            <view class="card">
                <view class="title">项目明细</view>
                <view class="card-content result-content" v-for="(item, index) in lisReportCaseData" :key="index">
                    <view class="cell-item item-hader">
                        <text class="header-t">{{ item.descripts }}</text>
                        <text class="unit">参考值：{{ item.refRange }}{{ item.unit }}</text>
                    </view>
                    <view class="cell-item cell-item-more">
                        <view class="cell-table">
                            <view class="cell-tr">
                                <text class="h">日期</text>
                                <text v-for="(reportDate, idx) in item.reportDateArr" :key="idx">{{ reportDate }}</text>
                            </view>
                            <view class="cell-tr">
                                <text class="h">结果值{{ !item.unit ? '' : '(' + item.unit + ')' }}</text>
                                <text v-for="(value, idx) in item.valueArr" :key="idx">{{ value }}</text>
                            </view>
                        </view>
                        <view class="cell-unit" v-if="item.showCanvas && item.total > 1 && item.unit">(单位:{{ item.unit }})
                        </view>
                        <view class="canvas-box" v-if="item.showCanvas && item.total > 1">
                            <!-- <canvas class="canvas" :canvas-id="'lineCanvas' + index" :data-index="index"
                                disable-scroll="true" @touchstart="touchHandler"></canvas> -->
                            <u-charts type="line" :canvasId="'lineCanvas' + index" :opts="opts" :chartData="chartData[index]" />
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>
<script>
import $http from "@/utils/https";
import httpConfig from '@/utils/httpConfig'
import navBar from '@/components/navBar/index'
import VanSkeleton from '@/components/skeleton/index'
import uCharts from '@/components/u-charts/u-charts'
const app = getApp();
var lineChart = [];
export default {
    components: {
        'nav-bar': navBar,
        'van-skeleton': VanSkeleton,
        'u-charts': uCharts
    },
    data() {
        return {
            pageLoading: true,
            height: app.globalData.height,
            windowHost: httpConfig && httpConfig.ipDeault,
            navbarData: {
                isGoHome: true,
                isGoBack: true,
                title: "历次报告趋势"
            },
            userData: null, // 用户信息 
            lisReportID: null, // 报告记录ID
            inspectionData: null, // 检测项目数据
            lisReportCaseData: null, // 检测项目详细检验项数据集
            reportInterval: '',
            chartData: [],
            //您可以通过修改 config-ucharts.js 文件中下标为 ['line'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
            opts: {
                color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
                padding: [15, 10, 0, 15],
                enableScroll: false,
                legend: {},
                xAxis: {
                    disableGrid: true
                },
                yAxis: {
                    gridType: "dash",
                    dashLength: 2
                },
                extra: {
                    line: {
                        type: "straight",
                        width: 2,
                        activeType: "hollow"
                    }
                }
            }
        }
    },
    onLoad(options) {
        const self = this
        const reportRecordCurrentData = app.globalData.reportRecordCurrentData
        if (reportRecordCurrentData) {
            self.lisReportID = reportRecordCurrentData.id
            self.inspectionData = reportRecordCurrentData
        }
        const userData = this.$cache.get('userData')
        if (userData) self.userData = userData
    },
    onReady() {
        const self = this
        self.getDetail().then(res => {
            setTimeout(function () {
                uni.hideLoading()
                self.pageLoading = false
                // self.initLineCavas()
            }, 500)
        }).catch(err => {
            uni.hideLoading()
            self.pageLoading = false
        })
    },
    methods: {
        initLineCavas(index, categories, data, unit) {
            const self = this
            //模拟从服务器获取数据时的延时
            setTimeout(() => {
                //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
                let res = {
                    categories: categories,
                    series: [
                        {
                            name: "结果值",
                            data: data,
                            format: function (val, name) {
                                return parseFloat(val).toFixed(2) + unit;
                            }
                        }
                    ]
                };
                self.chartData[index] = JSON.parse(JSON.stringify(res));
            }, 500);
        },
        // initLineCavas(index, categories, data, unit) {
        //     var windowWidth = 320;
        //     try {
        //         var res = uni.getSystemInfoSync();
        //         windowWidth = res.windowWidth - 33;
        //     } catch (e) {
        //         console.error('getSystemInfoSync failed!');
        //     }

        //     // var simulationData = this.createSimulationData();
        //     lineChart[index] = new wxCharts({
        //         canvasId: 'lineCanvas' + index,
        //         type: 'line',
        //         categories: categories, // simulationData.categories
        //         animation: true,
        //         // background: '#f5f5f5',
        //         series: [{
        //             name: '结果值',
        //             data: data, // simulationData.data
        //             format: function (val, name) {
        //                 return parseFloat(val).toFixed(2) + unit;
        //             }
        //         }],
        //         xAxis: {
        //             disableGrid: true
        //         },
        //         yAxis: {
        //             title: '结果值' + (unit ? '(' + unit + ')' : ''),
        //             format: function (val) {
        //                 return parseFloat(val).toFixed(2);
        //             },
        //             min: 0
        //         },
        //         width: windowWidth,
        //         height: 200,
        //         dataLabel: false,
        //         dataPointShape: true,
        //         extra: {
        //             lineStyle: 'curve'
        //         }
        //     });
        // },

        touchHandler: function (e) {
            const { index } = e.currentTarget.dataset
            lineChart[index].showToolTip(e, {
                // background: '#7cb5ec',
                format: function (item, category) {
                    return category + ' ' + item.name + ':' + item.data
                }
            });
        },

        getDetail() {
            const self = this
            const userData = self.userData
            const { inspectionData } = self
            return new Promise((resolve, reject) => {
                let data = {
                    params: [{
                        "patID": '1464', //userData.patID
                        "itemID": inspectionData.id
                    }]
                }
                uni.showLoading({
                    title: '数据加载中...',
                })
                $http.post("urlS", self, {
                    namespace: "Y",
                    code: "03100218",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            self.reportInterval = res.interval
                            let lisReportCaseData = res.data
                            const reportKeys = Object.keys(lisReportCaseData)
                            const resLisReportCaseData = []
                            reportKeys.map((item, index) => {
                                resLisReportCaseData[index] = {
                                    'total': lisReportCaseData[item].length,
                                    'list': lisReportCaseData[item],
                                    'valueArr': lisReportCaseData[item].map(data => data.vaule),
                                    'reportDateArr': lisReportCaseData[item].map(data => data.reportDate),
                                    'unit': (encodeURIComponent(lisReportCaseData[item][0].unit) == "%00" || !lisReportCaseData[item][0].unit) ? '' : lisReportCaseData[item][0].unit,
                                    'refRange': lisReportCaseData[item][0].refRange,
                                    'descripts': lisReportCaseData[item][0].descripts,
                                    'showCanvas': isNaN(parseInt(lisReportCaseData[item][0].vaule)) ? false : true
                                }
                                if (resLisReportCaseData[index].showCanvas) {
                                    self.initLineCavas(index, resLisReportCaseData[index].reportDateArr, resLisReportCaseData[index].valueArr, resLisReportCaseData[index].unit)
                                }
                            })
                            self.lisReportCaseData = resLisReportCaseData
                            resolve(resLisReportCaseData)
                        } else {
                            resolve([])
                        }
                    },
                    fail(err) {
                        reject(err)
                    }
                })
            })
        },
    }
}
</script>

<style>
@import "../style/inspection.css";
</style>