<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="2.5">
							<InputText
								:parentPrgmId="myPrgmId"
								label="배치ID"
								valueNm="batchId"
								:searchOption="true"
								:iconShow="true"
								customClass="input-large"
							/>
						</v-col>
						<v-col :cols="2.5">
							<InputText
								:parentPrgmId="myPrgmId"
								label="배치명"
								valueNm="batchNm"
								:searchOption="true"
								:iconShow="true"
								customClass="input-large"
							/>
						</v-col>
						<v-col :cols="2.5">
							<component
								:is="'selectCodeList'"
								:parentPrgmId="myPrgmId"
								:label="'실행 결과'"
								:dataKey="'execRsltCd'"
								:sendParam="{ commGrpCd: 'CO_BATCH_EXEC_RSLT', useFg: '1' }"
								:addAll="true"
								:iconShow="true"
								customClass="select-large"
							/>
						</v-col>
						<v-col :cols="2.5">
							<component
								:is="'Datepicker'"
								:parentPrgmId="myPrgmId"
								:label="'조회기간'"
								:customClass="'input-large'"
							/>
						</v-col>
						<v-col :cols="2" class="text-right d-flex align-end justify-end ga-1" style="gap: 4px">
							<BtnSearch size="large" />
							<BtnExcelDownload :parentPrgmId="myPrgmId" :gridName="gridName" size="large" />
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>

		<v-row ref="contents">
			<!-- 배치 리스트 -->
			<v-col :cols="12" style="height:50%">
				<v-card class="pb-5 h100">
					<v-card-title>배치 리스트</v-card-title>
					<div class="h100" style="height:calc(100% - 70px)">
						<div ref="gridParent" class="px-5 h100">
							<component
								:ref="gridName"
								:is=" 'Grid' "
								:parentPrgmId="myPrgmId"
								:gridName="gridName"
								@getRowsData="getRowData"
								:dataPath="dataPathMock"
							/>
						</div>
					</div>
				</v-card>
			</v-col>
			<!-- 배치 상세 -->
			<v-col :cols="12" style="height:50%">
				<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>
					<div style="height:calc(100% - 50px)">
						<div ref="gridParent" class="px-5 h100">
							<component
								:is="'Form'"
								:parentPrgmId="myPrgmId"
								:detailList="detailList"
								@gridEditingFinish="gridEditingFinish"
							/>
						</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 Datepicker from '@/components/common/Datepicker';
