<template>
    <div class="subjectChart" v-loading="loading">
        <el-form :inline="true">
            <!-- Site -->
            <el-form-item :label="$t('subjectChart:table:subject')">
                <span>{{ data.Code }}</span>
            </el-form-item>
            <el-form-item :label="$t('subjectChart:table:CriterionType')">
                <el-select v-model="TrialReadingCriterionId" clearable filterable @change="handleChange">
                    <el-option v-for="(item) of trialCriterionList" :key="item.TrialReadingCriterionId"
                        :label="item.TrialReadingCriterionName" :value="item.TrialReadingCriterionId" />
                </el-select>
            </el-form-item>
        </el-form>
        <el-table :data="tableList" border style="width: 100%">
            <el-table-column v-for="(item, index) in tableKey" :key="item.key" :prop="item.key" :label="item.title">
                <template slot-scope="scope">
                    <span :class="{ IsHighlight: scope.row.IsHighlight.includes(item.key) }">{{ scope.row[item.key]
                        }}</span>
                    <el-button icon="el-icon-view" circle v-if="index > 0 && scope.row[item.key]" size="mini"
                        style="margin-left: 5px;" :title="$t('common:button:view')"
                        @click="lookReadingResults(scope.row.VisitTaskId[item.key])"></el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="chartBox">
            <div class="R1box" v-if="R1ChartList.length > 0">
                <h3>{{ $t("subjectChart:chart:titie:R1") }}</h3>
                <div v-for="item in R1ChartList" :key="item.id">
                    <div class="title">{{ item.title }}</div>
                    <div v-for="d in item.list" :key="d.id" :ref="`chartContainer_${d.id}`" class="canvasBox"
                        style="width: 90%; height: 290px;">
                    </div>
                </div>
            </div>
            <div class="R2box" v-if="R2ChartList.length > 0">
                <h3>{{ $t("subjectChart:chart:titie:R2") }}</h3>
                <div v-for="item in R2ChartList" :key="item.id">
                    <div class="title">{{ item.title }}</div>
                    <div v-for="d in item.list" :key="d.id" :ref="`chartContainer_${d.id}`" class="canvasBox"
                        style="width: 90%; height: 290px;">
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import {
    getTrialCriterionList,
    getReportsChartSummary
} from '@/api/trials'
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { getToken } from '@/utils/auth'
import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    DataZoomComponent,
    LegendComponent,
    DatasetComponent,
    // 内置数据转换器组件 (filter, sort)
    TransformComponent
} from 'echarts/components';
// 标签自动布局、全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features';
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([
    TitleComponent,
    TooltipComponent,
    GridComponent,
    DatasetComponent,
    TransformComponent,
    DataZoomComponent,
    LegendComponent,
    LineChart,
    LabelLayout,
    UniversalTransition,
    CanvasRenderer
]);
// let echarts = require('echarts/lib/echarts');

// 按需引入图表
// require('echarts/lib/chart/bar');
// require('echarts/lib/chart/line');
// require('echarts/lib/chart/pie');
// require('echarts/lib/chart/scatter');

