<template>
	<div>
		<!-- <v-btn :ripple="false" @click="dialog = !dialog">경고창</v-btn> -->
		<v-dialog
			v-model="dialog"
			width="900"
			overlay-color="#000"
			overlay-opacity="0.8"
		>
			<v-card>
				<v-toolbar
					:color="isDarkMode ? '#2d3355' : '#3f4d7d'"
					class="py-4 pr-3 pl-5"
					height="auto"
				>
					<v-toolbar-title>{{ label }}</v-toolbar-title>
					<v-btn
						icon
						tile
						small
						:ripple="false"
						@click="dialog = !dialog"
						:style="{ backgroundColor: isDarkMode ? '#2d3355' : '#3f4d7d' }"
					>
						<v-icon>mdi-close</v-icon>
					</v-btn>
				</v-toolbar>
				<v-card-title>
					VOC 내용
				</v-card-title>
				<!-- <template v-for="(item, index) in detailList"> -->
				<template>
					<div style="padding : 10px 40px">
						<div v-for="n in detailList.length" :key="n">
							<v-row v-if="n % 2 == 1" align="center" no-gutters>
								<!-- {{detailList[n-1]}} {{detailList[n-1].type}} -->
								<!-- v-model="detailList[n-1].valueNm" -->
								<v-col
									:cols="detailList[n - 1].cols"
									:class="detailList[n - 1].class"
								>
									<component
										:ref="detailList[n - 1].valueNm"
										:is="detailList[n - 1].type"
										:item="detailList[n - 1]"
										:parentPrgmId="parentPrgmId"
										:bindingData="bindingData"
										@getValue="getValue"
									/>
								</v-col>
								<v-col
									v-if="detailList[n] != undefined"
									:cols="detailList[n].cols"
									:class="detailList[n].class"
								>
									<component
										:ref="detailList[n].valueNm"
										:is="detailList[n].type"
										:item="detailList[n]"
										:parentPrgmId="parentPrgmId"
										:bindingData="bindingData"
										@getValue="getValue"
									/>
								</v-col>
							</v-row>
						</div>
						<div>
							<v-row v-show="!componentDisableFlag" align="center" no-gutters>
								<v-col :cols="2">
									<label
										for=""
										class="search-box-label"
										style="padding-left:10px"
									>
										<v-icon x-small :color="'primary'" class="mr-1"
											>mdi-record-circle</v-icon
										>
										첨부파일
									</label>
								</v-col>
								<v-col :cols="8">
									<v-file-input
										multiple
										background-color="#47535c"
										show-size
										v-model="fileData"
										hide-details="true"
									>
									</v-file-input>
								</v-col>
							</v-row>
							<v-row v-show="state === 'update' || state === 'read'">
								<v-col :cols="12">
									<v-row class="search-box" align="center" no-gutters>
										<v-col :cols="2">
											<label class="search-box-label" style="padding-left:10px">
												<v-icon x-small color="primary" class="mr-1"
													>mdi-record-circle</v-icon
												>
												파일 목록
											</label>
										</v-col>
										<v-col :cols="10">
											<v-row
												v-for="fileData in fileList"
												:key="fileData.apndFileId"
											>
												<a @click.prevent="downloadFile(fileData)">
													<v-col :cols="12">
														<div class="search-box-label">
															{{
																fileData.apndFileNm + '.' + fileData.apndFileExt
															}}
														</div>
													</v-col>
												</a>
												<v-icon
													v-show="state === 'update'"
													class="pl-5"
													@click="addFileToDeleteFileList(fileData)"
												>
													mdi-close
												</v-icon>
											</v-row>
										</v-col>
									</v-row>
								</v-col>
							</v-row>
						</div>
					</div>
					<div v-if="answerDialog == true">
						<v-card-title style="padding : 16px 24px 10px ">
							답변 내용
						</v-card-title>
						<div style="padding : 10px 40px">
							<div v-for="n in answerList.length" :key="n">
								<v-row v-if="n % 2 == 1" align="center" no-gutters>
									<v-col
										:cols="answerList[n - 1].cols"
										:class="answerList[n - 1].class"
									>
										<component
											:is="answerList[n - 1].type"
											:item="answerList[n - 1]"
											:parentPrgmId="parentPrgmId"
											:bindingData="bindingData"
										/>
									</v-col>
									<v-col
										v-if="answerList[n] != undefined"
										:cols="answerList[n].cols"
										:class="answerList[n].class"
									>
										<component
											:is="answerList[n].type"
											:item="answerList[n]"
											:parentPrgmId="parentPrgmId"
											:bindingData="bindingData"
										/>
									</v-col>
								</v-row>
							</div>
							<div>
								<!-- <v-row v-show="!componentDisableFlag" align="center" no-gutters>
                  <v-col :cols="2">
                    <label for="" class="search-box-label">
                      <v-icon x-small :color="'primary'" class="mr-1">mdi-record-circle</v-icon>
                      첨부파일
                    </label>
                  </v-col>
                  <v-col :cols="8"> 
                    <v-file-input
                      multiple
                      background-color="#47535c"
                      show-size
                      v-model="fileData"
                      hide-details="true"
                      >
                    </v-file-input>
                  </v-col>
                </v-row> -->
								<v-row>
									<v-col :cols="12">
										<v-row class="search-box" align="center" no-gutters>
											<v-col :cols="2">
												<label
													class="search-box-label"
													style="padding-left:10px"
												>
													<v-icon x-small color="primary" class="mr-1"
														>mdi-record-circle</v-icon
													>
													파일 목록
												</label>
											</v-col>
											<v-col :cols="10">
												<v-row
													v-for="replyFileData in replyFileList"
													:key="replyFileData.apndFileId"
												>
													<a @click.prevent="downloadFile(replyFileData)">
														<v-col :cols="12">
															<div class="search-box-label">
																{{
																	replyFileData.apndFileNm +
																		'.' +
																		replyFileData.apndFileExt
																}}
															</div>
														</v-col>
													</a>
													<!-- <v-icon v-show="state === 'update'" class="pl-5" @click="addFileToDeleteFileList(replyFileData)">
                            mdi-close
                          </v-icon> -->
												</v-row>
											</v-col>
										</v-row>
									</v-col>
								</v-row>
							</div>
						</div>
					</div>
				</template>
				<v-card-actions class="justify-end">
					<v-btn :ripple="false" @click="clickOk()">등록</v-btn>
					<v-btn :ripple="false" @click="clickCancle()">취소</v-btn>
				</v-card-actions>
			</v-card>
		</v-dialog>
	</div>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import InputText from '~/components/common/form/InputText';
