<template>
	<div style="background-color:#f7f7f7;padding:10px 10px;">
		<div class="zhuti ">
			<div style="height:58px;line-height:58px;">
				<div style="color:#0006"> <span>招商资源监测</span> <span style="padding:0 5px;">></span> <span
						style="color:#000000e6">统计分析</span></div>
			</div>
			<div style="width: 100%;margin-bottom:30px;">
				<div style="display:flex;justify-content: space-between">
					<div style="display:flex;">
						<el-date-picker v-model="FormTime" value-format="yyyy-MM-dd" type="daterange"
							range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
							style="width: 300px;margin-right: 10px;" prefix-icon="none">
						</el-date-picker>
						<el-select v-model="msgList.belongingGreenwaySection" placeholder="请选择"
						  style="width: 168px;margin-right: 10px;">
						  <el-option :label="item.name" :value="item.code" v-for="(item,index) in lvdaoList"
						    :key="index"></el-option>
						</el-select>
						<el-button @click="onSubmit" style="background-color: #3F9B6A;color: #fff;">查询
						</el-button>
						<el-button @click="resetting" class="buttonHover"
							style="color: #000;border: 1px solid #DBDBDB;background-color: #fff;">重置
						</el-button>
					</div>
					<div>
						<el-button @click="gitOut" style="background-color: #3F9B6A;color: #fff">导出
						</el-button>
					</div>
				</div>
			</div>
			<div style="width: 100%;display: flex;margin-bottom: 20px;">
				<div style="width: 50%;">
					<div>
						<TitleWithCircle title="资源数量增长趋势" style="margin: 10px 0;" />
					</div>
					<div>
						<div ref="echarts1" style="width:100%;height: 400px;"></div>
					</div>
				</div>
				<div style="width: 50%;">
					<div>
						<TitleWithCircle title="资源分布统计" style="margin: 10px 0;" />
					</div>
					<div>
						<div ref="shop2TJ" style="width:100%;height: 400px;"></div>
					</div>
				</div>
			</div>
			<div style="width: 100%;display: flex;">
				<div style="width: 50%;">
					<div>
						<TitleWithCircle title="资源情况占比" style="margin: 10px 0;" />
					</div>
					<div>
						<div ref="zyzbTJ" style="width:100%;height: 400px;"></div>
					</div>
				</div>
				<div style="width: 50%;">
					<div>
						<TitleWithCircle title="资源利用率占比" style="margin: 10px 0;" />
					</div>
					<div>
						<div ref="zylhlTJ" style="width:100%;height: 400px;"></div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import html2canvas from 'html2canvas'
	import jsPDF from 'jspdf'
	import TitleWithCircle from '@/components/top/index';
	import * as echarts from 'echarts'
	import {
	resourceQuantityGrowth,
    resourceDistributionStatistics,
    resourceSituationProportion,
    resourceUtilizationProportion,
  } from '@/api/newly.js'
  import {
    lvdaoduan,
  	parkTrails
  } from '@/api/information.js';
	export default {
		components: {
			TitleWithCircle,
		},
		name: 'atmosphereGl',
		data() {
			return {
				currentPage: 1,
				radio1: 0,
				total: 100,
				flag: false,
				pageSize: 10,
				tableData: [],
				FormTime: [],
				pageindex: {
					startTime: "1990-09-11",
					endTime: "2024-11-09"
				},
				msgList:{
					belongingGreenwaySection:'',
					belongingParkTrail:''
				},
				lvdaoList: [],
			}
		},
		computed: {},
		created() {
			//获取今天日期和一个月前的日期
			let today = new Date();
			let monthAgo = new Date();
			monthAgo.setMonth(monthAgo.getMonth() - 1);
			monthAgo.setDate(monthAgo.getDate() + 1);
			this.pageindex.startTime = monthAgo.toISOString().slice(0, 10);
			this.pageindex.endTime = today.toISOString().slice(0, 10);
			this.FormTime = [
				this.pageindex.startTime,
				this.pageindex.endTime
			]
			this.getAll()
			this.getlvdao()
		},
		mounted() {
		},
		methods: {
			async getlvdao(){
			const lvdao = await lvdaoduan()
			const gongyua  = await parkTrails() 
			  this.lvdaoList = lvdao.data.concat(gongyua.data)	
			},
			initecharts1(datas) {
				let Dom = this.$refs.echarts1
				let myChart = echarts.init(Dom);  
				  // 提取所有日期
				      const allDates = [];
				      Object.values(datas).forEach(trend => {
				        trend.forEach(item => {
				          if (!allDates.includes(item.trendDate)) {
				            allDates.push(item.trendDate);
				          }
				        });
				      });
				      allDates.sort();
				
				      // 提取每条折线的数据
				      const shopData =datas.shopTrend.map(item => item.trendQuantity);
				      const venueData = datas.venueTrend.map(item => item.trendQuantity);
				      const advertisingData = datas.advertisingTrend.map(item => item.trendQuantity);
				      const greenwayData = datas.greenwayTrend.map(item => item.trendQuantity);
				
				      const option = {
				        tooltip: {
				          trigger: 'axis'
				        },
				        legend: {
				          data: ['商铺资源增长趋势', '场地资源增长趋势', '广告位资源增长趋势', '总资源增长趋势'],
					
				        },
				        xAxis: {
				          type: 'category',
				          data: allDates
				        },
				        yAxis: {
				          type: 'value'
				        },
						  color: ['#4A90E2', '#37c954', '#F7C153', '#7a69d8'], // 使用浅色系颜色
				        series: [
				          {
				            name: '商铺资源增长趋势',
				            type: 'line',
				            data: shopData
				          },
				          {
				            name: '场地资源增长趋势',
				            type: 'line',
				            data: venueData
				          },
				          {
				            name: '广告位资源增长趋势',
				            type: 'line',
				            data: advertisingData
				          },
				          {
				            name: '总资源增长趋势',
				            type: 'line',
				            data: greenwayData
				          }
				        ]
				      };

				option && myChart.setOption(option);
				window.addEventListener('resize', function() {
					myChart.resize();
				})
			},
			initecharts2(val) {
				// 获取图表容器的 DOM 元素
				const chartDom = this.$refs.shop2TJ
				// 初始化 ECharts 实例
				const myChart = echarts.init(chartDom);
			
				// 处理数据
				      const processedData = [
				        { name: '商铺分布占比', value: val.shopCount },
				        { name: '场地分布占比', value: val.vendorCount },
				        { name: '广告位分布占比', value: val.advertisingCount }
				      ];
			 const option = {
			        tooltip: {
			          trigger: 'axis',
			          axisPointer: {
			            type: 'shadow'
			          },
			          formatter: function (params) {
			            return `${params[0].name}: ${params[0].value}%`;
			          }
			        },
			        xAxis: {
			          type: 'category',
			          data: processedData.map(item => item.name)
			        },
			        yAxis: {
			          type: 'value',
			          name: '分布占比(%)',
			          axisLabel: {
			            formatter: '{value}%'
			          }
			        },
			        series: [
			          {
			            name: '资源分布',
			            type: 'bar',
			            data: processedData.map(item => item.value),
			            itemStyle: {
			              color: function (params) {
			                const colors = ['#3F7BC5', '#3F9B6A', '#F7C153'];
			                return colors[params.dataIndex % colors.length];
			              }
			            }
			          }
			        ]
			      };

				// 使用刚指定的配置项和数据显示图表
				option && myChart.setOption(option)
				window.addEventListener('resize', function() {
					myChart.resize();
				})
			},
			initecharts3(val) {
				// 获取图表容器的 DOM 元素
				const chartDom = this.$refs.zyzbTJ
				// 初始化 ECharts 实例
				const myChart = echarts.init(chartDom);
			
			   // 统计不同发布状态的总数
			      const statusCountMap = {
			        0: 0,
			        1: 0,
			        2: 0,
			        4: 0
			      };
			
			      Object.values(val).forEach(resourceType => {
			        resourceType.forEach(item => {
			          statusCountMap[item.publishStatus] += item.statusCount;
			        });
			      });
			
			      const statusLabels = {
			        0: '待发布',
			        1: '待审核',
			        2: '已发布',
			        4: '已租赁'
			      };
			
			      const chartData = Object.keys(statusCountMap).map(status => ({
			        name: statusLabels[status],
			        value: statusCountMap[status]
			      }));
			
			      const option = {
			        tooltip: {
			          trigger: 'item',
			          formatter: '{b}: {c}%'
			        },
			        legend: {
			   orient: 'horizontal', // 横向展示
			          left: 'center', // 居中显示
			          data: chartData.map(item => item.name)
			        },
			        series: [
			          {
						  color: ['#F7C153', '#3F7BC5', '#3F9B6A','#904bf7'],
			            name: '发布状态',
			            type: 'pie',
			            radius: '50%',
			            data: chartData,
			            label: {
			              formatter: '{b}: {d}%'
			            }
			          }
			        ]
			      };
				// 使用刚指定的配置项和数据显示图表
				option && myChart.setOption(option)
				window.addEventListener('resize', function() {
					myChart.resize();
				})
			},
			initecharts4(val) {
				// 获取图表容器的 DOM 元素
				const chartDom = this.$refs.zylhlTJ
				// 初始化 ECharts 实例
				const myChart = echarts.init(chartDom);
			
			 // 处理数据
			      const processedData = [
			        { name: '商铺', value: val.shop },
			        { name: '场地', value: val.venue },
			        { name: '广告位', value: val.adv }
			      ];
			
			    const option = {
					title: [
					    {
					      text: `已发布总数:${val.total}`,
					      left: 'center',
					      top: 'center',
					      textStyle: {
					        fontSize: 14,
					        fontWeight: 'bold'
					      }
					    }
					  ],
			      tooltip: {
			        trigger: 'item',
			        formatter: function (params) {
			          return `${params.name}: ${params.value}%`;
			        }
			      },
			      legend: {
			         orient: 'horizontal', // 横向展示
			                left: 'center', // 居中显示
			        data: processedData.map(item => item.name)
			      },
			      series: [
			        {
			    					 color: ['#F7C153', '#3F7BC5', '#3F9B6A'],
			          name: '资源分布',
			          type: 'pie',
			    				   radius: ['40%', '60%'],
			          avoidLabelOverlap: false,
			          label: {
			            show: true,
			            position: 'outside',
			            formatter: '{b}: {c}%'
			          },
			          labelLine: {
			            show: true
			          },
			         data: processedData
			        },
			        
			      ]
			    };
				// 使用刚指定的配置项和数据显示图表
				option && myChart.setOption(option)
				window.addEventListener('resize', function() {
					myChart.resize();
				})
			},
			async getAll() {
				const res1 = await resourceQuantityGrowth({...this.pageindex})
				const res2 = await resourceDistributionStatistics({...this.msgList})
				const res3 = await resourceSituationProportion()
				
				 const res4 = await resourceUtilizationProportion()
					
				this.initecharts1(res1.data)
				this.initecharts2(res2.data)
				this.initecharts3(res3.data)
				this.initecharts4(res4.data)
			},
			resetting() {
				let today = new Date();
				let monthAgo = new Date();
				monthAgo.setMonth(monthAgo.getMonth() - 1);
				monthAgo.setDate(monthAgo.getDate() + 1);
				this.pageindex.startTime = monthAgo.toISOString().slice(0, 10);
				this.pageindex.endTime = today.toISOString().slice(0, 10);
				this.FormTime = [
					this.pageindex.startTime,
					this.pageindex.endTime
				]
				this.getAll()
			},
			async onSubmit() {

				let Msg = {
					startTime: this.FormTime[0],
					endTime: this.FormTime[1]
				}
				
				const res1 = await resourceQuantityGrowth(Msg)
				const res2 = await resourceDistributionStatistics({...this.msgList})
				const res3 = await resourceSituationProportion()
					
				 const res4 = await resourceUtilizationProportion()
					
				this.initecharts1(res1.data)
				this.initecharts2(res2.data)
				this.initecharts3(res3.data)
				this.initecharts4(res4.data)
			},
			async gitOut() {
				const content = this.$refs.contentToConvert;

				// 使用 html2canvas 将 div 渲染为画布
				const canvas = await html2canvas(content);

				// 获取画布的图像数据
				const imgData = canvas.toDataURL('image/png');

				// 创建一个新的 PDF 文档
				const pdf = new jsPDF('p', 'mm', 'a4');

				// 添加图像到 PDF，第二个参数是图像格式，第三个参数是缩放比例
				const imgWidth = 190; // 图像的宽度（mm）
				const imgHeight = (canvas.height * imgWidth) / canvas.width; // 保持图像的宽高比

				pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight); // 10, 10 是图像在 PDF 中的位置（mm）

				// 保存 PDF 文件
				pdf.save('downloaded.pdf');
			},
		}
	}
