<template>
	<div ref="mainDiv" 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="useFg"
								:sendParam="{ commGrpCd: 'CO_USEFG', useFg: '1' }"
								:addAll="true"
							/>
						</v-col>
						<v-col :cols="3">
							<component
								:is="'SelectBox'"
								ref="SelectBox1"
								:propsValue="selectValue01"
								:itemList="selectValueList01"
								:label="'설비종류'"
								@update:propsValue="selectValue01 = $event"
							/>
						</v-col>
						<v-col :cols="3">
							<InputText
								:parentPrgmId="myPrgmId"
								label="설비 그룹 명"
								valueNm="eqpmGrpNm"
								:searchOption="true"
								:textCols="8"
								:labelCols="4"
							/>
						</v-col>
						<v-col :cols="3" class="text-right">
							<BtnSearch @click="search" />
						</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 class="d-flex justify-space-between align-end">
						<span class="tit ft-size_20 ft-weight_600">설비 그룹</span>
						<Buttons
							:parentPrgmId="myPrgmId"
							:bindingData="gridName"
							:btnActionsFnc="btnActions"
						/>
					</v-card-title>

					<div class="h100 px-5" style="height:calc(100% - 70px)">
						<div ref="gridParent" class="w100 h100">
							<component
								:ref="gridName"
								:is="loadGrid ? 'Grid' : null"
								:gridName="gridName"
								:parentPrgmId="myPrgmId"
								@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>
					<div class="px-5" style="height:calc(100% - 76px)">
						<component
							:is="'Form'"
							:parentPrgmId="myPrgmId"
							:detailList="detailList"
							@gridEditingFinish="gridEditingFinish"
						/>
					</div>
				</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 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 Grid from '~/components/common/Grid';
import Utility from '~/plugins/utility';
import SelectBox from '@/components/common/select/SelectBox';
let myTitle;
// const myPrgmId = "PRG0013";
let myPrgmId;

export default {
	mixins: [mixinGlobal, resize],
	async asyncData(context) {
		const myState = context.store.state;
		// context.store.commit("setActiveMenuInfo", myState.menuData[myPrgmId]);
		// myTitle = myState.activeMenuInfo.menuNm;
		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,
		Grid,
		Utility,
		SelectBox,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			gridName: 'rowGrid',
			loadGrid: false,
			tab: null,
			detailList: myDetail,
			selectValueList01: [],
			selectValue01: null,
		};
	},
	computed: {
		// ...mapState({
		//   pageData: state => state.pageData[myPrgmId]
		// }),
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkUseFg() {
			// 사용여부 선택 감지
			return this.pageData.useFg;
		},
		loadFlag() {
			var init1 = this.pageData.useFgList.length > 0 ? true : false;

			return init1;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkUseFg() {
			this.setPageData({ isFind: true });
		},
		loadFlag(val) {
			if (val) {
				this.gridInit();
			}
			// await this.gridInit();
		},
		selectValue01(val) {
			this.setPageData({ isFind: true });
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	created() {},
	mounted() {
		this.setSelectValueList01();
		// if (this.loadFlag) {
		// 	this.gridInit();
		// }
		// this.init();
	},
	beforeDestroy() {
		this.chkOpenTabList({ key: 'destroy', prgmId: myPrgmId });
	},
	methods: {
		...mapActions({}),
		init() {
			// this.gridInit();
		},
		async setSelectValueList01() {
			var res = await this.postApiReturn({
				apiKey: 'selectEmsEqpmKindList',
				resKey: 'eqpmGrpPysclQtyMngData',
				sendParam: {},
			});

			this.setPageData({
				eqpmKindIdList: res,
				eqpmKindId: res[0].eqpmKindId,
			});

			if (res.length > 0) {
				this.selectValueList01 = await res.map(item => {
					return {
						text: item.eqpmKindNm,
						value: item.eqpmKindId,
						data: {
							...item,
						},
					};
				});
				this.selectValueList01.unshift({
					text: '전체',
					value: '',
				});
				this.selectValue01 = this.selectValueList01[0].value;
			} else {
				this.selectValueList01 = [];
				this.selectValue01 = null;
			}
		},
		gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 70;

			const myOptions = {
				columnOptions: {
					resizable: true,
				},
			};
			this.setGridOption({
				gridKey: this.gridName,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});

			const _this = this;
			const myColumns = [
				{ header: '회사 ID', name: 'comId', hidden: true },
				{
					header: '설비 그룹 ID',
					name: 'eqpmGrpId',
					width: 150,
					align: 'left',
				},
				{
					header: '설비 그룹 명',
					name: 'eqpmGrpNm',
					minwidth: 210,
					align: 'left',
				},
				{
					header: '설비종류',
					name: 'eqpmKindId',
					minWidth: 175,
					align: 'left',
					formatter({ value }) {
						let retVal = '';
						const newValue = _this.pageData.eqpmKindIdList.filter(
							item => item.eqpmKindId == value,
						);
						if (newValue.length > 0) {
							retVal = newValue[0].eqpmKindNm;
						}
						return retVal;
					},
				},
				{
					header: '사용여부',
					name: 'useFg',
					width: 100,
					align: 'center',
					formatter({ value }) {
						value = value === true ? '1' : '0';
						const newValue = _this.pageData.useFgList.filter(
							item => item.commCd == value,
						);
						return newValue[0].commCdNm;
					},
				},
				{ 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.loadGrid = true;

			this.getRowGridData();
		},
		async search() {
			this.loadGrid = false;
			// if (this.loadFlag == false) {
			// 	return;
			// }
			await this.getRowGridData();
			await this.setPageData({
				isFind: false,
			});
		},
		async getRowGridData() {
			const res = await this.postApiReturn({
				apiKey: 'selectEqpmGrp',
				resKey: 'eqpmGrpData',
				sendParam: {
					comId: this.userInfo.comCd,
					useFg: this.pageData.useFg,
					eqpmGrpNmLike: this.pageData.eqpmGrpNm,
					eqpmKindId: this.selectValue01,
				},
			});
			const newRes = res.map(item => {
				const newObj = {
					...item,
					rowStat: null,
					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,
						setScroll: true,
					});
				}
			});
		},
		async getRowData(data) {
			this.setPageData({
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: data,
			});
		},

		gridEditingFinish(data) {
			this.$refs[this.gridName].editingFinish(data);
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'add':
					var defaultRow = {
						comId: '',
						eqpmGrpId: '',
						eqpmGrpNm: null,
						eqpmKindId: this.pageData.eqpmKindIdList[0].eqpmKindId,
						useFg: '1',
						rowStat: null,
					};
					this.$refs[this.gridName].addRow(defaultRow);
					break;

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

				case 'save':
					dataArr = this.$refs[this.gridName].save();
					if (dataArr.length > 0) {
						var validCheck = true;
						dataArr.map(item => {
							if (item.rowStat != 'D')
								for (var i = 0; i < dataArr.length; i++) {
									if (
										dataArr[i].eqpmGrpNm == null ||
										dataArr[i].eqpmGrpNm == ''
									) {
										validCheck = false;
										alert('필수 입력값을 입력해주세요');
										break;
									} else {
										validCheck = true;
										break;
									}
								}
						});

						if (validCheck) {
							const sendParam = {
								datas: {
									dsEqpmGrp: dataArr.map(item => ({
										...item,
										useFg: item.useFg == true ? '1' : '0',
									})),
								},
								params: {},
							};
							var result = await this.postUpdateApi({
								apiKey: 'saveEqpmGrp',
								sendParam: sendParam,
							});

							if (result.data.dataset && result.data.dataset.deleteYn != '') {
								alert(result.data.dataset.deleteYn);
							} else {
								this.$nextTick(() => {
									this.setPageData({ isFind: true });
								});
							}
						}
					} else {
						alert('저장할 내용이 없습니다.');
					}
					break;

				default:
					break;
			}
		},
	},
};

