<template>
	<div>
		<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="btnAction('close')"
            :style="{ backgroundColor: isDarkMode ? '#2d3355' : '#3f4d7d' }"
          >
            <v-icon>mdi-close</v-icon>
          </v-btn> -->
				</v-toolbar>
				<template>
					<div style="padding : 20px">
						<v-col :cols="12">
							<v-row>
								<v-col :cols="6">
									<v-row class="search-box" align="center" no-gutters>
										<v-col :cols="4">
											<label 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-text-field
												v-model="chkMan"
												class="v-input__custom"
												:disabled="componentDisableFlag"
												outlined
												:hide-details="true"
											></v-text-field>
										</v-col>
									</v-row>
								</v-col>
								<v-col :cols="6">
									<v-row class="search-box" align="center" no-gutters>
										<v-col :cols="4">
											<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">
											<div class="startpicker-container2">
												<v-text-field
													id="startpicker2"
													ref="startpicker2"
													v-model="targetDateTimeValue"
													:class="'v-input__custom'"
													:hide-details="true"
													readonly
													outlined
													:disabled="componentDisableFlag"
												>
													<template #append>
														<v-icon size="20">$icoCalendar</v-icon>
													</template>
													<template #append-outer>
														<div
															ref="startpicker-container2"
															id="startpicker-container2"
														></div>
													</template>
												</v-text-field>
											</div>
										</v-col>
									</v-row>
								</v-col>
							</v-row>
							<v-row>
								<v-col :cols="6">
									<EqpmPop
										:parentPrgmId="parentPrgmId"
										:bindOption="myBindOption"
										ref="eqpmPopInDetailPop"
										:disabled="componentDisableFlag"
										:textCols="8"
									/>
								</v-col>
								<v-col :cols="6">
									<v-row class="search-box" align="center" no-gutters>
										<v-col :cols="4">
											<label 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-text-field
												v-model="eqpmCapa"
												class="v-input__custom"
												:disabled="componentDisableFlag"
												outlined
												:hide-details="true"
												type="number"
											></v-text-field>
										</v-col>
									</v-row>
								</v-col>
							</v-row>
							<v-row>
								<v-col :cols="6">
									<v-row class="search-box" align="center" no-gutters>
										<v-col :cols="4">
											<label 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-text-field
                        v-model="chkRslt"
                        class="v-input__custom"
                        :disabled="componentDisableFlag"
                        outlined
                        :hide-details="true"
                      ></v-text-field> -->
											<v-select
												v-model="chkRslt"
												:items="chkRsltList"
												:item-text="chkRsltList.text"
												:item-value="chkRsltList.value"
												outlined
												:hide-details="true"
												append-icon="mdi-chevron-down"
												class="v-select__custom"
												:disabled="componentDisableFlag"
											></v-select>
										</v-col>
									</v-row>
								</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">
												<v-icon x-small color="primary" class="mr-1"
													>mdi-record-circle</v-icon
												>
												점검 실시 내용
											</label>
										</v-col>
										<v-col :cols="10">
											<v-textarea
												v-model="chkExctCntn"
												class="v-input__custom"
												:disabled="componentDisableFlag"
												outlined
												:hide-details="true"
												:maxlength="1000"
											></v-textarea>
										</v-col>
									</v-row>
								</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">
												<v-icon x-small color="primary" class="mr-1"
													>mdi-record-circle</v-icon
												>
												안전관리 의견
											</label>
										</v-col>
										<v-col :cols="10">
											<v-textarea
												v-model="elecEqpmSafeMngOpn"
												class="v-input__custom"
												:disabled="componentDisableFlag"
												outlined
												:hide-details="true"
												:maxlength="1000"
											></v-textarea>
										</v-col>
									</v-row>
								</v-col>
							</v-row>
							<v-row>
								<v-col v-show="!componentDisableFlag" :cols="12">
									<v-row class="search-box" align="center" no-gutters>
										<v-col :cols="2">
											<label class="search-box-label">
												<v-icon x-small color="primary" class="mr-1"
													>mdi-record-circle</v-icon
												>
												파일 첨부
											</label>
										</v-col>
										<v-col :cols="10">
											<v-file-input
												multiple
												background-color="#47535c"
												show-size
												v-model="fileData"
												hide-details="true"
											>
											</v-file-input>
										</v-col>
									</v-row>
								</v-col>
							</v-row>
							<v-row
								v-show="popUpAction === 'read' || popUpAction === 'update'"
							>
								<v-col :cols="12">
									<v-row class="search-box" align="center" no-gutters>
										<v-col :cols="2">
											<label class="search-box-label">
												<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="popUpAction === 'update'"
													class="pl-5"
													@click="addFileToDeleteFileList(fileData)"
												>
													mdi-close
												</v-icon>
											</v-row>
										</v-col>
									</v-row>
								</v-col>
							</v-row>
						</v-col>
					</div>
				</template>
				<v-card-actions class="justify-end">
					<v-btn
						v-show="!componentDisableFlag"
						:ripple="false"
						@click="btnAction('save')"
						>저장</v-btn
					>
					<v-btn :ripple="false" @click="btnAction('close')">닫기</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 Label from '~/components/common/form/Label';
