<template>
	<div class="l-layout">
		<!-- 조회조건 -->
		<v-row ref="searchFilter">
			<v-col :cols="12">
				<v-card class="searchFilter">
					<v-row align="center" no-gutters>
						<v-col :cols="3">
							<component
								:is="'selectCodeList'"
								:parentPrgmId="myPrgmId"
								:label="'사용여부'"
								:dataKey="'selectUseFg'"
								:sendParam="{ commGrpCd: 'CO_USEFG', useFg: '1' }"
								:addAll="true"
							/>
						</v-col>
						<v-col :cols="4">
							<InputText
								:parentPrgmId="myPrgmId"
								label="위젯명"
								valueNm="widgetNm"
								:searchOption="true"
								:labelCols="3"
								:textCols="9"
							/>
						</v-col>
						<v-col :cols="5" class="text-right">
							<BtnSearch />
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>

		<v-row ref="contents">
			<!-- 위젯 리스트 -->
			<v-col :cols="5" class="h100">
				<v-card class="pb-5">
					<v-card-title>위젯 리스트</v-card-title>
					<div style="height:calc(100% - 70px)">
						<div ref="gridParent" class="px-5 h100">
							<component
								:ref="gridName"
								:is="loadGrid ? 'Grid' : null"
								:parentPrgmId="myPrgmId"
								:gridName="gridName"
								@getRowsData="getRowData"
							/>
						</div>
					</div>
				</v-card>
			</v-col>
			<!-- 위젯 상세 -->
			<v-col :cols="7" class="h100">
				<v-card class="pb-5">
					<div class="d-flex align-center justify-space-between pa-5">
						<v-card-title class="pa-0">위젯 상세</v-card-title>
						<div>
							<Buttons
								:parentPrgmId="myPrgmId"
								:bindingData="gridName"
								:detailList="detailList"
								:btnActionsFnc="btnActions"
							/>
						</div>
					</div>
					<div class="px-5 h100" style="height:calc(100% - 70px)">
						<div class="w100">
							<component
								:is="'Form'"
								:parentPrgmId="myPrgmId"
								:detailList="detailList"
								@gridEditingFinish="gridEditingFinish"
							/>
							<v-row class="search-box py-2" 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-row class="search-box py-2" 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" class="h100">
									<!-- <div class="wrapper-image"> -->
									<img
										ref="uploadItemImage"
										id="itemImage"
										src=""
										style="width: 100%; height: 270px; border: 1px solid; object-fit: cover;"
									/>
									<!-- </div> -->
								</v-col>
							</v-row>
						</div>
					</div>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import mixinGlobal from '@/mixin/global.js';
// import { mapState, mapMutations, mapActions } from "vuex";
import selectCodeList from '@/components/common/select/selectCodeList';
import InputText from '@/components/common/input/InputText';
import BtnSearch from '~/components/common/button/BtnSearch';
import Buttons from '~/components/common/button/Buttons';
import Grid from '~/components/common/Grid';
import Form from '~/components/common/form/Form';
import Utility from '~/plugins/utility';

