<template>
	<div class="l-layout">
	    <PageTitle text="공통코드" />
		<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="sysDivCd"
								:labelCols="12"
                 				:textCols="12"
								:sendParam="{ commGrpCd: 'CO_SYSDIV', useFg: '1' }"
								:addAll="true"
								customClass="select-large"
							/>
						</v-col>
						<v-col :cols="3">
							<component
								:is="'selectCodeList'"
								:parentPrgmId="myPrgmId"
								:label="'사용여부'"
								:labelCols="12"
                 				:textCols="12"
								:dataKey="'useFg'"
								customClass="select-large"
								:sendParam="{ commGrpCd: 'CO_USEFG', useFg: '1' }"
							/>
						</v-col>
						<v-col :cols="3">
							<InputText
								:parentPrgmId="myPrgmId"
								label="그룹코드"
								valueNm="commGrpCd"
								:searchOption="true"
								:labelCols="12"
								:textCols="12"
								customClass="input-large"

							/>
						</v-col>
						<v-col :cols="3">
							<InputText
								:parentPrgmId="myPrgmId"
								label="그룹코드명"
								valueNm="commGrpCdNm"
								:searchOption="true"
								:labelCols="12"
								:textCols="12"
								customClass="input-large"

							/>
						</v-col>
						
						<v-col :cols="12" class="text-right">
							<BtnSearch style="margin-top:20px" @click="search" />
						</v-col>
					</v-row>
					<!-- <v-row align="center" no-gutters>
						<v-col :cols="4">
							<InputText
								:parentPrgmId="myPrgmId"
								label="그룹코드"
								valueNm="commGrpCd"
								:searchOption="true"
								:labelCols="4"
								:textCols="8"
							/>
						</v-col>
						<v-col :cols="4">
							<InputText
								:parentPrgmId="myPrgmId"
								label="그룹코드명"
								valueNm="commGrpCdNm"
								:searchOption="true"
								:labelCols="4"
								:textCols="8"
							/>
						</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 h100">
					<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" style="height:calc(100% - 70px);">
						<div ref="gridParent" class="h100 w100">
							<component
								:ref="gridName"
								:is="loadGrid ? 'Grid' : null"
								:gridName="gridName"
								:parentPrgmId="myPrgmId"
								@getRowsData="getRowData"
								@sendSelectedRowStatInfo="getSelectedRowStatInfo"
								:selectedRowDataWatchFlag="true"
							/>
						</div>
					</div>
				</v-card>
			</v-col>
			<v-col :cols="7" class="h100">
				<v-card class="pb-5">
					<v-card-title>공통그룹코드 상세</v-card-title>
					<div class="px-5" style="height:calc(100% - 70px)">
						<v-tabs v-model="tab" >
							<v-tab
								v-for="item in items"
								:key="item.id"
								:disabled="item.disabledFlag"
							>
								{{ item.name }}
							</v-tab>
						</v-tabs>
						<v-tabs-items
							v-model="tab"
							style="height: calc(100% - 65px);"
							class="py-6"
						>
							<!-- <v-tab-item v-for="item in items" :key="item.id"> -->
							<v-tab-item v-for="(item, idx) in items" :key="item.id">
								<component
									v-if="item.id == 'grpInfoTab'"
									:is="'Form'"
									:parentPrgmId="myPrgmId"
									:detailList="detailList"
									@gridEditingFinish="gridEditingFinish"
								/>
								<CommCdTab
									v-if="item.id == 'commCdTab'"
									:parentPrgmId="myPrgmId"
									:innerTabGridInfo="{ tab, idx }"
								/>
							</v-tab-item>
						</v-tabs-items>
					</div>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import mixinGlobal from '@/mixin/global.js';
