<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="4">
							<component :is="'SelectSysDiv'" :parentPrgmId="myPrgmId" />
						</v-col>
						<v-col :cols="4">
							<component :is="'SelectUseFg'" :parentPrgmId="myPrgmId" />
						</v-col>
						<v-col :cols="4" class="text-right">
							<BtnSearch @click="search" />
						</v-col>
					</v-row>
					<v-row align="center" no-gutters>
						<v-col :cols="4">
							<InputText
								:parentPrgmId="myPrgmId"
								label="그룹코드"
								valueNm="commGrpCd"
							/>
						</v-col>
						<v-col :cols="4">
							<InputText
								:parentPrgmId="myPrgmId"
								label="그룹코드명"
								valueNm="commGrpCdNm"
							/>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents">
			<v-col :cols="5" class="h100">
				<v-card class="py-5 h100">
					<v-card-title class="d-flex justify-between">
						<span class="tit ft-size_20 ft-weight_600">공통그룹코드</span>
						<div>
							<v-btn
								class="v-btn-radius__20 v-btn-bg__white-blue mr-1"
								@click="addRow"
							>
								<v-icon>mdi-plus</v-icon>
								<span>추가</span>
							</v-btn>
							<v-btn
								class="v-btn-radius__20 v-btn-bg__white-blue mr-1"
								@click="removeRow"
							>
								<v-icon>mdi-delete-outline</v-icon>
								<span>삭제</span>
							</v-btn>
							<v-btn class="v-btn-radius__20 v-btn-bg__blue" @click="save">
								<v-icon>mdi-content-save</v-icon>
								<span>저장</span>
							</v-btn>
						</div>
					</v-card-title>
					<v-card-actions>
						<div ref="gridParent" class="h100 w100">
							<component
								ref="myGrid"
								:is="loadGrid ? 'Grid' : null"
								:gridName="gridName"
								:parentPrgmId="myPrgmId"
								@getRowsData="getRowData"
							/>
						</div>
					</v-card-actions>
				</v-card>
			</v-col>
			<v-col :cols="7" class="h100">
				<v-card class="py-5">
					<v-card-title>
						<span class="tit ft-size_20 ft-weight_600">설비그룹 상세</span>
					</v-card-title>
					<v-card-actions class="flex-column">
						<v-tabs v-model="tab">
							<v-tab v-for="item in items" :key="item.id">
								{{ item.name }}
							</v-tab>
						</v-tabs>
						<v-tabs-items v-model="tab" style="height: calc(100% - 65px);">
							<v-tab-item v-for="item in items" :key="item.id">
								<GrpinfoTab
									v-if="item.id == 'grpInfoTab'"
									:parentPrgmId="myPrgmId"
								/>
								<CommCdTab
									v-if="item.id == 'commCdTab'"
									:parentPrgmId="myPrgmId"
								/>
							</v-tab-item>
						</v-tabs-items>
					</v-card-actions>
				</v-card>
			</v-col>
		</v-row>
	</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 SelectSysDiv from '@/components/common/select/SelectSysDiv';
import SelectUseFg from '@/components/common/select/SelectUseFg';
import InputText from '@/components/common/input/InputText';
import GrpinfoTab from '@/components/pages/comm/GrpCdInfoTab';
import CommCdTab from '@/components/pages/comm/CommCdTab';
import Grid from '~/components/common/Grid';