import InputNumber from '~/components/common/form/InputNumber';
import TextArea from '~/components/common/form/TextArea';
import SelectBox from '~/components/common/form/SelectBox';
import SelectBoxes from '~/components/common/form/SelectBoxes';
import CheckBox from '~/components/common/form/CheckBox';
import ChangeUserPswdPopPage from '~/components/common/modal/ChangeUserPswdPopPage';
import EnrgReadPlacePop2Page from '~/components/common/modal/EnrgReadPlacePop2Page';
import EnrgCostCenterPop from '~/components/common/modal/EnrgCostCenterPop';
import ReadPlcPop from '~/components/common/modal/ReadPlcPop';
import EvtObjPop from '~/components/common/modal/EvtObjPop';
import FtnPlcFormPop from '~/components/common/modal/FtnPlcMultiPop2';
import Label from '~/components/common/form/Label';
import mixinGlobal from '@/mixin/global.js';
export default {
	mixins: [mixinGlobal],
	props: {
		parentPrgmId: {
			type: String,
			require: true,
		},
		detailList: {
			type: Array,
			require: false,
			default: () => {
				return [];
			},
		},
		answerList: {
			type: Array,
			require: false,
			default: () => {
				return [];
			},
		},
		label: {
			type: String,
			require: true,
		},
		bindingData: {
			type: String,
			require: false,
		},
		gridName: {
			type: String,
			require: false,
		},
	},
	components: {
		InputText,
		InputNumber,
		TextArea,
		SelectBox,
		SelectBoxes,
		CheckBox,
		ChangeUserPswdPopPage,
		EnrgReadPlacePop2Page,
		EnrgCostCenterPop,
		ReadPlcPop,
		EvtObjPop,
		Label,
		FtnPlcFormPop,
	},
	data() {
		return {
			fileList: null,
			fileData: null,
			dialog: false,
			answerDialog: true,
			param: {},
			state: '',
			deleteFileList: [],
			replyFileList: null,
			replyFileData: null,
			chkcomNm: '',
		};
	},
	computed: {
		...mapState({
			searchParam(state) {
				return state.pageData[this.parentPrgmId];
			},
			isDarkMode: 'isDarkMode',
		}),
		chkDialog() {
			return this.dialog;
		},
		chkAnswerDialog() {
			return this.answerDialog;
		},
		componentDisableFlag() {
			if (this.state === 'read') {
				return true;
			} else {
				return false;
			}
		},
	},
	watch: {
		async chkDialog(val) {
			if (val) {
				this.openDialog();
			}
		},
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
		}),
		...mapActions({
			postUpdateApi: 'modules/list/postUpdateApi',
			getDomain: 'modules/list/getDomain',
		}),
		async clickOk() {
			this.dialog = !this.dialog;
			switch (this.state) {
				case 'insert':
					await this.insertDetail();
					break;
				case 'update':
					await this.updateDetail();
					break;
			}

			// apndFileUuid = this.postUpdateApi({
			//   apiKey: "saveFile",
			//   resKey: "apndFileUuid",
			//   sendParam: formData
			// })
		},
		async getFileList(apndFileUuid) {
			var fileList = [];

			if (apndFileUuid === null || apndFileUuid === '') {
				return fileList;
			}

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

			return fileList.data.dataset.apndFile;
		},
		async openDialog() {
			this.fildList = null;
			this.fileData = null;
			this.deleteFileList = [];
			this.replyFileData = null;
			this.replyFileList = null;

			switch (this.state) {
				case 'insert':
					break;
				case 'update':
					this.fileList = await this.getFileList(
						this.searchParam[this.gridName]['rowGridSelectData'].apndFileUuid,
					);
					this.replyFileList = await this.getFileList(
						this.searchParam[this.gridName]['rowGridSelectData']
							.answApndFileUuid,
					);
					break;
				case 'read':
					this.fileList = await this.getFileList(
						this.searchParam[this.gridName]['rowGridSelectData'].apndFileUuid,
					);
					this.replyFileList = await this.getFileList(
						this.searchParam[this.gridName]['rowGridSelectData']
							.answApndFileUuid,
					);
					break;
			}
		},
		async insertDetail() {
			var fileList = this.fileData;
			var apndFileUuid = null;
			var formData = new FormData();

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

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

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

			this.param = {
				comId: this.userInfo.comId,
				userNm: this.$refs['userNm'][0].InputValue,
				comNm: this.$refs['comNm'][0].InputValue,
				rowStat: 'I',
				apndFileUuid: apndFileUuid,
				...this.param,
			};

			await this.postUpdateApi({
				apiKey: 'saveVocRqst',
				sendParam: {
					datas: {
						vocRqstData: [this.param],
					},
					params: {},
				},
			});
			this.param = {};
			this.setPageData({
				isFind: true,
			});
		},
		async updateDetail() {
			var fileList = this.fileData;
			var apndFileUuid = null;
			var formData = new FormData();

			if (fileList !== null) {
				for (var i = 0; i < fileList.length; i++) {
					formData.append('file', fileList[i]);
				}
				formData.append(
					'rcptNo',
					this.searchParam[this.gridName].rowGridSelectData.rcptNo,
				);

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

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

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

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

			this.param = {
				...this.param,
				comId: this.userInfo.comId,
				userNm: this.$refs['userNm'][0].InputValue,
				comNm: this.$refs['comNm'][0].InputValue,
				rowStat: 'U',
				apndFileUuid: apndFileUuid,
				rcptNo: this.searchParam[this.gridName].rowGridSelectData.rcptNo,
			};

			await this.postUpdateApi({
				apiKey: 'saveVocRqst',
				sendParam: {
					datas: {
						vocRqstData: [this.param],
					},
					params: {},
				},
			});
			this.param = {};
			this.setPageData({
				isFind: true,
			});
		},
		clickCancle() {
			this.dialog = !this.dialog;
		},
		getValue(data) {
			this.param[data.key] = data.value;
		},
		async downloadFile(item) {
			var menuId = 'MNU1102';
			var urlPrefix = await this.getDomain();
			// console.log("getDomain", 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);
		},
		addFileToDeleteFileList(item) {
			this.deleteFileList.push({ apndFileId: item.apndFileId });
			var index = null;

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

				this.fileList.splice(index, 1);
			}
		},
	},
};
</script>

<style scoped lang="scss">
::v-deep {
	.v-toolbar__content {
		justify-content: space-between;
		padding: 0;

		.v-btn {
			margin-right: 0 !important;
		}
	}

	.v-card__actions {
		padding-bottom: 30px !important;
	}
}
</style>
