<template>
	<div class="l-layout">
		<v-row ref="searchFilter"> </v-row>
		<v-row ref="contents">
			<v-col cols="12">
				<v-card>
					<v-card-title class="justify-space-between">
						<span class="custom-title-4">개인 대시보드 관리</span>
						<BtnSearch @click="search()" class="mr-1" />
					</v-card-title>
					<v-row
						align="center"
						no-gutters
						:style="{ height: 'calc(100% - 62px)' }"
						class="px-5"
					>
						<v-col :cols="6" class="h100">
							<span
								class="body-1 font-weight-bold d-flex align-center"
								:style="{ minHeight: '36px' }"
								>[미배정] 위젯 리스트</span
							>
							<div
								ref="gridParent"
								class="py-5"
								:style="{ height: 'calc(50% - 100px)' }"
							>
								<component
									:ref="gridName"
									:is="loadGrid ? 'Grid' : null"
									:parentPrgmId="myPrgmId"
									:gridName="gridName"
									@getRowsData="getUnAsgnRowData"
								/>
							</div>
							<div class="">
								<component
									:is="'Form'"
									:parentPrgmId="myPrgmId"
									:bindingData="gridName"
									:detailList="detailList"
								/>
								<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">
										<img
											ref="uploadItemImage"
											id="itemImage"
											src=""
											style="width: 100%; height: 210px; border: 1px solid; object-fit: cover;"
										/>
									</v-col>
								</v-row>
							</div>
						</v-col>
						<v-col :cols="1">
							<ActionButtons
								:parentPrgmId="myPrgmId"
								:leftGridName="gridName"
								:rightGridName="gridName2"
								:btnActionsFnc="dualGridBtnActions"
							/>
						</v-col>
						<v-col :cols="5" class="h100">
							<v-row
								justify="space-between"
								align="center"
								no-gutters
								class="pl-5 pr-1"
							>
								<v-col>
									<span class="body-1 font-weight-bold"
										>[배정] 위젯 리스트</span
									>
								</v-col>
								<v-col class="text-right">
									<Buttons
										:parentPrgmId="myPrgmId"
										:bindingData="gridName2"
										:btnActionsFnc="btnActions"
									/>
								</v-col>
							</v-row>
							<div
								ref="gridParent2"
								class="pa-5"
								:style="{ height: 'calc(100% - 64px)' }"
							>
								<component
									:ref="gridName2"
									:is="loadGrid2 ? 'Grid' : null"
									:parentPrgmId="myPrgmId"
									:gridName="gridName2"
									:editorGrid="true"
									@getRowsData="getAsgnRowData"
								/>
							</div>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import mixinGlobal from '@/mixin/global.js';
