<template>
	<div class="div_main">
		<div>
			<div class="div_search">
				<el-form :inline="true" :model="formData" ref="ref_searchform" :label-width="'80px'">
					<div>
						<el-form-item label="所属组织" prop="orgId">
							<el-cascader
								class="customer_cascader"
								ref="myCascader"
								filterable
								v-model="formData.orgId"
								:options="orgOptions"
								:props="orgOptionProps"
								:show-all-levels="false"
								@change="handleChangeAgency"
							></el-cascader>
						</el-form-item>

						<el-form-item label="更新时间" prop="startDate">
							<el-date-picker
								v-model="formData.startDate"
								:picker-options="startPickerOptions"
								class="item_width_2"
								size="small"
								type="date"
								value-format="yyyy-MM-dd HH:mm:ss"
								value="yyyy-MM-dd"
								placeholder="开始时间"
								@change="handleSearch"
							></el-date-picker>
							<span class="data-tag">至</span>
							<el-date-picker
								v-model="formData.endDate"
								:picker-options="endPickerOptions"
								class="item_width_2 data-tag"
								size="small"
								type="date"
								value-format="yyyy-MM-dd HH:mm:ss"
								value="yyyy-MM-dd"
								placeholder="结束时间"
								@change="handleSearch"
							></el-date-picker>
						</el-form-item>

						<el-button class="btnSearch" size="small" @click="handleSearch">查询</el-button>
						<el-button class="diy-button--output" size="small" @click="resetForm">重置</el-button>
					</div>
				</el-form>
				<div class="flex">
					<div class="census_searchcensus" v-if="level == 'city'">
						<div class="census_searchcensus_box">
							<img src="../../../assets/img/census/区级.png" />
							<div>
								<h2>{{ censusData.district }}</h2>
								<h3>区县数</h3>
							</div>
						</div>
					</div>
					<div class="census_searchcensus" v-if="level == 'city' || level == 'district'">
						<div class="census_searchcensus_box">
							<img src="../../../assets/img/census/镇街.png" />
							<div>
								<h2>{{ censusData.street }}</h2>
								<h3>镇街数</h3>
							</div>
						</div>
					</div>

					<div class="census_searchcensus" v-if="level == 'city' || level == 'district' || level == 'street'">
						<div class="census_searchcensus_box">
							<img src="../../../assets/img/census/社区.png" />
							<div>
								<h2>{{ censusData.community }}</h2>
								<h3>社区数</h3>
							</div>
						</div>
					</div>

					<div class="census_searchcensus">
						<div class="census_searchcensus_box">
							<img src="../../../assets/img/census/网格数.png" />
							<div>
								<h2>{{ censusData.grid }}</h2>
								<h3>网格数</h3>
							</div>
						</div>
					</div>
					<div class="census_searchcensus" @click="show(3)">
						<div class="census_searchcensus_box">
							<img src="../../../assets/img/census/工作人员.png" />
							<div>
								<h2>{{ censusData.staff }}</h2>
								<h3>工作人员数</h3>
							</div>
						</div>
					</div>
				</div>
			</div>
			<el-row :gutter="20">
				<el-col :span="24">
					<div class="div_table">
						<div class="div_table_title">下级社区数量统计</div>
						<div :style="'height:' + TableHeight + 'px;margin-top:20px'" :height="maxTableHeight">
							<screen-echarts-frame
								@handelClickMyPei="handelClickMyPei"
								:style="{ width: '100%', height: '100%' }"
								@myChartMethod="pieInitOk"
								ref="pieChart"
							></screen-echarts-frame>
						</div>
					</div>
				</el-col>
			</el-row>
		</div>
		<el-dialog :title="title" :visible.sync="dialogVisible" v-if="dialogVisible" width="50%" :before-close="handleClose">
			<el-table :data="tableDataView" border v-loading="tableLoading2" :header-cell-style="{ background: '#2195FE', color: '#FFFFFF' }" class="table" style="width: 100%">
				<el-table-column label="序号" type="index" align="center" width="50" />
				<el-table-column prop="name" align="center" label="社区名称" :show-overflow-tooltip="true"></el-table-column>
				<el-table-column prop="streeName" label="所属街道" align="center" :show-overflow-tooltip="true" />
				<el-table-column prop="districtName" label="所属区县" align="center" :show-overflow-tooltip="true"></el-table-column>
				<el-table-column prop="createTime" align="center" width="200" label="开通时间" :show-overflow-tooltip="true"></el-table-column>
			</el-table>

			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page.sync="pageNo"
				:page-sizes="[10, 20, 50, 100, 200]"
				:page-size="parseInt(pageSize)"
				layout="sizes, prev, pager, next, total,jumper"
				:total="total"
			></el-pagination>
		</el-dialog>
	</div>