const defaultData = {
	/* 검색옵션 */
	eqpmGrpNm: '',
	useFg: '1',
	useFgList: [],
	eqpmKindIdList: [],
	eqpmKindId: '',

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

	isFind: false, // true 경우 조회, 조회버튼도 이 값으로 연동 예정
	/* data 세팅 */
	// 로컬 gridName 값과 동일한 이름으로 세팅
	rowGrid: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
		defaultRow: {
			comId: '',
			eqpmGrpId: '',
			eqpmGrpNm: null,
			eqpmKindId: '',
			useFg: '1',
			rowStat: null,
		},
		buttonAuth: {
			add: true,
			remove: true,
			save: true,
			excel: false,
		},
	},
};

const myDetail = [
	{
		type: 'InputText',
		label: '설비 그룹 ID',
		valueNm: 'eqpmGrpId',
		disabled: true,
		cols: 6,
		class: 'py-2',
		required: false,
		placeholder: '시스템 자동입력',
	},
	{
		type: 'InputText',
		label: '설비 그룹 명',
		valueNm: 'eqpmGrpNm',
		disabled: false,
		cols: 6,
		class: 'py-2',
		required: true,
	},
	{
		type: 'CheckBox',
		label: '사용 여부',
		valueNm: 'useFg',
		disabled: false,
		cols: 6,
		class: 'py-2',
		value: { '1': true, '0': false },
		required: true,
	},
	{
		type: 'SelectBox',
		label: '설비종류',
		valueNm: 'eqpmKindId',
		disabled: false,
		cols: 6,
		class: 'py-2',
		list: 'eqpmKindIdList',
		itemText: 'eqpmKindNm',
		itemValue: 'eqpmKindId',
		required: true,
	},
	{
		type: 'InputText',
		label: '등록자NO',
		valueNm: 'regUserNo',
		disabled: true,
		cols: 6,
		class: 'py-2',
		placeholder: '시스템 자동입력',
	},
	{
		type: 'InputText',
		label: '등록일시',
		valueNm: 'regDttm',
		disabled: true,
		cols: 6,
		class: 'py-2',
		placeholder: '시스템 자동입력',
	},
	{
		type: 'InputText',
		label: '수정자NO',
		valueNm: 'procUserNo',
		disabled: true,
		cols: 6,
		class: 'py-2',
		placeholder: '시스템 자동입력',
	},
	{
		type: 'InputText',
		label: '수정일시',
		valueNm: 'procDttm',
		disabled: true,
		cols: 6,
		class: 'py-2',
		placeholder: '시스템 자동입력',
	},
];
</script>
<style lang="scss">
@import '@/assets/scss/common.scss';
</style>
