var page_function = {
	components: {
		"soft-item": httpVueLoader.load("./components/soft_item_demand.vue"),
		// "data-table": httpVueLoader("components/layout/data_table.vue"),
	},
	data() {
		return {
			VarMenuPage: "parameter_settings",
			VarMenu: "area",
			VarPageContainerCss: "height:calc(100vh - 65px);",

			tab: 'meter',
			// tab:'meter',
			//各廠區資料
			pageSoftTag: {},

			area_select: "G1",
			carbon_conversion: "",

			options: {
				device: [
					{ label: '大型退火爐', value: 'test1' },
				],
				mode: [
					{ label: '手動', value: '0' },
					{ label: '自動', value: '1' },
				],
			},

			cellStyleOption: {
				headerCellClass: ({ column, rowIndex }) => {
					return "bg-primary text-white custom-p-unset ";
				},
			},



			table_data: [
				// { device_name: '13MT', mode: 1, start_time: '09:00', end_time: '18:30', },
				// { device_name: '8MT', mode: 0, start_time: '09:00', end_time: '18:30', },
				// {},
			],
			table_data_dialog: [
				// { item_name: '融湯', checked: 'R00001', upper_limit: 'D00001', },
				// { item_name: '模進水流量', checked: 'R00001', upper_limit: 'D00002', lower_limit: 'D00003', },
			],
			dialog: {
				show: false,
				data: {
					id: null,
					device_name: null,
					device_key: null,
					mode: null,
					start_time: moment().format('HH:mm'),
					end_time: moment().format('HH:mm'),
				},
				//記錄點位原始狀態 不儲存時復原
				origin_switch: {}
			},
			date_picker_open: [false, false, false, false, false, false,],
		};
	},
	computed: {
		selectOptions() {
			var temp = _.filter(deviceGroupOptions, function (option) {
				return option.label != '';
			});
			return temp;
		},
		//電表區域 依顯示區域 選出裝置對應電表
		// meter_selected(){
		// 	let temp =[];
		// 	if(deviceLimitOptions[this.area_select]){
		// 		_.each(deviceLimitOptions[this.area_select],(v,k)=>{
		// 			if(v.temp)
		// 		})
		// 	}
		// },

		tableColumns() {
			let arr = [
				{
					field: "no",
					key: "no",
					title: "No.",
					align: "center",
					width: 70,
					renderBodyCell: ({ row, column, rowIndex }, h) => {
						return rowIndex + 1;
					}
				},
				{
					field: "device_name",
					key: "device_name",
					title: "設備名稱",
					align: "center",
					width: 150,
				},
				{
					field: "mode",
					key: "mode",
					title: "模式",
					align: "center",
					width: 150,
					renderBodyCell: ({ row, column, rowIndex }, h) => {
						let temp = "";
						switch (row.mode) {
							case '0':
								temp = '手動';
								break;
							case '1':
								temp = '自動';
								break;
							default:
								break;
						}
						return temp;
					}
				},
				{
					field: "all_switch",
					key: "all_switch",
					title: "全部啟停",
					align: "center",
					width: 150,
					renderBodyCell: ({ row, column, rowIndex }, h) => {
						let dom = [],
							mode = '';
						if (row.mode == '1') {
							mode = 'pointer-events-none';
						}

						dom = h('div', {
							class: 'model-switch relative-position ' + mode,
							on: {
								click: (event) => {
									this.switch_confirm(row);
									// this.fn_all_switch(row.device_key);
								},
							}
						}, [
							h("div", {
								class: "cursor-pointer hidden-input",

							},),
							h("div", {
								class: "checkbox",
								style: "",
								attrs: {
									"data-str": "啟動"
								},
							}, [
								h("input", {
									class: "",
									style: "",
									attrs: {
										type: 'checkbox',
										checked: this.all_switch_list[row.device_key],
									},
								},),
								h("label", {
									class: "",
									style: "",
									attrs: {
										"data-str": "啟動"
									}
								},),
							]),
						]);
						return dom;
					},
				},
				{
					field: "auto_time",
					key: "auto_time",
					title: "自動排程時間",
					align: "center",
					width: 150,
					renderBodyCell: ({ row, column, rowIndex }, h) => {
						let temp = "";
						if (row.mode == '1') {
							temp = row.start_time + ' ~ ' + row.end_time;
						}
						return temp;
					},
				},
				{
					field: "_edit",
					key: "_edit",
					title: "-",
					align: "center",
					width: 100,
					renderBodyCell: ({ row, column, rowIndex }, h) => {
						let dom = [];
						dom = [
							h("q-btn", {
								class: "glossy",
								style: "margin:0px 10px; min-height: 2em;",
								props: {
									color: 'positive',
									label: '瀏覽',
								},
								attrs: {
								},
								on: {
									click: () => {
										this.open_dialog(row);
									},
								},
							},),
						];
						return dom;
					},
				},

			];
			return arr;
		},
		tableColumns_dialog() {
			let arr = [
				{
					field: "switch",
					key: "switch",
					title: "啟停",
					align: "center",
					width: 150,
					renderBodyCell: ({ row, column, rowIndex }, h) => {
						let dom = [];
						let p_none = this.dialog.data.mode == 1 ? ' pointer-events-none' : '';
						dom = h('div', {
							class: 'model-switch' + p_none,
							style: "position: relative;",
							on: {
								click: (event) => {
									this.switch_confirm(row);
									// this.fn_switch(row.tag_name);
								},
							}
						}, [
							h("div", {
								class: "cursor-pointer",
								style: "position: absolute;top: 0;left: 0;right: 0;bottom: 0;z-index: 9999; ",

							},),
							h("div", {
								class: "checkbox",
								style: "",
								attrs: {
									"data-str": "啟動"
								},
							}, [
								h("input", {
									class: "",
									style: "",
									attrs: {
										type: 'checkbox',
										checked: this.single_switch_list[row.tag_name + '_switch'],
									},
								},),
								h("label", {
									class: "",
									style: "",
									attrs: {
										"data-str": "啟動"
									}
								},),
							]),
						]);
						return dom;
					},
				},
				{
					field: "item_name",
					key: "item_name",
					title: "項目名稱",
					align: "center",
					width: 150,
				},
				{
					field: "upper_limit",
					key: "upper_limit",
					title: "上限警示值",
					align: "center",
					width: 150,
					renderBodyCell: ({ row, column, rowIndex }, h) => {
						let dom = [],
							str = "(略)",
							unit = "",
							tag_name = row.tag_name + '_upper',
							lower_value = 0;
						switch (row.type) {
							case 'temp':
								unit = '\u2103';
								break;
							case 'pressure':
								unit = 'kg/cm\u00B2'
							case 'flow':
								unit = 'm\u00B2/s'
							default:
								break;
						}

						if (this.SoftTagName[tag_name]) {
							lower_value = this.SoftTagName[row.tag_name + '_upper'].value
							str = lower_value + unit;
						}
						dom = h('div', {
							class: this.SoftTagName[tag_name] ? 'cursor-pointer' : 'pointer-events-none',
							on: {
								click: () => {
									this.set_alarm(tag_name, lower_value)
								},
							}
						}, [
							h("span", {
								class: "",
								style: "",
								attrs: {
								},
							}, str),
						]);
						return dom;
					},
				},
				{
					field: "lower_limit",
					key: "lower_limit",
					title: "下限警示值",
					align: "center",
					width: 150,
					renderBodyCell: ({ row, column, rowIndex }, h) => {
						let dom = [],
							str = "(略)",
							unit = "",
							tag_name = row.tag_name + '_lower',
							lower_value = 0;
						switch (row.type) {
							case 'temp':
								unit = '\u2103';
								break;
							case 'pressure':
								unit = 'kg/cm\u00B2'
							case 'flow':
								unit = 'm\u00B2/s'
							default:
								break;
						}

						if (this.SoftTagName[tag_name]) {
							lower_value = this.SoftTagName[row.tag_name + '_lower'].value
							str = lower_value + unit;
						}
						dom = h('div', {
							class: this.SoftTagName[tag_name] ? 'cursor-pointer' : 'pointer-events-none',
							on: {
								click: () => {
									this.set_alarm(tag_name, lower_value)
								},
							}
						}, [
							h("span", {
								class: "",
								style: "",
								attrs: {
								},
							}, str),
						]);
						return dom;
					},
				},

			];
			return arr;
		},
		all_switch_list() {
			let temp = {};
			if (this.SoftTagName) {
				_.each(this.SoftTagName, (v, k) => {
					let arr = k.split('_');
					if (!temp.hasOwnProperty(arr[0])) {
						temp[arr[0]] = true;
					}
					if (temp[arr[0]] && arr[2] == 'switch' && v.value == 0) {
						temp[arr[0]] = false;
					}
				})
			};
			return temp;
		},
		single_switch_list() {
			let temp = {};
			if (this.SoftTagName) {
				_.each(this.SoftTagName, (v, k) => {
					if (k.endsWith('_switch')) {
						temp[k] = v.value == 1 ? true : false;
					}
				})
			};
			return temp;
		},

	},

	watch: {},

	mounted() {
		this.$set(this.WebSetup, "caption", this.$t("menu.parameter_settings"));
		this.MenuSetup.opened = false;
		this.VarMenuIsOverlay = true;
		// this.loadData();
	},

	methods: {
		fnInitial(cfg) {
			this.IsSoftStartup = true; // cfg載入完成時執行第一次
			if (cfg.demand_control) {
				// this.$set(this, 'pageSoftTag', cfg.demand_control);
				_.each(cfg.demand_control, (v, k) => {
					this.$set(this.pageSoftTag, v.Name, v);
				})
			}
			// if (cfg.demand_device) {
			// 	// this.$set(this, 'pageSoftTag', cfg.demand_control);
			// 	_.each(cfg.demand_control, (v, k) => {
			// 		this.$set(this.deviceSoftTag, v.Name, v);
			// 	})
			// }
		},
		//取得點位數值
		fnSoft(v) {
			if (this.SoftTagName[v] != undefined) {
				return this.SoftTagName[v]["value"];
			} else {
				return 0;
			}
		},
		changeTab(_tab) {
			this.$set(this, 'tab', _tab);
			switch (_tab) {
				case 'device':
					this.loadDevice();
					break;
				case 'carbon':
					this.loadCarbon();
					break;
				default:
					break;
			}
		},
		loadCarbon() {
			let that = this;
			var params = {
				Action: "LoadCarbon",
				Datas: {
					input: that.area_select,
				},
			};
			that.FnWebAPIGet(params).then((res) => {
				if (res.data.result) {
					var resData = res.data.data;
					this.carbon_conversion = parseFloat(resData.carbon_conversion_factor);
				} else {
					that.FnNotify("錯誤", "error");
				}
				that.$q.loading.hide();
			});
		},
		loadDevice() {
			let that = this;
			var params = {
				Action: "LoadDevice",
				Datas: {
				},
			};
			that.FnWebAPIGet(params).then((res) => {
				if (res.data.result) {
					var resData = res.data.data;
					console.log(resData);
					this.table_data = resData;
				} else {
					that.FnNotify("錯誤", "error");
				}
				that.$q.loading.hide();
			});
		},
		//設定警示值
		async set_alarm(tag_name, value) {
			var that = this;
			var err = "";
			var title = "";
			var val = value;

			var cancel = false;

			await this.$q
				.dialog({
					title: "請輸入設定數值",
					message: "限定數字",
					prompt: {
						model: value,
						type: "text",
					},
					ok: "確定",
					cancel: "取消",
					preventClose: true,
				})
				.then(function (pn) {
					val = pn.trim();
					if (val == "" || isNaN(Number(pn))) {
						err = "僅可輸入數字";
					} else {
						that.$q.loading.show();
					}
				})
				.catch(() => {
					cancel = true;
				});
			if (!cancel) {
				if (err != "") {
					title = "更新失敗";
				} else {
					let temp = {};
					if (this.SoftTagName[tag_name]) {
						temp[this.SoftTagName[tag_name].OPCTag] = {
							decimal: "0",
							value: val,
						}
					}
					console.log(temp);
					this.FnSoftValueModify(temp);
					that.$q.loading.hide();
				}

			}
		},
		//設定碳排係數
		async set_data() {
			var that = this;
			var err = "";
			var title = "";
			var val = "";

			var cancel = false;

			await this.$q
				.dialog({
					title: "請輸入設定數值",
					message: "限定數字",
					prompt: {
						model: "",
						type: "text",
					},
					ok: "確定",
					cancel: "取消",
					preventClose: true,
				})
				.then(function (pn) {
					val = pn.trim();
					if (val == "" || isNaN(Number(pn))) {
						err = "僅可輸入數字";
					} else {
						that.$q.loading.show();
					}
				})
				.catch(() => {
					cancel = true;
				});
			if (!cancel) {
				if (err != "") {
					title = "更新失敗";
				} else {
					var params = {
						Action: "add_data",
						Datas: {
							val: val,
						},
					};
					await that.FnWebAPIPost(params).then((res) => {
						if (!res.data.result) {
							err = "資料庫更新失敗";
						}
					});
					if (err == "") {
						that.carbon_conversion = val;
						title = "更新成功";
					} else {
						title = "更新失敗";
					}
					that.$q.loading.hide();
				}

				await this.$q.dialog({
					title: title,
					message: err,
					ok: "確定",
					preventClose: true,
				});
			}
		},
		async fnSoftToAlarm(data) {
			let that = this;
			let info = data.name.split('_');
			console.log(data.points);

			if (info.length > 1) {
				let params = {
					info: info,
					value: data.value,
				};

				var formData = new FormData();
				formData.append("Action", "SaveDemand");
				formData.append("Datas", JSON.stringify(params));

				await that
					.FnWebAPIPost(formData)
					.then(function (res) {
						let resData = res.data.data;
						console.log(resData);
						if (resData.status) {
							// that.FnNotify(resData.msg, "success");

							that.FnSoftValueModify(data.points);
						} else {
							// that.FnNotify(resData.msg, "error");
						}
					})
					.catch(async function (err) {
						console.log(err);
					});
			} else {
				that.FnSoftValueModify(data.points);
			}
		},
		fnSoftMeter(data) {
			console.log(data.points);
			this.FnSoftValueModify(data.points);
		},
		fnOnOff(key) {
			let temp = {};
			temp[this.SoftTagName[key].OPCTag] = {
				demical: '0',
				value: !this.SoftTagName[key].value ? '1' : '0',
			};
			this.FnSoftValueModify(temp);
		},

		open_dialog(row) {
			_.each(this.dialog.data, (v, k) => {
				if (row[k]) {
					this.dialog.data[k] = row[k];
				}
			})
			let table_data = [],
				origin_switch = {};

			_.each(deviceLimitOptions[row.device_key], (v, k) => {
				if (v.type != 'meter') {
					table_data.push({
						item_name: v.label,
						tag_name: v.value,
						type: v.type
					});
					//記錄開啟時啟停點位狀態
					let switch_tag = this.SoftTagName[v.value + '_switch'];
					if (switch_tag) {
						origin_switch[switch_tag.OPCTag] = {
							decimal: "0",
							value: switch_tag.value == 1 ? '1' : '0',
						}
					}
				}
			})

			this.table_data_dialog = table_data;
			this.dialog.origin_switch = origin_switch;
			this.dialog.show = true;
		},

		async save_dialog() {
			let that = this;

			that.$q.loading.show();
			try {
				if (that.dialog.data["start_time"] == null || that.dialog["start_time"] == "") {
					throw "開始時間有誤";
				}
				if (that.dialog.data["end_time"] == null || that.dialog["end_time"] == "") {
					throw "結束時間有誤";
				}

				var params = {
					Action: "SaveDevice",
					Datas: that.dialog.data
				};
				await that
					.FnWebAPIPost(params)
					.then(function (res) {
						if (res.data.result) {
							that.FnNotify(`成功`, "success");
							that.loadDevice();
							//判斷是否啟用自動模式 若啟用自動模式 才可以進入全部啟停控制函式
							if (that.dialog.data.mode == 1) {
								that.fn_all_switch(that.dialog.data.device_key, 'auto');
							}
							that.close_dialog();
						} else {
							that.FnNotify(`失敗: ${res.data.message}`, "error");
							that.$q.loading.hide();
						}
					})
					.catch(async function (err) {
						that.FnNotify("系統異常", "error");
						that.$q.loading.hide();
					});
			} catch (e) {
				that.FnNotify(e, "warning");
				that.$q.loading.hide();
				return;
			}
		},

		//關閉新增、修改視窗
		close_dialog(state) {
			var that = this;
			if (state == 'cancel') {
				that.FnSoftValueModify(that.dialog.origin_switch);
			}
			that.$data.dialog = that.$options.data().dialog;
		},

		async switch_confirm(row) {
			//第一層才有device_key
			if (row.device_key) {
				let str = "確定全部啟停" + row.device_name + "？";
				if (await this.FnConfirm(str)) {
					this.fn_all_switch(row.device_key);
				}
			} else {
				let str = "確定啟停" + row.item_name + "？";
				if (await this.FnConfirm(str)) {
					this.fn_switch(row.tag_name);
				}
			}
		},

		fn_all_switch(key, mode) {
			let temp = {},
				now_state = this.all_switch_list[key];
			if (mode == 'auto') {
				let state = false;
				let start_time = this.dialog.data.start_time;
				let end_time = this.dialog.data.end_time;

				// 獲取當前時間
				let current_time = moment();

				// 格式化開始時間和結束時間，並以今天的日期為基礎
				let start = moment(start_time, 'HH:mm');
				let end = moment(end_time, 'HH:mm');

				// 如果開始時間大於結束時間
				if (start.isAfter(end)) {
					//現在時間比開始時間晚 或比結束時間早
					if (current_time.isAfter(start) || current_time.isBefore(end)) {
						state = true;
					}
				} else {
					if (current_time.isBetween(start, end)) {
						state = true;
					}
				}
				// // 判斷當前時間是否在區間內
				// if (current_time.isBetween(start, end)) {
				// 	state = true;
				// }
				_.each(this.SoftTagName, (v, k) => {
					if (k.startsWith(key) && k.endsWith('switch')) {
						temp[v.OPCTag] = {
							decimal: "0",
							value: !state ? '0' : '1',
						};
					}
				})
			} else {
				_.each(this.SoftTagName, (v, k) => {
					if (k.startsWith(key) && k.endsWith('switch')) {
						temp[v.OPCTag] = {
							decimal: "0",
							value: now_state ? '0' : '1',
						};
					}
				})
			}
			this.FnSoftValueModify(temp);
		},
		fn_switch(key) {
			let temp = {};
			_.each(this.SoftTagName, (v, k) => {
				if (k.startsWith(key) && k.endsWith('switch')) {
					temp[v.OPCTag] = {
						decimal: "0",
						value: v.value == 1 ? '0' : '1',
					};
				}
			})
			this.FnSoftValueModify(temp);
		},

		handleChange(value, type) {
			if (type === 'minute') {
				this.date_picker_open = _.fill(this.date_picker_open, false);
			}
		},


	},
};