</template>

<script>
import screenEchartsFrame from './chart';

import { requestPost, requestGet } from '@/js/dai/request';
import nextTick from 'dai-js/tools/nextTick';
import { mapGetters } from 'vuex';

import axios from 'axios';

export default {
	components: {},

	data() {
		let endDisabledDate = time => {
			//这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
			let nowData = Date.now();
			if (this.formData.startDate) {
				let startDate = new Date(this.formData.startDate);
				return time.getTime() > nowData || time.getTime() < startDate || time.getTime() === startDate;
			} else {
				return time.getTime() > nowData;
			}
		};
		let startDisabledDate = time => {
			//这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
			let nowData = Date.now();
			return time.getTime() > nowData;
		};
		return {
			pieChart: '',
			pieOption: {},
			pieInitState: false,
			pieData: [],
			title: '',
			dialogVisible: false,
			tableLoading: false,
			tableLoading2: false,
			pageType: 'list', // 列表list 新增add  处理dispose 详情info
			user: {},
			agencyId: '',
			gridList: [], //所属网格list--场所区域
			agencyIdArray: [],
			orgOptions: [],
			orgOptionProps: {
				multiple: false,
				checkStrictly: true,
				emitPath: false,
				children: 'subAgencyList',
				label: 'agencyName',
				value: 'agencyId'
			},
			tableData: [],
			tableDataView: [],
			censusData: { district: '', street: '', community: '', grid: '', staff: '' },
			formData: {
				orgId: '',
				level: '',
				startDate: '',
				endDate: ''
			},

			cateOptions: [],
			eventTypeCheck: [],
			pageNo: 1,
			pageSize: window.localStorage.getItem('pageSize') || 10,
			total: 1,
			endPickerOptions: {
				disabledDate: endDisabledDate
			},
			startPickerOptions: {
				disabledDate: startDisabledDate
			},
			eventId: '',
			orgType: '',
			eventDetailData: {},

			showVoice: false,
			selVoiceUrl: '',

			multipleSelection: [],
			TableHeight: '',
			pieData: {},
			agencyId: '',
			level: ''
		};
	},
	components: {
		screenEchartsFrame
	},
	computed: {
		maxTableHeight() {
			this.TableHeight = this.$store.state.inIframe ? this.clientHeight - 431 + this.iframeHeigh : this.clientHeight - 431;
			console.log('this.TableHeight', this.TableHeight);
			return this.TableHeight;
		},

		...mapGetters(['clientHeight', 'iframeHeight'])
	},
	watch: {
		'formData.endDate': function(val) {
			if (val && val != '') {
				let arrayTemp = val.split(' ');
				this.formData.endDate = arrayTemp[0] + ' 23:59:59';
			}
		}
	},
	mounted() {
		console.log(this.$store.state);
		this.user = this.$store.state.user;
		this.agencyId = this.user.agencyId;
		console.log(this.user);
		this.getOrgTreeList();

		this.getTableData();
		this.getsubData();
		this.getCountLevel();

		// this.getPie();
	},
	methods: {
		resetForm() {
			for (const n in this.formData) {
				if (typeof this.formData[n] == 'object') this.formData[n] = [];
				else this.formData[n] = '';
			}
			this.handleSearch();
		},
		handleSearch(val) {
			this.getTableData();
			this.getsubData();
			this.getCountLevel();
		},
		show() {
			this.pageNo = 1;
			this.showNext();
			this.dialogVisible = true;
		},
		handleClose() {
			this.dialogVisible = false;
		},
		async showNext() {
			let url = '';
			let param = {};
			console.log('this.orgType', this.orgType);
			this.title = this.orgName + '社区列表';
			// district street community
			// 1 是区县 2是镇街 3是社区  4是下级
			url = '/gov/org/customeragency/getCommunityList';
			param = {
				agencyId: this.orgId,
				timeStart: this.formData.startDate,
				timeEnd: this.formData.endDate,
				pageNum: this.pageNo,
				pageSize: this.pageSize
			};
			this.tableLoading2 = true;
			const { data, code, msg } = await requestPost(url, param);
			this.tableLoading2 = false;
			if (code === 0) {
				this.total = data.total || 0;
				this.tableDataView = data.list
					? data.list.map(item => {
							return item;
					  })
					: [];
			} else {
				this.$message.error(msg);
			}
		},

		handleChangeAgency(val) {
			let obj = this.$refs['myCascader'].getCheckedNodes()[0].data;
			console.log(obj);
			this.formData.orgId = obj.agencyId;
			this.formData.level = obj.level;
		},
		getOrgTreeList() {
			// gov/org/customeragency/staffinagencylist

			const { user } = this.$store.state;
			this.$http
				.post('gov/org/customeragency/staffinAgencyLevelList', {})
				.then(({ data: res }) => {
					if (res.code !== 0) {
						return this.$message.error(res.msg);
					} else {
						console.log('获取组织树成功', res.data);
						let { agencyList, subAgencyList } = res.data;
						const _arr = [{ ...agencyList, subAgencyList: [...subAgencyList] }];
						this.orgOptions = this.deepTree(_arr);
					}
				})
				.catch(() => {
					return this.$message.error('网络错误');
				});
		},

		//加载组织数据
		async handleDispose(row) {
			this.eventId = row.icEventId;
			const url = '/gov/project/icEvent/detail';
			// const url = "http://yapi.elinkservice.cn/mock/245/gov/project/icEvent/detail";

			const { data, code, msg } = await requestPost(url, {
				icEventId: this.eventId
			});

			if (code === 0) {
				this.eventDetailData = { ...data };
				this.pageType = 'dispose';
			} else {
				this.$message.error(msg);
			}
		},

		async getCountLevel() {
			console.log('this.formData.orgId', this.formData.orgId);

			let agencyId = '';
			let tmp = this.formData.orgId;
			if (!tmp && typeof tmp != 'undefined' && tmp != 0 && tmp != null) {
				agencyId = this.formData.orgId;
				this.level = this.formData.level;
			} else {
				agencyId = this.agencyId;
				this.level = this.user.level;
			}

			const url = '/gov/org/customeragency/getAgencyCountList';
			let params = { agencyId: agencyId, timeStart: this.formData.startDate, timeEnd: this.formData.endDate };
			const { data, code, msg } = await requestPost(url, params);

			if (code === 0) {
				data.map(item => {
					return (this.censusData[item.level] = item.count);
				});
				console.log('this.censusData', this.censusData);
			} else {
				this.$message.error(msg);
			}
		},
		async getTableData() {},
		async getsubData() {
			this.$refs.pieChart.showLoading();
			let url = '/gov/org/customeragency/getCommunityCountList';
			let agencyId = '';
			let tmp = this.formData.orgId;
			if (!tmp && typeof tmp != 'undefined' && tmp != 0 && tmp != null) {
				agencyId = this.formData.orgId;
			} else {
				agencyId = this.agencyId;
			}
			const { data, code, msg } = await requestPost(url, { agencyId: agencyId, timeStart: this.formData.startDate, timeEnd: this.formData.endDate });

			this.$refs.pieChart.hideLoading();

			if (code === 0) {
				this.pieData = data;
				// console.log('this.pieData ', this.pieData);
				this.getPie();
			} else {
				this.$message.error(msg);
			}
		},
		handleSizeChange(val) {
			this.pageSize = val;
			window.localStorage.setItem('pageSize', val);
			this.showNext();
		},
		handleCurrentChange(val) {
			this.pageNo = val;
			this.showNext();
		},
		deepTree(arr) {
			if (Array.isArray(arr)) {
				return arr.map(item => {
					return {
						...item,
						subAgencyList: (item.subAgencyList.length > 0 && this.deepTree(item.subAgencyList)) || null
					};
				});
			}
		},
		pieInitOk() {
			this.pieInitState = true;
		},
		getPie() {
			if (this.pieInitState) {
				this.setPieData();
			} else {
				setTimeout(() => {
					this.getPie();
				}, 500);
			}
		},
		setPieData() {
			let data = [...this.pieData];
			console.log('data', data);
			let chartData = {};
			chartData.name = data.map(item => item.agencyName);
			chartData.data = data.map(item => {
				return { value: item.count, id: item.agencyId, name: item.agencyName };
			});
			console.log('chartData', chartData);
			this.iniPieChart(chartData);
		},
		// 获取饼状图
		async iniPieChart(chartData) {
			this.$refs.pieChart.clear();
			
			// 获取pieChart配置
			this.pieOption = {
				grid: {
					x: 50,
					y: 50,
					x2: 50,
					y2: 50
				},
				tooltip: {
					trigger: 'axis'
				},
				xAxis: {
					type: 'category',
					data: chartData.name,
					axisLine: {
						show: true,
						lineStyle: {
							color: '#F3F7FD'
						}
					},
					axisLabel: {
						color: '#666666',
						interval: 0,
						interval: 0, //设置横坐标为斜
						rotate: 30, //文字倾斜角度
						formatter: function(value) {
							if (value.length > 10) {
								value = value.substring(0, 9) + '..';
							}
							return value;
						}
					}
				},
				yAxis: {
					type: 'value',
					splitArea: {
						show: true,
						areaStyle: {
							color: ['#fff', '#F3F7FD']
						}
					},
					axisLabel: {
						color: '#666666'
					},
					axisLine: {
						show: true,
						lineStyle: {
							color: '#F3F7FD'
						}
					},
					min: 0,
					max: 1000
				},
				series: [
					{
						data: chartData.data,
						barWidth: 24,
						type: 'bar',
						itemStyle: {
							color: 'rgb(33, 149, 254)',
							borderRadius: [4, 4, 0, 0]
						}
					}
				]
			};
			if (chartData.data.length>0) {
				this.pieOption.yAxis.max=null
			} 
			this.$refs.pieChart.setOption(this.pieOption);
		},
		handelClickMyPei(param) {
			if (param.data.level != 'community') {
				if (param.data.level == 'district') {
					this.orgType = 'street';
				}
				if (param.data.level == 'street') {
					this.orgType = 'community';
				}

				this.orgId = param.data.id;
				this.orgName = param.data.name;
				this.pageNo = 1;
				this.show();
				this.dialogVisible = true;
			}
		}
	}
};
</script>

