<template>
    <div class="reportForms">
        <div class="search">
            <el-form :inline="true">
                <!-- 阅片标准 -->
                <el-form-item :label="$t('trials:reportForms:table:Criterion')">
                    <el-select v-model="searchData.TrialReadingCriterionId" clearable filterable>
                        <el-option v-for="(item, index) of trialCriterionList" :key="index"
                            :label="item.TrialReadingCriterionName" :value="item.TrialReadingCriterionId" />
                    </el-select>
                </el-form-item>
            </el-form>
        </div>
        <div class="contentBox">
            <div class="chartBox" :style="{ height: isTumor ? '50%' : '100%' }">
                <div ref="chartContainer_left" style="width: 100%; height: 100%;" v-loading="loading_left"></div>
            </div>
            <div class="chartBox" :style="{ height: isTumor ? '50%' : '100%' }">
                <div ref="chartContainer_right" style="width: 100%; height: 100%;" v-loading="loading_right"></div>
            </div>
            <div class="chartBox" v-if="isTumor">
                <div ref="chartContainer_bottom" style="width: 100%; height: 100%;" v-loading="loading_bottom"></div>
            </div>
            <div class="chartBox" :style="{ position: 'relative' }" v-if="isTumor && !isPCWG">
                <div ref="chartContainer_bottom_left" style="width: 100%; height: 100%;" v-loading="loading_bottom">
                </div>
                <span v-if="ORR" style="position: absolute;top: 0;right:20px">{{
                    $t("trials:reportForms:cjart:title:totleORR") }} {{ ORR }}</span>
            </div>
            <div class="chartBox" v-if="isTumor" :style="{ width: isPCWG ? '50%' : '100%' }">
                <div ref="chartContainer_bottom_right" style="width: 100%; height: 100%;" v-loading="loading_bottom">
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import BaseContainer from '@/components/BaseContainer'
import * as echarts from 'echarts/core';
import { BarChart, FunnelChart } from 'echarts/charts';
import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    DataZoomComponent,
    LegendComponent,
    MarkLineComponent,
    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,
    MarkLineComponent,
    LegendComponent,
    BarChart,
    FunnelChart,
    LabelLayout,
    UniversalTransition,
    CanvasRenderer
]);
// let echarts = require('echarts/lib/echarts');

