<template>
	<div class="l-layout">
		<CommonPageTitle />
		<!-- 리스트 페이지 시작 -->
		<div v-if="pageActionFlag == 'list'" class="h1001">
			<v-card class="">
				<div class="pa-5 pb-0">
					<v-row align="center" no-gutters>
						<v-col :cols="12" class="d-flex align-center justify-space-between">
							<v-card-title class="pa-0 custom-title-4">공지사항</v-card-title>
							<div class="d-flex align-center">
								<!-- <v-btn @click="listPageButtonGroupClickEvent('view')" :ripple="false" class="mr-1">상세보기</v-btn> -->
								<a-button type="primary" @click="listPageButtonGroupClickEvent('write')" :ripple="false"
									icon="edit" class="mr-1">작성</a-button>
								<!-- <v-btn @click="listPageButtonGroupClickEvent('delete')" :ripple="false">삭제</v-btn> -->
							</div>
						</v-col>
						<v-col :cols="12" ref="contents" class="mt-5" style="min-height: calc(100% - 73px);">
							<div ref="gridParent" class="px-50" style="min-height: 64vh;">
								<component :ref="gridName" :is="loadGrid ? 'Grid' : null" :gridName="gridName"
									:parentPrgmId="myPrgmId" @getRowsData="getRowData" />
							</div>
							<div class="d-flex align-center justify-center pa-5" v-if="loadGrid && totalCount > 0">
								<pagination id="pagination" :total-count="totalCount" :page-num="page" :limit="limit"
									@loadData="changeGrid" />
							</div>
						</v-col>
					</v-row>
				</div>
			</v-card>
		</div>
		<!-- 리스트 페이지 끝 -->
		<!-- 상세보기 페이지 시작 -->
		<div v-if="pageActionFlag == 'view'">
			<v-card>
				<v-row class="pa-5">
					<v-col :cols="12" class="d-flex align-center justify-space-between ">
						<v-card-title class="pa-0 custom-title-4">공지사항 보기</v-card-title>
						<div class="d-flex align-center">
							<a-button @click="viewPageButtonGroupClickEvent('list')" type="primary" :ripple="false"
								class="mr-1" icon="unordered-list">목록</a-button>
							<a-button @click="viewPageButtonGroupClickEvent('reply')" type="primary" :ripple="false"
								class="mr-1" icon="send-outlined">
								<v-icon small :class="['mr-2']">$icoSend</v-icon>
								답글
							</a-button>
							<a-button @click="viewPageButtonGroupClickEvent('update')" type="primary" :ripple="false"
								class="mr-1" icon="edit">수정</a-button>
							<a-button @click="viewPageButtonGroupClickEvent('delete')" type="danger" ghost
								icon="delete">삭제</a-button>
						</div>
					</v-col>
					<v-col :cols="12" class="mt-5 pb-4">
						<v-card-title class="custom-title-6 pa-0">{{ viewActionData.title }}</v-card-title>
					</v-col>
					<v-col :cols="12" style="min-height: 50vh;" class="pa-0 custom-view">
						<v-card class="pa-3" style="overflow-y:auto;">
							<viewer v-if="viewActionData.viewerFlag" ref="tuiViewer" height="inherit"
								:initialValue="viewActionData.content" theme="white"
								:class="[isDarkMode ? 'theme--white' : 'theme--black']" />
						</v-card>
					</v-col>
					<v-col :cols="6" class="mt-5">
						<v-card-title class="custom-title-7 pa-0">
							파일목록
						</v-card-title>
						<div v-for="fileData in viewActionData.fileData" :key="fileData.apndFileId"
							:class="['file-item', isDarkMode ? 'dark' : 'light']" style="background-color: unset;">
							<a @click.prevent="downloadFile(fileData)" class="pa-0">
								<div class="d-flex justify-start search-box-label mb-0">
									<v-icon>mdi-paperclip</v-icon>
									<span class="file-item-name ml-2">{{ fileData.apndFileNm + '.' +
										fileData.apndFileExt }}</span>
								</div>
							</a>
						</div>
					</v-col>
				</v-row>
			</v-card>
		</div>
		<!-- 상세보기 페이지 끝 -->
		<!-- 작성 페이지 시작 -->
		<div v-if="pageActionFlag == 'write'">
			<v-card>
				<div class="pa-5">
					<v-row class="pa-50">
						<v-col :cols="12" class="">
							<v-card-title class="custom-title-4 pa-0">공지사항 작성</v-card-title>
						</v-col>
						<v-col :cols="12" class="mt-4">
							<v-card-title class="custom-title-7 pa-0">제목</v-card-title>
							<v-text-field v-model="writeActionData.title" class="v-input__custom" hide-details outlined>
							</v-text-field>
						</v-col>
						<v-col :cols="12" style="min-height: calc(100vh - 450px);">
							<editor ref="tuiEditor" height="100%" initialEditType="wysiwyg"
								:class="[isDarkMode ? 'toastui-editor-dark' : 'toastui-editor-light']" />
						</v-col>

						<v-col :cols="6" class="mt-5">
							<v-card-title class="custom-title-7 pa-0">파일첨부</v-card-title>
							<div class="" v-if="writeActionData.fileData">
								<div v-for="(fileData, index) in writeActionData.fileData" :key="fileData.apndFileId"
									:class="['file-item d-flex justify-space-between', isDarkMode ? 'dark' : 'light']">
									<div class="file-item-detail">
										<v-icon>mdi-paperclip</v-icon>
										<span href="#" class="file-item-name">{{ fileData.name }}</span>
									</div>
									<a-icon type="delete" class="v-icon pointer"
										@click="writeActionData.업로드fileData.splice(index, 1)" />
								</div>
							</div>
							<a-button class="ant-btn-popup-default mt-3" color="primary" icon="upload"
								@click="$refs.writeInputFile.$refs.input.click()">
								업로드
							</a-button>
							<v-file-input ref="writeInputFile" v-model="writeActionData.fileData" multiple outlined
								hide-input class="d-none" prepend-icon="mdi-tray-arrow-up"></v-file-input>
						</v-col>
						<v-col :cols="12" class="text-right">
							<a-button @click="writePageButtonGroupClickEvent('cancel')" :ripple="false"
								class="ant-btn-popup-default mr-2" color="primary">취소</a-button>
							<a-button @click="writePageButtonGroupClickEvent('write')" :ripple="false"
								type="primary">등록</a-button>
						</v-col>
					</v-row>
				</div>
			</v-card>
		</div>
		<!-- 작성 페이지 끝 -->
		<!-- 답글 작성 페이지 시작 -->
		<div v-if="pageActionFlag == 'reply'">
			<v-card class="pa-5">
				<v-row align="center" class="mt-0">
					<v-col :cols="12" class="">
						<v-card-title class="custom-title-4 pa-0">공지사항</v-card-title>
					</v-col>
					<v-col :cols="12" class="mt-4">
						<v-card-title class="custom-title-7 pa-0">제목</v-card-title>
						<v-text-field v-model="replyActionData.title" class="v-input__custom" outlined hide-details>
						</v-text-field>
					</v-col>
					<v-col :cols="12" style="height: calc(100vh - 270px);" class="mt-2">
						<editor ref="tuiReplyEditor" height="100%" initialEditType="wysiwyg"
							:class="[isDarkMode ? 'toastui-editor-dark' : 'toastui-editor-light']" />
					</v-col>
					<v-col :cols="6" class="mt-5">
						<v-card-title class="custom-title-7 pa-0">파일첨부</v-card-title>
						<div class="" v-if="replyActionData.fileData">
							<div v-for="(fileData, index) in replyActionData.fileData" :key="fileData.apndFileId"
								:class="['file-item d-flex justify-space-between', isDarkMode ? 'dark' : 'light']">
								<div class="file-item-detail">
									<v-icon>mdi-paperclip</v-icon>
									<span href="#" class="file-item-name">{{ fileData.name }}</span>
								</div>
								<a-icon type="delete" class="v-icon pointer"
									@click="replyActionData.fileData.splice(index, 1)" />
							</div>
						</div>
						<a-button class="ant-btn-popup-default mt-3" color="primary" icon="upload"
							@click="$refs.replyInputFile.$refs.input.click()">
							업로드
						</a-button>
						<v-file-input ref="replyInputFile" multiple show-size v-model="replyActionData.fileData"
							hide-details="true" class="d-none">
						</v-file-input>
					</v-col>
					<v-col :cols="12" class="text-right">
						<a-button @click="replyPageButtonGroupClickEvent('cancel')" class="ant-btn-popup-default mr-2"
							color="primary" :ripple="false">취소</a-button>
						<a-button @click="replyPageButtonGroupClickEvent('reply')" :ripple="false"
							type="primary">등록</a-button>
					</v-col>
				</v-row>
			</v-card>
		</div>
		<!-- 답글 작성 페이지 끝 -->
		<!-- 수정 페이지 시작 -->
		<div v-if="pageActionFlag == 'update'" class="update">
			<v-card>
				<div class="pa-5">
					<v-row align="center" no-gutters>
						<v-col :cols="12">
							<v-card-title class="custom-title-4 pa-0">공지사항 수정</v-card-title>
						</v-col>
						<v-col :cols="12" class="mt-4">
							<v-card-title class="custom-title-7 pa-0">제목</v-card-title>
							<v-text-field v-model="updateActionData.title" class="v-input__custom" hide-details
								outlined>
							</v-text-field>
						</v-col>
						<v-col :cols="12" style="height: calc(90vh - 270px);" class="mt-4">
							<editor ref="tuiUpdateEditor" height="100%" initialEditType="wysiwyg"
								:initialValue="updateActionData.content"
								:class="[isDarkMode ? 'toastui-editor-dark' : 'toastui-editor-light']" />
						</v-col>
						<v-col :cols="6" class="mt-5">
							<v-card-title class="custom-title-7 pa-0">파일첨부</v-card-title>
							<div class="" v-if="updateActionData.fileData">
								<div v-for="(fileData, index) in updateActionData.fileData" :key="fileData.apndFileId"
									:class="['file-item d-flex justify-space-between', isDarkMode ? 'dark' : 'light']">
									<div class="file-item-detail">
										<v-icon style="font-size: 18px;">mdi-paperclip</v-icon>
										<span href="#" class="file-item-name">{{ fileData.name }}</span>
									</div>
									<a-icon type="delete" class="v-icon pointer"
										@click="updateActionData.fileData.splice(index, 1)" />
								</div>
							</div>
							<div class="current-files" v-if="updateActionData.currentFileList">
								<div v-for="(fileData, index) in updateActionData.currentFileList"
									:key="fileData.apndFileId"
									:class="['file-item d-flex justify-space-between', isDarkMode ? 'dark' : 'light']">
									<div class="file-item-detail">
										<v-icon style="font-size: 18px;">mdi-paperclip</v-icon>
										<span @click.prevent="downloadFile(fileData)" href="#"
											class="file-item-name pointer">{{ fileData.apndFileNm + '.' +
												fileData.apndFileExt }}</span>
									</div>
									<a-icon type="delete" class="v-icon pointer"
										@click="addFileToDeleteFileList(fileData)" />
								</div>
							</div>
							<a-button class="ant-btn-popup-default mt-2" color="primary" icon="upload"
								@click="$refs.updateInputFile.$refs.input.click()">
								업로드
							</a-button>
							<v-file-input ref="updateInputFile" multiple show-size v-model="updateActionData.fileData"
								hide-details="true" class="d-none">
							</v-file-input>
						</v-col>
						<v-col :cols="12" class="text-right">
							<a-button @click="updatePageButtonGroupClickEvent('cancel')"
								class="ant-btn-popup-default mr-2" color="primary">취소</a-button>
							<a-button @click="updatePageButtonGroupClickEvent('update')" type="primary">등록</a-button>
						</v-col>
					</v-row>
				</div>
			</v-card>
		</div>
		<!-- 수정 페이지 끝 -->
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import mixinGlobal from '@/mixin/global.js';
import { resize } from '@/mixin/resize.js';
import BtnSearch from '~/components/common/button/BtnSearch';
import Grid from '~/components/common/Grid';
import Utility from '~/plugins/utility';
import '@toast-ui/editor/dist/toastui-editor.css';
import { Editor } from '@toast-ui/vue-editor';
import '@toast-ui/editor/dist/toastui-editor-viewer.css';
import { Viewer } from '@toast-ui/vue-editor';
import pagination from '~/components/common/Pagination';