let myTitle;
let myPrgmId;
export default {
	mixins: [mixinGlobal],
	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: {
		selectCodeList,
		Form,
		Grid,
		BtnSearch,
		Buttons,
		InputText,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			loadGrid: false,
			gridName: 'rowGrid',
			// rowGridOrigin: [],
			detailList: myDetail,
			fileData: null,
			gridRowKey: 0,
		};
	},
	computed: {
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkUseFg() {
			return this.pageData.selectUseFg;
		},
		chkRowGridSelectKey() {
			return this.pageData.rowGridSelectKey;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkUseFg() {
			this.setPageData({ isFind: true });
		},
		async fileData(val) {
			if (val != null && typeof val == 'object') {
				var fileList = this.fileData;
				var formData = new FormData();
				var thumbnail = null;
				if (fileList !== null) {
					for (var i = 0; i < fileList.length; i++) {
						formData.append('file', fileList[i]);
					}
					const apndFileUuid = this.postUpdateApi({
						apiKey: 'selectFileToBase64',
						resKey: 'apndFileUuid',
						sendParam: formData,
					});

					await apndFileUuid.then(apndFileUuid => {
						thumbnail = apndFileUuid.data.dataset.apndFileUuid;
					});

					var data = {
						columnName: 'widgetThumbnail',
						value: atob(thumbnail),
					};
					this.$refs[this.gridName].editingFinish(data);

					var data2 = {
						columnName: 'widgetThumbnailFile',
						value: val[0].name,
					};
					this.$refs[this.gridName].editingFinish(data2);
				}
			}
		},
	},
	beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	mounted() {
		this.init();
	},
	beforeDestroy() {
		this.chkOpenTabList({ key: 'destroy', prgmId: myPrgmId });
	},
	methods: {
		init() {
			this.gridInit();
		},
		gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 36;

			const myOptions = {
				scrollX: false,
			};
			this.setGridOption({
				gridKey: this.gridName,
				// value: myOptions
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});

			const _this = this;
			const myColumns = [
				{ header: '위젯ID', name: 'widgetId' },
				{ header: '위젯명', name: 'widgetNm' },
				{
					header: '사용여부',
					name: 'useFg',
					align: 'center',
					formatter({ value }) {
						value = value === true ? '1' : '0';
						const newValue = _this.pageData.selectUseFgList.filter(
							item => item.commCd == value,
						);
						return newValue[0].commCdNm;
					},
				},
				{ header: '파일', name: 'widgetThumbnailFile' },
				{ header: '썸네일', name: 'widgetThumbnail', hidden: true },
				{ header: '위젯설명', name: 'widgetDesc', hidden: true },
				{ header: '프로그램ID', name: 'prgmId', hidden: true },
				{ header: '등록자NO', name: 'regUserNo', hidden: true },
				{ header: '등록일시', name: 'regDttm', hidden: true },
				{ header: '수정자NO', name: 'procUserNo', hidden: true },
				{ header: '수정일시', name: 'procDttm', hidden: true },
			];
			this.setGridColumn({
				gridKey: this.gridName,
				value: myColumns,
			});

			// this.getRowGridData();

			this.loadGrid = true;
		},
		async search() {
			await this.getRowGridData();
			await this.setPageData({
				isFind: false,
			});
		},
		async getRowGridData() {
			const res = await this.postApiReturn({
				apiKey: 'selectWidget',
				resKey: 'widgetData',
				sendParam: {
					useFg: this.chkUseFg,
					prgmNm: this.pageData.prgmNm, // 검색키워드: 프로그램명
				},
			});
			const newRes = res.map(item => {
				const newObj = {
					...item,
					rowStat: null,
					useFg: item.useFg === '1' ? true : false, // 화면 개발 편의를 위해 boolean 타입으로 교체, 저장시 "1", "0" 으로 바꿔 보내야 함
				};
				return newObj;
			});

			// 엑셀 다운로드용 데이터 재정렬
			this.xlsDataBind(res);
			// this.rowGridOrigin = Utility.copyObj(newRes);
			this.setGridData({
				gridKey: this.gridName,
				value: newRes,
			});

			this.$nextTick(() => {
				if (newRes.length > 0) {
					this.$refs[this.gridName].focus({
						// rowKey: this.chkRowGridSelectKey || 0,
						rowKey: 0,
						setScroll: true,
					});
				}
			});
		},
		async getRowData(data, gridName) {
			if (data.rowStat === 'I') {
				this.detailList[0].disabled = false;
			} else {
				this.detailList[0].disabled = true;
			}
			this.gridRowKey = data.rowKey;

			this.setPageData({
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: data,
			});
			if (data.widgetThumbnail == null) {
				itemImage.src = '';
			} else {
				itemImage.src = 'data:image/png;base64, ' + data.widgetThumbnail;
			}
		},
		compareData(type, newDt) {
			if (this.selectedCommCdData[type] == newDt) {
				return true;
			} else {
				return false;
			}
		},
		gridEditingFinish(data) {
			this.$refs[this.gridName].editingFinish(data);
		},
		async btnActions(action) {
			switch (action) {
				case 'add':
					this.$refs[this.gridName].addRow();
					this.detailList[0].disabled = false;
					break;

				case 'remove':
					this.$refs[this.gridName].removeRow();
					break;

				case 'save':
					var dataArr = this.$refs[this.gridName].save();
					if (dataArr.length > 0) {
						const sendParam = {
							datas: {
								dsWidget: dataArr.map(item => ({
									...item,
									useFg: item.useFg ? '1' : '0',
								})),
							},
							params: {},
						};
						for (var i = 0; i < sendParam.datas.dsWidget.length; i++) {
							var prgmChk = sendParam.datas.dsWidget[i].widgetNm;
						}
						if (prgmChk == null || prgmChk == undefined || prgmChk == '') {
							alert('위젯명을 입력하세요.');
						} else {
							await this.postUpdateApi({
								apiKey: 'saveWidget',
								sendParam: sendParam,
							});
							this.setPageData({ isFind: true });
						}
					} else {
						alert('저장할 내용이 없습니다.');
					}
					break;

				default:
					break;
			}
		},
		xlsDataBind(res) {
			const xlsRowData = res.map(item => {
				const obj = {
					...item,
					useFg: item.useFg == '1' ? '사용' : '사용안함',
				};
				return obj;
			});
			this.setPageData({
				xlsFileInfo: {
					[this.gridName]: {
						rowData: xlsRowData,
					},
				},
			});
		},
	},
};