import { resize } from '@/mixin/resize.js';
import BtnSearch from '~/components/common/button/BtnSearch';
import Buttons from '~/components/common/button/Buttons';
import selectCodeList from '@/components/common/select/selectCodeList';
import InputText from '@/components/common/input/InputText';
import Form from '~/components/common/form/Form';
import CommCdTab from '@/components/pages/comm/CommCdTab';
import Grid from '~/components/common/Grid';
import Utility from '~/plugins/utility';
import PageTitle from "~/components/common/PageTitle";

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,
		Buttons,
		selectCodeList,
		InputText,
		Form,
		CommCdTab,
		Grid,
		PageTitle
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			gridName: 'rowGrid',
			loadGrid: false,
			tab: null,
			items: [
				{ name: '그룹코드정보', id: 'grpInfoTab', disabledFlag: false },
				{ name: '공통코드', id: 'commCdTab', disabledFlag: false },
			],
			detailList: myDetail,
		};
	},
	computed: {
		// ...mapState({
		//   pageData: state => state.pageData[myPrgmId]
		// }),
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkSysDivCd() {
			// 시스템구분 선택 감지
			return this.pageData.sysDivCd;
		},
		chkUseFg() {
			// 사용여부 선택 감지
			return this.pageData.useFg;
		},
		mySysDivCdList() {
			return this.pageData.sysDivCdList;
		},
		myUseFgList() {
			return this.pageData.useFgList;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkSysDivCd() {
			this.setPageData({ isFind: true });
		},
		chkUseFg() {
			this.setPageData({ isFind: true });
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	beforeDestroy() {
		this.chkOpenTabList({ key: 'destroy', prgmId: myPrgmId });
	},
	mounted() {
		this.init();
	},
	methods: {
		init() {
			this.gridInit();
		},
		gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 36;

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

			const sysCdList = this.mySysDivCdList;
			const _this = this;
			const myColumns = [
				{
					header: '시스템구분',
					name: 'sysDivCd',
					align: 'left',
					formatter({ value }) {
						let commCdNm = '';
						if (sysCdList.length > 0) {
							commCdNm = sysCdList.find(item => {
								if (item.commCd == value) {
									return item.commCdNm;
								}
							});
						} else {
							// 데이터에 따른 더미데이터
							switch (value) {
								case 'COMM':
									commCdNm = '공통관리';
									break;
								case 'CMMS':
									commCdNm = '설비관리';
									break;
								case 'EMS':
									commCdNm = '에너지관리';
									break;
								case 'GMS':
									commCdNm = '온실가스관리';
									break;
								case 'MDL':
									commCdNm = '온실가스관리';
									break;
							}
						}
						return commCdNm;
					},
				},
				{ header: '그룹코드', name: 'commGrpCd', align: 'left' },
				{ header: '그룹코드명', name: 'commGrpNm' },
				{
					header: '사용여부',
					name: 'useFg',
					align: 'left',
					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();
		},
		async search() {
			await this.getRowGridData();
			await this.setPageData({
				isFind: false,
			});
		},
		async getRowGridData() {
			this.loadGrid = false;
			const res = await this.postApiReturn({
				apiKey: 'selectCommGrpCd',
				resKey: 'commGrpCdData',
				sendParam: {
					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,
					sysDivCd: item.sysDiv,
					useFg: item.useFg === '1' ? true : false, // 화면 개발 편의를 위해 boolean 타입으로 교체, 저장시 "1", "0" 으로 바꿔 보내야 함
				};
				return newObj;
			});
			this.setGridData({
				gridKey: this.gridName,
				value: newRes,
			});
			this.loadGrid = true;
			this.$nextTick(() => {
				if (newRes.length > 0) {
					this.$refs[this.gridName].focus({
						//rowKey: 0,
						rowKey:
							this.pageData.rowGridSelectKey == '' ||
							this.pageData.rowGridSelectKey == null
								? 0
								: this.pageData.rowGridSelectKey ==
								  this.$refs[this.gridName].getData().length - 1
								? this.pageData.rowGridSelectKey
								: 0,
						columnName: 'sysDivCd',
						setScroll: true,
					});
				} else {
					this.detailDataInit();
				}
			});
		},
		async getRowData(data) {
			if (data.rowStat === 'I') {
				this.detailList[0].disabled = false;
			} else {
				this.detailList[0].disabled = true;
			}
			this.setPageData({
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: data,
			});

			const res = await this.postApiReturn({
				apiKey: 'selectCommCd',
				resKey: 'commCdData',
				sendParam: {
					commGrpCd: data.commGrpCd,
				},
			});
			const newRes = res.map(item => {
				const newObj = {
					...item,
					commCd: item.commCd || '',
					commCdNm: item.commCdNm || '',
					commCdAbbrnm: item.commCdAbbrnm || '',
					sortSeq: item.sortSeq || '',
					useFg: item.useFg || '',
					userDefVal1: item.userDefVal1 || '',
					userDefVal2: item.userDefVal2 || '',
					userDefVal3: item.userDefVal3 || '',
					rmrk: item.rmrk || '',
					rowStat: null,
				};
				return newObj;
			});

			this.setGridData({
				gridKey: 'rowDetailGrid',
				value: newRes,
			});
		},
		detailDataInit() {
			this.setPageData({
				rowGridSelectKey: null,
				rowGridSelectData: [],
			});
			this.setGridData({
				gridKey: 'rowDetailGrid',
				value: [],
			});
		},
		getSelectedRowStatInfo(data) {
			if (data) {
				var rowStat = data.rowStat;
				if (rowStat === 'I') {
					this.tab = 0;
					for (var i = 1; i < this.items.length; i++) {
						this.items[i].disabledFlag = true;
					}
				} else if (rowStat === 'U') {
					for (var i = 1; i < this.items.length; i++) {
						this.items[i].disabledFlag = false;
					}
				} else if (rowStat === 'D') {
					for (var i = 1; i < this.items.length; i++) {
						this.items[i].disabledFlag = false;
					}
				} else if (rowStat === null) {
					for (var i = 1; i < this.items.length; i++) {
						this.items[i].disabledFlag = false;
					}
				}
			}
		},
		async btnActions(action) {
			let dataArr = [];
			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':
					dataArr = this.$refs[this.gridName].save();
					var validCheck = true;
					dataArr.filter(item => {
						if (item.rowStat === 'I') {
							if (item.commGrpCd == '' || item.commGrpNm == '') {
								alert('필수 입력값을 입력해주세요.');
								validCheck = false;
							}
						} else if (item.rowStat === 'U') {
							if (item.commGrpNm == '') {
								alert('그룹코드명을 입력해주세요.');
								validCheck = false;
							}
						}
					});
					if (validCheck) {
						if (dataArr.length > 0) {
							const sendParam = {
								datas: {
									dsGrpCd: dataArr.map(item => ({
										...item,
										sysDiv: item.sysDivCd,
										useFg: item.useFg ? '1' : '0',
									})),
								},
								params: {},
							};
							await this.postUpdateApi({
								apiKey: 'saveCommGrpCd',
								sendParam: sendParam,
							});

							this.$nextTick(() => {
								this.$refs[this.gridName].gridInstance.invoke('refreshLayout');

								this.setPageData({ isFind: true });
							});
						} else {
							alert('저장할 내용이 없습니다.');
						}
					}
					break;

				default:
					break;
			}
		},
		gridEditingFinish(data) {
			this.$refs[this.gridName].editingFinish(data);
		},
	},
};

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

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

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

const myDetail = [
	{
		type: 'InputText',
		label: '그룹코드',
		valueNm: 'commGrpCd',
		disabled: true,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pr-2',
		required: true,
	},
	{
		type: 'InputText',
		label: '그룹코드명',
		valueNm: 'commGrpNm',
		disabled: false,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pl-2',
		required: true,
	},
	{
		type: 'SelectBox',
		label: '시스템구분',
		valueNm: 'sysDivCd',
		disabled: false,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pr-2 mt-3',
		list: 'sysDivCdList',
		itemText: 'commCdNm',
		itemValue: 'commCd',
		required: true,
	},
	{
		type: 'CheckBox',
		label: '사용여부',
		valueNm: 'useFg',
		disabled: false,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pl-2 mt-10',
		value: { '1': true, '0': false },
		required: true,
	},
	{
		type: 'InputText',
		label: '비고',
		valueNm: 'rmrk',
		disabled: false,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pr-2 mt-3',
	},
];
</script>
