<template>
	<div class="l-layout">
		<!-- 조회조견 -->
		<v-row ref="searchFilter">
			<v-col :cols="12">
				<v-card class="searchFilter">
					<v-row align="end" no-gutters>
						<v-col :cols="3">
							<component
								:is="'selectCodeList'"
								:parentPrgmId="myPrgmId"
								:label="'사용여부'"
								:dataKey="'selectUseFg'"
								:sendParam="{ commGrpCd: 'CO_USEFG', useFg: '1' }"
								:addAll="true"
								customClass="select-large"
							/>
						</v-col>
						<v-col :cols="4">
							<InputText
								:parentPrgmId="myPrgmId"
								label="프로그램명"
								valueNm="prgmNm"
								:searchOption="true"
								:labelCols="12"
								:textCols="12"
								customClass="input-large"
							/>
						</v-col>
						<v-col :cols="5" class="text-right">
							<BtnSearch 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">
					<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 style="min-height:calc(100% - 70px)">
						<div ref="gridParent" class="px-5 h100">
							<component
								:ref="gridName"
								:is="loadGrid ? 'Grid' : null"
								:parentPrgmId="myPrgmId"
								:gridName="gridName"
								@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="min-height:calc(100% - 76px)">
						<component
							:is="'Form'"
							:parentPrgmId="myPrgmId"
							:bindingData="gridName"
							:detailList="detailList"
							@gridEditingFinish="gridEditingFinish"
						/>
						<!-- <div class="w100">
						</div> -->
					</div>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import mixinGlobal from '@/mixin/global.js';