</script>

<style scoped>
	.zhuti {
		padding: 0 20px 20px 20px;
		min-height: calc(100vh - 50px - 20px);
		background-color: #Fff;

	}

	/deep/ .el-form-item__content {
		line-height: 0;
	}



	.formSearch {
		position: relative;
		margin-top: 30px;
		display: flex;
		width: 100%;
		height: 30px;
		font-size: 14px;
		margin-bottom: 10px;
	}

	.greens {
		color: #3F9B6A;
	}


	.fenye {
		margin-top: 20px;
		display: flex;
		justify-content: flex-start;
		position: relative;
	}

	/deep/ .el-pagination.is-background .el-pager li:not(.disabled).active {
		background-color: #3F9B6A;
	}

	.el-row {
		margin-bottom: 20px;
	}

	:last-child {
		margin-bottom: 0;
	}

	.el-col {
		border-radius: 4px;
	}

	.bg-purple-dark {
		background: #99a9bf;
	}

	.bg-purple {
		background: #d3dce6;
	}

	.bg-purple-light {
		background: #e5e9f2;
	}

	.grid-content {
		border-radius: 4px;
		min-height: 36px;
	}

	.row-bg {
		padding: 10px 0;
		background-color: #f9fafc;
	}

	/deep/ .bg-purple[data-v-0e3fe4ec] {
		background: #fff;
		height: 50px;
	}

	/deep/ .el-form--label-top .el-form-item__label {
		padding: 0;
	}

	.demo-input-suffix {
		display: flex;
		margin-right: 20px;
	}

	.pagination {
		text-align: right;
		line-height: 20px;
	}

	/deep/ .el-pagination__total {
		margin-top: 4px;
	}

	::v-deep .el-select .el-input.is-focus .el-input__inner {
		border-color: #3F9B6A
	}

	/deep/ .el-dialog__header {
		background-color: #fff;
		padding: 0
	}

	/deep/ .el-radio__input.is-checked .el-radio__inner {
		border-color: #3F9B6A;
		background: #3F9B6A;
	}

	::v-deep .buttonHover:hover {
		color: #3f9b6a !important;
		border-color: #c5e1d2 !important;
		background-color: #ecf5f0 !important;
		outline: none;
	}
</style>