<template>
	<sgc-modal :title="title" :toolbars="toolbars" scrollMode="fix" :useRefresh="true" @sgcRefresh="reloadFiles" @sgcCloseModal="closeModal">
		<sgc-loading :loadStatus="loadStatus" loadType="view">
			<ion-grid class="ion-no-margin ion-no-padding">
				<ion-row>
					<ion-col>
						<ion-button
							expand="full"
							:color="params.selectedTab === 'BEFORE' ? 'danger' : 'light'"
							:class="{ selected: params.selectedTab === 'BEFORE' }"
							@click="changeTab('BEFORE')"
							>{{ $t('DEFT.BTN_PHOTO_BEFORE') }}</ion-button
						>
					</ion-col>
					<ion-col>
						<ion-button
							expand="full"
							:color="params.selectedTab === 'AFTER' ? 'danger' : 'light'"
							:class="{ selected: params.selectedTab === 'AFTER' }"
							@click="changeTab('AFTER')"
							>{{ $t('DEFT.BTN_PHOTO_AFTER') }}</ion-button
						>
					</ion-col>
				</ion-row>
			</ion-grid>
			<div class="image-preview" v-if="params.swiperReady">
				<swiper
					:style="{
						'--swiper-navigation-color': '#fff',
						'--swiper-pagination-color': '#fff',
					}"
					@swiper="setPreviewSwiper"
					:spaceBetween="10"
					:navigation="true as any"
					:thumbs="{ swiper: params.thumbsSwiper } as any"
					:modules="modules"
					@slideChange="slideChange($event)"
					class="preview-swiper"
				>
					<swiper-slide v-for="(previewImg, i) in params.fileBucketList" :key="i">
						<img :src="previewImg.thumbnail.imageSrc" />
					</swiper-slide>
				</swiper>
				<swiper @swiper="setThumbsSwiper" :spaceBetween="10" :slidesPerView="4" :watchSlidesProgress="true" :modules="modules" class="thumb-swiper">
					<swiper-slide v-for="(thumb, i) in params.fileBucketList" :key="i" :class="{ selected: thumb.selected }">
						<img :src="thumb.thumbnail.imageSrc" @click="changePreview(thumb, true)" />
					</swiper-slide>
				</swiper>
			</div>
		</sgc-loading>
		<template #foote1r>
			<ion-segment v-if="params.fileBucketList" scrollable color="secondary" class="attach-list">
				<ion-segment-button v-for="(item, i) in params.fileBucketList" :key="i" @click="changePreview(item, true)">
					<ion-img
						:src="item.thumbnail.imageSrc"
						:class="{
							selected: item.selected,
							previewed: item === params.selectedBucket,
						}"
					></ion-img>
				</ion-segment-button>
			</ion-segment>
		</template>
		<form novalidate enctype="multipart/form-data" method="POST" ref="grdForm" style="display: none">
			<input name="grdFile" type="file" multiple="true" accept=".png,.jpg,.jpeg,.gif" @change="uploadStart()" ref="grdFile" />
		</form>
	</sgc-modal>
</template>

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

import { IonSegment, IonSegmentButton } from '@ionic/vue';
import { FileBucketVo, ViewDataVo } from '../../../services/common.interface';
import { Swiper, SwiperSlide } from 'swiper/vue';

// Import Swiper styles
import 'swiper/css';
import 'swiper/css/zoom';
import 'swiper/css/pagination';
import 'swiper/css/free-mode';
import 'swiper/css/navigation';
import 'swiper/css/thumbs';

import { Navigation, Thumbs, Zoom } from 'swiper';

