var page_function = {
	components: {
		"multi-yaxis-chart": httpVueLoader("components/layout/multi_yaxis_chart.vue"),
	},
	data() {
		return {
			VarMenuPage: "system_power_trend",
			VarMenu: "area",
			VarPageContainerCss: "height:calc(100vh - 65px); ",

			tab: "trend1",

			//  查詢條件
			search: {
				trend1: {
					start_at: new Date(new Date().setDate(new Date().getDate() - 7)),
					end_at: new Date(),
					device: [],
					item: [], //選項複選用 資料範例 ['VLL_avg', 'VLN_avg', 'I_avg']
					item_single: "KWH", //選項單選用
				},
				bar1: {
					data_type: "hour",
					meter_group: "G1",
					meter_group_item: [],
					time1: moment().format('YYYY-MM-DD'),
					time2: moment().format('YYYY-MM-DD'),
				},
				trend2: {
					start_at: new Date(new Date().setDate(new Date().getDate() - 7)),
					end_at: new Date(),
					device: 'Other_08',
					item: [],
				},
				bar2: {
					data_type: "hour",
					meter_group: "G1",
					meter_group_item: [],
					time1: moment().format(),
					time2: moment().format(),
				},
			},
			//  機台下拉選項
			deviceOptions: [],
			//  Y 軸分組的 key / value
			yAxisGroup: {
				'mwh': 'MWh',
				'kwh': 'KWh',
				'kw': 'kW',
				'mw': 'MW',
				'v': 'V',
				'a': 'A',
				'kvar': 'kVAr',
				'kva': 'kVA',
				'kvarh': 'kVArH',
				'kvah': 'kVAH',
				'pf': 'PF',
				'hz': 'Hz',
				'temp': '°C',
				'wm2': 'W/m2',
				'%': '%',
				'ms': 'm/s',

			},
			yAxisGroup2: {
				'mwh': 'MWh',
				'kwh': 'KWh',
				'kw': 'kW',
				'mw': 'MW',
				'v': 'V',
				'a': 'A',
				'kvar': 'kVAr',
				'kva': 'kVA',
				'kvarh': 'kVArH',
				'kvah': 'kVAH',
				'pf': 'PF',
				'hz': 'Hz',
				'temp': '°C',
				'°C': '°C',
				'wm2': 'W/m2',
				'%': '%',
				'ms': 'm/s',
			},


			"xAxisItemName": "tm", // 要成 xAxis 的資料表欄位名
			"xAxis": [], // 取出資料的X軸(日期或時間)
			"xAxisTemp": {}, // ajax 取得後根據所有資料union後的值,待確認無誤後,才會寫入xAxis
			"series": [], // 繪製 chart 的資料
			"seriesTemp": [], // ajax 取值的暫存值,待確認無誤後,才會寫入series
			"csvName": {
				"filename": null,
			},

			"xAxisItemName2": "tm", // 要成 xAxis 的資料表欄位名
			"xAxis2": [], // 取出資料的X軸(日期或時間)
			"xAxisTemp2": {}, // ajax 取得後根據所有資料union後的值,待確認無誤後,才會寫入xAxis
			"series2": [], // 繪製 chart 的資料
			"seriesTemp2": [], // ajax 取值的暫存值,待確認無誤後,才會寫入series
			"csvName2": {
				"filename": null,
			},

			dataTable: {
				columns: [],
				data: [],
			},

			options: {
				data_type: [
					{ label: "月", value: "month" },
					{ label: "日", value: "day" },
					{ label: "時", value: "hour" },
				],
				meter_group: [],
				meter_group_item: {},
				meter_line: [],
				trend2_device: [],
				trend2_item: [],
				bar2_device: [
					//value之後調整
					{ "label": '4MT溶解爐 模進水', "value": '4mt' },
					{ "label": '8MT保溫爐 模進水', "value": '4mt' },
				],
			},
			search_bar1: {},
			res_bar1: {},

		};
	},

	computed: {
		itemOptions() {
			return [ // 項目的下拉選項
				{ value: 'VLL_RS', y_axis_group: 'v', label: "線電壓_RS" },
				{ value: 'VLL_ST', y_axis_group: 'v', label: "線電壓_ST" },
				{ value: 'VLL_TR', y_axis_group: 'v', label: "線電壓_TR" },
				{ value: 'VLL_avg', y_axis_group: 'v', label: "平均線電壓" },
				{ value: 'VLN_R', y_axis_group: 'v', label: "相電壓_R" },
				{ value: 'VLN_S', y_axis_group: 'v', label: "相電壓_S" },
				{ value: 'VLN_T', y_axis_group: 'v', label: "相電壓_T" },
				{ value: 'VLN_avg', y_axis_group: 'v', label: "平均相電壓" },
				{ value: 'I_R', y_axis_group: 'a', label: "電流_R" },
				{ value: 'I_S', y_axis_group: 'a', label: "電流_S" },
				{ value: 'I_T', y_axis_group: 'a', label: "電流_T" },
				{ value: 'I_avg', y_axis_group: 'a', label: "平均電流" },
				// { value: 'I_tot', y_axis_group: '', label: "" },
				// { value: 'PF_R', y_axis_group: '', label: "" },
				// { value: 'PF_S', y_axis_group: '', label: "" },
				// { value: 'PF_T', y_axis_group: '', label: "" },
				// { value: 'PF_avg', y_axis_group: '', label: "" },
				{ value: 'KW_R', y_axis_group: 'kw', label: "有效功率_R" },
				{ value: 'KW_S', y_axis_group: 'kw', label: "有效功率_S" },
				{ value: 'KW_T', y_axis_group: 'kw', label: "有效功率_T" },
				{ value: 'KW_tot', y_axis_group: 'kw', label: "總有效功率" },
				{ value: 'Kvar_R', y_axis_group: 'kvar', label: "無效功率_R" },
				{ value: 'Kvar_S', y_axis_group: 'kvar', label: "無效功率_S" },
				{ value: 'Kvar_T', y_axis_group: 'kvar', label: "無效功率_T" },
				{ value: 'Kvar_tot', y_axis_group: 'kvar', label: "總無效功率" },
				{ value: 'KVA_R', y_axis_group: 'kva', label: "視在功率_R" },
				{ value: 'KVA_S', y_axis_group: 'kva', label: "視在功率_S" },
				{ value: 'KVA_T', y_axis_group: 'kva', label: "視在功率_T" },
				{ value: 'KVA_tot', y_axis_group: 'kva', label: "總視在功率" },
				{ value: 'Coin', y_axis_group: '%', label: "功率因數" },
				{ value: 'Hz', y_axis_group: 'hz', label: "頻率" },
				{ value: 'CO2', y_axis_group: '', label: "碳排量" },
				{ value: 'KvarH', y_axis_group: 'kvarh', label: "無效電能" },
				{ value: 'KVAH', y_axis_group: 'kvah', label: "視在電能" },
				{ value: 'KWH', y_axis_group: 'kwh', label: "有效電能" },
			]
		},

		itemOptionsMap() {
			return _.reduce(this.itemOptions, (obj, val) => {
				obj[val['value']] = val['label'];
				return obj;
			}, {});
		},
		deviceOptionsMap() {
			return _.reduce(this.deviceOptions, (obj, val) => {
				obj[val['value']] = val['label'];
				return obj;
			}, {});
		},

		itemOptionsMap2() {
			return _.reduce(this.options.trend2_item, (obj, val) => {
				obj[val['value']] = val['label'];
				return obj;
			}, {});
		},
		deviceOptionsMap2() {
			return _.reduce(this.options.trend2_device, (obj, val) => {
				obj[val['value']] = val['label'];
				return obj;
			}, {});
		},

		Trendbar() {
			var time1 = "";
			var time2 = "";

			var temp_x = [];
			var temp_1 = [];
			var temp_2 = [];

			if (Object.keys(this.res_bar1).length) {
				time1 = "時段1:" + this.search_bar1.time1;
				time2 = "時段2:" + this.search_bar1.time2;
				var check =
					Object.keys(this.res_bar1.data_1).length -
					Object.keys(this.res_bar1.data_2).length;

				_.each(this.res_bar1.data_1, (v, k) => {
					if (check >= 0) {
						temp_x.push(v.label);
					}
					temp_1.push(v.value);
				});
				_.each(this.res_bar1.data_2, (v, k) => {
					if (check < 0) {
						temp_x.push(v.label);
					}
					temp_2.push(v.value);
				});
			}


			let temp = {
				tooltip: {
					trigger: "axis",
					axisPointer: {
						type: "cross",
					},
					formatter: function (item) {
						let str = `
									${item[0].seriesName} : ${item[0].value} (kwh)
									<br>
									${item[1].seriesName} : ${item[1].value} (kwh)
									`;
						return str;
					},
				},
				toolbox: {
					show: true,
					feature: {
						magicType: { show: true, type: ["line", "bar"] },
						saveAsImage: {}
					},

				},
				grid: {
					show: true,
					left: "1%",
					right: "1%",
					bottom: "3%",
					containLabel: true,
				},

				legend: {
					data: [time1, time2],
				},
				xAxis: [
					{
						type: "category",
						axisTick: {
							alignWithLabel: true,
						},
						// prettier-ignore
						data: temp_x,
					},
				],
				yAxis: [
					{
						type: "value",
						position: "left",
						alignTicks: true,
						axisLine: {
							show: true,
							lineStyle: {
								color: "black",
							},
						},
						axisLabel: {
							formatter: "{value} KWH",
						},
					},
				],
				series: [
					{
						name: time1,
						type: "bar",
						data: temp_1,
					},
					{
						name: time2,
						type: "bar",
						data: temp_2,
					},
				],
			};
			return temp;
		}
	},
	created() {
		this.loadOptions();
	},

	watch: {},

	mounted() {
		this.$set(this.WebSetup, "caption", "電力趨勢圖");
		this.MenuSetup.opened = false;
		this.VarMenuIsOverlay = true;
		if (this.tab == 'trend1') {
			this.singel_item_ctrl(this.search.trend1.item_single)
		}
		this.loadDeviceOptions().then( // 取得 設備 下拉選項
			this.getData // 取得資料
		);
	},

	methods: {
		changeTab(_tab) {
			this.$set(this, 'tab', _tab);
		},

		//選項初始化
		loadOptions() {
			let that = this;

			let trend2_device = [];
			_.each(deviceindexinfo, (v, k) => {
				let x = _.find(v.item, { is_electricity: 0 });
				let y = _.find(deviceGroupOptions, { value: v.value });
				if (x) {
					trend2_device.push({
						label: v.label,
						value: y.other
					})
				}
			})
			that.options.trend2_device = trend2_device;

			that.trend2_select_device(that.search.trend2.device);

			var params = {
				Action: "LoadOptions",
				Datas: {},
			};
			return that.FnWebAPIGet(params).then((res) => {
				if (res.data.result) {
					var resData = res.data.data;
					let meter_group = [];
					_.each(resData.meter_group, (item) => {
						let target = _.find(deviceGroupOptions, { value: item.value });
						if (target) {
							meter_group.push(target);
						}
					})
					this.options.meter_group = meter_group;
					let meter_line = [];
					// _.each(resData.meter_line, (item) => {
					// 	let target = _.find(deviceGroupOptions, { value: item.value });
					// 	if (target) {
					// 		meter_group.push({
					// 			label:''
					// 		});
					// 	}
					// })
					this.options.meter_line = res.meter_line;
					this.options.meter_group_item = resData.meter_group_item;
					//長條圖日期選項初始化

					// //長條圖電表選項初始化 先判斷是否有選擇電錶(如果有電錶表示為頁面轉跳來的，就不用再預設選項)
					if (this.search.bar1.meter_group_item.length == 0) {
						this.options.meter_group_item[
							this.search.bar1.meter_group
						].forEach((el) => {
							this.search.bar1.meter_group_item.push(el.value);
						});
					}
				} else {
					that.FnNotify("錯誤", "error");
				}
			});
		},

		//  載入各機台下拉選單
		async loadDeviceOptions() {
			let that = this;

			that.$q.loading.show();
			var params = {
				Action: "LoadDeviceOptions",
				Datas: {},
			}
			let sp = new URLSearchParams(window.location.search);
			await this.FnWebAPIGet(params).then((res) => {
				this.deviceOptions = _.map(res.data.data, (item) => {
					return {
						"value": item['ColumnTable'],
						"label": item['ColumnName']
					}
				})
				if (sp.get('ColumnTable') != undefined) {
					this.search.trend1.device = [sp.get('ColumnTable')]; // 預選第一筆
				} else {
					this.search.trend1.device = [_.head(this.deviceOptions)["value"]]; // 預選第一筆
				}
				that.$q.loading.hide();
				// this.searchData();
			}).catch(function (err) {
				that.$q.loading.hide();
				console.log(err);
			});
		},

		getData() {
			this.$set(this.csvName, "filename", "電力趨勢圖");
			let begDate = moment(this.search.trend1.start_at).startOf('day').format("YYYY-MM-DD HH:mm:ss");
			let endDate = moment(this.search.trend1.end_at).endOf('day').format("YYYY-MM-DD HH:mm:ss");
			let pList = _.map(this.search.trend1.device, (val) => {
				return this.getAjaxData(begDate, endDate, val);
			});
			// 將各個設備拆成多個AJAX,再到前端來整理成series
			Promise.all(pList).then((resList) => {
				this.xAxisTemp = {};
				this.seriesTemp = [];
				let isOk = false;
				_.each(resList, (res, idx) => {
					if (res.data.result) {
						var resData = res.data.data;
						this.pushSeriesTemp(resData, idx);
						isOk = true; // 只要有值則會寫入xAxis & series
					} else {
						that.FnNotify(res.data.message, "error");
					}
				});

				if (isOk) { // 確認無誤後,才會寫入xAxis & series
					this.xAxis = _.sortBy(_.keys(this.xAxisTemp));
					this.series = this.seriesTemp;
				}
			}).catch((err) => {
				this.FnNotify(err, "error");
			})
		},

		getAjaxData(begDate, endDate, stn) { // 抓取資料
			let that = this;
			var params = {
				Action: 'Data',
				Datas: { 'beg_date': begDate, 'end_date': endDate, 'db_name': stn },
			};
			return that.FnWebAPIGet(params);
		},

		pushSeriesTemp(list, idx) { // 將取得的資料整理成series的每一個項目
			let resultMap = {};
			let deviceKey = this.search.trend1['device'][idx];
			let deviceName = this.deviceOptionsMap[deviceKey];

			_.each(list, (row) => {
				let xAxisKey = row[this.xAxisItemName];
				this.xAxisTemp[xAxisKey] = true;
				_.each(this.search.trend1['item'], (itemKey) => {
					let itemName = this.itemOptionsMap[itemKey];
					let seriesName = itemName + " (" + deviceName + ")";
					let mapKey = deviceKey + "_" + itemKey;
					if (_.isUndefined(resultMap[mapKey])) {
						resultMap[mapKey] = { "name": seriesName, "select_value": itemKey, "data": [] };
					}
					resultMap[mapKey]["data"].push([xAxisKey, this.FnRoundToDecimal(row[itemKey])]);
				});
			});
			_.each(resultMap, (row, key) => {
				this.seriesTemp.push(row);
			});
		},

		searchOk() {
			// this.getData();
		},

		exportData() {
			// if (this.dataTable.columns.length > 0 && this.dataTable.data.length > 0) {
			//   this.FnReportDownload('csv', this.dataTable.data, this.dataTable.columns, '趨勢圖下載');
			// } else {
			//   this.FnNotify('無資料', 'warning');
			// }
		},

		getData2() {
			this.$set(this.csvName2, "filename", "其它趨勢圖");
			let begDate = moment(this.search.trend2.start_at).startOf('day').format("YYYY-MM-DD HH:mm:ss");
			let endDate = moment(this.search.trend2.end_at).endOf('day').format("YYYY-MM-DD HH:mm:ss");
			//fit原格式 將單項寫入陣列
			let to_arr = [this.search.trend2.device];
			let pList = _.map(to_arr, (val) => {
				return this.getAjaxData2(begDate, endDate, val);
			});
			// 將各個設備拆成多個AJAX,再到前端來整理成series
			Promise.all(pList).then((resList) => {
				this.xAxisTemp = {};
				this.seriesTemp = [];
				let isOk = false;
				_.each(resList, (res, idx) => {
					if (res.data.result) {
						var resData = res.data.data;
						this.pushSeriesTemp2(resData, idx);
						isOk = true; // 只要有值則會寫入xAxis & series
					} else {
						that.FnNotify(res.data.message, "error");
					}
				});
				if (isOk) { // 確認無誤後,才會寫入xAxis & series
					this.xAxis2 = _.sortBy(_.keys(this.xAxisTemp2));
					this.series2 = this.seriesTemp2;
				}
			}).catch((err) => {
				this.FnNotify(err, "error");
			})
		},
		getAjaxData2(begDate, endDate, stn) { // 抓取資料
			let that = this;
			var params = {
				Action: 'Data2',
				Datas: { 'beg_date': begDate, 'end_date': endDate, 'db_name': stn },
			};
			return that.FnWebAPIGet(params);
		},

		pushSeriesTemp2(list, idx) { // 將取得的資料整理成series的每一個項目
			let resultMap = {};
			let deviceKey = this.search.trend2['device'];
			let deviceName = this.deviceOptionsMap2[deviceKey];

			_.each(list, (row) => {
				let xAxisKey = row[this.xAxisItemName2];
				this.xAxisTemp2[xAxisKey] = true;
				_.each(this.search.trend2['item'], (itemKey) => {
					let itemName = this.itemOptionsMap2[itemKey];
					let seriesName = itemName + " (" + deviceName + ")";
					let mapKey = deviceKey + "_" + itemKey;
					if (_.isUndefined(resultMap[mapKey])) {
						resultMap[mapKey] = { "name": seriesName, "select_value": itemKey, "data": [] };
					}
					resultMap[mapKey]["data"].push([xAxisKey, this.FnRoundToDecimal(row[itemKey])]);
				});
			});
			_.each(resultMap, (row, key) => {
				this.seriesTemp2.push(row);
			});
		},

		searchOk2() {
			this.getData2();
		},

		//長條圖廠區電表控制項
		bar_meter_option_ctrl(type) {
			this.search.bar1.meter_group_item = [];
			if (type == "bar1") {
				let arr = this.options.meter_group_item[this.search.bar1.meter_group];
				arr.forEach((el) => {
					if (arr.length == 1 || el.IsTotal != '1') {
						this.search.bar1.meter_group_item.push(el.value);
					}
				});
				//長條圖時間切換 刷新日期預設值
				let time1 = this.search.bar1.time1;
				let time2 = this.search.bar1.time2;
				switch (this.search.bar1.data_type) {
					case 'hour':
						this.search.bar1.time1 = moment(time1).format('YYYY-MM-DD');
						this.search.bar1.time2 = moment(time2).format('YYYY-MM-DD');
						break;
					case 'day':
						this.search.bar1.time1 = moment(time1).format('YYYY-MM');
						this.search.bar1.time2 = moment(time2).format('YYYY-MM');
						break;
					case 'month':
						this.search.bar1.time1 = moment(time1).format('YYYY');
						this.search.bar1.time2 = moment(time2).format('YYYY');
						break;
					default:
						break;
				}
			};
		},

		loadBar1() {
			let that = this;
			let item_bar = [];
			that.search.bar1.meter_group_item.forEach((el) => {
				item_bar.push(el);
			});
			var s_date_1 = "",
				s_date_2 = "";
			switch (this.search.bar1.data_type) {
				case "hour":
					s_date_1 = this.search.bar1.time1;
					s_date_2 = this.search.bar1.time2;
					break;
				case "day":
					s_date_1 = `${this.search.bar1.time1}-01`;
					s_date_2 = `${this.search.bar1.time2}-01`;
					break;
				case "month":
					s_date_1 = `${this.search.bar1.time1}-01-01`;
					s_date_2 = `${this.search.bar1.time2}-01-01`;
					break;
				default:
					s_date_1 = this.search.bar1.time1;
					s_date_2 = this.search.bar1.time2;
					break;
			}
			var params = {
				Action: "bar1_data",
				Datas: {
					date_1: s_date_1,
					date_2: s_date_2,
					item_1: item_bar, //日期1的電表資料表清單陣列
					item_2: item_bar, //日期2的電表資料表清單陣列
					data_type: this.search.bar1.data_type, //資料類型 共三種 hour day month
				},
			};
			return that.FnWebAPIGet(params).then((res) => {
				if (res.data.result) {
					var resData = res.data.data;
					this.search_bar1 = _.cloneDeep(this.search.bar1);
					this.res_bar1 = resData;


				} else {
					that.FnNotify("錯誤", "error");
				}
			});
		},

		//選取其它趨勢圖設備後 刷新選取項目
		trend2_select_device(key) {
			//重置選取內容
			this.search.trend2.item = [];
			//重製趨勢圖項目
			this.series2 = [];
			let arr = [];
			let target_key = _.find(deviceGroupOptions, { other: key })
			let target = _.find(deviceindexinfo, { value: target_key.value });
			if (target) {
				//設備下非電力選項寫入
				_.each(target.item, (v) => {
					if (v.is_electricity != 1) {
					arr.push({
						label: v.label,
						value: v.other_field,
						y_axis_group: v.unit
					});
					}
				})
			}
			this.options.trend2_item = arr;
		},

		//電力趨勢圖 項目單選控制
		singel_item_ctrl(val) {
			this.search.trend1.item = [val];
		},
	},
};