import InputText from '@/components/common/input/InputText';
import BtnSearch from '~/components/common/button/BtnSearch';
import Grid from '~/components/common/Grid';
import Buttons from '~/components/common/button/Buttons';
import ActionButtons from '~/components/common/button/ActionButtons';
import BtnExcelDownload from '~/components/common/button/BtnExcelDownload';
import Utility from '~/plugins/utility';
import Form from '~/components/common/form/Form';
// import ChangePassword from "~/components/common/modal/ChangePassword";

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: {
		Grid,
		BtnSearch,
		BtnExcelDownload,
		InputText,
		ActionButtons,
		Buttons,
		Form,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			gridName: 'rowGrid',
			gridName2: 'rowGrid2',
			loadGrid: false,
			loadGrid2: false,
			leftSelectRowData: {},
			rightSelectRowData: {},
			test: false,
			detailList: myDetail,
		};
	},
	computed: {
		...mapState({
			pageData: state => state.pageData[myPrgmId],
		}),
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},

		ChkRowGridSelectData() {
			return this.pageData.rowGridSelectData;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	mounted() {
		this.init();
	},
	beforeDestroy() {
		this.chkOpenTabList({ key: 'destroy', prgmId: myPrgmId });
	},
	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',
		}),
		async init() {
			await this.gridInit();
		},

		async gridInit() {
			//---------------------gridOption 설정 시작----------------------------
			const gridHeight = this.$refs.gridParent.offsetHeight - 30;
			const gridHeight2 = this.$refs.gridParent2.offsetHeight - 30;
			// const gridHeight = this.$refs.contents.offsetHeight - 30;

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

			this.setGridOption({
				gridKey: this.gridName2,
				// value: myOptions
				value: Object.assign(Utility.defaultGridOption(gridHeight2), myOptions),
			});

			const myColumns = [
				{ header: '위젯ID', name: 'widgetId' },
				{ header: '위젯명', name: 'widgetNm' },
				{ header: '썸네일', name: 'widgetThumbnail', hidden: true },
			];

			const myColumns2 = [
				{ header: '위젯ID', name: 'widgetId' },
				{ header: '위젯명', name: 'widgetNm' },
				{
					header: '순서',
					name: 'widgetOrdrSeq',
					align: 'center',
					editor: 'text',
				},
				{
					header: '재조회기간(분)',
					name: 'widgetReflashMm',
					align: 'center',
					editor: 'text',
				},
			];

			this.setGridColumn({
				gridKey: this.gridName,
				value: myColumns,
			});
			this.setGridColumn({
				gridKey: this.gridName2,
				value: myColumns2,
			});

			//---------------------gridColumn 설정 끝----------------------------
			await this.getRowGridData();
		},

		async search() {
			await this.setPageData({
				isFind: false,
			});
			await this.getRowGridData();
		},

		async getRowGridData() {
			this.loadGrid = false;
			this.loadGrid2 = false;
			let res = [];
			res = await this.postApiReturn({
				apiKey: 'selectNotMyWidget',
				resKey: 'widgetData',
				sendParam: {
					blocId: this.pageData.blocId,
					comId: this.pageData.comId,
				},
			});

			let res2 = [];
			res2 = await this.postApiReturn({
				apiKey: 'selectMyWidget',
				resKey: 'widgetData',
				sendParam: {
					blocId: this.pageData.blocId,
					comId: this.pageData.comId,
				},
			});

			this.setGridData({
				gridKey: this.gridName,
				value: res,
			});

			this.setGridData({
				gridKey: this.gridName2,
				value: res2,
			});

			this.loadGrid = true;
			this.loadGrid2 = true;

			this.setPageData({ isFind: false });
			this.$nextTick(() => {
				if (res.length > 0) {
					this.$refs[this.gridName].focus({
						// rowKey: this.chkRowGridSelectKey || 0,
						rowKey: 0,
						setScroll: true,
					});
				}
			});
		},

		getUnAsgnRowData(data) {
			const getRowData = data;
			this.leftSelectRowData = Object.assign({}, getRowData);
			if (data.widgetThumbnail == null) {
				itemImage.src = '';
			} else {
				itemImage.src = 'data:image/png;base64, ' + data.widgetThumbnail;
			}
			this.setGridSelectData({
				gridKey: this.gridName,
				gridSelect: true,
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: data,
			});
		},

		getAsgnRowData(data) {
			const getRowData = data;
			this.rightSelectRowData = Object.assign({}, getRowData);
		},
		async dualGridBtnActions(action) {
			let addTargetGrid = '';
			let removeTargetGrid = '';
			switch (action) {
				case 'addLeftToRight':
					addTargetGrid = this.$refs[this.gridName2];
					removeTargetGrid = this.$refs[this.gridName];
					if (!this.leftSelectRowData.widgetId) {
						alert('선택된 위젯이 없습니다.');
						return false;
					} else {
						addTargetGrid.addTreeRow({
							widgetNm: this.leftSelectRowData.widgetNm,
							widgetId: this.leftSelectRowData.widgetId,
							widgetOrdrSeq: addTargetGrid.gridData.data.length + 1,
							widgetReflashMm: 15,
						});
						removeTargetGrid.removeRow('immediately');
						this.leftSelectRowData = ''; // 배정 후 초기화
					}
					break;

				case 'removeRightToLeft':
					addTargetGrid = this.$refs[this.gridName];
					removeTargetGrid = this.$refs[this.gridName2];
					if (!this.rightSelectRowData.widgetId) {
						alert('선택된 위젯이 없습니다.');
						return false;
					} else {
						addTargetGrid.addTreeRow({
							widgetNm: this.rightSelectRowData.widgetNm,
							widgetId: this.rightSelectRowData.widgetId,
						});
						removeTargetGrid.removeRow('immediately');
						this.rightSelectRowData = ''; // 미배정 후 초기화
					}
					break;

				default:
					break;
			}
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'add':
					this.$refs[this.gridName2 + this.myPrgmId].addRow();
					break;

				case 'remove':
					this.$refs[this.gridName2 + this.myPrgmId].removeRow();
					break;

				case 'save':
					dataArr = this.$refs[this.gridName2].save();
					dataArr = dataArr.map(item => {
						const newData = {
							...item,
							widgetId: item.widgetId,
							widgetNm: item.widgetNm,
							widgetOrdrSeq: item.widgetOrdrSeq,
						};
						return newData;
					});
					if (dataArr.length > 0) {
						const sendParam = {
							datas: { dsWidget: dataArr },
							params: {},
						};
						await this.postUpdateApi({
							apiKey: 'saveMyWidget',
							sendParam: sendParam,
						});

						//this.search();
					} else {
						alert('저장할 내용이 없습니다.');
					}
					break;

				default:
					break;
			}
		},
	},
};

const defaultData = {
	/* 검색옵션 */
	isFind: false,
	roleNm: '',
	roleId: '',
	comId: '',

	// 선택된 그룹코드 상세 데이터
	rowGridSelectKey: 0,
	rowGridSelectData: {},

	/* data 세팅 */
	rowGrid: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
		defaultRow: {},
		rowGridSelectKey: 0,
		rowGridSelectData: null,
	},
	rowGrid2: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
		defaultRow: {
			widgetId: null,
			widgetNm: null,
			widgetOrdrSeq: null,
			widgetReflashMm: null,
			rowStat: null,
		},
		buttonAuth: {
			add: false,
			remove: false,
			save: true,
			excel: false,
		},
	},
	xlsFileInfo: {
		// 출력하려는 grid 와 같은 이름으로 세팅
		rowGrid: {
			fileName: null, // 갑이 없으면 해당 페이지 메뉴명
			sheetName: null, //  갑이 없으면 'Sheet1'
		},
	},
};

const myDetail = [
	{
		type: 'InputText',
		label: '위젯ID',
		valueNm: 'widgetId',
		cols: 6,
		class: 'py-2',
		disabled: true,
	},
	{
		type: 'InputText',
		label: '위젯명',
		valueNm: 'widgetNm',
		cols: 6,
		class: 'py-2',
		disabled: true,
	},
	{
		type: 'TextArea',
		label: '위젯 설명',
		valueNm: 'widgetDesc',
		disabled: true,
		cols: 12,
		textCols: 10,
		rows: 4,
		class: 'py-2',
	},
];

function numberFormatter({ value }) {
	if (value == null) {
		return 0;
	} else {
		return value;
	}
}
</script>