export default defineComponent({
	name: 'DeftPhotoModal',
	components: {
		...IonPageModules,
		...IonFormModules,
		IonSegment,
		IonSegmentButton,
		Swiper,
		SwiperSlide,
	},
	props: ['deft'],
	setup() {
		return {
			Icon,
			utils,
			modules: [Navigation, Thumbs, Zoom],
		};
	},
	mounted() {
		this.loadDeft();
	},
	data(): ViewDataVo<
		{
			deftImgAflList: FileBucketVo[];
			prcgAflIdList: FileBucketVo[];
		},
		{
			selectedId: string;
			selectedBucket: FileBucketVo;
			fileBucketList: FileBucketVo[];
			deftImgAflId: string;
			prcgAflId: string;
			previewBackNumber: number;
			selectedTab: string;
			deftNo: string;
			deftPrcgStusCd: string;
			thumbsSwiper: typeof Swiper;
			swiperReady: boolean;
		}
	> {
		return {
			title: 'DEFT.TIT_PHOTO_ADD',
			loadStatus: 'loading',
			dataView: {
				deftImgAflList: null,
				prcgAflIdList: null,
			},
			params: {
				selectedId: '',
				selectedBucket: null,
				fileBucketList: [],
				deftImgAflId: '',
				previewBackNumber: null,
				prcgAflId: '',
				selectedTab: 'BEFORE',
				deftNo: null,
				deftPrcgStusCd: null,
				thumbsSwiper: null,
				swiperReady: false,
			},
			toolbars: [
				{
					color: 'primary',
					label: 'DEFT.BTN_PHOTO_TAKE',
					icon: Icon.attach,
					click: () => {
						this.selectPhoto();
					},
				},
				{
					color: 'danger',
					label: 'DEFT.BTN_DELETE_SELECTED',
					icon: Icon.trash,
					click: () => {
						this.deleteSelected();
					},
				},
				{
					color: 'primary',
					label: 'DEFT.BTN_DOWNLOAD_SELECTED',
					icon: Icon.download,
					get disabled() {
						return !this._swiper || this._swiper.activeIndex === -1 || this._swiper.imagesLoaded === 0;
					},
					click: () => {
						this.downloadPreview();
					},
				},
			],
		};
	},
	watch: {
		deft() {
			this.loadDeft();
		},
	},
	methods: {
		/** 모달 닫기 */
		closeModal() {
			return modalController.dismiss();
		},
		/** 슬라이드 변경 */
		slideChange(e: any) {
			if (this.params.fileBucketList.length > 0) {
				this.params.selectedBucket = this.params.fileBucketList[e.activeIndex];
			}
		},
		/** 미리 보기 변경 */
		setPreviewSwiper(swiper: any) {
			this.toolbars[2]._swiper = swiper;
		},
		/** 썸네일 스위퍼 설정 */
		setThumbsSwiper(swiper: any) {
			this.params.thumbsSwiper = swiper;
		},
		/** 선택된 이미지 변경 */
		_changeSelected() {
			if (this.params.fileBucketList && this.params.fileBucketList.length > 0) {
				this.toolbars[1].disabled = this.params.fileBucketList.filter((item) => item.selected).length > 0 ? false : true;
			} else {
				this.toolbars[1].disabled = false;
			}
		},
		/** 미리 보기 변경 */
		changePreview(item: FileBucketVo, toggleSelect: boolean) {
			this.params.selectedBucket = item;
			if (item && toggleSelect) {
				item.selected = !item.selected;
			}
			this._changeSelected();
		},
		/** 현재 미지 보기 다운로드 */
		downloadPreview() {
			if (this.params.selectedBucket) {
				const selectedBucket = this.params.selectedBucket;
				let link = document.createElement('a');
				link.setAttribute('download', selectedBucket.originalFilename);
				link.setAttribute('href', '/mobile/api/files/' + selectedBucket.id + '/' + selectedBucket.backNumber + '/download');
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);
			}
		},
		/** 텝 변경 */
		changeTab(tabType: string) {
			this.params.selectedTab = tabType;
			switch (this.params.selectedTab) {
				case 'BEFORE':
					this.params.selectedId = this.params.deftImgAflId;
					this.params.fileBucketList = this.dataView.deftImgAflList || [];
					break;
				case 'AFTER':
					this.params.selectedId = this.params.prcgAflId;
					this.params.fileBucketList = this.dataView.prcgAflIdList || [];
					break;
			}
			let previewItem: FileBucketVo = null;
			if (this.params.previewBackNumber) {
				this.params.fileBucketList.forEach((item) => {
					if (item.backNumber === this.params.previewBackNumber) {
						previewItem = item;
					}
				});
				this.params.previewBackNumber = null;
			}
			if (this.params.fileBucketList && this.params.fileBucketList.length > 0) {
				previewItem = this.params.fileBucketList[0];
			}
			this.params.swiperReady = false;
			this.params.thumbsSwiper = null;
			this.toolbars[2]._swiper = null;
			window.setTimeout(() => {
				this.params.swiperReady = true;
			}, 500);
			this.changePreview(previewItem, false);
		},
		/** 하자 정보 불러오기 */
		loadDeft() {
			if (commonService.isNotNull(this.params.deftImgAflId) || commonService.isNotNull(this.params.prcgAflId)) {
				this.loadData();
			} else if (commonService.isNotNull(this.deft)) {
				if (commonService.isNotNull(this.deft.deftImgAflId) && commonService.isNotNull(this.deft.prcgAflId) && commonService.isNotNull(this.deft.deftPrcgStusCd)) {
					this.params.deftImgAflId = this.deft.deftImgAflId;
					this.params.prcgAflId = this.deft.prcgAflId;
					this.params.deftNo = this.deft.deftNo;
					this.params.deftPrcgStusCd = this.deft.deftPrcgStusCd;
					this.loadData();
				} else if (commonService.isNotNull(this.deft.deftNo)) {
					commonService.getView('api/selectTcsDeftView/' + this.deft.deftNo).then((view: any) => {
						this.params.deftNo = view.deftNo;
						this.params.deftImgAflId = view.deftImgAflId;
						this.params.prcgAflId = view.prcgAflId;
						this.params.deftPrcgStusCd = view.deftPrcgStusCd;
						this.loadData();
					});
				}
			}
		},
		/** 기존 이미지 불러 오기 */
		loadData() {
			if (commonService.isNotNull(this.params.deftImgAflId) && this.dataView.deftImgAflList === null) {
				this.loadStatus = 'loading';
				commonService.getList('api/files/' + this.params.deftImgAflId + '/thumb/auto500').then((list) => {
					this.dataView.deftImgAflList = list;
					this.loadData();
				});
				return;
			}
			if (commonService.isNotNull(this.params.prcgAflId) && this.dataView.prcgAflIdList === null) {
				this.loadStatus = 'loading';
				commonService.getList('api/files/' + this.params.prcgAflId + '/thumb/auto500').then((list) => {
					this.dataView.prcgAflIdList = list;
					this.loadData();
				});
				return;
			}
			this.loadStatus = 'loaded';
			switch (this.params.deftPrcgStusCd) {
				case 'A':
				case 'B':
				case 'C':
				case 'D':
					this.toolbars[0].hide = false;
					this.toolbars[1].hide = false;
					break;
				case 'Z':
				case 'X':
				default:
					this.toolbars[0].hide = true;
					this.toolbars[1].hide = true;
					break;
			}

			this.changeTab(this.params.selectedTab);
		},
		/** 이미지 업로드 시작 */
		uploadStart() {
			const grdFile = this.$refs.grdFile as HTMLInputElement;
			const grdForm = this.$refs.grdForm as HTMLFormElement;
			if (grdFile.files.length > 0) {
				const params: string[] = [];
				if (commonService.isNotNull(this.params.selectedId)) {
					params.push('id=' + this.params.selectedId);
				}
				params.push('others=runtime');
				params.push('others=files');
				const formData = new FormData();
				let fileCnt = 0;
				for (let i = 0; i < grdFile.files.length; i++) {
					formData.append('file[' + i + ']', grdFile.files[i]);
					fileCnt++;
				}
				commonService
					.getCreate('api/files?' + params.join('&'), formData, {
						headers: {
							'Content-Type': 'multipart/form-data',
						},
					})
					.then((result: any) => {
						if (result && result.length > 0) {
							this.params.previewBackNumber = result[0].backNumber;
							if (commonService.isNull(this.params.selectedId)) {
								const selectedId = result[0].id;
								switch (this.params.selectedTab) {
									case 'BEFORE':
										this.params.deftImgAflId = selectedId;
										break;
									default:
										this.params.prcgAflId = selectedId;
										break;
								}
								commonService
									.getUpdate('api/updateTcsDeftAttach', {
										deftNo: this.params.deftNo,
										deftImgAflId: this.params.deftImgAflId,
										prcgAflId: this.params.prcgAflId,
									})
									.then((result: any) => {
										if (result) {
											this.params.deftImgAflId = result.deftImgAflId;
											this.params.prcgAflId = result.prcgAflId;
											commonService.openToast('DEFT.MSG_SAVE_PHOTO', { cnt: fileCnt }, null, this.title, 'success');
										}
									})
									.finally(() => {
										this.reloadFiles();
									});
							} else {
								this.reloadFiles();
							}
						}
					})
					.catch(() => {
						// todo
					})
					.finally(() => {
						grdForm.reset();
					});
			}
		},
		/** 이미지 리로드 */
		reloadFiles() {
			switch (this.params.selectedTab) {
				case 'BEFORE':
					this.dataView.deftImgAflList = null;
					break;
				default:
					this.dataView.prcgAflIdList = null;
					break;
			}
			this.loadData();
		},
		/** 파일 선택하기 */
		selectPhoto() {
			(this.$refs.grdFile as HTMLInputElement).click();
		},
		/** 선택된 파일 삭제하기 */
		deleteSelected() {
			let selectedFileBuckets: FileBucketVo[] = [];
			this.params.fileBucketList.forEach((item: FileBucketVo) => {
				if (item.selected) {
					selectedFileBuckets.push(item);
				}
			});
			if (selectedFileBuckets.length > 0) {
				commonService
					.openConfirm('DEFT.MSG_CONFIRM_DELETE', {
						selectedCnt: selectedFileBuckets.length,
					})
					.then((bl) => {
						if (bl) {
							let backNumbers: number[] = [];
							let id = this.params.selectedId;
							selectedFileBuckets.forEach((item) => {
								backNumbers.push(item.backNumber);
							});
							commonService.getDelete('api/files/' + id + '/' + backNumbers.join(',') + '').then(() => {
								this.reloadFiles();
							});
						}
					});
			} else {
				commonService.openToast('DEFT.MSG_NO_SELECTED', null, null, this.title, 'warning');
			}
		},
	},
});
</script>