<style lang="scss" scoped>
@import '@/assets/scss/buttonstyle.scss';
@import '@/assets/scss/modules/management/list-main.scss';
@import '@/assets/scss/modules/shequzhili/event-info.scss';
// .div_main .div_search{padding:35px}
.btnSearch {
	width: 100px;
	height: 36px;
	background: #2195fe;
	box-shadow: 0px 2px 6px 0px rgba(28, 107, 253, 0.31);
	border-radius: 6px;
	color: #fff;
}
.div_search {
	.item_width_2 {
		width: 200px;
	}
}
.flex {
	display: flex;
}
.census_searchcensus {
	text-align: center;
	margin: 0 auto;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 30px;
	margin-top: 20px;
	.census_searchcensus_box {
		cursor: pointer;
		display: flex;
		img {
			width: 64px;
			height: 64px;
			margin-right: 20px;
		}
		h2 {
			font-size: 28px;
			color: #333333;
			height: 40px;
			text-align: left;
			line-height: 40px;
			margin: 0px;
		}
		h3 {
			font-size: 14px;
			color: #333333;

			text-align: left;

			margin: 0px;
			font-weight: normal;
		}
	}
}
.div_table {
	padding: 30px !important;
}
.div_table_title {
	margin-top: -10px;
	line-height: 30px;
	font-size: 20px;

	font-weight: bold;
	color: #333333;
}
.diy-button--output {
	width: 100px;
	height: 38px;

	background: #feb349;
	box-shadow: 0px 2px 6px 0px rgba(198, 122, 16, 0.31);
	border-radius: 6px;
	color: #fff;
}
</style>
