<template>
	<view class="content">
		<scrollView ref="scrollViewComponent"></scrollView>
		<view class="chart-con">
			<view class="cartsList-all">
				<view class="cartsList-name">
					消耗数据趋势
				</view>
				<view class="select-button">
					<view :style="{
			       border: flagE === index + 1 ? '1px solid #90ffe4' : '1px solid #808080',
					color: flagE === index + 1 ? '#90ffe4' : '#808080',
					height: '40rpx',
					width: '100rpx',
					display: 'inline-block',
					cursor: 'pointer',
					textAlign: 'center',
					fontSize: '24rpx',
					fontFamily: '微软雅黑',
					lineHeight: '40rpx',
			    }" v-for="(item, index) in navList" :key="item.id" @click="handleClickBtnE(index)">
					{{ item.name }}
				</view>
				</view>
				<view class="cartsList-seleven">
					<uni-data-select v-model="valueList" :localdata="rangelineChart" @change="changelineChart"
						:clear="false"></uni-data-select>
				</view>
			</view>
			<view class="chart-wrap">
				<view class="line-chart-con">
					<Lechart class="line-chart" ref="lineChart"></Lechart>
				</view>
			</view>
		</view>

		<!-- 药耗服务费逐月趋势统计卡片和折线图 -->
		<view class="chart-con">
   			 <view class="cartsList-all">
        <view class="cartsList-name">
            耗材服务费逐月趋势
        </view>
        <view class="cartsList-seleven">
            <uni-data-select v-model="fwfTrendType" :localdata="rangelineChart" @change="changeFwfTrendType" :clear="false"></uni-data-select>
        </view>
    	</view>
    	<view class="trend-summary-wrap">
        <view class="trend-summary-item">
            <view class="trend-summary-title">耗材总服务费</view>
            <view class="trend-summary-value">￥{{ supplierSummary.totalFwf }}</view>
        </view>
    </view>
    	<view class="chart-wrap">
        <view class="line-chart-con">
            <Lechart class="line-chart" ref="fwfTrendChart"></Lechart>
        </view>
    		</view>
		</view>
        <view class="chart-con">
            <view class="cartsList-all">
                <view class="cartsList-name">
                    各供应商贡献度
                </view>
            </view>
            <view class="supplier-summary-wrap">
        <view class="supplier-summary-item">
            <view style="color:#008080; font-size:22rpx;">总服务费</view>
            <view style="font-size:32rpx; font-weight:bold; color:#333; margin-top:8rpx;">￥{{ supplierSummary.totalFwf }}</view>
        </view>
        <view class="supplier-summary-item">
            <view style="color:#008080; font-size:22rpx;">合作供应商</view>
            <view style="font-size:32rpx; font-weight:bold; color:#333; margin-top:8rpx;">{{ supplierSummary.supplierCount }}家</view>
        </view>
    </view>
            <view class="supplier-list-scroll supplier-list-border">
                <view
                    v-for="(item, idx) in supplierList"
                    :key="item.id"
                    class="supplier-list-item"
                >
                    <view
                        :style="{
                    width: '40rpx',
                    textAlign: 'center',
                    fontSize: '28rpx',
                    fontWeight: 'bold',
                    color:
                        idx === 0
                            ? '#ff4d4f'
                            : idx === 1
                            ? '#faad14'
                            : idx === 2
                            ? '#36cfc9'
                            : '#008080'
                }"
            >
            {{ idx + 1 }}
        </view>
        <view style="flex:1; margin-left:16rpx;">
            <view style="font-size:26rpx; color:#333; font-weight:bold;">{{ item.name }}</view>
            <view style="display:flex; gap:24rpx; margin-top:6rpx;">
                <view style="color:#008080; font-size:20rpx;">贡献度 {{ item.rate }}</view>
                <view style="color:#333; font-size:20rpx;">服务费 ￥{{ item.fwf }}</view>
            </view>
        </view>
    </view>
    <view v-if="supplierList.length > 8" style="text-align:center; color:#999; font-size:20rpx; margin:18rpx 0;">上拉加载更多</view>
            </view>
        </view>
		<PieCharts ref="PieChartsComponent"></PieCharts>
		<view class="chart-con">
			<view class="cartsList-all">
				<view class="cartsList-name">
					分类消耗占比
				</view>
				<view class="cartsList-seleven">
					<uni-data-select v-model="valueTimeType" :localdata="rangeringChart" @change="changeringChart"
						:clear="false"></uni-data-select>
				</view>
			</view>
			<view class=".chart-wrap-bing">
				<view class="ring-chart">
					<Lechart ref="ringChart"></Lechart>
				</view>
			</view>
		</view>
		<tiewk ref="tiewkComponent"></tiewk>
		<enterprise ref="enterpriseComponent"></enterprise>
	</view>
