<template>
	<div>
		<div
			class="d-flex justify-space-between align-center"
			style="height: 50px;"
		>
			<span class="txt">태그 정보</span>
			<Buttons
				:parentPrgmId="parentPrgmId"
				:bindingData="gridName"
				:btnActionsFnc="btnActions"
			/>
		</div>
		<div ref="gridParent" style="height: calc(100vh - 760px);">
			<component
				:ref="gridName"
				:is="loadGrid ? 'Grid' : null"
				:gridName="gridName"
				:parentPrgmId="parentPrgmId"
				@getRowsData="getRowData"
				:innerTabGridInfo="innerTabGridInfo"
			/>
		</div>
		<div>
			<component
				:is="'Form'"
				:bindingData="gridName"
				:parentPrgmId="parentPrgmId"
				:detailList="detailList"
				@gridEditingFinish="gridEditingFinish"
			/>
		</div>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
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 mixinGlobal from '@/mixin/global.js';
export default {
	mixins: [mixinGlobal],
	components: {
		Buttons,
		Grid,
		Form,
		Utility,
	},
	props: {
		parentPrgmId: {
			type: String,
			require: true,
		},
		innerTabGridInfo: {
			type: Object,
			default: null,
		},
	},
	data() {
		return {
			loadGrid: false,
			gridName: 'rowTagInfoGrid',
			itemList: [],
			tagTpList: [],
			detailList: myDetail,
		};
	},
	computed: {
		...mapState({
			pageData(state) {
				return state.pageData[this.parentPrgmId];
			},
		}),
		selectedCommCd() {
			return this.pageData[this.gridName].data;
		},
		selectedComId() {
			return this.pageData.rowGridSelectData.comId;
		},
		selectedBlocId() {
			return this.pageData.rowGridSelectData.blocId;
		},
	},
	watch: {},
	created() {},
	mounted() {
		this.init();
	},
	methods: {
		...mapMutations({
			setPageData: 'setPageData',
			setGridData: 'setGridData',
			setGridColumn: 'setGridColumn',
			setGridOption: 'setGridOption',
			setGridSelectData: 'setGridSelectData',
		}),
		...mapActions({
			postApi: 'modules/list/postApi',
			postUpdateApi: 'modules/list/postUpdateApi',
			postApiReturn: 'modules/list/postApiReturn',
			setTree: 'modules/list/setTree',
			chkOpenTabList: 'chkOpenTabList',
			getCodeList: 'modules/search/getCodeList',
		}),
		init() {
			this.gridInit();
		},
		search() {},
		setEditorContent() {
			this.itemList = this.pageData.itemList.map(item => {
				return {
					text: item.commCdNm,
					value: item.commCd,
				};
			});
			this.tagTpList = this.pageData.tagTpList.map(item => {
				return {
					text: item.commCdNm,
					value: item.commCd,
				};
			});

			this.setPageData({});
		},
		gridInit() {
			this.setEditorContent();
			const gridHeight = this.$refs.gridParent.offsetHeight - 30;

			this.loadGrid = false;

			const myOptions = {
				columnOptions: {
					resizable: true,
				},
				bodyHeight: gridHeight,
				minBodyHeight: gridHeight,
				header: {
					height: 28,
				},
				rowHeight: 29,
				minRowHeight: 29,
				selectionUnit: 'row',
				editingEvent: 'click',
			};
			this.setGridOption({
				gridKey: this.gridName,
				value: myOptions,
			});

			const _this = this;
			let useFgSelectList = [];
			const myColumns = [
				{ header: '회사 ID', name: 'comId', hidden: true },
				{ header: '공정코드', name: 'eccId', hidden: true },
				{ header: '태그별칭', name: 'tagNm', width: 200, align: 'left' },
				{ header: '케이스ID', name: 'ucId', hidden: true },
				{ header: '태그ID', name: 'tagId', hidden: true },
				{
					header: '변수명-콤보',
					name: 'tagAlis',
					align: 'left',
					align: 'center',
				},
				{
					header: '검침대상',
					name: 'readObjId',
					align: 'center',
					hidden: true,
					formatter({ value }) {
						let retVal = '';
						const newValue = _this.pageData.energyList.filter(
							item => item.cd == value,
						);
						if (newValue.length > 0) {
							retVal = newValue[0].readObjNm;
						}
						return retVal;
					},
				},
				{
					header: '항목명',
					name: 'item',
					align: 'center',
					formatter({ value }) {
						const newValue = _this.pageData.itemList.filter(
							item => item.commCd == value,
						);
						return newValue[0].commCdNm;
					},
				},
				{
					header: '항목계산식',
					name: 'calcFrmlItem',
					align: 'left',
					align: 'center',
				},
				{
					header: '태그타입',
					name: 'tagTp',
					align: 'center',
					formatter({ value }) {
						const newValue = _this.pageData.tagTpList.filter(
							item => item.commCd == value,
						);
						return newValue[0].commCdNm;
					},
				},
				{ header: '디폴트값', name: 'dfltVal', align: 'center' },
				{
					header: '사용자세팅값',
					name: 'userVal',
					align: 'center',
					hidden: true,
				},
				{ header: '순번', name: 'seq', align: 'right' },
				{
					header: '사용여부',
					name: 'useFg',
					align: 'right',
					formatter({ value }) {
						value = value === true ? '1' : '0';
						const newValue = _this.pageData.useFgList.filter(
							item => item.commCd == value,
						);
						return newValue[0].commCdNm;
					},
				},
				{ header: '비고', name: 'rmrk', align: 'center', hidden: true },
				{ header: '등록 사용자', name: 'regUserNo', hidden: true },
				{ header: '등록 일자', name: 'regDttm', hidden: true },
				{ header: '수정 사용자', name: 'procUserNo', hidden: true },
				{ header: '수정 일자', name: 'procDttm', hidden: true },
				{ header: 'rowStat', name: 'rowStat', hidden: true },
			];

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

			this.loadGrid = true;
		},
		async getRowData(data, gridName) {
			if (data.tagTp == 'FIX_VAL') {
				this.detailList[2].showValue = false;
				this.detailList[3].showValue = true;
				this.detailList[4].showValue = true;
			} else if (data.tagTp == 'READ_VAL') {
				this.detailList[2].showValue = true;
				this.detailList[3].showValue = false;
				this.detailList[4].showValue = false;
			}
			this.setGridSelectData({
				gridKey: gridName,
				gridSelect: true,
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: Object.assign({}, data),
			});
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'add':
					const defaultRow = {
						comId: '',
						tagId: '',
						tagNm: '',
						calcFrml: this.pageData.calcFrml,
						calcFrmlTxt: this.pageData.calcFrmlTxt,
						tagAlis: 'A',
						item: 'ENRG_USE_QTY',
						calcFrmlItem: '',
						tagTp: 'READ_VAL',
						ucId: this.pageData.ucId,
					};
					this.$refs[this.gridName].addRow(defaultRow);
					break;

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

				case 'save':
					this.loadGrid = false;
					dataArr = this.$refs[this.gridName].save();
					if (dataArr.length > 0) {
						var validCheck = true;
						// console.log('dataArr : ', dataArr);
						dataArr.forEach(item => {
							if (
								item.tagId == '' ||
								item.tagId == null ||
								item.tagNm == '' ||
								item.tagNm == null ||
								item.tagAlis == '' ||
								item.tagAlis == null ||
								item.tagTp == '' ||
								item.tagTp == null ||
								item.item == '' ||
								item.item == null ||
								item.dfltVal == '' ||
								item.dfltVal == null ||
								item.seq == '' ||
								item.seq == null
							) {
								validCheck = false;
								alert('필수 입력값을 입력해주세요');
								// this.setPageData({ isFind: true });
								this.loadGrid = true;
							}
						});
						// dataArr.forEach(item =>{
						//   if(item.tagTp == 'FIX_VAL'){
						//     console.log('11');
						//     item.tagId = item.tagNm;
						//   }
						// });

						if (validCheck) {
							const sendParam = {
								datas: {
									dsOnlnBasicTagInfoData: dataArr.map(item => ({
										...item,
										useFg: item.useFg === true ? '1' : '0',
										eccId: this.pageData.rowGrid.rowGridSelectData.eccId,
										readObjId: this.pageData.rowGrid.rowGridSelectData
											.readObjId,
									})),
								},
								params: {},
							};
							await this.postUpdateApi({
								apiKey: 'saveOnlnBasicUnitTagInfoMng',
								sendParam: sendParam,
							});
							this.setPageData({ isFind: true });
							this.loadGrid = true;
						}
					} else {
						alert('저장할 내용이 없습니다.');
					}
					break;

				default:
					break;
			}
		},
		gridEditingFinish(data) {
			// console.log('data : ', data);
			// console.log("data.columnName == 'tagTp' : ", data.columnName == 'tagTp');
			// console.log("data.value == 'FIX_VAL' : ", data.value == 'FIX_VAL');
			// console.log("data.value == 'READ_VAL' : ", data.value == 'READ_VAL');
			// console.log("data.columnName == 'tagTp' && data.value == 'FIX_VAL' : ", (data.columnName == 'tagTP' && data.value == 'FIX_VAL'));
			// console.log("(data.columnName == 'tagTp' && data.value == 'READ_VAL') : ", (data.columnName == 'tagTP' && data.value == 'READ_VAL'));
			if (data.columnName == 'tagTp' && data.value == 'FIX_VAL') {
				// console.log('if case 1 ...');
				this.detailList[2].showValue = false;
				this.detailList[3].showValue = true;
				this.detailList[4].showValue = true;
				// }else{
			} else if (data.columnName == 'tagTp' && data.value == 'READ_VAL') {
				// console.log('if case 2 ...');
				this.detailList[2].showValue = true;
				this.detailList[3].showValue = false;
				this.detailList[4].showValue = false;
			}
			if (!this.detailList[2].showValue && data.columnName == 'tagId') {
				data = {
					columnName: 'tagNm',
					value: data.value,
				};
			}
			this.$refs[this.gridName].editingFinish(data);
		},
	},
};

