<template>
	<div ref="mainDiv" class="l-layout">
		<v-row ref="searchFilter">
			<v-col :cols="12">
				<v-card class="searchFilter">
					<v-row >
						<v-col :cols="3">
							<component
								:is="'SelectAddGrp'"
								:parentPrgmId="myPrgmId"
								:label="'추가 정보 그룹'"
								dataKey="searchAddGrp"
								:sendParam="{ useFg: '1' }"
								:addAll="true"
								:iconShow="true"
								customClass="select-large"
							/>
						</v-col>
						<v-col :cols="3">
							<InputText
								:parentPrgmId="myPrgmId"
								label="추가 정보명"
								valueNm="addInfoNm"
								:searchOption="true"
								:iconShow="true"
								customClass="input-large"
							/>
						</v-col>
						<v-col :cols="3">
							<component
								:is="'selectCodeList'"
								:parentPrgmId="myPrgmId"
								:label="'사용여부'"
								dataKey="useFg"
								:sendParam="{ commGrpCd: 'CO_USEFG', useFg: '1' }"
								:addAll="true"
								:iconShow="true"
								customClass="select-large"
							/>
						</v-col>
						<v-col :cols="3" class="d-flex align-end justify-end text-right">
							<BtnSearch @click="search" size="large" />
						</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="px-5" style="height:calc(100% - 76px)">
						<div ref="gridParent" class="w100 h100">
							<component
								:ref="gridName"
								:is="loadGrid ? 'Grid' : null"
								:gridName="gridName"
								:parentPrgmId="myPrgmId"
								@getRowsData="getRowData"
								:dataPath="dataPathMock"
							/>
						</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 SelectAddGrp from '@/components/common/select/SelectAddGrp';
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 SelectUseFg from '@/components/common/select/SelectUseFg';
import selectCodeList from '@/components/common/select/selectCodeList';
let myTitle;
// const myPrgmId = "PRG0059";
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]);
		console.log('myState.menuData : ', myState.menuData);
		myTitle = await myState.activeMenuInfo.menuNm;
	},
	meta: {
		title: () => {
			return myTitle;
		},
		prgmId: myPrgmId,
		closable: true,
	},
	components: {
		BtnSearch,
		Buttons,
		SelectAddGrp,
		InputText,
		Form,
		Grid,
		SelectUseFg,
		selectCodeList,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			gridName: 'rowGrid',
			loadGrid: true,
			tab: null,
			detailList: myDetail,
			initedFlag: false,
			dataPathMock : {
				'rowGrid': {
					column: [
						{ header: '추가 정보 그룹', name: 'addGrpId', align: 'left' },
						{ header: '추가 정보 ID', name: 'addInfoId', align: 'left' },
						{ header: '추가 정보 명', name: 'addInfoNm', align: 'left' },
						{ header: 'Data 형식', name: 'addInfoDataKind', align: 'center' },
						{ header: '사용여부', name: 'useFg', align: 'center' },
					],
					data: dataMockExample,
					defaultRow: dataMockExample,
					option: {},
				},
			},
		};
	},
	computed: {
		// ...mapState({
		//   pageData: state => state.pageData[myPrgmId]
		// }),
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkAddGrp() {
			return this.pageData.searchAddGrp;
		},
		chkUseFg() {
			// 사용여부 선택 감지
			return this.pageData.useFg;
		},
		initFlag() {
			if (
				!this.initedFlag &&
				this.pageData.addInfoDataKindList &&
				this.pageData.blocMstrList &&
				this.pageData.useFgList &&
				this.pageData.addInfoDataKindList.length > 0 &&
				this.pageData.blocMstrList.length > 0 &&
				this.pageData.useFgList.length > 0
			) {
				return true;
			} else {
				return false;
			}
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkUseFg() {
			this.setPageData({ isFind: true });
		},
		chkAddGrp() {
			this.setPageData({ isFind: true });
		},
		initFlag(val) {
			if (val) {
				this.init();
				this.initedFlag = true;
			}
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	created() {
		/////////// 추가 정보 Tab 에서 사용
		// 데이터 유형 목록 조회
		this.getCodeList({
			dataKey: 'addInfoDataKind',
			params: { commGrpCd: 'CO_DATA_TYPE', useFg: '1' },
			addAll: false,
		});

		// 추가 정보 목록 조회
		this.getAddGrpInfoList({
			dataKey: 'addGrp',
			params: { useFg: '1' },
			addAll: false,
		});
	},
	mounted() {
		this.init();
	},
	beforeDestroy() {
		this.initedFlag = false;
		this.chkOpenTabList({ key: 'destroy', prgmId: myPrgmId });
	},
	methods: {
		...mapActions({
			getCodeList: 'modules/search/getCodeList',
			getAddGrpInfoList: 'modules/search/getAddGrpInfoList',
		}),
		async init() {
			await this.gridInit();
		},
		async gridInit() {
			// await this.getCodeList({
			//   dataKey: "addInfoDataKind",
			//   params: { commGrpCd: 'CO_DATA_TYPE', useFg: '1'},
			//   addAll: false
			// });

			// // 추가 정보 목록 조회
			// await this.getAddGrpInfoList({
			//   dataKey: "addGrp",
			//   params: { useFg: '1'},
			//   addAll: false
			// });

			const gridHeight = this.$refs.gridParent.offsetHeight - 30;

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

			const _this = this;
			const myColumns = [
				{
					header: '추가 정보 그룹',
					name: 'addGrpId',
					minWidth: 125,
					align: 'left',
					formatter({ value }) {
						let retVal = '';
						const newValue = _this.pageData.addGrpList.filter(
							item => item.addGrpId == value,
						);
						if (newValue.length > 0) {
							retVal = newValue[0].addGrpNm;
						}
						return retVal;
					},
				},
				{
					header: '추가 정보 ID',
					name: 'addInfoId',
					minWidth: 170,
					align: 'left',
				},
				{
					header: '추가 정보 명',
					name: 'addInfoNm',
					minWidth: 170,
					align: 'left',
				},
				{
					header: 'Data 형식',
					name: 'addInfoDataKind',
					minWidth: 85,
					align: 'center',
					formatter({ value }) {
						let retVal = '';
						const newValue = _this.pageData.addInfoDataKindList.filter(
							item => item.commCd == value,
						);
						console.log('newValue[데이터 형식] : ', newValue);
						if (newValue.length > 0) {
							retVal = newValue[0].commCdNm;
						}
						return retVal;
					},
				},
				{
					header: '사용여부',
					name: 'useFg',
					minWidth: 85,
					align: 'center',
					formatter({ value }) {
						let retVal = '';
						value = value === true ? '1' : '0';
						const newValue = _this.pageData.useFgList.filter(
							item => item.commCd == value,
						);
						console.log('newValue[사용여부] : ', newValue);
						if (newValue.length > 0) {
							retVal = newValue[0].commCdNm;
						}
						return retVal;
					},
				},
				{ 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.search();
		},
		async search() {
			//process
			this.loadGrid = true;
			await this.getRowGridData();
			await this.setPageData({
				isFind: false,
			});
		},
		async getRowGridData() {
			const res = await this.postApiReturn({
				apiKey: 'selectAddInfo',
				resKey: 'addInfoData',
				sendParam: {
					useFg: this.pageData.useFg,
					addGrpId: this.pageData.searchAddGrp,
					addInfoNmLike: this.pageData.addInfoNm,
				},
			});
			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) {
			if (data.rowStat === 'I') {
				this.detailList[0].disabled = false;
				this.detailList[1].disabled = false;
			} else {
				this.detailList[0].disabled = true;
				this.detailList[1].disabled = true;
			}

			this.setPageData({
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: data,
			});
		},

		gridEditingFinish(data) {
			this.$refs[this.gridName].editingFinish(data);
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'add':
					this.$refs[this.gridName].addRow();
					this.detailList[0].disabled = false;
					this.detailList[1].disabled = false;
					break;

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

				case 'save':
					dataArr = this.$refs[this.gridName].save();
					var validCheck = true;
					if (dataArr.length > 0) {
						dataArr.filter(item => {
							if (item.rowStat === 'I') {
								if (
									item.addGrpId == '' ||
									item.addInfoId == '' ||
									item.addInfoNm == '' ||
									item.addInfoDataKind == ''
								) {
									alert('필수 입력값을 입력해주세요.');
									validCheck = false;
								}
							} else if (item.rowStat === 'U') {
								if (item.addInfoNm == '') {
									alert('추가 정보 명을 입력해주세요');
									validCheck = false;
								}
							}
						});
						if (validCheck) {
							const sendParam = {
								datas: {
									dsAddInfo: dataArr.map(item => ({
										...item,
										addGrpId: item.addGrpId,
										useFg: item.useFg ? '1' : '0',
									})),
								},
								params: {},
							};
							await this.postUpdateApi({
								apiKey: 'saveAddInfo',
								sendParam: sendParam,
							});

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

				default:
					break;
			}
		},
	},
};

const defaultData = {
	/* 검색옵션 */
	addInfoNm: '',
	useFg: '1',
	useFgList: [],
	searchAddGrp: '',
	searchAddGrpList: [],
	addInfoDataKind: '',
	addInfoDataKindList: [],
	addGrp: '',
	addGrpList: [],

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

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

const myDetail = [
	{
		type: 'SelectBox',
		label: '추가 정보 그룹',
		valueNm: 'addGrpId',
		disabled: true,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pr-4',
		list: 'addGrpList',
		itemText: 'addGrpNm',
		itemValue: 'addGrpId',
		required: true,
	},
	{
		type: 'InputText',
		label: '추가정보 ID',
		valueNm: 'addInfoId',
		disabled: true,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pl-4',
		required: true,
	},
	{
		type: 'InputText',
		label: '추가 정보 명',
		valueNm: 'addInfoNm',
		disabled: false,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pr-4',
		required: true,
	},
	{
		type: 'SelectBox',
		label: 'Data 형식',
		valueNm: 'addInfoDataKind',
		disabled: false,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pl-4',
		list: 'addInfoDataKindList',
		itemText: 'commCdNm',
		itemValue: 'commCd',
		required: true,
	},
	{
		type: 'CheckBox',
		label: '사용 여부',
		valueNm: 'useFg',
		disabled: false,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pr-4',
		value: { '1': true, '0': false },
		required: true,
	},
	{
		type: 'InputText',
		label: '등록자NO',
		valueNm: 'regUserNo',
		disabled: true,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pl-4',
		placeholder: '시스템 자동입력',
	},
	{
		type: 'InputText',
		label: '등록일시',
		valueNm: 'regDttm',
		disabled: true,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pr-4',
		placeholder: '시스템 자동입력',
	},
	{
		type: 'InputText',
		label: '수정자NO',
		valueNm: 'procUserNo',
		disabled: true,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pl-4',
		placeholder: '시스템 자동입력',
	},
	{
		type: 'InputText',
		label: '수정일시',
		valueNm: 'procDttm',
		disabled: true,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pr-4',
		placeholder: '시스템 자동입력',
	},
];

const dataMockExample = [
  {
    addGrpId: 'GRP001',
    addInfoId: 'INFO001',
    addInfoNm: '온도 센서',
    addInfoDataKind: 'DATA01',
    useFg: true,
  },
  {
    addGrpId: 'GRP002',
    addInfoId: 'INFO002',
    addInfoNm: '압력 센서',
    addInfoDataKind: 'DATA02',
    useFg: false,
  },
  {
    addGrpId: 'GRP003',
    addInfoId: 'INFO003',
    addInfoNm: '압력 센서',
    addInfoDataKind: 'DATA03',
    useFg: false,
  },
  {
    addGrpId: 'GRP004',
    addInfoId: 'INFO004',
    addInfoNm: '압력 센서',
    addInfoDataKind: 'DATA04',
    useFg: false,
  },
  {
    addGrpId: 'GRP005',
    addInfoId: 'INFO005',
    addInfoNm: '압력 센서',
    addInfoDataKind: 'DATA05',
    useFg: false,
  },
];

</script>