<style scoped lang="scss">
div.image-preview {
	display: block;
	position: relative;
	overflow: auto;
	width: 100%;
	height: calc(100% - var(--padding-top) - var(--padding-end));
	text-align: center;
	background-color: var(--ion-color-medium-tint);
}

.swiper {
	width: 100%;
	height: 300px;
	margin-left: auto;
	margin-right: auto;

	.swiper-slide {
		text-align: center;
		font-size: 18px;
		background: #fff;

		/* Center slide text vertically */
		display: -webkit-box;
		display: -ms-flexbox;
		display: -webkit-flex;
		display: flex;
		-webkit-box-pack: center;
		-ms-flex-pack: center;
		-webkit-justify-content: center;
		justify-content: center;
		-webkit-box-align: center;
		-ms-flex-align: center;
		-webkit-align-items: center;
		align-items: center;
		img {
			display: block;
			width: 100%;
			height: 100%;
			object-fit: cover;
			background-size: cover;
			background-position: center;
			display: block;
		}
	}
	&.preview-swiper {
		height: 80%;
		width: 100%;
	}

	&.thumb-swiper {
		height: 20%;
		box-sizing: border-box;
		padding: 10px 0;
		.swiper-slide {
			width: 25%;
			height: 100%;
			opacity: 0.4;
			&.selected,
			&.swiper-slide-thumb-active {
				opacity: 1;
			}
			&.selected::after {
				content: '';
				mask-image: url(../../../assets/checkmark-circle-outline.svg);
				background-color: var(--ion-color-danger);
				display: inline-block;
				position: absolute;
				width: 1.5rem;
				height: 1.5rem;
				left: 0;
				top: 0;
			}
		}
	}
}
</style>