let myTitle;
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: {
		BtnSearch,
		SelectSysDiv,
		SelectUseFg,
		InputText,
		GrpinfoTab,
		CommCdTab,
		Grid,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			gridName: 'rowGrid',
			loadGrid: false,
			tab: null,
			items: [
				{ name: '그룹코드정보', id: 'grpInfoTab' },
				{ name: '공통코드', id: 'commCdTab' },
			],
		};
	},
	computed: {
		...mapState({
			pageData: state => state.pageData[myPrgmId],
		}),
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkSysDivCd() {
			// 시스템구분 선택 감지
			return this.pageData.sysDivCd;
		},
		chkUseFg() {
			// 사용여부 선택 감지
			return this.pageData.useFg;
		},
		selectedCommCdData() {
			return this.pageData.selectedCommCdData;
		},
		modifySysDivCd() {
			return this.pageData.modifySysDivCd;
		},
		modifyUseFg() {
			return this.pageData.modifyUseFg;
		},
		modifyCommGrpCd() {
			return this.pageData.modifyCommGrpCd;
		},
		modifyCommGrpCdNm() {
			return this.pageData.modifyCommGrpCdNm;
		},
		modifyRmrk() {
			return this.pageData.rmrk;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkSysDivCd() {
			this.setPageData({ isFind: true });
		},
		chkUseFg() {
			this.setPageData({ isFind: true });
		},
		modifyCommGrpCd(val) {
			const isSameData = this.compareData('commGrpCd', val);
			if (!isSameData) {
				const dt = {
					name: 'commGrpCd',
					value: val,
				};
				this.$refs.myGrid.externalDataEdit(dt);
			}
		},
		modifyCommGrpCdNm(val) {
			const isSameData = this.compareData('commGrpNm', val);
			if (!isSameData) {
				const dt = {
					name: 'commGrpNm',
					value: val,
				};
				this.$refs.myGrid.externalDataEdit(dt);
			}
		},
		modifySysDivCd(val) {
			const isSameData = this.compareData('sysDiv', val);
			if (!isSameData) {
				const dt = {
					name: 'sysDiv',
					value: val,
				};
				this.$refs.myGrid.externalDataEdit(dt);
			}
		},
		modifyUseFg(val) {
			const isSameData = this.compareData('useFg', val);
			if (!isSameData) {
				const dt = {
					name: 'useFg',
					value: val,
				};
				this.$refs.myGrid.externalDataEdit(dt);
			}
		},
		modifyRmrk(val) {
			const isSameData = this.compareData('rmrk', val);
			if (!isSameData) {
				const dt = {
					name: 'rmrk',
					value: val,
				};
				this.$refs.myGrid.externalDataEdit(dt);
			}
		},
	},
	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',
		}),
		init() {
			this.layoutInit();
			this.gridInit();
		},
		layoutInit() {
			const searchFilterHeight = this.$refs.searchFilter.offsetHeight;
			this.$refs.contents.style.height = `calc(100% - ${searchFilterHeight}px)`;
		},
		gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 30;

			const myOptions = {
				columnOptions: {
					resizable: true,
				},
				bodyHeight: gridHeight,
				minBodyHeight: gridHeight,
				header: {
					height: 28,
				},
				rowHeight: 29,
				minRowHeight: 29,
			};
			this.setGridOption({
				gridKey: this.gridName,
				value: myOptions,
			});
			const _this = this;
			const myColumns = [
				{
					header: '시스템구분',
					name: 'sysDiv',
					align: 'center',
					formatter({ value }) {
						const newValue = _this.pageData.sysDivCdList.filter(
							item => item.commCd == value,
						);
						return newValue[0].commCdNm;
					},
				},
				{ header: '그룹코드', name: 'commGrpCd', align: 'center' },
				{ header: '그룹코드명', name: 'commGrpNm' },
				{
					header: '사용여부',
					name: 'useFg',
					align: 'center',
					formatter({ value }) {
						const newValue = _this.pageData.useFgList.filter(
							item => item.commCd == value,
						);
						return newValue[0].commCdNm;
					},
				},
				{ header: '비고', name: 'rmrk', 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: 'selectCommGrpCd',
				resKey: 'commGrpCdData',
				sendParm: {
					commGrpCd: this.pageData.commGrpCd,
					commGrpNm: this.pageData.commGrpCdNm,
					sysDivCd: this.pageData.sysDivCd,
					useFg: this.pageData.useFg,
				},
			});
			const newRes = res.map(item => {
				const newObj = {
					...item,
					rowStat: null,
				};
				return newObj;
			});
			this.setGridData({
				gridKey: this.gridName,
				value: newRes,
			});

			this.$nextTick(() => {
				if (newRes.length > 0) {
					this.$refs['myGrid'].focus({
						rowKey: 0,
						columnName: 'sysDiv',
						setScroll: true,
					});
				} else {
					this.detailDataInit();
				}
			});
		},
		async getRowData(data) {
			this.setPageData({
				selectedRowKey: data.rowKey,
				modifySysDivCd: data.sysDiv,
				modifyUseFg: data.useFg,
				modifyCommGrpCdNm: data.commGrpNm,
				modifyCommGrpCd: data.commGrpCd,
				rmrk: data.rmrk,
				selectedCommCdData: data,
			});

			const res = await this.postApiReturn({
				apiKey: 'selectCommCd',
				resKey: 'commCdData',
				sendParm: {
					commGrpCd: data.commGrpCd,
				},
			});
			const newRes = res.map(item => {
				const newObj = {
					...item,
					rowStat: null,
				};
				return newObj;
			});

			this.setGridData({
				gridKey: 'rowDetailGrid',
				value: newRes,
			});
		},
		detailDataInit() {
			this.setPageData({
				selectedCommCdData: null,
				selectedRowKey: null,
				modifySysDivCd: 'COMM',
				modifyUseFg: '1',
				modifyCommGrpCdNm: '',
				modifyCommGrpCd: '',
				rmrk: '',
			});
			this.setGridData({
				gridKey: 'rowDetailGrid',
				value: [],
			});
		},
		compareData(type, newDt) {
			if (this.selectedCommCdData[type] == newDt) {
				return true;
			} else {
				return false;
			}
		},
		addRow() {
			this.$refs.myGrid.addRow();
		},
		removeRow() {
			this.$refs.myGrid.removeRow();
		},
		async save() {
			const dataArr = this.$refs.myGrid.save();
			const sendParam = {
				datas: { dsGrpCd: dataArr },
				params: {},
			};
			await this.postUpdateApi({
				apiKey: 'saveCommGrpCd',
				sendParm: sendParam,
			});

			await this.search();
		},
	},
};

const defaultData = {
	/* 검색옵션 */
	sysDivCd: 'COMM',
	sysDivCdList: [],
	useFg: '1',
	useFgList: [],
	commGrpCd: '',
	commGrpCdNm: '',

	/* 그룹코드정보 탭 옵션 */
	// 그롭코드정보 탭에서 사용될 사용여부 model 값 셋팅
	modifySysDivCd: 'COMM',
	modifyUseFg: '1',
	modifyCommGrpCdNm: '',
	modifyCommGrpCd: '',
	rmrk: '',

	isFind: false, // true 경우 조회, 조회버튼도 이 값으로 연동 예정
	/* data 세팅 */
	// 로컬 gridName 값과 동일한 이름으로 세팅
	rowGrid: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
		defaultRow: {
			sysDiv: 'COMM',
			commGrpCd: '',
			commGrpNm: '',
			useFg: '1',
			rmrk: '',
			rowStat: null,
		},
	},
	rowDetailGrid: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
		defaultRow: {
			commCd: '',
			commCdNm: '',
			commCdAbbrnm: '',
			sortSeq: '',
			useFg: '1',
			userDefVal1: '',
			userDefVal2: '',
			userDefVal3: '',
			rowStat: null,
		},
	},

	// 선택된 그룹코드 상세 데이터
	selectedRowKey: null,
	selectedCommCdData: null,
};
</script>