// 按需引入组件
// require('echarts/lib/component/tooltip');
// require('echarts/lib/component/title');
// require('echarts/lib/component/legend');
// require('echarts/lib/component/grid');
// require('echarts/lib/component/dataZoom');
export default {
    name: "SubjectChart",
    props: {
        data: {
            type: Object,
            default: () => {
                return {}
            }
        }
    },
    data() {
        return {
            loading: false,
            trialCriterionList: [],
            TrialReadingCriterionId: null,
            tableKey: [],
            tableList: [],
            R1ChartList: [],
            R2ChartList: [],
            openWindow: null
        }
    },
    mounted() {
        this.getTrialCriterionList()
    },
    methods: {
        // 查看阅片结果
        lookReadingResults(id) {
            if (this.openWindow) {
                this.openWindow.close()
            }
            var token = getToken()
            var path = null
            let trialCriterion = this.trialCriterionList.find(item => item.TrialReadingCriterionId === this.TrialReadingCriterionId)
            let trialId = this.$route.query.trialId
            if (trialCriterion.ReadingTool === 0 || trialCriterion.ReadingTool === 2 || trialCriterion.ReadingTool === 3) {
                path = `/readingDicoms?TrialReadingCriterionId=${this.TrialReadingCriterionId}&trialId=${trialId}&subjectCode=${this.data.Code}&subjectId=${this.data.Id}&visitTaskId=${id}&isReadingTaskViewInOrder=${trialCriterion.IsReadingTaskViewInOrder}&criterionType=${trialCriterion.CriterionType}&readingTool=${trialCriterion.ReadingTool}&TokenKey=${token}`
            } else {
                path = `/noneDicomReading?TrialReadingCriterionId=${this.TrialReadingCriterionId}&trialId=${trialId}&subjectCode=${this.data.Code}&subjectId=${this.data.Id}&visitTaskId=${id}&isReadingTaskViewInOrder=${trialCriterion.IsReadingTaskViewInOrder}&criterionType=${trialCriterion.CriterionType}&readingTool=${trialCriterion.ReadingTool}&TokenKey=${token}`
            }
            // const routeData = this.$router.resolve({
            //   path: `/readingPage?subjectId=${row.SubjectId}&trialId=${row.TrialId}&visitTaskId=${row.Id}&TokenKey=${token}`
            // })
            this.openWindow = window.open(path, '_blank')
        },
        handleChange(v) {
            this.getList()
        },
        getTrialCriterionList() {
            this.loading = true
            getTrialCriterionList(this.$route.query.trialId, false).then(res => {
                this.trialCriterionList = res.Result.filter(item => [1, 18, 2, 3, 7, 10, 17].includes(Number(item.CriterionType)))
                this.loading = false
                if (this.trialCriterionList.length > 0) {
                    this.TrialReadingCriterionId = this.trialCriterionList[0].TrialReadingCriterionId
                    this.getList()
                    this.loading = false
                }
            }).catch(() => { this.loading = false })
        },
        async getList() {
            try {
                let data = {
                    SubjectId: this.data.Id,
                    TrialCriterionId: this.TrialReadingCriterionId
                }
                this.loading = true
                let res = await getReportsChartSummary(data)
                this.loading = false
                if (res.IsSuccess) {
                    let Evaluation = res.Result.Evaluation.Evaluation
                    this.tableKey = [
                        {
                            title: this.$t(`subjectChart:table:label:visit`),
                            key: 'visit',
                            IsHighlight: []
                        }
                    ]
                    Evaluation[0].forEach(key => {
                        let obj = {
                            title: key.Value,
                            key: key.Value,
                            IsHighlight: []
                        }
                        this.tableKey.push(obj)
                    })
                    this.tableList = []
                    if (Evaluation[1] && Evaluation[1].length > 0) {
                        let obj = {
                            IsHighlight: [],
                            VisitTaskId: {}
                        }
                        this.tableKey.forEach((item, index) => {
                            if (index === 0) {
                                obj[item.key] = 'R1'
                            } else {
                                obj.VisitTaskId[item.key] = Evaluation[1][index - 1].VisitTaskId
                                obj[item.key] = Evaluation[1][index - 1].DictionaryCode ? this.$fd(Evaluation[1][index - 1].DictionaryCode, parseFloat(Evaluation[1][index - 1].Value)) : Evaluation[1][index - 1].Value
                                if (Evaluation[1][index - 1].IsHighlight) {
                                    obj.IsHighlight.push(item.key)
                                }

                            }
                        })
                        this.tableList.push(obj)
                    }
                    if (Evaluation[2] && Evaluation[2].length > 0) {
                        let obj = {
                            IsHighlight: [],
                            VisitTaskId: {}
                        }
                        this.tableKey.forEach((item, index) => {
                            obj[item.key] = index === 0 ? 'R2' : Evaluation[2][index - 1].DictionaryCode ? this.$fd(Evaluation[2][index - 1].DictionaryCode, parseFloat(Evaluation[2][index - 1].Value)) : Evaluation[2][index - 1].Value
                            if (index > 0 && Evaluation[2][index - 1].IsHighlight) {
                                obj.IsHighlight.push(item.key)
                            }
                            if (index > 0) {
                                obj.VisitTaskId[item.key] = Evaluation[2][index - 1].VisitTaskId
                            }
                        })
                        this.tableList.push(obj)
                    }
                    let chartData = [...res.Result.TargetCharts, ...res.Result.QuestionCharts]
                    let R1ChartData = chartData.map(item => {
                        if (item.Arm === 1) return item
                    }).filter(item => item && item.VisitTaskNameList.length > 0)
                    let R2ChartData = chartData.map(item => {
                        if (item.Arm === 2) return item
                    }).filter(item => item && item.VisitTaskNameList.length > 0)
                    if (Array.isArray(R1ChartData)) {
                        this.R1ChartList = []
                        R1ChartData.forEach(item => {
                            let index = this.R1ChartList.findIndex(i => i.title === item.GroupName)
                            let o = {
                                id: this.$guid(),
                                series: [],
                                unit: this.$fd("ValueUnit", item.Unit),
                                visitName: item.VisitTaskNameList,
                            }
                            item.ChartDataList.forEach((i) => {
                                let arr = []
                                i.Value.forEach((d) => {
                                    arr.push(d)
                                })
                                o.series.push({
                                    name: i.Name,
                                    data: arr,
                                    type: 'line'
                                })
                            });
                            if (index < 0) {
                                let obj = {
                                    title: item.GroupName,
                                    list: [o],
                                    id: this.$guid(),
                                }
                                this.R1ChartList.push(obj)
                            } else {
                                this.R1ChartList[index].list.push(o)
                            }
                        })
                        this.$nextTick(() => {
                            if (this.R1ChartList.length > 0) {
                                this.R1ChartList.forEach(item => {
                                    if (item.list.length > 0) {
                                        item.list.forEach(d => {
                                            this.initChart(d)
                                        })
                                    }
                                })
                            }
                        })
                    }
                    if (Array.isArray(R2ChartData)) {
                        this.R2ChartList = []
                        R2ChartData.forEach(item => {
                            let index = this.R2ChartList.findIndex(i => i.title === item.GroupName)
                            let o = {
                                id: this.$guid(),
                                series: [],
                                unit: this.$fd("ValueUnit", item.Unit),
                                visitName: item.VisitTaskNameList,
                            }
                            item.ChartDataList.forEach((i) => {
                                let arr = []
                                i.Value.forEach((d) => {
                                    arr.push(d)
                                })
                                o.series.push({
                                    name: i.Name,
                                    data: arr,
                                    type: 'line'
                                })
                            });
                            if (index < 0) {
                                let obj = {
                                    title: item.GroupName,
                                    list: [o],
                                    id: this.$guid(),
                                }
                                this.R2ChartList.push(obj)
                            } else {
                                this.R2ChartList[index].list.push(o)
                            }
                        })
                        this.$nextTick(() => {
                            if (this.R2ChartList.length > 0) {
                                this.R2ChartList.forEach(item => {
                                    if (item.list.length > 0) {
                                        item.list.forEach(d => {
                                            this.initChart(d)
                                        })
                                    }
                                })
                            }
                        })
                    }
                }
            } catch (err) {
                this.loading = false
                console.log(err)
            }

        },
        initChart(obj) {
            let chart = echarts.init(this.$refs[`chartContainer_${obj.id}`][0]);
            // ...图表配置
            const option = {
                // title: {
                //     text: obj.title,
                //     textStyle: {
                //         color: "#fff"
                //     }
                // },
                tooltip: {
                    trigger: 'axis',
                },
                grid: {
                    left: 30,
                    bottom: 30
                },
                xAxis: {
                    data: obj.visitName,
                },
                yAxis: {
                    name: obj.unit,
                    type: 'value',
                    axisLine: {
                        show: true
                    }
                },
                series: obj.series
            };
            // 4. 使用配置项渲染图表
            chart.setOption(option);
        },
    }
}
</script>
<style lang="scss" scoped>
.subjectChart {
    width: 80%;
    min-width: 800px;
    margin: auto;
}

.IsHighlight {
    color: #00f;
}

.chartBox {
    display: flex;

    width: 100%;

    .R1box,
    .R2box {
        width: 100%;

        .title {
            margin-top: 10px;
        }

        .canvasBox {
            margin: auto;
        }
    }
}
</style>