const myDetail = [
	{
		type: 'InputText',
		label: '계산식(명칭)',
		valueNm: 'calcFrmlTxt',
		disabled: true,
		cols: 12,
		labelCols: 2,
		textCols: 5,
		class: 'py-2',
		required: true,
	},
	{
		type: 'InputText',
		label: '계산식(변수)',
		valueNm: 'calcFrml',
		disabled: true,
		cols: 12,
		labelCols: 2,
		textCols: 5,
		class: 'py-2',
		required: true,
	},
	{
		type: 'InputText',
		label: '태그',
		valueNm: 'tagId',
		disabled: false,
		cols: 12,
		labelCols: 2,
		textCols: 5,
		class: 'py-2',
		required: true,
		showValue: true,
	},
	{
		type: 'OnlnBasicUnitAddInfoPop',
		labelContent: '태그',
		modalTitle: 'TAG 리스트',
		valueNm: 'tagId',
		valueNm2: 'tagNm',
		disabled: true,
		cols: 6,
		class: 'py-2',
		required: true,
		showValue: false,
	},
	{
		type: 'InputText',
		label: '태그별칭',
		valueNm: 'tagNm',
		disabled: false,
		cols: 6,
		labelCols: 2,
		textCols: 5,
		class: 'py-2',
		required: true,
		showValue: false,
	},
	{
		type: 'SelectBox',
		label: '태그타입',
		disabled: false,
		cols: 6,
		class: 'py-2',
		list: 'tagTpList',
		valueNm: 'tagTp',
		itemText: 'commCdNm',
		itemValue: 'commCd',
		required: true,
	},
	{
		type: 'InputText',
		label: '디폴트값',
		valueNm: 'dfltVal',
		readonly: false,
		cols: 6,
		class: 'py-2',
		required: true,
	},
	{
		type: 'InputText',
		label: '순번',
		valueNm: 'seq',
		readonly: false,
		cols: 6,
		class: 'py-2',
		required: true,
	},
	{
		type: 'SelectBox',
		label: '항목명',
		disabled: false,
		cols: 6,
		class: 'py-2',
		list: 'itemList',
		valueNm: 'item',
		itemText: 'commCdNm',
		itemValue: 'commCd',
		required: true,
	},
	{
		type: 'InputText',
		label: '항목계산식',
		disabled: false,
		readonly: false,
		cols: 6,
		class: 'py-2',
		valueNm: 'calcFrmlItem',
		required: true,
	},
	{
		type: 'CheckBox',
		label: '사용 여부',
		valueNm: 'useFg',
		disabled: false,
		cols: 6,
		class: 'py-2',
		value: { '1': true, '0': false },
		required: true,
	},
];
</script>
