<template>
	<div
		class="searchBarBox divHeight"
		ref="searchBarRef"
		:style="{ paddingRight: isFold ? '55px' : '0px' }">
		<el-form
			:inline="true"
			class="demo-form-inline">
			<span class="blue-block"></span>
			<el-form-item
				label="能源类型"
				required>
				<el-select
					v-model="queryParams.energyTypeId"
					placeholder="请选择"
					size="small"
					@change="chooseType"
					filterable
					style="width: 100%">
					<el-option
						v-for="item in energyTypeList"
						:key="item.id"
						:label="item.labelName"
						:value="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item
				v-if="energyType === 1"
				label="对象选择"
				required>
				<el-cascader
					v-model="objArr"
					:options="objList"
					:show-all-levels="false"
					:props="{ checkStrictly: true, value: 'id', label: 'name' }"
					size="small"
					@change="changeLine"
					clearable></el-cascader>
			</el-form-item>
			<el-form-item
				v-if="energyType === 2"
				label="对象选择"
				required>
				<el-select
					v-model="objId"
					placeholder="请选择"
					style="width: 250px"
					filterable
					size="small">
					<el-option
						v-for="item in objList"
						:key="item.id"
						:label="item.name"
						:value="item.id"
						:clearable="false"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item
				label="时间维度"
				required>
				<el-select
					v-model="queryParams.timeDim"
					placeholder="请选择"
					style="width: 80px"
					size="small">
					<el-option
						v-for="item in getDictDatas(this.DICT_TYPE.TIME_DIM)"
						:key="item.value"
						:label="item.label"
						:value="item.value"
						size="small"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item
				label="时间范围"
				required>
				<div v-show="queryParams.timeDim === '1'">
					<el-date-picker
						v-model="timeValue"
						type="datetimerange"
						range-separator="至"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
						format="yyyy-MM-dd HH:mm"
						value-format="timestamp"
						:picker-options="pickerOptions"
						popper-class="noneMinute"
						@change="timeSelect"
						size="small"
						style="width: 350px"></el-date-picker>
				</div>
				<div v-show="queryParams.timeDim === '2'">
					<el-date-picker
						v-model="dateValue"
						type="daterange"
						range-separator="至"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
						value-format="timestamp"
						:picker-options="pickerOptions"
						@change="timeSelect"
						size="small"
						style="width: 350px"></el-date-picker>
				</div>
				<div v-show="queryParams.timeDim === '3'">
					<el-date-picker
						v-model="weekValue1"
						type="week"
						format="yyyy 第 WW 周"
						style="width: 170px"
						:picker-options="pickerOptionsWeek"
						@change="startWeek"
						size="small"
						placeholder="选择周"></el-date-picker>
					-
					<el-date-picker
						v-model="weekValue2"
						type="week"
						format="yyyy 第 WW 周"
						:picker-options="pickerOptionsWeek"
						style="width: 170px"
						@change="endWeek"
						size="small"
						placeholder="选择周"></el-date-picker>
				</div>
				<div v-show="queryParams.timeDim === '4'">
					<el-date-picker
						v-model="monthValue"
						type="monthrange"
						range-separator="至"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
						value-format="timestamp"
						:picker-options="pickerOptions"
						size="small"
						style="width: 350px"
						@change="timeSelect"></el-date-picker>
				</div>
				<div v-show="queryParams.timeDim === '5'">
					<el-date-picker
						style="width: 170px"
						v-model="yearValue1"
						type="year"
						:picker-options="pickerOptions"
						value-format="timestamp"
						placeholder="选择年"
						size="small"
						@change="startYear"></el-date-picker>
					-
					<el-date-picker
						style="width: 170px"
						v-model="yearValue2"
						type="year"
						:picker-options="pickerOptions"
						value-format="timestamp"
						placeholder="选择年"
						size="small"
						@change="endYear"></el-date-picker>
				</div>
			</el-form-item>
			<el-form-item>
				<el-button
					type="primary"
					size="small"
					@click="handBtn('search')">
					查询
				</el-button>
				<el-button
					size="small"
					@click="resetBtn">
					重置
				</el-button>
				<span
					class="separateStyle"
					v-hasPermi="['analysis:trend-analysis:export']"></span>
				<el-button
					v-hasPermi="['analysis:trend-analysis:export']"
					type="primary"
					size="small"
					plain
					@click="handBtn('exportBtn')">
					导出
				</el-button>
			</el-form-item>
		</el-form>
		<span
			v-if="isFold"
			class="foldClass"
			@click="switchMode">
			{{ isExpand ? '收起' : '展开' }}
			<svg-icon :icon-class="isExpand ? 'upward' : 'downward'" />
		</span>
	</div>