import InputText from '@/components/common/input/InputText';
import TextArea from '@/components/common/form/TextArea';
import BtnSearch from '~/components/common/button/BtnSearch';
import BtnExcelDownload from '~/components/common/button/BtnExcelDownload';
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,
		Datepicker,
		InputText,
		TextArea,
		Form,
		Grid,
		BtnSearch,
		BtnExcelDownload,
		Buttons,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			loadGrid: true,
			gridName: 'rowGrid',
			// rowGridOrigin: [],
			detailList: myDetail,
			dataPathMock : {
				'rowGrid': {
					column: [
					{ header: 'No.', name: 'batchLogSeq', align: 'center', width: 100 },
					{ header: '배치ID', name: 'batchId', align: 'center', width: 100 },
					{ header: '배치명', name: 'batchNm', align: 'left', width: 150 },
					{ header: '실행 일자', name: 'execDt', align: 'center', width: 80 },
					{
						header: '실행 결과',
						name: 'execRsltCd',
						align: 'center',
						width: 80,
						// formatter({ value }) {
						// 	let retVal = '';
						// 	const newValue = _this.pageData.execRsltCdList.filter(
						// 		item => item.commCd == value,
						// 	);
						// 	if (newValue.length > 0) {
						// 		retVal = newValue[0].commCdNm;
						// 	}
						// 	return retVal;
						// },
					}, // "1": 프로그램, "2": 팝업
					{ header: '실행 로그', name: 'execLogCont', minWidth: 150 },
					{
						header: '배치 시작 일시',
						name: 'batchStrtDttm',
						align: 'center',
						width: 160,
					},
					{
						header: '배치 종료 일시',
						name: 'batchEndDttm',
						align: 'center',
						width: 160,
					},
					{ header: '등록자NO', name: 'regUserNo', width: 120 },
					{ header: '등록일시', name: 'regDttm', align: 'center', width: 160 },
					{ header: '수정자NO', name: 'procUserNo', width: 120 },
					{ header: '수정일시', name: 'procDttm', align: 'center', width: 160 },
					],
					data: dataMockExample,
					defaultRow: dataMockExample,
					option: {},
				},
			},
		};
	},
	computed: {
		// ...mapState({
		//   pageData: state => state.pageData[myPrgmId]
		// }),
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkExecRsltCd() {
			// 배치 실행 결과 선택 감지
			return this.pageData.execRsltCd;
		},
		chkRowGridSelectKey() {
			return this.pageData.rowGridSelectKey;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkExecRsltCd() {
			this.setPageData({ isFind: true });
		},
	},
	beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	mounted() {
		this.userComId = this.userInfo.comId;
		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();
			
			// _this.pageData = {
			// execRsltCdList: [
			// 	{ commCd: '1', commCdNm: '성공' },
			// 	{ commCd: '2', commCdNm: '실패' },
			// ],
			// };

		},
		// layoutInit() {
		//   const searchFilterHeight = this.$refs.searchFilter.offsetHeight;
		//   this.$refs.contents.style.height = `calc(100% - ${searchFilterHeight}px)`;
		// },
		gridInit() {
			this.loadGrid = false;
			const gridHeight = this.$refs.gridParent.offsetHeight - 30;

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

			const _this = this;
			const myColumns = [
				{ header: 'No.', name: 'batchLogSeq', align: 'center', width: 100 },
				{ header: '배치ID', name: 'batchId', align: 'center', width: 100 },
				{ header: '배치명', name: 'batchNm', align: 'left', width: 150 },
				{ header: '실행 일자', name: 'execDt', align: 'center', width: 80 },
				{
					header: '실행 결과',
					name: 'execRsltCd',
					align: 'center',
					width: 80,
					formatter({ value }) {
						let retVal = '';
						const newValue = _this.pageData.execRsltCdList.filter(
							item => item.commCd == value,
						);
						if (newValue.length > 0) {
							retVal = newValue[0].commCdNm;
						}
						return retVal;
					},
				}, // "1": 프로그램, "2": 팝업
				{ header: '실행 로그', name: 'execLogCont', minWidth: 150 },
				{
					header: '배치 시작 일시',
					name: 'batchStrtDttm',
					align: 'center',
					width: 160,
				},
				{
					header: '배치 종료 일시',
					name: 'batchEndDttm',
					align: 'center',
					width: 160,
				},
				{ header: '등록자NO', name: 'regUserNo', width: 120 },
				{ header: '등록일시', name: 'regDttm', align: 'center', width: 160 },
				{ header: '수정자NO', name: 'procUserNo', width: 120 },
				{ header: '수정일시', name: 'procDttm', align: 'center', width: 160 },
			];

			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: 'selectBatchLog',
				resKey: 'batchLogData',
				sendParam: {
					batchId: this.pageData.batchId, // 검색키워드: 배치ID
					batchNm: this.pageData.batchNm, // 검색키워드: 배치명
					execRsltCd: this.pageData.execRsltCd, //배치 실행 결과
					fromDt: this.pageData.fromDt,
				},
			});
			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: this.chkRowGridSelectKey || 0,
						//rowKey: 0,
						setScroll: true,
					});
				}
			});
		},
		// async getRowData(data) {
		async getRowData() {
			console.log("something")
			this.setPageData({
				// rowGridSelectKey: data.rowKey,
				rowGridSelectKey: 1,
				rowGridSelectData: fakeRowData,
			});
		},
		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) {
				default:
					break;
			}
		},
		xlsDataBind(res) {
			const xlsRowData = res.map(item => {
				const obj = {
					...item,
					useFg: item.useFg == '1' ? '사용' : '사용안함',
					execRsltCd: this.convExecRsltNm(item.execRsltCd),
				};
				return obj;
			});

			this.setPageData({
				xlsFileInfo: {
					[this.gridName]: {
						rowData: xlsRowData,
					},
				},
			});
		},
		convExecRsltNm(value) {
			let retVal = '';
			const newValue = this.pageData.execRsltCdList.filter(
				item => item.commCd == value,
			);
			if (newValue.length > 0) {
				retVal = newValue[0].commCdNm;
			}
			return retVal;
		},
	},
};