</template>

<script>
	import * as echarts from '@/subpkg/uni_modules/lime-echart/static/echarts.min.js';
	import scrollView from './scrollView/scrollView.vue';
	import PieCharts from './PieCharts/PieCharts.vue';
	import enterprise from './enterprise/enterprise.vue';
	import tiewk from './tiewk/tiewk.vue';
	import Lechart from '@/subpkg/uni_modules/lime-echart/components/l-echart/l-echart.vue';
	import {
		mapState
	} from 'vuex';
	export default {
		components: {
			scrollView,
			PieCharts,
			tiewk,
			enterprise,
			Lechart
		},
		data() {
			return {
				navList: [
					// 	{
					// 	name: "按科室"
					// },

					{
						name: "按种类"
					}, {
						name: "集采"
					}
				],
				statType: "mcsType",
				LineData: [], //折线图数据
				EllData: [], //总汇折线图
				AllData: [], //存放全部数据
				yearl: [], //切换年月的数组
				pieData: [], //饼图
				AdList: null, //main实例
				type: 1, //交易分析模块里的类型
				valueList: 'Y',
				valueTimeType: "Y",
				flagE: 1,
				rangelineChart: [{
						value: 'Y',
						text: "年"
					},
					{
						value: 'M',
						text: "月"
					},
				],
				rangeringChart: [{
					value: 'Y',
					text: "年",
				}, {
					value: 'M',
					text: "月",
				}, {
					value: 'W',
					text: "周",
				}, {
					value: 'D',
					text: "日",
				}],
				fwfTrendType: 'Y', // 药耗服务费趋势时间类型
				fwfTrendData: [],  // 药耗服务费折线图数据
				fwfTrendYearl: [], // x轴数据
				supplierSummary: {
					totalFwf: 0,
					supplierCount: 0
				},
				supplierList: []
			}
		},
		computed: {
			...mapState(['instData'])
		},
		created() {
			this.listData();
			this.Listson();
			this.loadSupplierSummary();
			this.loadSupplierList(); 
		},
		mounted() {
			console.log('页面加载了没有');
			//加载饼环数据
			this.loadRingData();
			//加载折线图数据
			this.loadLineData();
			this.loadFwfTrendData();
		},
		methods: {
			onPullDownRefresh() {
				this.listData();
				this.Listson();
				this.$refs.enterpriseComponent.getData();
				this.$refs.tiewkComponent.listData();
				this.$refs.scrollViewComponent.listData();
				this.$refs.PieChartsComponent.listData();
				setTimeout(function() {
					uni.stopPullDownRefresh(); //停止下拉刷新动画
				}, 1000);
			},
			Listson() {
				this.$http('homePage.amtCosm', {
					timeType: this.valueTimeType
				}, '加载中').then((res) => {
					this.pieData = res.data;
					this.pieData = res.data.map((item) => {
						return {
							value: item.mcsAmt,
							name: item.mcsType,
						};
					});
					// 获取饼图的图例数据
					this.pieName = res.data.map((item) => item.mcsType);
					this.loadRingData();
				});
			},
			listData() {
				this.AllData = [];
				// 获取每个月的天数;
				const getDaysInMonth = (year, month) => {
					return new Date(year, month, 0).getDate();
				};
				this.$http('homePage.statCosm', {
					timeType: this.valueList,
					statType: this.statType
				}, '加载中').then((res) => {
					const year = new Date().getFullYear(); // 获取当前年份
					if (this.valueList === "M") {
						const daysInMonth = getDaysInMonth(year, new Date().getMonth() + 1); // 获取当前月份的天数
						this.yearl = Array.from({
							length: daysInMonth
						}, (_, i) => i + 1).map(
							(day) => `${day}`
						);
					} else {
						this.yearl = Array.from({
							length: 12
						}, (_, i) => i + 1).map(
							(month) => `${month}月`
						);
					}
					this.LineData = res.data.deptCosmList;
					this.EllData = res.data.totalCosm;
					const ellSeries = {
						name: "全部",
						data: this.EllData,
						smooth: true,
						type: "line",
					};
					this.AllData.push(ellSeries);
					const lineSeries = this.LineData.map((item) => ({
						name: item.type,
						data: item.cnt,
						smooth: true,
						type: "line",
					}));
					this.AllData = this.AllData.concat(lineSeries);
					this.loadLineData();
				})
			},
			changelineChart(e) {
				this.valueList = e
				this.updateListData();
			},
			// 消耗数据统计
			handleClickBtnE(index) {
				this.flagE = index + 1;
				if (index === 0) {
					// this.handleQuery("dept");
					// this.updateListData();
					this.handleQuery("mcsType");
					this.updateListData();
				} else if (index === 1) {
					this.handleQuery("isFas");
					this.updateListData();
				} else if (index === 2) {

				}
			},
			handleQuery(param) {
				this.statType = param;
			},
			updateListData() {
				this.listData({
					mcsType: this.valueList,
					timeType: this.value
				});
			},
			changeringChart(e) {
				this.valueTimeType = e
				this.Listson({
					timeType: this.valueTimeType
				})
			},
			loadRingData() {
				//这里请求服务器得到数据
				let data = this.pieData

				//这里option配置参考文档：https://echarts.apache.org/zh/option.html
				this.$refs.ringChart.init(echarts, chart => {
					chart.setOption({
						legend: {
							data: this.pieData.map((item) => item.name),
							left: "3%",
							top: "30%",
							orient: "vertical",
						},
						tooltip: {
							trigger: "item",
							position: ['30%', '30%'],
							axisPointer: {
								type: "shadow",
							},
							backgroundColor: "#fff", // 悬浮框背景色
							// borderColor: "#000", // 悬浮框边框颜色
							borderWidth: 1, // 悬浮框边框宽度
							textStyle: {
								// 悬浮框文字样式
								color: "#000",
								fontSize: '10rpx',
							},
							formatter: "{b} : {c}万元: {d}%", //鼠标移入提示框显示内容
						},
						series: [{
							type: 'pie',
							// selectedMode: 'single',
							// selectedOffset: 0,
							// hoverAnimation: false,
							radius: [40, 65],
							left: 'center',
							width: '98%',
							//隐藏默认白边
							itemStyle: {
								borderColor: '#fff',
								borderWidth: 0
							},
							//格式化label显示
							label: {
								alignTo: 'edge',
								show: true,
								formatter: "{b} : {c}万元: {d}%",
								minMargin: 5,
								edgeDistance: 20,
								lineHeight: 24,
								rich: {
									time: {
										fontSize: 10,
										color: '#999'
									}
								}
							},
							//指向label的线设置
							labelLine: {
								length: 15,
								length2: 0,
								maxSurfaceAngle: 80
							},
							//布局样式
							labelLayout: function(params) {
								const isLeft = params.labelRect.x < chart.getWidth() / 2;
								const points = params.labelLinePoints;

								points[2][0] = isLeft ?
									params.labelRect.x :
									params.labelRect.x + params.labelRect.width;
								return {
									labelLinePoints: points
								};
							},

							//数据
							data: this.pieData
						}]
					});
					//默认突出高亮显示，可以放开下面注释
					// chart.dispatchAction({
					// 	type: 'highlight',
					// 	seriesIndex: 0,
					// 	dataIndex: 0
					// });
					//监听图标项点击事件
					chart.on("click", function(e) {
						for (var i = 0; i < data.length; i++) {
							if (i != e.dataIndex) {
								chart.dispatchAction({
									type: 'downplay', //取消高亮显示;
									seriesIndex: 0,
									dataIndex: i
								});
							} else {
								chart.dispatchAction({
									type: 'highlight', //突出高亮显示;
									seriesIndex: 0,
									dataIndex: i
								});
							}
						}
					});
				});
			},
			//加载折线图数据
			loadLineData() {
				let chartColors = [
					'#FF6B6B', // 红
					'#4ECDC4', // 青绿
					'#FFD93B', // 黄
					'#1A535C', // 深青
					'#FF8C42', // 橙
					'#6A4C93', // 紫
					'#00B8A9', // 蓝绿
					'#F6416C', // 粉
					'#43DDE6', // 浅蓝
					'#3D5A80', // 蓝
					'#EE6C4D', // 橙红
					'#FFB400', // 金黄
					'#8D8741', // 棕
				];
				let option = {
					legend: {
						data: this.AllData.map((item) => item.name),
					},
					dataZoom: [{
						bottom: 10,
						height: 20,
						type: 'inside',
						show: true,
						xAxisIndex: [0],
						start: this.valueList === "M" ? 10 : 120,
						end: this.valueList === "M" ? 35 : 350
					}],
					xAxis: {
						type: 'category',
						axisLabel: { color: '#a7a7a7' },
						axisLine: { lineStyle: { color: '#f1f1f1' } },
						axisTick: { show: false },
						data: this.yearl,
					},
					grid: { top: 40, bottom: 30 },
					yAxis: {
						type: 'value',
						axisLabel: { color: '#a7a7a7' },
						splitLine: { show: true, lineStyle: { type: 'dashed' } }
					},
					tooltip: {
						trigger: 'axis',
						triggerOn: 'click',
						formatter: '{b}:  \n {a0}: {c0} \n {a1}: {c1} \n {a2}: {c2} \n {a3}: {c3}'
					},
					color: chartColors,
					series: this.AllData
				};

				this.$refs.lineChart.init(echarts, chart => {
					chart.setOption(option);
				});
			},
			changeFwfTrendType(e) {
				this.fwfTrendType = e;
				this.loadFwfTrendData();
			},
			loadFwfTrendData() {
				// 获取每个月的天数
				const getDaysInMonth = (year, month) => {
					return new Date(year, month, 0).getDate();
				};
				this.$http('homePage.statFwfCosm', {
					timeType: this.fwfTrendType
				}, '加载中').then((res) => {
					const year = new Date().getFullYear();
					if (this.fwfTrendType === "M") {
						const daysInMonth = getDaysInMonth(year, new Date().getMonth() + 1);
						this.fwfTrendYearl = Array.from({ length: daysInMonth }, (_, i) => i + 1).map(day => `${day}`);
					} else {
						this.fwfTrendYearl = Array.from({ length: 12 }, (_, i) => i + 1).map(month => `${month}月`);
					}
					this.fwfTrendData = [{
						name: "服务费",
						data: res.data.fwfAmt || [],
						smooth: true,
						type: "line",
					}];
					this.loadFwfTrendChart();
				});
			},
			loadFwfTrendChart() {
				let option = {
					legend: {
						data: this.fwfTrendData.map(item => item.name),
					},
					xAxis: {
						type: 'category',
						axisLabel: { color: '#a7a7a7' },
						axisLine: { lineStyle: { color: '#f1f1f1' } },
						axisTick: { show: false },
						data: this.fwfTrendYearl,
					},
					grid: { top: 40, bottom: 30 },
					yAxis: {
						type: 'value',
						axisLabel: { color: '#a7a7a7' },
						splitLine: { show: true, lineStyle: { type: 'dashed' } }
					},
					tooltip: {
						trigger: 'axis',
						triggerOn: 'click',
						formatter: '{b}:  \n {a0}: {c0}'
					},
					color: ['#4e9d77'],
					series: this.fwfTrendData
				};
				this.$refs.fwfTrendChart.init(echarts, chart => {
					chart.setOption(option);
				});
			},
			loadSupplierSummary() {
        this.$http('homePage.mcsTotalFwf', {
            spdId: this.instData.spdId
        }, '加载中').then(res => {
            this.supplierSummary.totalFwf = res.data.totalFwf || 0;
            this.supplierSummary.supplierCount = res.data.splerSum || 0;
        });
    },
    // 各供应商贡献度列表
    loadSupplierList() {
        this.$http('homePage.mcsSplerFwfBl', {
            spdId: this.instData.spdId
        }, '加载中').then(res => {
            this.supplierList = (res.data || []).map(item => ({
                id: item.splerId,
                name: item.splerName,
                rate: item.gxd,
                fwf: item.splerAmt != null ? item.splerAmt : '--'
            }));
        });
    },
		}
	}
</script>

<style lang="scss" scoped>
@import './h1z1.css';
</style>