import { resize } from '@/mixin/resize.js';
// import { mapState, mapMutations, mapActions } from "vuex";
import selectCodeList from '@/components/common/select/selectCodeList';
import InputText from '@/components/common/input/InputText';
import BtnSearch from '~/components/common/button/BtnSearch';
import Buttons from '~/components/common/button/Buttons';
import Grid from '~/components/common/Grid';
import Form from '~/components/common/form/Form';
import Utility from '~/plugins/utility';

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: {
		selectCodeList,
		Form,
		Grid,
		BtnSearch,
		Buttons,
		InputText,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			loadGrid: false,
			gridName: 'rowGrid',
			// rowGridOrigin: [],
			detailList: myDetail,

			dataPathMock: {
        'rowGrid': {
          column: [
            { header: '프로그램ID', name: 'field1', align: 'left' },
            { header: '프로그램덤', name: 'field2', align: 'left' },
            { header: '타임', name: 'field3', align: 'left' },
            { header: '사용여부', name: 'field4', align: 'left' }
          ],
          data: dataPathDataExample,
          defaultRow: dataPathDataExample,
          option: {
						scrollY: false,
						scrollX: false,
					}
        }
      },
		};
	},
	computed: {
		// ...mapState({
		//   pageData: state => state.pageData[myPrgmId]
		// }),
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkUseFg() {
			// 사용여부 선택 감지
			return this.pageData.selectUseFg;
		},
		chkRowGridSelectKey() {
			return this.pageData.rowGridSelectKey;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkUseFg() {
			this.setPageData({ isFind: true });
		},
	},
	beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
		// console.log("3.vue::beforeCreate");
	},
	mounted() {
		this.init();
	},
	// mounted() {
	//   this.init();
	// },
	// beforeDestroy() {
	//   this.chkOpenTabList({ key: "destroy", prgmId: myPrgmId });
	//   // console.log(myPrgmId, " ,  3.vue::beforeDestroy");
	// },
	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 - 36;

			const myOptions = {
				scrollX: false,
			};
			// console.log("this.pageData", this.pageData)
			const _this = this;
			const myColumns = [
				{ header: '프로그램ID', name: 'prgmId', align: 'center' },
				{ header: '프로그램명', name: 'prgmNm' },
				{
					header: '타입',
					name: 'prgmTpCd',
					align: 'center',
					formatter({ value }) {
						return value ? (value === '1' ? '프로그램' : '팝업') : null;
					},
				}, // "1": 프로그램, "2": 팝업
				{
					header: '사용여부',
					name: 'useFg',
					align: 'center',
					formatter({ value }) {
						value = value === true ? '1' : '0';
						const newValue = _this.pageData.selectUseFgList.filter(
							item => item.commCd == value,
						);
						return newValue[0].commCdNm;
					},
				}, // "1": 사용, "0": 사용안함,
				{ header: '프로그램URL', name: 'url', hidden: true },
				{ header: '등록자NO', name: 'regUserNo', hidden: true },
				{ header: '등록일시', name: 'regDttm', hidden: true },
				{ header: '수정자NO', name: 'procUserNo', hidden: true },
				{ header: '수정일시', name: 'procDttm', hidden: true },
			];
			this.setGridOption({
				gridKey: this.gridName,
				// value: myOptions
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});
			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: 'selectPrgm',
				resKey: 'prgmData',
				sendParam: {
					useFg: this.chkUseFg,
					prgmNm: this.pageData.prgmNm, // 검색키워드: 프로그램명
				},
			});
			const newRes = res.map(item => {
				const newObj = {
					...item,
					rowStat: null,
					useFg: item.useFg === '1' ? true : false, // 화면 개발 편의를 위해 boolean 타입으로 교체, 저장시 "1", "0" 으로 바꿔 보내야 함
				};
				return newObj;
			});

			// 엑셀 다운로드용 데이터 재정렬
			this.xlsDataBind(res);
			// this.rowGridOrigin = Utility.copyObj(newRes);
			this.setGridData({
				gridKey: this.gridName,
				value: newRes,
			});

			this.$nextTick(() => {
				if (newRes.length > 0) {
					this.$refs[this.gridName].focus({
						//rowKey: 0,
						//rowKey: this.chkRowGridSelectKey || 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, gridName) {
			this.setGridSelectData({
				gridKey: gridName,
				gridSelect: true,
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: data,
			});

			this.setPageData({
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: data,
			});
		},
		compareData(type, newDt) {
			if (this.selectedCommCdData[type] == newDt) {
				return true;
			} else {
				return false;
			}
		},
		gridEditingFinish(data) {
			this.$refs[this.gridName].editingFinish(data);
		},
		async btnActions(action) {
			switch (action) {
				case 'add':
					this.$refs[this.gridName].addRow();
					break;

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

				case 'save':
					var dataArr = this.$refs[this.gridName].save();
					if (dataArr.length > 0) {
						const sendParam = {
							datas: {
								dsPrgm: dataArr.map(item => ({
									...item,
									useFg: item.useFg ? '1' : '0',
								})),
							},
							params: {},
						};
						for (var i = 0; i < sendParam.datas.dsPrgm.length; i++) {
							var prgmChk = sendParam.datas.dsPrgm[i].prgmNm;
						}
						if (prgmChk == null || prgmChk == undefined || prgmChk == '') {
							alert('프로그램명을 입력하세요.');
						} else {
							await this.postUpdateApi({
								apiKey: 'savePrgm',
								sendParam: sendParam,
							});
							this.setPageData({ isFind: true });
						}
					} else {
						alert('저장할 내용이 없습니다.');
					}
					break;

				default:
					break;
			}
		},
		xlsDataBind(res) {
			const xlsRowData = res.map(item => {
				const obj = {
					...item,
					useFg: item.useFg == '1' ? '사용' : '사용안함',
					prgmTpCd: item.prgmTpCd == '1' ? '프로그램' : '팝업',
				};
				return obj;
			});
			this.setPageData({
				xlsFileInfo: {
					[this.gridName]: {
						rowData: xlsRowData,
					},
				},
			});
		},
	},
};

const defaultData = {
	selectUseFg: false,
	selectUseFgList: [],

	prgmNm: '',

	/* 검색옵션 */
	isFind: false,

	/* data 세팅 */
	rowGrid: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
		defaultRow: {
			prgmId: null,
			prgmNm: null,
			prgmTpCd: '1',
			useFg: true,
			url: null,
			regUserNo: null,
			regDttm: null,
			procUserNo: null,
			procDttm: null,
			rowStat: null,
		},
		rowGridSelectKey: 0,
		rowGridSelectData: null,
		rowGridModify: false,
		buttonAuth: {
			add: true,
			remove: true,
			save: true,
			excel: true,
		},
	},
	rowGridSelectKey: 0,
	rowGridSelectData: null,
	rowGridModify: false,

	xlsFileInfo: {
		// 출력하려는 grid 와 같은 이름으로 세팅
		rowGrid: {
			rowData: [],
			// 엑셀변환시 데이타 가공이 추가로 필요하게 된다면 여기에 가공된 rowData 를 넣어야 할듯
			fileName: null, // 갑이 없으면 해당 페이지 메뉴명
			sheetName: null, //  갑이 없으면 'Sheet1'
		},
	},
};
// console.log("this.pageData",this.pageData)

const myDetail = [
	{
		type: 'InputText',
		label: '프로그램ID',
		valueNm: 'prgmId',
		readonly: true,
		cols: 6,
		class: 'py-2',
		required: false,
		placeholder: '시스템 자동입력',
		textCols: 12,
		iconShow: true
	},
	{
		type: 'InputText',
		label: '프로그램명',
		valueNm: 'prgmNm',
		cols: 6,
		class: 'py-2',
		required: true,
		textCols: 12,
		iconShow: true
	},
	{
		type: 'SelectBox',
		label: '프로그램구분',
		valueNm: 'prgmTpCd',
		essential: true,
		cols: 6,
		class: 'py-2',
		list: [
			{ text: '프로그램', value: '1' },
			{ text: '팝업', value: '2' },
		],
		textCols: 12,
		iconShow: true
	},
	{
		type: 'CheckBox',
		label: '사용여부',
		valueNm: 'useFg',
		essential: true,
		disabled: false,
		cols: 6,
		class: 'py-2',
		value: { '1': true, '0': false },
		required: true,
		textCols: 12,
		iconShow: true
	},
	{
		type: 'InputText',
		label: '프로그램URL',
		valueNm: 'url',
		disabled: false,
		cols: 12,
		class: 'py-2',
		required: true,
		textCols: 12,
		iconShow: true
	},
	{
		type: 'InputText',
		label: '등록자NO',
		valueNm: 'regUserNo',
		disabled: true,
		cols: 6,
		class: 'py-2',
		placeholder: '시스템 자동입력',
		textCols: 12,
		iconShow: true
	},
	{
		type: 'InputText',
		label: '등록일시',
		valueNm: 'regDttm',
		disabled: true,
		cols: 6,
		class: 'py-2',
		placeholder: '시스템 자동입력',
		textCols: 12,
		iconShow: true
	},
	{
		type: 'InputText',
		label: '수정자NO',
		valueNm: 'procUserNo',
		disabled: true,
		cols: 6,
		class: 'py-2',
		placeholder: '시스템 자동입력',
		textCols: 12,
		iconShow: true
	},
	{
		type: 'InputText',
		label: '수정일시',
		valueNm: 'procDttm',
		disabled: true,
		cols: 6,
		class: 'py-2',
		placeholder: '시스템 자동입력',
		textCols: 12,
		iconShow: true
	},
];


import { getPathDataExample } from '@/const/const'
const dataPathDataExample = getPathDataExample({
  field1: 'PRG0001',
  field2: '대시보드',
  field3: '프로그램', 
	field4: '사용'
});
</script>
