<template>
	<sgc-modal :title="title" @sgcCloseModal="closeModal" :toolbars="toolbars">
		<form novalidate @submit.prevent="onSubmit">
			<ion-list v-if="writeModel" class="item-form free-label">
				<ion-list-header>
					<ion-label>{{ $t('LOGIN.TIT_CHANGEPW') }}</ion-label>
				</ion-list-header>
				<sgc-item-input label="LOGIN.LBL_OLDPASSWD" type="password" :required="true" :clearInput="true" v-model="writeModel.oldPassWd" ref="oldPassWd"></sgc-item-input>
				<sgc-item-input
					label="LOGIN.LBL_CHPASSWD"
					type="password"
					:required="true"
					:clearInput="true"
					v-model="writeModel.passWd"
					ref="passWd"
					:helper="params.passwdGuide"
					@sgc-change="checkPassword"
					:max-length="16"
				></sgc-item-input>
				<sgc-item-input label="LOGIN.LBL_REPASSWD" type="password" :required="true" :clearInput="true" v-model="writeModel.rePasswd" ref="rePasswd"></sgc-item-input>
				<ion-item-divider>
					{{ params.initPasswdGuide }}
				</ion-item-divider>
			</ion-list>
		</form>
		<ion-list v-if="writeModel">
			<ion-list-header>
				<ion-label>{{ $t('LOGIN.TIT_PUSHNOTICE') }}</ion-label>
			</ion-list-header>
			<ion-item class="pushNotice">
				<ion-label>{{ $t('LOGIN.LBL_PUSHNOTI') }}</ion-label>
				<ion-toggle slot="end" v-model="writeModel.pushNoti" @ionChange="changePushNotice()"></ion-toggle>
			</ion-item>
		</ion-list>
	</sgc-modal>
</template>

<script lang="ts">
import { commonService, defineComponent, IonFormModules, IonPageModules, modalController } from '../../../services/index';

import { IonToggle } from '@ionic/vue';
import { AppConfVo, WriteDataVo, PasswdRuleVo } from '../../../services/common.interface';

/**
 * Setting Modal
 *
 * 협력업체 암호를 변경하거나 푸시 알림 정보를 변경함
 */
