<template>
	<ion-app>
		<ion-split-pane content-id="main-content">
			<ion-menu content-id="main-content" type="overlay">
				<ion-header>
					<ion-toolbar>
						<ion-title>
							<img src="./assets/SGC.svg" /> <span>{{ params.appConf.appName }}</span>
						</ion-title>
						<ion-buttons slot="end">
							<ion-button color="primary" @click="closeMenu()">
								<ion-icon slot="icon-only" :icon="Icon.close"></ion-icon>
							</ion-button>
						</ion-buttons>
					</ion-toolbar>
				</ion-header>
				<ion-content class="ion-no-padding">
					<ion-list class="login-info ion-no-margin">
						<ion-item v-if="params.loginType !== 'notlogin'">
							<ion-label>
								<span v-if="params.appConf.appType == 'portal'">{{ params.appConf.loginInfo?.cmpnNm }}</span
								>&nbsp;<br />
								<span class="department"> {{ params.appConf.loginInfo?.deptNm }} </span><br />
								{{ params.appConf.loginInfo?.userNm }}
								({{ params.appConf.loginInfo?.lginId }})
							</ion-label>
							<ion-button @click="setLogout" class="logout-button">
								<ion-icon slot="icon-only" :icon="Icon.logOut"></ion-icon>
								{{ $t('BTN_LOGOUT') }}
							</ion-button>
						</ion-item>
						<ion-item v-else>
							<ion-label>{{ $t('LOGIN.MGS_MENU_NEEDLOGIN') }}</ion-label>
						</ion-item>
					</ion-list>
					<ion-list id="menu-list" class="ion-no-margin">
						<ion-menu-toggle v-bind:auto-hide="false" v-for="(p, i) in dataList" :key="i">
							<ion-item router-direction="root" :router-link="p.url" lines="none" v-bind:detail="false" class="hydrated" :class="{ selected: p.selected }">
								<ion-icon slot="start" :icon="p.icon"></ion-icon>
								<ion-label>{{ $t(p.title) }}</ion-label>
							</ion-item>
						</ion-menu-toggle>
					</ion-list>
					<ion-list v-if="params.showLogger">
						<ion-button :color="$i18n.locale === 'ko' ? 'primary' : 'secondary'" expand="block" @click="changeLocale('ko')">Korean</ion-button>
						<ion-button :color="$i18n.locale === 'en' ? 'primary' : 'secondary'" expand="block" @click="changeLocale('en')">English</ion-button>
					</ion-list>
					<sgc-console v-if="params.showLogger"></sgc-console>
				</ion-content>
				<ion-footer>
					<ion-toolbar>
						<ion-buttons slot="start">
							<ion-button :disabled="params.deferredPrompt === null" @click="addHomeScreen()">
								<ion-icon slot="start" :icon="Icon.home"></ion-icon>
								{{ $t('BTN_ADDHOME') }}
							</ion-button>
						</ion-buttons>
						<ion-buttons slot="end">
							<ion-button
								@click="showSetting()"
								:disabled="params.loginType === 'notlogin' || params.appConf.loginInfo.userId === '' || params.appConf.appType == 'portal'"
							>
								<ion-icon slot="start" :icon="Icon.settings"></ion-icon>
								{{ $t('BTN_SETTING') }}
							</ion-button>
						</ion-buttons>
					</ion-toolbar>
				</ion-footer>
			</ion-menu>
			<ion-router-outlet id="main-content"></ion-router-outlet>
		</ion-split-pane>
	</ion-app>
</template>

<script lang="ts">
import { Device, DevicePlugin } from '@capacitor/device';
import { menuController } from '@ionic/vue';
import SettingModal from './views/common/modals/SettingModal.vue';
import SgcConsole from './views/components/SgcConsole.vue';

import {
	IonApp,
	IonButton,
	IonButtons,
	IonContent,
	IonFooter,
	IonHeader,
	IonIcon,
	IonItem,
	IonLabel,
	IonList,
	IonMenu,
	IonMenuToggle,
	IonRouterOutlet,
	IonSplitPane,
	IonTitle,
	IonToolbar,
	useIonRouter,
} from '@ionic/vue';

import { defineComponent } from 'vue';
import { useRoute } from 'vue-router';
import commonService from './services/common.service';

import { AppConfVo, AppMenuVo, ListDataVo } from './services/common.interface';
import Icon from './services/icon';

/**
 * App
 *
 * 최상단 APP
 */