</template>
<script>
import { getTree } from '@/api/analysis/energyAnalysis';
import { getEnergyTypeListAll } from '@/api/base/energyType';
import moment from 'moment';
export default {
	name: 'searchArea',
	props: {
		isFold: {
			// 多行模式（默认否）
			type: Boolean,
			default: false,
		},
	},
	data() {
		return {
			isExpand: false, // 展开收起
			// 查询参数
			queryParams: {
				energyTypeId: null,
				objId: null,
				timeDim: null,
				startTime: null,
				endTime: null,
				objType: 1, //1工厂2产线3工段
			},
			objId: null,
			objType: 1, //1工厂2产线3工段,非电使用
			energyTypeList: [],
			energyType: 0, //1电2非电
			objArr: [],
			timeValue: [], // 最大7天只能整点
			dateValue: [], // 最大30天
			weekValue1: null, //最多24周
			weekValue2: null,
			monthValue: [], //最多24月
			yearValue1: null, //最多10年
			yearValue2: null,
			objList: [],
			pickerOptions: {
				disabledDate(date) {
					return date.getTime() > Date.now();
				},
			},
			pickerOptionsWeek: {
				disabledDate(time) {
					let day = Date.now();
					let limitTime = moment(day).day(-1);
					return time.getTime() > new Date(limitTime).getTime();
				},
			},
		};
	},
	mounted() {
		this.getEnergyList();
		this.getObjTree();
		this.queryParams.timeDim = this.getDictDatas(
			this.DICT_TYPE.TIME_DIM
		)[0].value; // 默认时
		this.timeValue = [
			moment().startOf('day'),
			moment().endOf('day') - 59 * 61 * 1000,
		];
	},
	methods: {
		getObjTree() {
			getTree().then((res) => {
				this.objList = res.data || [];
				if (this.objList.length > 0) {
					this.objId = this.objList[0].id;
				}
			});
		},
		// 获取能源类型
		getEnergyList() {
			getEnergyTypeListAll().then((res) => {
				this.energyTypeList = res.data || [];
			});
		},
		// 切换能源类型
		chooseType(id) {
			let val;
			this.energyTypeList.map((item) => {
				if (item.id === id) {
					val = item.name;
				}
			});
			if (val == 1 || val == 2) {
				this.energyType = 1;
			} else {
				this.energyType = 2;
			}
		},
		// 选择工厂/产线/单元
		changeLine(val) {
			this.objType = val.length || 0;
		},
		// 范围选择器
		timeSelect() {
			switch (this.queryParams.timeDim) {
				case '1':
					if (!this.timeValue) {
						this.$modal.msgError('时间范围不能为空');
						return false;
					}
					if (this.timeValue[1] - this.timeValue[0] > 7 * 24 * 3600000) {
						this.$modal.msgError('最大时间范围为7天，请重新选择');
						this.timeValue = [];
					}
					break;
				case '2':
					if (!this.dateValue) {
						this.$modal.msgError('时间范围不能为空');
						return false;
					}
					if (this.dateValue[1] - this.dateValue[0] > 29 * 24 * 3600000) {
						this.$modal.msgError('最大时间范围为30天，请重新选择'); // 自动选择默认是0:00:00要求是23:59:59
						this.dateValue = [];
					}
					break;
				case '4':
					if (!this.monthValue) {
						this.$modal.msgError('时间范围不能为空');
						return false;
					}
					if (this.monthValue[1] - this.monthValue[0] > 729 * 24 * 3600000) {
						this.$modal.msgError('最大时间范围为24个月，请重新选择'); // 同理上面
						this.monthValue = [];
					}
					break;
				default:
			}
		},
		// 年选择器
		startYear() {
			if (this.yearValue2 && this.yearValue2 < this.yearValue1) {
				this.$modal.msgError('开始时间不能晚于结束时间，请重新选择');
				this.yearValue1 = null;
				return false;
			}
			if (this.yearValue1 && this.yearValue2) {
				if (this.yearValue2 - this.yearValue1 > 10 * 365 * 24 * 3600000) {
					this.$modal.msgError('最大时间范围为10年，请重新选择');
					this.yearValue1 = null;
					return false;
				}
			}
		},
		endYear() {
			if (this.yearValue2 && this.yearValue2 < this.yearValue1) {
				this.$modal.msgError('结束时间不能早于开始时间，请重新选择');
				this.yearValue2 = null;
				return false;
			}
			if (this.yearValue1 && this.yearValue2) {
				if (this.yearValue2 - this.yearValue1 > 10 * 365 * 24 * 3600000) {
					this.$modal.msgError('最大时间范围为10年，请重新选择');
					this.yearValue2 = null;
					return false;
				}
			}
		},
		// 周选择器
		startWeek() {
			if (this.weekValue1 && this.weekValue2) {
				let a = new Date(this.weekValue1).getTime();
				let b = new Date(this.weekValue2).getTime();
				if (a > b) {
					this.$modal.msgError('开始时间不能晚于结束时间，请重新选择');
					this.weekValue1 = null;
					return false;
				}
				if (b - a > 167 * 24 * 3600000) {
					this.$modal.msgError('最大时间范围为24周，请重新选择');
					this.weekValue1 = null;
					return false;
				}
			}
		},
		endWeek() {
			if (this.weekValue1 && this.weekValue2) {
				let a = new Date(this.weekValue1).getTime();
				let b = new Date(this.weekValue2).getTime();
				if (a > b) {
					this.$modal.msgError('结束时间不能早于开始时间，请重新选择');
					this.weekValue2 = null;
					return false;
				}
				if (b - a > 167 * 24 * 3600000) {
					this.$modal.msgError('最大时间范围为24周，请重新选择');
					this.weekValue2 = null;
					return false;
				}
			}
		},
		// 查询
		handBtn(val) {
			if (!this.queryParams.energyTypeId) {
				this.$modal.msgError('请选择能源类型');
				return false;
			}
			if (this.energyType == 1) {
				if (this.objArr.length === 0) {
					this.$modal.msgError('请选择对象');
					return false;
				} else {
					this.queryParams.objId = this.objArr[this.objArr.length - 1];
					this.queryParams.objType = this.objType;
				}
			} else if (this.energyType == 2) {
				if (!this.objId) {
					this.$modal.msgError('请选择对象');
					return false;
				} else {
					this.queryParams.objId = this.objId;
					this.queryParams.objType = 1;
				}
			}

			if (!this.queryParams.timeDim) {
				this.$modal.msgError('请选择时间维度');
				return false;
			}
			switch (this.queryParams.timeDim) {
				case '1':
					if (this.timeValue && this.timeValue.length > 0) {
						this.queryParams.startTime = this.timeValue[0];
						this.queryParams.endTime = this.timeValue[1]; // 不用转
					} else {
						this.$modal.msgError('时间范围不能为空');
						return false;
					}
					break;
				case '2':
					if (this.dateValue && this.dateValue.length > 0) {
						this.queryParams.startTime = this.dateValue[0];
						this.queryParams.endTime = this.dateValue[1] + 86399000; // 转为23:59:59
					} else {
						this.$modal.msgError('日范围不能为空');
						return false;
					}
					break;
				case '3':
					if (this.weekValue1 && this.weekValue2) {
						let a =
							moment(this.weekValue1).day(0).format('YYYY-MM-DD') + ' 00:00:00';
						let b =
							moment(this.weekValue2).day(6).format('YYYY-MM-DD') + ' 23:59:59';
						this.queryParams.startTime = new Date(a).getTime();
						this.queryParams.endTime = new Date(b).getTime();
					} else {
						this.$modal.msgError('周范围不能为空');
						return false;
					}
					break;
				case '4': // 转为本月最后一天的最后一秒
					if (this.monthValue && this.monthValue.length > 0) {
						this.queryParams.startTime = this.monthValue[0];
						this.queryParams.endTime = this.transformTime(this.monthValue[1]);
					} else {
						this.$modal.msgError('月范围不能为空');
						return false;
					}
					break;
				default: //本年最后一天
					if (this.yearValue1 && this.yearValue2) {
						if (this.yearValue2 < this.yearValue1) {
							this.$modal.msgError('结束时间不能早于开始时间');
							return false;
						} else {
							this.queryParams.startTime = this.yearValue1;
							this.queryParams.endTime = this.transformYear(this.yearValue2);
						}
					} else {
						this.$modal.msgError('年范围不能为空');
						return false;
					}
			}
			this.queryParams.startTime = this.queryParams.startTime + '';
			this.queryParams.endTime = this.queryParams.endTime + '';
			if (val === 'search') {
				this.$emit('submit', this.queryParams);
			} else {
				this.$emit('export', this.queryParams);
			}
		},
		// 重置
		resetBtn() {
			this.queryParams.energyTypeId = null;
			this.energyType = 0;
			this.queryParams.objId = null;
			this.objId = null;
			this.objType = 1;
			this.objArr = [];
			this.queryParams.timeDim = this.getDictDatas(
				this.DICT_TYPE.TIME_DIM
			)[0].value; // 默认时
			this.timeValue = [
				moment().startOf('day'),
				moment().endOf('day') - 59 * 61 * 1000,
			];
		},
		transformTime(timeStamp) {
			// 本月最后一天
			let year = moment(timeStamp).format('YYYY');
			let month = moment(timeStamp).format('MM');
			let newData =
				moment(new Date(year, month, 0)).format('YYYY-MM-DD') + ' 23:59:59';
			let value = new Date(newData).getTime();
			return value;
		},
		transformYear(timeStamp) {
			// 本年最后一天
			let year = moment(timeStamp).format('YYYY');
			let newData = year + '-12-31 23:59:59';
			let value = new Date(newData).getTime();
			return value;
		},
		switchMode() {
			// 展开和收起切换
			this.isExpand = !this.isExpand;
			const element = this.$refs.searchBarRef;
			if (this.isExpand) {
				element.classList.remove('divHeight');
			} else {
				element.classList.add('divHeight');
			}
		},
	},
};
</script>
<style lang='scss'>
/* 时间整点 */
.noneMinute .el-time-spinner__wrapper {
	width: 100%;
}
.noneMinute .el-scrollbar:nth-of-type(2) {
	display: none;
}
.demo-form-inline {
	.el-date-editor .el-range__icon {
		font-size: 16px;
		color: #0b58ff;
	}
	.el-input__prefix .el-icon-date {
		font-size: 16px;
		color: #0b58ff;
	}
}
</style>
<style lang="scss" scoped>
.demo-form-inline {
	.blue-block {
		display: inline-block;
		width: 4px;
		height: 16px;
		background-color: #0b58ff;
		border-radius: 1px;
		margin-right: 8px;
		margin-top: 12px;
	}
	.el-form-item {
		margin-right: 10px;
		margin-bottom: 4px;
	}
}
.searchBarBox .foldClass {
	position: absolute;
	top: 14px;
	right: 0;
	cursor: pointer;
	font-size: 12px;
	color: #0b58ff;
}
.searchBarBox .foldClass .iconfont {
	font-size: 14px;
}
.divHeight {
	height: 45px;
	overflow: hidden;
}
.separateStyle {
	display: inline-block;
	width: 1px;
	height: 24px;
	background: #e8e8e8;
	vertical-align: middle;
	margin: 0 10px;
}
</style>