const dt = new Date();
const defaultData = {
	/* 검색옵션 */
	execRsltCd: false,
	execRsltCdList: [],
	batchId: '',
	batchNm: '',

	cmCycle: 'CYC_HOUR', // 주기

	defaultRange: {
		//CYC_DAY: 7
		CYC_HOUR: 0,
	},
	fromDt: Utility.setFormatDate(dt, 'YYYYMMDD'), // 조회일자

	isFind: false, // true 경우 조회, 조회버튼도 이 값으로 연동 예정

	/* data 세팅 */
	rowGrid: {
		data: [],
		column: [], // myColumns,
		option: {}, // myOptions
		defaultRow: {
			batchLogSeq: null,
			batchId: null,
			batchNm: null,
			execDt: null,
			execRsltCd: null,
			execLogCont: null,
			batchStrtDttm: null,
			batchEndDttm: null,
			regUserNo: null,
			regDttm: null,
			procUserNo: null,
			procDttm: null,
			rowStat: null,
		},
		buttonAuth: {
			excel: true,
		},
	},
	rowGridSelectKey: 0,
	rowGridSelectData: null,
	rowGridModify: false,

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

const dataMockExample = [
  {
    batchLogSeq: 1,
    batchId: 'BATCH001',
    batchNm: '일일 데이터 백업',
    execDt: '2025-07-15',
    execRsltCd: '1', // sẽ được formatter thành "성공" hoặc tương tự
    execLogCont: '백업 완료. 오류 없음.',
    batchStrtDttm: '2025-07-15 01:00:00',
    batchEndDttm: '2025-07-15 01:30:00',
    regUserNo: 'admin01',
    regDttm: '2025-07-15 01:00:00',
    procUserNo: 'admin02',
    procDttm: '2025-07-15 01:35:00',
  },
  {
    batchLogSeq: 2,
    batchId: 'BATCH002',
    batchNm: '월간 리포트 생성',
    execDt: '2025-07-01',
    execRsltCd: '2',
    execLogCont: '리포트 생성 중 오류 발생: 파일 접근 실패.',
    batchStrtDttm: '2025-07-01 03:00:00',
    batchEndDttm: '2025-07-01 03:10:00',
    regUserNo: 'reportUser',
    regDttm: '2025-07-01 03:00:00',
    procUserNo: 'admin03',
    procDttm: '2025-07-01 03:15:00',
  },
  {
    batchLogSeq: 3,
    batchId: 'BATCH003',
    batchNm: '사용자 통계 갱신',
    execDt: '2025-07-14',
    execRsltCd: '1',
    execLogCont: '통계 갱신 완료.',
    batchStrtDttm: '2025-07-14 23:00:00',
    batchEndDttm: '2025-07-14 23:20:00',
    regUserNo: 'statUser',
    regDttm: '2025-07-14 23:00:00',
    procUserNo: 'admin01',
    procDttm: '2025-07-14 23:25:00',
  },
];

const fakeRowData = {
  rowKey: 1,
  batchLogSeq: 1,
  batchId: 'BATCH001',
  batchNm: '일일 데이터 백업',
  execDt: '2025-07-15',
  execRsltCd: '1',
  execLogCont: JSON.stringify({
    session: {
      userNo: 'admin01',
      userNm: '관리자',
      comId: 'SKCC',
      locale: 'ko_KR',
    },
    batch: {
      comId: 'SKCC',
      totStdDt: '20230110',
    },
  }),
  batchStrtDttm: '2025-07-15 01:00:00',
  batchEndDttm: '2025-07-15 01:30:00',
  regUserNo: 'admin01',
  regDttm: '2025-07-15 01:00:00',
  procUserNo: 'admin02',
  procDttm: '2025-07-15 01:35:00',
};


const myDetail = [
	{
		type: 'TextArea',
		valueNm: 'execLogCont',
		readonly: true,
		cols: 12,
		class: 'py-2 transparent',
	},
];
</script>
