<template>
	<div class="l-layout">
		<!-- 조회조견 -->
		<CommonPageTitle />
		<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"
								customClass="input-large"
							/>
						</v-col>
						<v-col :cols="2.5">
							<InputText
								:parentPrgmId="myPrgmId"
								label="배치명"
								valueNm="batchNm"
								:searchOption="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"
								customClass="select-large"
							/>
						</v-col>
						<v-col :cols="2.5">
							<component
								:is="'Datepicker'"
								:parentPrgmId="myPrgmId"
								:label="'조회기간'"
								customClass="datepicker-large"
							/>
						</v-col>
						<div class="text-right d-flex align-end justify-end pl-9" style="gap: 8px">
							<BtnSearch />
							<BtnExcelDownload :parentPrgmId="myPrgmId" :gridName="gridName" size="large" />
						</div>
					</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="loadGrid ? 'Grid' : null"
								:parentPrgmId="myPrgmId"
								:gridName="gridName"
								@getRowsData="getRowData"
							/>
						</div>
						<div class="d-flex align-center justify-center pa-5" v-if="loadGrid && totalCount > 0">
						<pagination id="pagination" :total-count="totalCount" :page-num="page" :limit="limit"
							@loadData="changeGrid" />
					</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';
import pagination from '~/components/common/Pagination';

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,
		pagination,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			loadGrid: false,
			gridName: 'rowGrid',
			// rowGridOrigin: [],
			detailList: myDetail,
			itemsPerPage: 10,
			itemsPerPageArray: [10, 20, 30],
			limit: 20,
			page: 1,
			totalCount: 0,
		};
	},
	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.page = 1;
				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();
		},
		layoutInit() {
		  this.$refs.contents.style.height = 'auto';
		},
		gridInit() {
			this.loadGrid = false;
			const gridHeight = this.$refs.gridParent.offsetHeight;

			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: 'right', width: 90 },
				{ header: '배치ID', name: 'batchId', align: 'right', width: 90 },
				{ header: '배치명', name: 'batchNm', align: 'left', width: 150 },
				{ header: '실행 일자', name: 'execDt', align: 'right', width: 70 },
				{
					header: '실행 결과',
					name: 'execRsltCd',
					align: 'left',
					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: 'left',
					width: 160,
				},
				{
					header: '배치 종료 일시',
					name: 'batchEndDttm',
					align: 'center',
					width: 160,
				},
				{ header: '등록자NO', name: 'regUserNo', width: 100 },
				{ header: '등록일시', name: 'regDttm', align: 'center', width: 160 },
				{ header: '수정자NO', name: 'procUserNo', width: 100 },
				{ 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() {
			this.loadGrid = false;
			// this.setGridData({
			// 	gridKey: this.gridName,
			// 	value: [],
			// });
			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,
					limit: this.limit,
					page: this.page,
					offset: (this.page - 1) * this.limit, // MariaDB Query에서 직접 계산이 안됨
				},
			});

			const res2 = await this.postApiReturn({
				apiKey: 'selectBatchLogPageTotal',
				resKey: 'batchLogPageTotal',
				sendParam: {
					batchId: this.pageData.batchId, // 검색키워드: 배치ID
					batchNm: this.pageData.batchNm, // 검색키워드: 배치명
					execRsltCd: this.pageData.execRsltCd, //배치 실행 결과
					fromDt: this.pageData.fromDt,
				},
			});
			this.totalCount = res2[0].totalcount;

			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(() => {
				this.loadGrid = true;
				if (newRes.length > 0) {
					this.$refs[this.gridName].focus({
						rowKey: this.chkRowGridSelectKey || 0,
						//rowKey: 0,
						setScroll: true,
					});
				}
			});
		},
		async getRowData(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) {
				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;
		},
		changeGrid: async function (pageNum, limit) {
			this.page = pageNum;
			this.limit = limit;

			this.search();
		},
	},
};

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 myDetail = [
	{
		type: 'TextArea',
		valueNm: 'execLogCont',
		readonly: true,
		cols: 12,
		class: 'py-2',
	},
];
</script>