export default defineComponent({
	name: 'SettingModal',
	components: {
		...IonPageModules,
		...IonFormModules,
		IonToggle,
	},
	mounted() {
		commonService.getView<PasswdRuleVo>('api/passwordRule').then((rule) => {
			this.setPassRule(rule);
		});
	},
	data(): WriteDataVo<
		{
			oldPassWd: string;
			passWd: string;
			rePasswd: string;
			pushNoti: boolean;
		},
		{
			appConf: AppConfVo;
			passwdRule: PasswdRuleVo;
			passwdGuide: string;
			initPasswdGuide: string;
			passwdIncludeRegx: RegExp[];
			passwdExcludeRegx: RegExp;
		}
	> {
		const appConf = commonService.getAppConf();
		return {
			title: 'TIT_SETTING',
			writeModel: {
				oldPassWd: '',
				passWd: '',
				rePasswd: '',
				pushNoti: appConf.loginInfo.pushUseYn === 'Y' ? true : false,
			},
			params: {
				appConf: appConf,
				passwdRule: null,
				passwdGuide: null,
				initPasswdGuide: null,
				passwdIncludeRegx: [],
				passwdExcludeRegx: null,
			},
			toolbars: [
				{
					color: 'primary',
					label: 'LOGIN.BTN_PASSWDCH',
					click: () => {
						this.onSubmit();
					},
				},
			],
		};
	},
	methods: {
		/** 모달 닫기 */
		closeModal() {
			return modalController.dismiss();
		},
		setPassRule(rule: PasswdRuleVo) {
			this.params.passwdRule = rule;
			let includeRule = '';
			let includeRules = [];
			switch (rule.pwComplexChk) {
				case 'CHK01':
					includeRule = '영문자';
					includeRules.push('[a-zA-Z]');
					break;
				case 'CHK02':
					includeRule = '숫자';
					includeRules.push('[0-9]');
					break;
				case 'CHK03':
					includeRule = '영문자,숫자';
					includeRules.push('[0-9]', '[a-zA-Z]');
					break;
				case 'CHK04':
				default:
					includeRule = '영문자,숫자,특수문자';
					includeRules.push('[0-9]', '[a-zA-Z]', '[' + '~!@#$%^*()_-+={}[]:;"\'<>,.?/'.replace(/[.*+\-?^/${}()|[\]\\]/g, '\\$&') + ']');
					break;
			}
			this.params.passwdIncludeRegx = [];
			includeRules.forEach((incRule) => {
				this.params.passwdIncludeRegx.push(new RegExp(incRule));
			});
			this.params.initPasswdGuide = includeRule + ' 포함하여 ' + (rule.pwMinLen || 4) + '~16자리';
			if (commonService.isNotNull(rule.pwNotStr)) {
				this.params.initPasswdGuide += '(' + rule.pwNotStr + '& 사용불가)';
			}
			this.params.passwdExcludeRegx = new RegExp('[' + (rule.pwNotStr || '').replace(/[.*+\-?^/${}()|[\]\\]/g, '\\$&') + '&]');
			this.checkPassword(this.writeModel.passWd);
		},
		checkPassword(passWd: string) {
			if (passWd === '') {
				this.params.passwdGuide = '';
			} else if (/ /.test(passWd)) {
				this.params.passwdGuide = '공백 사용불가';
			} else if (passWd.length > 16 || passWd.length < (this.params.passwdRule?.pwMinLen || 4)) {
				this.params.passwdGuide = (this.params.passwdRule?.pwMinLen || 4) + '~16자리';
			} else if (this.params.passwdIncludeRegx !== null || this.params.passwdExcludeRegx !== null) {
				this.params.passwdGuide = '';
				let checked = true;
				this.params.passwdIncludeRegx.forEach((rule) => {
					if (!rule.test(passWd)) {
						checked = false;
					}
				});
				if (checked) {
					if (this.params.passwdExcludeRegx !== null && this.params.passwdExcludeRegx.test(passWd)) {
						this.params.passwdGuide = '불포함 규칙 위반';
					}
				} else {
					this.params.passwdGuide = '포함 규칙 위반';
				}
			} else {
				this.params.passwdGuide = ' ';
			}
		},

		/** 푸시 받기 정보 변경 */
		changePushNotice() {
			commonService
				.getUpdate('api/info', {
					connSiteCd: this.params.appConf.loginInfo.connSiteCd,
					pushUseYn: this.writeModel.pushNoti ? 'Y' : 'N',
				})
				.then(() => {
					this.params.appConf.loginInfo.pushUseYn = this.writeModel.pushNoti ? 'Y' : 'N';
				});
		},
		/** 데이타 전송 */
		onSubmit() {
			if (commonService.isNull(this.writeModel.oldPassWd)) {
				return commonService.openFormInvalid('기존암호', this.$refs, 'oldPassWd');
			}
			if (commonService.isNull(this.writeModel.passWd)) {
				return commonService.openFormInvalid('변경암호', this.$refs, 'passWd');
			}
			if (commonService.isNull(this.writeModel.rePasswd)) {
				return commonService.openFormInvalid('변경암호 확인', this.$refs, 'rePasswd');
			}
			if (this.writeModel.passWd !== this.writeModel.rePasswd) {
				return commonService.openFormInvalid('암호 불일치', this.$refs, 'rePasswd');
			}
			if (this.params.passwdGuide !== '') {
				commonService.openToast('LOGIN.MSG_PASSWD_RULE_ERR', null, null, this.title, 'warning');
				return;
			}
			if (this.params.passwdRule?.pwSameYn === 'Y' && this.writeModel.passWd === this.writeModel.oldPassWd) {
				commonService.openToast('LOGIN.MSG_PASSWD_SAME_ERR', null, null, this.title, 'warning');
				return;
			}
			const formData = {
				cmpnCd: this.params.appConf.loginInfo.cmpnCd,
				scrtNo: window.btoa(this.writeModel.oldPassWd),
				tmpPasswd: window.btoa(this.writeModel.passWd),
			};
			commonService.getUpdate('api/execAsPasswordChange', formData).then((result: any) => {
				if (result) {
					if (commonService.isNotNull(result?.scrtNo)) {
						commonService.openToast('LOGIN.MSG_PASSWDCHANGED', null, null, this.title, 'success');
					} else {
						commonService.openToast('LOGIN.MSG_PASSDIFF', null, null, this.title, 'warning');
					}
				}
			});
		},
	},
});
</script>

<style scoped lang="scss">
ion-item-divider {
	font-size: 0.8em !important;
	--color: var(--ion-color-danger) !important;
}

ion-item.pushNotice {
	font-size: 0.9rem;
}
</style>