const defaultData = {
	selectUseFg: false,
	selectUseFgList: [],

	prgmNm: '',

	/* 검색옵션 */
	isFind: false,

	/* data 세팅 */
	rowGrid: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
		defaultRow: {
			widgetId: null,
			widgetNm: null,
			widgetDesc: null,
			widgetThumbnailFile: null,
			widgetThumbnail: null,
			prgmId: null,
			useFg: true,
			regUserNo: null,
			regDttm: null,
			procUserNo: null,
			procDttm: null,
			rowStat: null,
		},
		rowGridSelectKey: 0,
		rowGridSelectData: null,
		rowGridModify: false,
		buttonAuth: {
			add: true,
			remove: true,
			save: true,
			excel: true,
		},
	},
	rowGridSelectKey: 0,
	rowGridSelectData: null,
	rowGridModify: false,

	xlsFileInfo: {
		// 출력하려는 grid 와 같은 이름으로 세팅
		rowGrid: {
			rowData: [],
			// 엑셀변환시 데이타 가공이 추가로 필요하게 된다면 여기에 가공된 rowData 를 넣어야 할듯
			fileName: null, // 갑이 없으면 해당 페이지 메뉴명
			sheetName: null, //  갑이 없으면 'Sheet1'
		},
	},
};

const myDetail = [
	{
		type: 'InputText',
		label: '위젯ID',
		valueNm: 'widgetId',
		cols: 6,
		class: 'py-2',
		required: true,
		disabled: false,
	},
	{
		type: 'InputText',
		label: '위젯명',
		valueNm: 'widgetNm',
		cols: 6,
		class: 'py-2',
		required: true,
	},
	{
		type: 'InputText',
		label: '프로그램 ID',
		valueNm: 'prgmId',
		cols: 6,
		class: 'py-2',
		required: true,
	},
	{
		type: 'CheckBox',
		label: '사용여부',
		valueNm: 'useFg',
		essential: true,
		disabled: false,
		cols: 6,
		class: 'py-2',
		value: { '1': true, '0': false },
		required: true,
	},
	{
		type: 'TextArea',
		label: '위젯 설명',
		valueNm: 'widgetDesc',
		disabled: false,
		cols: 12,
		textCols: 10,
		rows: 4,
		class: 'py-2',
		required: true,
	},
	{
		type: 'InputText',
		label: '등록자NO',
		valueNm: 'regUserNo',
		disabled: true,
		cols: 6,
		class: 'py-2',
	},
	{
		type: 'InputText',
		label: '등록일시',
		valueNm: 'regDttm',
		disabled: true,
		cols: 6,
		class: 'py-2',
	},
	{
		type: 'InputText',
		label: '수정자NO',
		valueNm: 'procUserNo',
		disabled: true,
		cols: 6,
		class: 'py-2',
	},
	{
		type: 'InputText',
		label: '수정일시',
		valueNm: 'procDttm',
		disabled: true,
		cols: 6,
		class: 'py-2',
	},
];
</script>

<style lang="scss">
.v-text-field__details {
	display: none;
}
</style>