let myTitle;
// const myPrgmId = "PRG0034";
let myPrgmId;

export default {
	mixins: [mixinGlobal, resize],
	async asyncData(context) {
		const myState = context.store.state;
		myPrgmId = context.route.query.prgmId;
		await context.store.commit('setActiveMenuInfo', myState.menuData[myPrgmId]);
		myTitle = await myState.activeMenuInfo.menuNm;
	},
	meta: {
		title: () => {
			return myTitle;
		},
		prgmId: myPrgmId,
		closable: true,
	},
	components: {
		Grid,
		BtnSearch,
		Utility,
		Editor,
		Viewer,
		pagination,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			//comId: "SEMPIO",
			//comId: this.userInfo.comId,
			// comId: this.$store.state.userInfo.comId,

			bordNo: null,
			pageActionFlag: 'list',
			gridName: 'noticeMngGrid',
			loadGrid: false,
			selectedRowKey: null,
			selectedRowData: null,
			itemsPerPage: 10,
			itemsPerPageArray: [10, 20, 50],
			limit: 10,
			page: 1,
			totalCount: 0,
			writeActionData: {
				title: '',
				postNo: null,
				fileData: null,
			},
			replyActionData: {
				title: '',
				postNo: null,
				fileData: null,
			},
			updateActionData: {
				title: '',
				postNo: null,
				fileData: null,
				currentFileList: null,
				deleteFileList: [],
			},
			viewActionData: {
				title: '',
				content: '',
				fileData: null,
				viewerFlag: false,
				postGrpLayer: null,
				postGrpOrd: null,
				postOrgNo: null,
			},
		};
	},
	computed: {
		...mapState({
			isDarkMode: state => state.isDarkMode,
			pageData: state => state.pageData[myPrgmId],
		}),

		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) {
				this.page = 1;
				this.search();
			}
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	mounted() {
		this.init();
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setGridData: 'setGridData',
			setGridColumn: 'setGridColumn',
			setGridOption: 'setGridOption',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			setTree: 'modules/list/setTree',
			chkOpenTabList: 'chkOpenTabList',
			getDomain: 'modules/list/getDomain',
		}),
		onTest() {
			console.log(this.writeActionData.fileData);
		},
		async init() {
			this.initData();
			await this.gridInit();
		},
		initData() {
			var receivedQueryParams = this.$route.query;
			this.bordNo = receivedQueryParams.hasOwnProperty('bordNo')
				? receivedQueryParams.bordNo
				: 'BORD0001';
		},
		initActionData(action) {
			switch (action) {
				case 'list':
					this.selectedRowKey = null;
					this.selectedRowData = null;
				case 'write':
					this.selectedRowKey = null;
					this.selectedRowData = null;
					this.writeActionData.title = '';
					this.writeActionData.postNo = null;
					this.writeActionData.fileData = null;
					break;
				case 'view':
					this.selectedRowKey = null;
					this.selectedRowData = null;
					this.viewActionData.title = '';
					this.viewActionData.content = '';
					this.viewActionData.fileData = null;
					this.viewActionData.postGrpLayer = null;
					this.viewActionData.postGrpOrd = null;
					this.viewActionData.postOrgNo = null;
					break;
				case 'reply':
					this.selectedRowKey = null;
					this.selectedRowData = null;
					this.replyActionData.title = '';
					this.replyActionData.content = '';
					this.replyActionData.fileData = null;
					break;
				case 'update':
					this.selectedRowKey = null;
					this.selectedRowData = null;
					this.updateActionData.title = '';
					this.updateActionData.content = '';
					this.updateActionData.fileData = null;
					this.updateActionData.currentFileList = null;
					this.updateActionData.deleteFileList = [];
					break;
			}
		},
		search() {
			this.getGridData(false);
		},
		gridInit() {
			const gridHeight = this.$refs.contents.offsetHeight - 120;

			const myOptions = {
				header: {
					height: 38,
				},
			};
			this.setGridOption({
				gridKey: this.gridName,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});

			var columnList = [
				{
					header: '회사코드',
					name: 'comId',
					width: 150,
					align: 'center',
					hidden: true,
				},
				{
					header: '게시판코드',
					name: 'bordNo',
					width: 150,
					align: 'center',
					hidden: true,
				},
				{ header: '번호', name: 'postNo', width: 150, align: 'right' },
				{
					header: '원글번호',
					name: 'postOrgNo',
					width: 150,
					align: 'center',
					hidden: true,
				},
				{
					header: '원글과답글그룹',
					name: 'postGrpOrd',
					width: 150,
					align: 'center',
					hidden: true,
				},
				{
					header: '계층',
					name: 'postGrpLayer',
					width: 150,
					align: 'center',
					hidden: true,
				},
				{
					header: '제목',
					name: 'postTitl',
					width: 150,
					align: 'center',
					hidden: true,
				},
				{ header: '제목', name: 'title', align: 'left' },
				{ header: '작성자', name: 'regUserNo', width: 250, align: 'right' },
				{ header: '작성일', name: 'regDttm', width: 250, align: 'center' },
				{ header: '조회수', name: 'viewCnt', width: 150, align: 'right' },
				// {header: "파일아이디", name:"apndFileUuid", width:150, align:"center"}, // 수정필요
			];

			this.setGridColumn({
				gridKey: this.gridName,
				value: columnList,
			});
			this.getGridData();
		},
		async getGridData(isPaging) {
			var params = {
				bordNo: 'BORD0001',
				limit: this.limit,
				page: this.page,
				offset: (this.page - 1) * this.limit, // MariaDB Query에서 직접 계산이 안됨
			};
			if(!isPaging) {
				this.loadGrid = false;
			}
			const res = await this.postApiReturn({
				apiKey: 'selectPostData',
				resKey: 'postPage',
				sendParam: params,
			});

			const res2 = await this.postApiReturn({
				apiKey: 'selectPostPageTotal',
				resKey: 'postPageTotal',
				sendParam: {
					bordNo: 'BORD0001',
				}
			});

			this.totalCount = res2[0].totalcount;

			this.setGridData({
				gridKey: this.gridName,
				value: res,
			});
			this.$nextTick(() => {
				this.loadGrid = true;
			});
			this.setPageData({ isFind: false });
		},
		getRowData(data) {
			this.selectedRowKey = data.rowKey;
			this.selectedRowData = data;
			this.listPageButtonGroupClickEvent('view');
		},
		// 게시글 정보 가져오기
		async getPostData() {
			var result = {};
			var boardNo = this.selectedRowData.bordNo;
			var postNo = this.selectedRowData.postNo;
			var apndFileUuid = this.selectedRowData.apndFileUuid;

			if (apndFileUuid == undefined) {
				apndFileUuid = null;
			}

			var params = {
				bordNo: boardNo,
				postNo: postNo,
			};

			var postData = await this.postApiReturn({
				apiKey: 'selectPost',
				resKey: 'postData',
				sendParam: params,
			});

			var fileData = await this.postUpdateApi({
				apiKey: 'selectApndFile',
				sendParam: {
					params: {
						apndFileUuid: apndFileUuid,
					},
					datas: {},
				},
			});

			result = {
				postData: postData, // 글 정보
				fileData: fileData, // 파일 리스트 정보
			};

			return result;
		},
		// 게시글 리스트 페이지 클릭 이벤트
		async listPageButtonGroupClickEvent(action) {
			var selectedRowData = this.selectedRowData;
			var selectedRowKey = this.selectedRowKey;

			switch (action) {
				case 'view':
					if (selectedRowKey === null) {
						alert('선택된 행이 없습니다.');
						break;
					}
					this.pageActionFlag = 'view';
					this.viewActionData.viewerFlag = false;

					var data = await this.getPostData();

					var postData = data.postData[0];
					var fileData = data.fileData.data.dataset.apndFile;

					this.viewActionData.title = postData.title;
					this.viewActionData.content = postData.postCntn;
					this.viewActionData.fileData = fileData;
					this.viewActionData.postGrpLayer = postData.postGrpLayer;
					this.viewActionData.postGrpOrd = postData.postGrpOrd;
					this.viewActionData.postOrgNo = postData.postOrgNo;
					this.viewActionData.postNo = postData.postNo;

					this.viewActionData.viewerFlag = true;
					break; // 리스트 페이지 상세보기 버튼
				case 'write':
					this.pageActionFlag = 'write';

					break; // 리스트 페이지 작성 버튼
				case 'delete':
					if (selectedRowKey === null) {
						alert('선택된 행이 없습니다.');
						break;
					}

					var params = {
						comId: this.comId,
						bordNo: selectedRowData.bordNo,
						postNo: selectedRowData.postNo,
						apndFileUuid: selectedRowData.apndFileUuid,
					};

					await this.postApiReturn({
						apiKey: 'deletePostList',
						sendParam: params,
					});

					await this.deletePostGrp(selectedRowData);

					this.search();
					this.initActionData('list');
					break; // 리스트 페이지 삭제 버튼
			}
		},
		async writePageButtonGroupClickEvent(action) {
			switch (action) {
				case 'write':
					var postTitle = this.writeActionData.title;
					var content = this.$refs.tuiEditor.invoke('getHTML');
					var formData = new FormData();
					var fileList = this.writeActionData.fileData;
					var apndFileUuid = null;
					var uploadResult = null;
					var bordNo = this.bordNo;
					var postNo =
						this.writeActionData.postNo !== null
							? this.writeActionData.postNo
							: '';

					if (!this.writeActionData.title) {
						alert('제목을 입력해주세요.');
						break;
					}
					if (!content) {
						alert('내용을 입력해주세요.');
						break;
					}

					if (this.fileSizeCheck(fileList) == false) {
						alert('업로드 가능한 파일 용량을 초과하였습니다.');
						break;
					}

					if (fileList !== null) {
						for (var i = 0; i < fileList.length; i++) {
							formData.append('file', fileList[i]);
						}
						formData.append('bordNo', bordNo);
						formData.append('postNo', postNo);

						uploadResult = await this.postUpdateApi({
							apiKey: 'saveFile',
							resKey: 'apndFileUuid',
							sendParam: formData,
						});
					}

					if (uploadResult) {
						if (uploadResult.data.dataset.uploadStatus != 0) {
							if (uploadResult.data.dataset.uploadStatus == -1) {
								alert('허용되지 않는 형식의 파일입니다.');
							} else if (uploadResult.data.dataset.uploadStatus == -2) {
								alert('업로드 가능한 파일 용량을 초과하였습니다.');
							}
							break;
						}
					}

					apndFileUuid =
						uploadResult === null ? '' : uploadResult.data.dataset.apndFileUuid;

					var params = {
						comId: this.comId,
						bordNo: bordNo,
						postTitl: postTitle,
						postCntn: content,
						apndFileUuid: apndFileUuid,
					};

					await this.postApiReturn({
						apiKey: 'insertPost',
						sendParam: params,
					});

					this.pageActionFlag = 'list';
					this.search();
					this.initActionData('write');
					break; // 작성 페이지 작성 버튼
				case 'cancel':
					this.pageActionFlag = 'list';
					this.search();
					this.initActionData('write');
					break; // 작성 페이지 취소 버튼
			}
		},
		async viewPageButtonGroupClickEvent(action) {
			var selectedRowData = this.selectedRowData;
			var selectedRowKey = this.selectedRowKey;

			switch (action) {
				case 'list':
					this.pageActionFlag = 'list';
					this.search();
					this.initActionData('view');
					break; // 상세보기 페이지 작성 버튼
				case 'reply':
					this.pageActionFlag = 'reply';
					this.replyActionData.title = 'ㄴRE:' + this.viewActionData.title;
					// viewActionData를 초기화하지 않고 들고 감

					break; // 상세보기 페이지 목록 버튼
				case 'update':
					// viewActionData를 초기화하지 않고 들고 감

					this.updateActionData.title = this.viewActionData.title;
					this.updateActionData.content = this.viewActionData.content;
					this.updateActionData.currentFileList = this.viewActionData.fileData;

					this.pageActionFlag = 'update';
					break; // 상세보기 페이지 목록 버튼
				case 'delete':
					if (confirm('삭제하시겠습니까?') == false) {
						return;
					}
					var params = {
						comId: this.comId,
						bordNo: selectedRowData.bordNo,
						postNo: selectedRowData.postNo,
						apndFileUuid: selectedRowData.apndFileUuid,
					};

					await this.postApiReturn({
						apiKey: 'deletePostList',
						sendParam: params,
					});

					await this.deletePostGrp(selectedRowData);

					this.pageActionFlag = 'list';
					this.search();
					this.initActionData('view');
					break; // 상세보기 페이지 목록 버튼
			}
		},
		async replyPageButtonGroupClickEvent(action) {
			switch (action) {
				case 'reply':
					var postTitle = this.replyActionData.title;
					var content = this.$refs.tuiReplyEditor.invoke('getHTML');
					var formData = new FormData();
					var fileList = this.replyActionData.fileData;
					var apndFileUuid = null;
					var uploadResult = null;
					var bordNo = this.bordNo;
					var postNo =
						this.replyActionData.postNo !== null
							? this.replyActionData.postNo
							: '';
					var params;

					if (!this.replyActionData.title) {
						alert('제목을 입력해주세요.');
						break;
					}
					if (!content) {
						alert('내용을 입력해주세요.');
						break;
					}

					if (this.fileSizeCheck(fileList) == false) {
						alert('업로드 가능한 파일 용량을 초과하였습니다.');
						break;
					}

					if (fileList !== null) {
						for (var i = 0; i < fileList.length; i++) {
							formData.append('file', fileList[i]);
						}
						formData.append('bordNo', bordNo);
						formData.append('postNo', postNo);

						uploadResult = await this.postUpdateApi({
							apiKey: 'saveFile',
							resKey: 'apndFileUuid',
							sendParam: formData,
						});
					}

					if (uploadResult) {
						if (uploadResult.data.dataset.uploadStatus != 0) {
							if (uploadResult.data.dataset.uploadStatus == -1) {
								alert('허용되지 않는 형식의 파일입니다.');
							} else if (uploadResult.data.dataset.uploadStatus == -2) {
								alert('업로드 가능한 파일 용량을 초과하였습니다.');
							}
							break;
						}
					}

					apndFileUuid =
						uploadResult === null ? '' : uploadResult.data.dataset.apndFileUuid;

					if (
						this.viewActionData.postGrpOrd === null ||
						this.viewActionData.postGrpOrd === ''
					) {
						params = {
							comId: this.comId,
							bordNo: bordNo,
							postOrgNo: this.viewActionData.postOrgNo,
							postGrpOrd: this.viewActionData.postGrpOrd,
							postGrpLayer: 0,
							postTitl: postTitle,
							postCntn: content,
							apndFileUuid: apndFileUuid,
						};
					} else {
						params = {
							comId: this.comId,
							bordNo: bordNo,
							postOrgNo: this.viewActionData.postOrgNo,
							postGrpOrd: this.viewActionData.postGrpOrd,
							postGrpLayer: this.viewActionData.postGrpLayer,
							postTitl: postTitle,
							postCntn: content,
							apndFileUuid: apndFileUuid,
						};
					}

					await this.postApiReturn({
						apiKey: 'insertRplPost',
						sendParam: params,
					});

					this.pageActionFlag = 'list';
					this.search();
					this.initActionData('reply');
					this.initActionData('view');
					break;
				case 'cancel':
					this.pageActionFlag = 'list';
					this.search();
					this.initActionData('reply');
					this.initActionData('view');
					break;
			}
		},
		async updatePageButtonGroupClickEvent(action) {
			switch (action) {
				case 'update':
					var postTitle = this.updateActionData.title;
					var content = this.$refs.tuiUpdateEditor.invoke('getHTML');
					var formData = new FormData();
					var fileList = this.updateActionData.fileData;
					var apndFileUuid = null;
					var uploadResult = null;
					var bordNo = this.bordNo;
					var postNo =
						this.viewActionData.postNo !== null
							? this.viewActionData.postNo
							: '';

					if (!this.updateActionData.title) {
						alert('제목을 입력해주세요.');
						break;
					}
					if (!content) {
						alert('내용을 입력해주세요.');
						break;
					}

					if (this.fileSizeCheck(fileList) == false) {
						alert('업로드 가능한 파일 용량을 초과하였습니다.');
						break;
					}

					// postTitle = postTitle.replaceAll("RE:", "");

					if (fileList !== null) {
						for (var i = 0; i < fileList.length; i++) {
							formData.append('file', fileList[i]);
						}
						formData.append('bordNo', bordNo);
						formData.append('postNo', postNo);

						uploadResult = await this.postUpdateApi({
							apiKey: 'saveFile',
							resKey: 'apndFileUuid',
							sendParam: formData,
						});
					}

					if (uploadResult) {
						if (uploadResult.data.dataset.uploadStatus != 0) {
							if (uploadResult.data.dataset.uploadStatus == -1) {
								alert('허용되지 않는 형식의 파일입니다.');
							} else if (uploadResult.data.dataset.uploadStatus == -2) {
								alert('업로드 가능한 파일 용량을 초과하였습니다.');
							}
							break;
						}
					}

					apndFileUuid =
						uploadResult === null ? '' : uploadResult.data.dataset.apndFileUuid;

					var deleteFileParam = {
						apndFile: this.updateActionData.deleteFileList,
					};

					if (this.updateActionData.deleteFileList.length > 0) {
						await this.postApiReturn({
							apiKey: 'deleteApndFile',
							sendParam: deleteFileParam,
						});
					}

					var params = {
						comId: this.comId,
						postNo: postNo,
						bordNo: bordNo,
						postTitl: postTitle,
						postCntn: content,
						apndFileUuid: apndFileUuid,
					};

					await this.postApiReturn({
						apiKey: 'updatePost',
						sendParam: params,
					});

					this.pageActionFlag = 'list';
					this.search();
					this.initActionData('update');
					this.initActionData('view');
					break; // 작성 페이지 작성 버튼
				case 'cancel':
					this.pageActionFlag = 'list';
					this.search();
					this.initActionData('update');
					this.initActionData('view');
					break; // 작성 페이지 취소 버튼
			}
		},
		async addFileToDeleteFileList(item) {
			this.updateActionData.deleteFileList.push({
				apndFileId: item.apndFileId,
			});
			var index = null;

			if (
				typeof this.updateActionData.currentFileList === 'object' &&
				this.updateActionData.currentFileList.length - 1 >= 0
			) {
				for (var i = 0; i < this.updateActionData.currentFileList.length; i++) {
					if (
						item.apndFileId ===
						this.updateActionData.currentFileList[i].apndFileId
					) {
						index = i;
						break;
					}
				}

				this.updateActionData.currentFileList.splice(index, 1);
			}
		},
		async deletePostGrp(postData) {
			if (postData.postGrpOrd != 0) {
				return;
			}
			var res = await this.postApiReturn({
				apiKey: 'selectPostList',
				resKey: 'postData',
				sendParam: {
					bordNo: 'BORD0001',
					postOrgNo: postData.postOrgNo,
				},
			});

			for (var i = 0; i < res.length; i++) {
				var params = {
					comId: this.comId,
					bordNo: res[i].bordNo,
					postNo: res[i].postNo,
					apndFileUuid: res[i].apndFileUuid,
				};

				await this.postApiReturn({
					apiKey: 'deletePostList',
					sendParam: params,
				});
			}
		},
		async downloadFile(item) {
			var menuId = 'MNU0002';
			var urlPrefix = await this.getDomain();

			var downLoadUrl =
				urlPrefix +
				'comm/base/ApndFileCtr/selectDownloadApndFile?$menuId=' +
				menuId +
				'&apndFileId=' +
				item.apndFileId;
			await this.$axios
				.get(downLoadUrl, { responseType: 'blob' })
				.then(response => {
					const blob = new Blob([response.data]);
					const link = document.createElement('a');
					link.href = URL.createObjectURL(blob);
					link.download = item.apndFileNm + '.' + item.apndFileExt;
					link.click();
					URL.revokeObjectURL(link.href);
				})
				.catch(console.error);
		},
		fileSizeCheck(fileList) {
			var resultFlag = true;

			var limitSize = 20 * 1024 * 1024; //20mb

			if (!fileList) {
				return resultFlag;
			}

			for (var i = 0; i < fileList.length; i++) {
				if (fileList[i].size >= limitSize) {
					resultFlag = false;
					break;
				}
			}

			return resultFlag;
		},
		changeGrid: async function (pageNum, limit) {
			this.page = pageNum;
			this.limit = limit;

			// this.search();
			this.getGridData(true);
		},
	},
};

