<template>
	<div class="l-layout">
		<v-row ref="searchFilter">
			<v-col :cols="12">
				<v-card class="searchFilter">
					<v-row align="center" no-gutters>
						<v-col :cols="2">
							<component
								:is="'SelectBlocMstr'"
								ref="SelectBlocMstr"
								:parentPrgmId="myPrgmId"
							/>
						</v-col>
						<v-col :cols="3">
							<component
								:is="'selectCodeList'"
								:parentPrgmId="myPrgmId"
								:label="'검침대상 유형'"
								dataKey="readObjKind"
								:addAll="true"
								:sendParam="{ commGrpCd: 'CM_MTTTP', useFg: '1' }"
							/>
						</v-col>
						<v-col :cols="4">
							<component
								:is="'RadioStandard'"
								:parentPrgmId="myPrgmId"
								label="기준"
								:labelCols="2"
								:textCols="10"
							/>
						</v-col>

						<v-col :cols="3" class="text-right">
							<BtnSearch @click="search" />
							<BtnExcelDownload
								style="vertical-align: middle;"
								class="d-inline-flex"
								:parentPrgmId="myPrgmId"
								:gridName="gridName"
							/>
						</v-col>
					</v-row>
					<v-row aling="center" no-gutters>
						<v-col :cols="4">
							<v-row class="search-box" align="center" no-gutters>
								<v-col :cols="2">
									<label for="" class="search-box-label">
										<v-icon x-small color="primary" class="mr-1"
											>mdi-record-circle</v-icon
										>
										검색어
									</label>
								</v-col>
								<v-col :cols="10">
									<v-text-field
										append-icon="mdi-magnify"
										class="v-input__custom"
										outlined
										:placeholder="placeholderValue"
										:hide-details="true"
										v-model="searchWord"
										@keyup.enter="typeEnterKey"
									></v-text-field>
								</v-col>
							</v-row>
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents">
			<v-col :cols="12">
				<v-card class="px-5 py-5">
					<div ref="gridParent" id="test2" style="height:100%;">
						<component
							class="w100 h100"
							ref="myGrid"
							:is="loadGrid ? 'Grid' : null"
							:gridName="gridName"
							:parentPrgmId="myPrgmId"
						/>
					</div>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import BtnSearch from '~/components/common/button/BtnSearch';
import BtnExcelDownload from '~/components/common/button/BtnExcelDownload';
import Grid from '~/components/common/Grid';
import mixinGlobal from '@/mixin/global.js';
import SelectBlocMstr from '@/components/common/select/SelectBlocMstr';
import Utility from '~/plugins/utility';
import RadioStandard from '~/components/common/RadioStandard';
import selectCodeList from '@/components/common/select/selectCodeList';