// require('echarts/lib/component/markLine');
// require('echarts/lib/chart/funnel');
// require('echarts/lib/chart/bar');
// 按需引入组件
// 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');
import {
    getTrialCriterionList,
    getTrialVisitFinishedStatList,
    getTrialQuestionStatList,
    getTrialEfficacyEvaluationStatList
} from '@/api/trials'
export default {
    name: 'reportForms',
    components: { BaseContainer },
    data() {
        return {
            searchData: {
                TrialReadingCriterionId: null
            },
            color: [
                '#0ca8df',
                '#ffd10a',
                '#b6d634',
                '#3fbe95',
                '#785db0',
                '#5070dd',
                '#505372',
                '#ff994d',
                '#fb628b',
            ],
            trialCriterionList: [],
            loading_left: false,
            chart_left: null,
            loading_right: false,
            chart_right: null,
            loading_bottom: false,
            chart_bottom: null,
            chart_bottom_right: null,
            chart_bottom_left: null,
            // isHas_bottom_right: false,
            ORR: null
        }
    },
    created() {
        this.getTrialCriterionList()
    },
    computed: {
        isTumor() {
            let criterion = this.trialCriterionList.find(item => item.TrialReadingCriterionId === this.searchData.TrialReadingCriterionId)
            if (criterion) {
                return [1, 18, 2, 3, 7, 10, 17].includes(Number(criterion.CriterionType))
            } else {
                return false
            }
        },
        isPCWG() {
            let criterion = this.trialCriterionList.find(item => item.TrialReadingCriterionId === this.searchData.TrialReadingCriterionId)
            if (criterion) {
                return [10].includes(Number(criterion.CriterionType))
            } else {
                return false
            }
        }
    },
    watch: {
        'searchData.TrialReadingCriterionId': {
            handler() {
                if (this.searchData.TrialReadingCriterionId) {
                    this.getTrialVisitFinishedStatList()
                    this.getTrialQuestionStatList()
                    if (this.isTumor) {
                        this.getTrialEfficacyEvaluationStatList()
                    }
                }
            }
        },
    },
    methods: {
        getTrialCriterionList() {
            getTrialCriterionList(this.$route.query.trialId, false).then(res => {
                this.trialCriterionList = res.Result
                if (this.trialCriterionList.length > 0) {
                    this.searchData.TrialReadingCriterionId = this.trialCriterionList[0].TrialReadingCriterionId
                }
            }).catch(() => { })
        },
        // 获取访视完成度
        async getTrialVisitFinishedStatList() {
            try {
                let data = {
                    TrialId: this.$route.query.trialId,
                    TrialReadingCriterionId: this.searchData.TrialReadingCriterionId
                }
                this.loading_left = true
                let res = await getTrialVisitFinishedStatList(data)
                this.loading_left = false
                if (res.IsSuccess) {
                    let arr = []
                    let obj = {
                        titleText: this.$t("trials:reportForms:cjart:title:VisitFinishedStat"),
                        seriesData: [],
                        max: 0,
                        legendData: []
                    }
                    res.Result.ReadingFinishedCount = res.Result.CriterionList[0].ReadingFinishedCount
                    let keys = ['UploadedCount', 'QCFinishedCount', 'CheckFinishedCount', 'ReadingFinishedCount']
                    keys.forEach((item, index) => {
                        if (res.Result[item] != null) {
                            let o = {
                                name: this.$t(`trials:reportForms:cjart:title:${item}`),
                                value: res.Result[item]
                            }
                            obj.legendData.push(o.name)
                            obj.seriesData.push(o)
                            arr.push(res.Result[item])
                        }
                    })
                    // obj.legendData.forEach((item, index) => {
                    //     let o = {
                    //         name: item,
                    //         value: res.Result[keys[index]]
                    //     }
                    //     obj.seriesData.push(o)
                    //     arr.push(res.Result[keys[index]])
                    // })
                    obj.max = Math.max(...arr)
                    this.initChart_left(obj)
                }
            } catch (err) {
                console.log(err)
            }
        },
        initChart_left(obj) {
            this.chart_left = echarts.init(this.$refs.chartContainer_left);
            // ...图表配置
            const option = {
                richInheritPlainLabel: false,
                title: {
                    text: obj.titleText,
                    left: 0,
                    top: 0
                },
                color: this.color,
                tooltip: {
                    trigger: 'item',
                    formatter: `{b} : {c}`
                },
                toolbox: {
                    show: false
                },
                legend: {
                    data: obj.legendData,
                    bottom: 0
                },
                series: [
                    {
                        name: 'Funnel',
                        type: 'funnel',
                        left: '10%',
                        top: 30,
                        bottom: 40,
                        width: '80%',
                        min: 0,
                        max: obj.max ? obj.max : 100,
                        minSize: '0%',
                        maxSize: '100%',
                        sort: 'descending',
                        gap: 2,
                        label: {
                            show: true,
                            formatter: `{c}`,
                            position: 'inside',
                            textStyle: {
                                fontSize: 14, // 设置字体大小为 14px
                                color: '#000', // 设置字体颜色为白色
                                // fontWeight: 'bold' // 设置字体加粗
                            }
                        },
                        // labelLine: {
                        //     length: 10,
                        //     lineStyle: {
                        //         width: 1,
                        //         type: 'solid'
                        //     }
                        // },
                        itemStyle: {
                            borderColor: '#fff',
                            borderWidth: 1
                        },
                        emphasis: {
                            label: {
                                fontSize: 20
                            }
                        },
                        data: obj.seriesData
                    }
                ]
            };
            // 4. 使用配置项渲染图表
            this.chart_left.setOption(option);
            this.$nextTick(() => {
                this.chart_left.resize()
            })
        },
        // 获取质疑统计列表
        async getTrialQuestionStatList() {
            try {
                let data = {
                    TrialId: this.$route.query.trialId,
                    TrialReadingCriterionId: this.searchData.TrialReadingCriterionId
                }
                this.loading_right = true
                let res = await getTrialQuestionStatList(data)
                this.loading_right = false
                if (res.IsSuccess) {
                    let obj = {
                        titleText: this.$t("trials:reportForms:cjart:title:QuestionStat"),
                        seriesData: [
                            {
                                name: this.$t("trials:reportForms:cjart:data:IngCount"),
                                type: 'bar',
                                stack: 'Ad',
                                barWidth: 20,
                                emphasis: {
                                    focus: 'series'
                                },
                                label: {
                                    show: true,
                                    formatter: `{c}`,
                                    position: 'inside',
                                    textStyle: {
                                        fontSize: 14, // 设置字体大小为 14px
                                        color: '#000', // 设置字体颜色为白色
                                        // fontWeight: 'bold' // 设置字体加粗
                                    }
                                },
                                data: [res.Result.QCQuestion_IngCount, res.Result.CheckQuestion_IngCount, res.Result.MedicalReviewQuestion_IngCount]
                            },
                            {
                                name: this.$t("trials:reportForms:cjart:data:ClosedCount"),
                                type: 'bar',
                                stack: 'Ad',
                                barWidth: 20,
                                emphasis: {
                                    focus: 'series'
                                },
                                label: {
                                    show: true,
                                    formatter: `{c}`,
                                    position: 'inside',
                                    textStyle: {
                                        fontSize: 14, // 设置字体大小为 14px
                                        color: '#000', // 设置字体颜色为白色
                                        // fontWeight: 'bold' // 设置字体加粗
                                    }
                                },
                                data: [res.Result.QCQuestion_ClosedCount, res.Result.CheckQuestion_ClosedCount, res.Result.MedicalReviewQuestion_ClosedCount]
                            }
                        ],
                        xAxisData: [
                            this.$t("trials:reportForms:cjart:title:QCQuestion"),
                            this.$t("trials:reportForms:cjart:title:CheckQuestion"),
                            this.$t("trials:reportForms:cjart:title:MedicalReviewQuestion"),
                        ],
                        unit: this.$t("trials:reportForms:cjart:unit:count")
                    }
                    this.initChart_right(obj)
                }
            } catch (err) {
                console.log(err)
            }
        },
        initChart_right(obj) {
            this.chart_right = echarts.init(this.$refs.chartContainer_right);
            // ...图表配置
            const option = {
                title: {
                    text: obj.titleText,
                    left: 0,
                    top: 0
                },
                grid: {
                    left: 80,
                    bottom: 50
                },
                toolbox: {
                    show: false
                },
                color: this.color,
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {
                    bottom: 0
                },
                xAxis: [
                    {
                        type: 'category',
                        data: obj.xAxisData
                    }
                ],
                yAxis: [
                    {
                        axisLine: {
                            show: true
                        },
                        name: obj.unit,
                        type: 'value'
                    }
                ],
                series: obj.seriesData
            };
            // 4. 使用配置项渲染图表
            this.chart_right.setOption(option);
            this.$nextTick(() => {
                this.chart_right.resize()
            })
        },
        // 获取疗效统计表
        async getTrialEfficacyEvaluationStatList() {
            try {
                let data = {
                    TrialId: this.$route.query.trialId,
                    TrialReadingCriterionId: this.searchData.TrialReadingCriterionId
                }
                this.loading_bottom = true
                let res = await getTrialEfficacyEvaluationStatList(data)
                if (data.TrialReadingCriterionId !== this.searchData.TrialReadingCriterionId) return false
                this.loading_bottom = false
                if (res.IsSuccess) {
                    let OtherInfo = res.OtherInfo || {}
                    this.ORR = OtherInfo.ORR
                    let obj = {
                        xAxisData: [],
                        seriesData: [],
                        unit: this.$t("trials:reportForms:cjart:unit:subjectCount"),
                        titleText: this.$t("trials:reportForms:cjart:title:EfficacyEvaluationStat"),
                    }
                    res.Result.forEach(item => {
                        obj.xAxisData.push(item.OverallTumorEvaluation)
                        obj.seriesData.push(item.SubjectCount)
                    })
                    this.$nextTick(() => {
                        this.initChart_bottom(obj)
                    })
                    let obj2 = {
                        xAxisData: [],
                        seriesData: [],
                        medianValue: 0,
                        unit: this.$t("trials:reportForms:cjart:unit:DaysDiff"),
                        titleText: this.$t("trials:reportForms:cjart:title:dataDistribution"),
                    }
                    if (OtherInfo.PDList && OtherInfo.PDList.length > 0) {
                        // this.isHas_bottom_right = true
                        OtherInfo.PDList.forEach(item => {
                            obj2.xAxisData.push(item.SubjectCode)
                            obj2.seriesData.push(item.MonthsDiff)
                        })
                        obj2.medianValue = this.calculateMedian(obj2.seriesData)
                    }
                    let obj3 = {
                        xAxisData: [],
                        seriesData: [],
                        unit: this.$t("trials:reportForms:cjart:unit:ORRValue"),
                        titleText: this.$t("trials:reportForms:cjart:title:ORR"),
                    }
                    if (OtherInfo.SiteORRList && OtherInfo.SiteORRList.length > 0) {
                        // this.isHas_bottom_right = true
                        OtherInfo.SiteORRList.forEach(item => {
                            obj3.xAxisData.push(item.TrialSiteCode)
                            obj3.seriesData.push(item.OrrPercent.split("%")[0])
                        })
                    }
                    this.$nextTick(() => {
                        this.initChart_bottom_right(obj2)
                        this.initChart_bottom_left(obj3)
                    })
                    //  else {
                    //     this.isHas_bottom_right = false
                    // }

                }
            } catch (err) {
                console.log(err)
            }
        },
        initChart_bottom(obj) {
            this.chart_bottom = echarts.init(this.$refs.chartContainer_bottom);
            // ...图表配置
            const option = {
                title: {
                    text: obj.titleText,
                    left: 0,
                    top: 0
                },
                toolbox: {
                    show: false
                },
                color: this.color,
                grid: {
                    left: 80,
                    bottom: 50
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                xAxis: {
                    type: 'category',
                    data: obj.xAxisData
                },
                yAxis: {
                    axisLine: {
                        show: true
                    },
                    name: obj.unit,
                    type: 'value',
                    minInterval: 1
                },
                series: [
                    {
                        data: obj.seriesData,
                        type: 'bar',
                        barWidth: 20,
                        label: {
                            show: true,
                            formatter: `{c}`,
                            position: 'top',
                            textStyle: {
                                fontSize: 14, // 设置字体大小为 14px
                                color: '#000', // 设置字体颜色为白色
                                // fontWeight: 'bold' // 设置字体加粗
                            }
                        },
                    }
                ]
            };
            // 4. 使用配置项渲染图表
            this.chart_bottom.setOption(option);
            this.$nextTick(() => {
                this.chart_bottom.resize()
            })
        },
        initChart_bottom_left(obj) {
            this.chart_bottom_left = echarts.init(this.$refs.chartContainer_bottom_left);
            // ...图表配置
            const option = {
                title: {
                    text: obj.titleText,
                    left: 0,
                    top: 0
                },
                toolbox: {
                    show: false
                },
                grid: {
                    left: 80,
                    bottom: 50
                },
                color: this.color,
                tooltip: {
                    trigger: 'item',
                    formatter: `{b} : {c}%`
                },
                // tooltip: {
                //     trigger: 'axis',
                //     axisPointer: {
                //         type: 'shadow'
                //     }
                // },
                xAxis: {
                    type: 'category',
                    data: obj.xAxisData
                    // data: ['aaa', 'bbb', 'ccc']
                },
                yAxis: {
                    name: obj.unit,
                    type: 'value',
                    axisLine: {
                        show: true
                    },
                    axisLabel: {
                        formatter: '{value}%',
                    }
                },
                series: {
                    label: {
                        show: true,
                        formatter: `{c}%`,
                        position: 'top',
                        textStyle: {
                            fontSize: 14, // 设置字体大小为 14px
                            color: '#000', // 设置字体颜色为白色
                            // fontWeight: 'bold' // 设置字体加粗
                        }
                    },
                    data: obj.seriesData,
                    // data: [1, 2, 3],
                    type: 'bar',
                    barWidth: 20,
                }

            };
            // 4. 使用配置项渲染图表
            this.chart_bottom_left.setOption(option);
            this.$nextTick(() => {
                this.chart_bottom_left.resize()
            })
        },
        initChart_bottom_right(obj) {
            this.chart_bottom_right = echarts.init(this.$refs.chartContainer_bottom_right);
            // ...图表配置
            const option = {
                title: {
                    text: obj.titleText,
                    left: 0,
                    top: 0
                },
                grid: {
                    left: 80,
                    bottom: 50
                },
                toolbox: {
                    show: false
                },
                color: this.color,
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                xAxis: {
                    type: 'category',
                    data: obj.xAxisData
                    // data: ['aaa', 'bbb', 'ccc']
                },
                yAxis: {
                    name: obj.unit,
                    type: 'value',
                    axisLine: {
                        show: true
                    }
                },
                series: {
                    markLine: {
                        // symbol: ['none', 'none'], // 隐藏标记线两端的箭头
                        label: {
                            show: true,
                            position: 'end', // 将标签显示在线的起点
                            formatter: `${this.$t('trials:reportForms:cjart:data:median')}: {c}` // 使用 {c} 自动显示 yAxis 的值
                        },
                        data: [
                            {
                                name: this.$t('trials:reportForms:cjart:data:median'),
                                // yAxis 的值设置为我们计算出的中位数
                                yAxis: obj.medianValue,
                                lineStyle: {
                                    type: 'dashed', // 设置为虚线
                                    color: this.color[7]
                                }
                            }
                        ]
                    },
                    label: {
                        show: true,
                        formatter: `{c}`,
                        position: 'top',
                        textStyle: {
                            fontSize: 14, // 设置字体大小为 14px
                            color: '#000', // 设置字体颜色为白色
                            // fontWeight: 'bold' // 设置字体加粗
                        }
                    },
                    data: obj.seriesData,
                    // data: [1, 2, 3],
                    type: 'bar',
                    barWidth: 20,
                }

            };
            // 4. 使用配置项渲染图表
            this.chart_bottom_right.setOption(option);
            this.$nextTick(() => {
                this.chart_bottom_right.resize()
            })
        },
        calculateMedian(numbers) {
            // 1. 创建副本并排序
            const sorted = [...numbers].sort((a, b) => a - b);
            const middle = Math.floor(sorted.length / 2);

            // 2. 判断数组长度是奇数还是偶数
            if (sorted.length % 2 === 0) {
                // 偶数长度：取中间两个数的平均值
                return (sorted[middle - 1] + sorted[middle]) / 2;
            } else {
                // 奇数长度：直接取中间的数
                return sorted[middle];
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.reportForms {
    width: 100%;
    height: 100%;
    background-color: #fff;
    overflow-y: auto;

    .search {
        padding: 5px;
    }

    .contentBox {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-around;
        align-items: center;
        width: 100%;
        height: calc(100% - 70px);

        .chartBox {
            box-sizing: border-box;
            width: 50%;
            height: 50%;

        }
    }
}
</style>