export default defineComponent({
	name: 'App',
	components: {
		IonApp,
		IonContent,
		IonIcon,
		IonItem,
		IonLabel,
		IonList,
		IonMenu,
		IonMenuToggle,
		IonHeader,
		IonTitle,
		IonFooter,
		IonToolbar,
		IonButtons,
		IonButton,
		IonRouterOutlet,
		IonSplitPane,
		SgcConsole,
	},
	created() {
		const router = useIonRouter();
		commonService.setRouter(router);
	},
	mounted() {
		this.params._installSubscribe = commonService
			.getSharedService()
			.subscribe('install')
			.subscribe((deferredPrompt: any) => {
				this.params.deferredPrompt = deferredPrompt;
			});
		const device: DevicePlugin = Device;
		device.getLanguageCode().then((res) => {
			let language = '';
			if (res.value.includes('-')) {
				language = res.value.split('-')[0];
			} else {
				language = res.value;
			}
			switch (language) {
				case 'ko':
				default:
					this.$i18n.locale = 'ko';
					break;
			}
		});
		commonService
			.getSharedService()
			.subscribe('login')
			.subscribe(() => {
				this.changeLogin();
			});
		this.changeLogin();
	},
	unmounted() {
		this.params._installSubscribe.unsubscribe();
	},
	data(): ListDataVo<
		AppMenuVo,
		any,
		{
			/** 환경 정보 */
			appConf: AppConfVo;

			/** 로그인 형태 */
			loginType: string;

			/** 홈스크린 추가 프롬프트 */
			deferredPrompt: any;

			/** 홈스크린 추가 스크립터 로드 변경 구독 */
			_installSubscribe: any;

			/** 로그 보이기 - (로컬 개발기에서만 작동) */
			showLogger: boolean;
		}
	> {
		const appConf = commonService.getAppConf();
		return {
			dataList: [],
			params: {
				appConf: appConf,
				loginType: 'notlogin',
				deferredPrompt: appConf.deferredPrompt,
				_installSubscribe: null,
				showLogger: false,
			},
		};
	},
	setup() {
		commonService.getSharedService().setRouteLocation(useRoute());
		return {
			Icon,
		};
	},
	methods: {
		/**
		 * 로케일 변경
		 *
		 * 번역이 미진하여 한국어만 사용할 것
		 *
		 * @param locale 로케일 (ko, en)
		 */
		changeLocale(locale: string) {
			this.$i18n.locale = locale;
		},
		/**
		 * 로그 아웃
		 */
		setLogout() {
			commonService
				.getSharedService()
				.checkLogout()
				.then(() => {
					commonService.openToast('LOGIN.MSG_LOGOUTED', null, null, 'LOGIN.TIT_LOGOUT', 'warning');
					commonService.changePage('/login');
					this.closeMenu();
				});
		},
		/**
		 * 메뉴 닫기
		 */
		closeMenu() {
			menuController.close();
		},
		/**
		 * 설정 보이기
		 *
		 * 협력업체만 접근하도록 할 것
		 */
		showSetting() {
			commonService.openModal(SettingModal);
		},
		/**
		 * 홈스크린에 추가하기(A2HS)
		 *
		 * 1회에 한해서 가능함. 다음의 경우는 작동하지 않음.
		 *
		 * - 이미 홈 스크린에 추가 된 경우
		 * - https:// 로 접근하지 않은 경우
		 * - manifest.json 파일에 오류가 있는 경우
		 * - serviceWorker 가 작동되지 않은 경우
		 */
		addHomeScreen() {
			if (this.params.appConf.addHomeScreen) {
				this.params.appConf.addHomeScreen();
			}
		},
		/**
		 * 로그인 정보가 변경된 경우 추가 작업
		 */
		changeLogin() {
			const sharedService = commonService.getSharedService();
			const info = sharedService.getLoginInfo();
			this.dataList = sharedService.getAppMenu();
			this.params.showLogger = this.params.appConf.showLogger;
			if (info.userId !== null && info.userId !== '') {
				if (sharedService.isAsMember()) {
					this.params.loginType = 'as';
				} else {
					this.params.loginType = 'portal';
				}
			} else {
				this.params.loginType = 'notlogin';
			}
		},
	},
});
</script>

<style scoped lang="scss">
ion-menu ion-content {
	ion-list.login-info {
		margin: 0;
		border-radius: 0;
		background: var(--sgc-background-dark-bg);
		--ion-item-background: var(--sgc-background-dark-bg);

		ion-item {
			background: transparent;
			margin: 0 1rem;
			--min-height: 7rem;

			&::part(native) {
				--border-color: transparent;
				padding: 1rem 0;
				color: var(--sgc-background-dark-font);

				div.item-inner {
					border-style: none;

					div.input-wrapper {
						display: flex;
					}
				}
			}

			ion-label {
				position: absolute;
				left: 0.5rem;
				top: 0;

				span.department {
					color: var(--sgc-color-primary-50);
				}
			}

			ion-button.logout-button {
				position: absolute;
				left: 0;
				bottom: 0.5em;
			}
		}
	}
}

ion-menu ion-item {
	&.selected {
		--background: var(--sgc-color-primary-70);
	}

	ion-icon {
		color: var(--sgc-color-primary-50);
	}
}

#menu-list {
	margin: 0;
	padding: 0 0;
	background: #fff;

	ion-menu-toogle {
		ion-item {
			ion-label {
				--color: var(--ion-color-primary);
			}
		}
	}
}

ion-menu {
	ion-title {
		img {
			max-height: 1.5em;
			vertical-align: middle;
		}

		span {
			vertical-align: middle;
		}
	}
}

ion-menu.md {
	ion-list#menu-list ion-list-header {
		font-size: 22px;
		font-weight: 600;
		min-height: 20px;
	}

	ion-list#labels-list ion-list-header {
		font-size: 16px;
		margin-bottom: 18px;
		color: #757575;
		min-height: 26px;
	}

	ion-item ion-label {
		font-weight: 500;
	}
}

ion-menu.ios {
	ion-note {
		line-height: 24px;
		margin-bottom: 20px;
	}

	ion-item {
		--padding-start: 16px;
		--padding-end: 16px;
		--min-height: 50px;

		ion-icon {
			font-size: 24px;
			color: var(-sgc-background-dark-bg);
		}

		&.selected ion-icon {
			color: var(-sgc-background-dark-bg);
		}
	}

	ion-list#labels-list ion-list-header {
		margin-bottom: 8px;
	}

	ion-list-header,
	ion-note {
		padding-left: 16px;
		padding-right: 16px;
	}

	ion-note {
		margin-bottom: 8px;
	}
}

ion-note {
	display: inline-block;
	font-size: 16px;

	color: var(--ion-color-secondary-tint);
}
</style>