let myTitle;
// const myPrgmId = "PRG0054";
let myPrgmId;
export default {
	mixins: [mixinGlobal],

	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,
		SelectBlocMstr,
		RadioStandard,
		selectCodeList,
		Grid,
		BtnExcelDownload,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			loadGrid: false,
			gridName: 'rowGrid',
			myRowKey: 0,
			searchWord: '',
			apiKey: '',
			placeholderValue: '',
		};
	},
	computed: {
		...mapState({
			pageData: state => state.pageData[myPrgmId],
		}),
		chkIsFind() {
			return this.pageData.isFind;
		},
		chkBloc() {
			return this.pageData.blocId;
		},
		chkStandard() {
			return this.pageData.rdbStandard;
		},
		chkReadObjKind() {
			return this.pageData.readObjKind;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		chkBloc() {
			this.setPageData({ isFind: true });
		},
		chkStandard() {
			this.searchWord = '';
			this.setPageData({ isFind: true });
		},
		chkReadObjKind() {
			this.setPageData({ isFind: true });
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	created() {
		//공정 유형 조회
		this.getCodeList({
			dataKey: 'eccKind',
			params: { commGrpCd: 'EM_ECC_KIND', useFg: '1' },
			addAll: false,
		});

		//개소 종류 조회
		this.getCodeList({
			dataKey: 'plcKind',
			params: { commGrpCd: 'CM_CHKKIND', useFg: '1' },
			addAll: false,
		});

		//READ_DATA_TYPE 조회
		this.getCodeList({
			dataKey: 'readDataTypeCd',
			params: { commGrpCd: 'EM_READ_DATA_TYPE', useFg: '1' },
			addAll: false,
		});

		//사용여부 조회
		this.getCodeList({
			dataKey: 'eccFg',
			params: { commGrpCd: 'CO_USEFG', useFg: '1' },
			addAll: false,
		});
	},
	mounted() {},
	beforeDestroy() {
		this.chkOpenTabList({ key: 'destroy', prgmId: myPrgmId });
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setGridData: 'setGridData',
			setGridColumn: 'setGridColumn',
			setGridOption: 'setGridOption',
		}),
		...mapActions({
			getCodeList: 'modules/search/getCodeList',
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			chkOpenTabList: 'chkOpenTabList',
		}),
		async search() {
			await this.getRowGridData();
			await this.setPageData({
				isFind: false,
			});
		},
		typeEnterKey() {
			this.getRowGridData();
		},
		init() {
			this.layoutInit();
			this.gridInit();
			this.pageData.blocId = this.userInfo.blocId;
		},
		layoutInit() {
			const searchFilterHeight = this.$refs.searchFilter.offsetHeight;
			this.$refs.contents.style.height = `calc(100% - ${searchFilterHeight}px)`;
		},
		gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 30;

			const myOptions = {
				columnOptions: {
					resizable: true,
				},
				header: {
					height: 60,
					complexColumns: [
						{
							header: '태그',
							name: 'tagColumns',
							childNames: [
								'tagNm',
								'readDataTypeCd',
								'readObjNm',
								'mgnf',
								'distRt',
							],
						},
						{
							header: '검침개소',
							name: 'readPlcColumns',
							childNames: ['readPlcNm', 'plcKind', 'distRt2'],
						},
						{
							header: '공정',
							name: 'eccColumns',
							childNames: ['eccNm', 'eccKind', 'eccFg'],
						},
						{
							header: '설비',
							name: 'eqpmColumns',
							childNames: ['1', '2', '3'],
						},
					],
				},
			};

			this.setGridOption({
				gridKey: this.gridName,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});
			this.getRowGridData();
		},
		async getRowGridData() {
			this.loadGrid = false;
			const _this = this;
			let myColumns = [
				{
					header: '태그명',
					name: 'tagNm',
					align: 'left',
					width: 'auto',
				},
				{
					header: '타입',
					name: 'readDataTypeCd',
					align: 'center',
					formatter({ value }) {
						let retVal = '';
						const newVal = _this.pageData.readDataTypeCdList.filter(
							item => item.commCd == value,
						);
						if (newVal.length > 0) {
							retVal = newVal[0].commCdNm;
						}
						return retVal;
					},
				},
				{
					header: '검침대상',
					name: 'readObjNm',
					align: 'center',
				},
				{
					header: '배부율',
					name: 'mgnf',
					align: 'center',
				},
				{
					header: '매핑배율',
					name: 'distRt',
					align: 'center',
				},
				{
					header: '개소명',
					name: 'readPlcNm',
					align: 'left',
					width: 'auto',
				},
				{
					header: '개소유형',
					name: 'plcKind',
					align: 'center',
					formatter({ value }) {
						let retVal = '';
						const newVal = _this.pageData.plcKindList.filter(
							item => item.commCd == value,
						);
						if (newVal.length > 0) {
							retVal = newVal[0].commCdNm;
						}
						return retVal;
					},
				},
				{
					header: '매핑배율',
					name: 'distRt2',
					align: 'center',
				},
				{
					header: '공정명',
					name: 'eccNm',
					align: 'left',
					width: 'auto',
				},
				{
					header: '공정타입',
					name: 'eccKind',
					align: 'center',
					formatter({ value }) {
						let retVal = '';
						const newVal = _this.pageData.eccKindList.filter(
							item => item.commCd == value,
						);
						if (newVal.length > 0) {
							retVal = newVal[0].commCdNm;
						}
						return retVal;
					},
				},
				{
					header: 'ECC여부',
					name: 'eccFg',
					align: 'center',
					formatter({ value }) {
						let retVal = '';
						const newVal = _this.pageData.eccFgList.filter(
							item => item.commCd == value,
						);
						if (newVal.length > 0) {
							retVal = newVal[0].commCdNm;
						}
						return retVal;
					},
				},
			];

			var apiKeyMapper = {
				tag: 'selectStndInfoReadTag',
				readPlc: 'selectStndInfoReadReadPlc',
				ecc: 'selectStndInfoReadEcc',
				eqpm: 'selectStndInfoReadEqpm',
			};

			this.apiKey = apiKeyMapper[this.pageData.rdbStandard];
			let res = [];

			res = await this.postApiReturn({
				apiKey: this.apiKey,
				resKey: 'stndInfoReadData',
				sendParam: {
					search: this.searchWord,
					// blocId: this.pageData.blocId,
					blocId: this.pageData.blocMstrList[this.pageData.blocId].blocId,
					readObjKind: this.pageData.readObjKind,
				},
			});

			this.setGridColumn({
				gridKey: this.gridName,
				value: myColumns,
			});

			this.setGridData({
				gridKey: this.gridName,
				value: res,
			});

			let placeObj = {
				tag: '태그명 검색',
				readPlc: '검침개소명 검색',
				ecc: '공정명 검색',
				eqpm: '설비명 검색',
			};

			this.$nextTick(() => {
				this.placeholderValue = placeObj[this.pageData.rdbStandard];
			});

			this.loadGrid = true;

			this.setPageData({ isFind: false });
		},
	},
};

const defaultData = {
	/* 검색옵션 */
	isFind: false,
	blocId: '',
	blocMstrList: [],
	rdbStandard: 'tag',
	plcKind: '',
	plcKindList: [],
	eccKind: '',
	readObjKind: '',
	readObjKindList: [],
	eccFg: '',
	eccFgList: [],
	eccKindList: [],
	readDataTypeCd: '',
	readDataTypeCdList: [],
	rowGrid: {
		data: [],
		column: [],
		option: {},
		defaultRow: {},
	},
	xlsFileInfo: {
		// 출력하려는 grid 와 같은 이름으로 세팅
		rowGrid: {
			fileName: null, // 갑이 없으면 해당 페이지 메뉴명
			sheetName: null, //  갑이 없으면 'Sheet1'
		},
	},
};
</script>
<style lang="scss">
@import '@/assets/scss/common.scss';
</style>