import EqpmPop from '~/components/common/modal/EqpmPop';
import TuiDatepicker from 'tui-date-picker';
import Utility from '~/plugins/utility';

export default {
	props: {
		parentPrgmId: {
			type: String,
			require: true,
		},
		label: {
			type: String,
			require: false,
			default: '',
		},
	},
	components: {
		InputText,
		InputNumber,
		TextArea,
		SelectBox,
		SelectBoxes,
		CheckBox,
		Label,
		EqpmPop,
		TuiDatepicker,
		Utility,
	},
	data() {
		return {
			dialog: false,
			popUpAction: 'read', // 'read', 'insert', 'update'
			myBindOption: {
				eqpmId: 'modalmodalEqpmId',
				eqpmNm: 'modalmodalEqpmNm',
				parentModalState: 'close',
			},
			chkMan: '',
			chkDd: '',
			eqpmNm: '',
			eqpmId: '',
			eqpmCapa: '',
			chkRslt: '',
			chkExctCntn: '',
			elecEqpmSafeMngOpn: '',
			fileData: null,
			fileList: null,
			targetDateTimeValue: new Date().toISOString().substr(0, 10),
			startDatepickerInstance: null,
			deleteFileList: [],
			chkRsltList: [
				{ text: '적합', value: 'Y' },
				{ text: '부적합', value: 'N' },
			],
		};
	},
	computed: {
		...mapState({
			searchParam(state) {
				//console.log("#################")
				return state.pageData[this.parentPrgmId];
			},
			isDarkMode: 'isDarkMode',
		}),
		chkDialog() {
			return this.dialog;
		},
		componentDisableFlag() {
			if (this.popUpAction === 'read') {
				return true;
			} else {
				return false;
			}
		},
	},
	watch: {
		async chkDialog(val) {
			if (val) {
				this.openDialog();

				this.$nextTick(() => {
					if (this.popUpAction === 'insert') {
						this.$refs['eqpmPopInDetailPop'].parentModalState = 'openWithInit';
					} else {
						this.$refs['eqpmPopInDetailPop'].parentModalState = 'open';
					}
				});
			} else {
				this.$nextTick(() => {
					this.$refs['eqpmPopInDetailPop'].parentModalState = 'close';
				});
			}
		},
	},
	mounted() {
		// this.tuiCalendarInit();
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			setTree: 'modules/list/setTree',
			chkOpenTabList: 'chkOpenTabList',
			getDomain: 'modules/list/getDomain',
		}),
		tuiCalendarInit() {
			const startContainer = document.getElementById('startpicker-container2');
			const startTarget = document.getElementById('startpicker2');

			this.startDatepickerInstance = new TuiDatepicker(startContainer, {
				date: new Date(),
				language: 'ko',
				type: 'date',
				input: {
					element: startTarget,
					format: 'YYYY-MM-DD',
				},
				timePicker: false,
			});
			this.startDatepickerInstance.on('change', () => this.getStartDt());
		},
		getStartDt() {
			const dt = this.startDatepickerInstance.getDate();

			this.targetDateTimeValue = String(dt.toISOString()).substr(0, 10);
		},
		convertStringToDateFormat(val) {
			var result = '';

			result = Utility.setFormatDate(val, 'YYYY-MM-DD');

			return result;
		},
		convertDateFormatToString(val) {
			return val.replaceAll('-', '');
		},
		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.targetDateTimeValue = '';
			this.fileList = null;
			this.fileData = null;
			this.deleteFileList = [];

			//datepicker setting
			this.$nextTick(() => {
				this.tuiCalendarInit();
				switch (this.popUpAction) {
					case 'read':
						this.targetDateTimeValue = this.convertStringToDateFormat(
							this.searchParam.rowGridSelectData.chkDd,
						);
						break;
					case 'insert':
						this.targetDateTimeValue = this.convertStringToDateFormat(
							new Date(),
						);
						break;
					case 'update':
						this.targetDateTimeValue = this.convertStringToDateFormat(
							this.searchParam.rowGridSelectData.chkDd,
						);
						break;
				}
			});

			switch (this.popUpAction) {
				case 'read':
					this.chkMan = this.searchParam.rowGridSelectData.chkMan;
					this.eqpmNm = this.searchParam.rowGridSelectData.eqpmNm;
					this.eqpmId = this.searchParam.rowGridSelectData.eqpmId;
					this.eqpmCapa = this.searchParam.rowGridSelectData.eqpmCapa;
					this.chkRslt = this.searchParam.rowGridSelectData.chkRslt;
					this.chkExctCntn = this.searchParam.rowGridSelectData.chkExctCntn;
					this.elecEqpmSafeMngOpn = this.searchParam.rowGridSelectData.elecEqpmSafeMngOpn;

					this.fileList = await this.getFileList(
						this.searchParam.rowGridSelectData.apndFileUuid,
					);
					break;
				case 'insert':
					this.chkMan = '';
					this.eqpmNm = '';
					this.eqpmId = '';
					this.eqpmCapa = '';
					this.chkRslt = '';
					this.chkExctCntn = '';
					this.elecEqpmSafeMngOpn = '';
					this.fileData = null;
					break;
				case 'update':
					this.chkMan = this.searchParam.rowGridSelectData.chkMan;
					this.eqpmNm = this.searchParam.rowGridSelectData.eqpmNm;
					this.eqpmId = this.searchParam.rowGridSelectData.eqpmId;
					this.eqpmCapa = this.searchParam.rowGridSelectData.eqpmCapa;
					this.chkRslt = this.searchParam.rowGridSelectData.chkRslt;
					this.chkExctCntn = this.searchParam.rowGridSelectData.chkExctCntn;
					this.elecEqpmSafeMngOpn = this.searchParam.rowGridSelectData.elecEqpmSafeMngOpn;

					this.fileList = await this.getFileList(
						this.searchParam.rowGridSelectData.apndFileUuid,
					);
					break;
			}
		},
		async btnAction(action) {
			switch (action) {
				case 'close':
					this.dialog = !this.dialog;
					break;
				case 'save':
					this.dialog = !this.dialog;
					if (this.popUpAction === 'insert') {
						await this.insertDetail();
					} else if (this.popUpAction === 'update') {
						await this.updateDetail();
					}
					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('elecSafeChkNo', '');

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

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

			var params = {
				chkMan: this.chkMan,
				chkDd: this.convertDateFormatToString(this.targetDateTimeValue),
				eqpmId: this.searchParam[this.myBindOption.eqpmId],
				eqpmCapa: this.eqpmCapa,
				chkRslt: this.chkRslt,
				chkExctCntn: this.chkExctCntn,
				elecEqpmSafeMngOpn: this.elecEqpmSafeMngOpn,
				apndFileUuid: apndFileUuid,
				rowStat: 'I',
			};

			await this.postUpdateApi({
				apiKey: 'saveElecSafeChk',
				sendParam: {
					datas: {
						dsElecSafeChkData: [params],
					},
					params: {},
				},
			});

			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(
					'elecSafeChkNo',
					this.searchParam.rowGridSelectData.elecSafeChkNo,
				);

				apndFileUuid = await this.postUpdateApi({
					apiKey: 'saveFileElecSafeChk',
					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;

			var params = {
				elecSafeChkNo: this.searchParam.rowGridSelectData.elecSafeChkNo,
				chkMan: this.chkMan,
				chkDd: this.convertDateFormatToString(this.targetDateTimeValue),
				eqpmId: this.searchParam[this.myBindOption.eqpmId],
				eqpmCapa: this.eqpmCapa,
				chkRslt: this.chkRslt,
				chkExctCntn: this.chkExctCntn,
				elecEqpmSafeMngOpn: this.elecEqpmSafeMngOpn,
				apndFileUuid: apndFileUuid,
				rowStat: 'U',
			};

			await this.postUpdateApi({
				apiKey: 'saveElecSafeChk',
				sendParam: {
					datas: {
						dsElecSafeChkData: [params],
					},
					params: {},
				},
			});

			this.setPageData({
				isFind: true,
			});
		},
		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);
		},
		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">
.startpicker-container2 {
	display: flex;
	align-items: center;
	justify-content: space-between;
	position: relative;

	.v-input {
		.v-input__append-outer {
			margin-top: 0;
			margin-left: 0;

			#startpicker-container2,
			#endpicker-container2 {
				width: 100%;
				position: absolute;
				top: 36px;
				left: 0;
			}
		}
	}
}

.v-input__custom {
	flex: 0 0 auto;
	&.half {
		width: calc(50% - 20px);
	}
}
::v-deep {
	.tui-timepicker-row {
		display: flex;
		justify-content: space-around;
		background-color: #edf4fc;
		.tui-timepicker-column.tui-timepicker-colon {
			color: #000 !important;
		}
	}
}
</style>