const defaultData = {
	/* 검색옵션 */
	isFind: false,
	noticeMngGrid: {
		data: [],
		option: {},
		column: [],
	},
};

</script>

<style lang="scss" scoped>
.pointer,
.tui-grid-table tr {
	cursor: pointer;
}

::v-deep {
	.v-input__slot {
		padding-left: 8px;
		padding-right: 8px;
	}

	.custom-view {
		border: 1px solid;
		border-radius: 6px;
		height: 0;

		@each $theme in dark, light {
			@include theme($theme);
			border-color: map-deep-get($config, #{$theme}, "v-input-textarea-border");
			;
		}
	}

	.toastui-editor-mode-switch {
		font-family: Inter !important;
		font-size: 1.0rem !important;
	}

	.v-icon.anticon-delete svg {
		width: 14px;
		height: 14px;
	}
}

@each $theme in dark, light {
	@include theme($theme);

	::v-deep {
		.toastui-editor-#{$theme} {
			.toastui-editor-mode-switch {
				>.tab-item {
					border: none;
					background-color: transparent;
					color: map-deep-get($config, #{$theme}, "card-title-color") !important;

					&.active {
						color: map-deep-get($config, #{$theme}, "card-text-info-color") !important;
						border-top: 1px solid map-deep-get($config, #{$theme}, "card-text-info-color");
					}

				}
			}

		}
	}

	.file-item {
		&.#{$theme} {
			width: auto;
			margin: 2px 0;
			padding: 4px;
			background-color: map-deep-get($config, #{$theme}, "v-calendar-day-in-not-month-color");

			.file-item-name {
				color: map-deep-get($config, #{$theme}, "card-text-info-color");
			}

		}
	}
}
</style>
