<template>
	<div>
		<div class="d-flex justify-space-between" >
			<v-card-title class="px-0 pt-0 custom-title-4">검침개소 TAG 연결 정보</v-card-title>
			<Buttons :parentPrgmId="parentPrgmId" :bindingData="gridName" :detailList="detailReadPlcTagList"
				:btnActionsFnc="btnActions" />
		</div>
		<div ref="gridParent" style="height: calc((100vh - 520px) /2);">
			<Grid
				:ref="gridName"
				:is="loadGrid ? 'Grid' : null"
				:gridName="gridName"
				:parentPrgmId="parentPrgmId"
				@getRowsData="getRowData"
				:innerTabGridInfo="innerTabGridInfo"
			/>
		</div>
		<div ref="formParent" style="height: calc((100vh - 400px) /2);">
			<component
				:is="'Form'"
				:parentPrgmId="parentPrgmId"
				:bindingData="gridName"
				:detailList="detailReadPlcTagList"
				@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 { CustomCheckbox } from '~/plugins/gridUtility';
import { CustomNumberEditor } from '~/plugins/gridUtility';
import Form from '~/components/common/form/Form';
import mixinGlobal from '@/mixin/global.js';
import Utility from '~/plugins/utility';
export default {
	mixins: [mixinGlobal],
	components: {
		Buttons,
		Grid,
		Form,
	},
	props: {
		parentPrgmId: {
			type: String,
			require: true,
		},
		innerTabGridInfo: {
			type: Object,
			default: null,
		},
	},
	data() {
		return {
			loadGrid: false,
			gridName: 'rowReadPlcTagRelGrid',
			detailReadPlcTagList: myReadPlcTagDetail,

		};
	},
	computed: {
		...mapState({
			pageData(state) {
				return state.pageData[this.parentPrgmId];
			},
		}),
		selectedCommCd() {
			return this.pageData[this.gridName].data;
		},
		myUseFgList() {
			return this.pageData.useFgList;
		},
		selectedComId() {
			return this.pageData.rowGridSelectData.comId;
		},
		selectedBlocId() {
			return this.pageData.rowGridSelectData.blocId;
		},
		selectedReadPlcId() {
			return this.pageData.rowGridSelectData.readPlcId;
		},
	},

	mounted() {
		this.init();
	},
	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.gridInit();
		},
		gridInit() {
			const gridHeight = this.$refs['gridParent'].offsetHeight - 36;

			const myOptions = {
				// bodyHeight: gridHeight,
				// minBodyHeight: gridHeight,
				header: {
					height: 37,
				},
				rowHeight: 37,
				minRowHeight: 29,
				selectionUnit: 'row',
				editingEvent: 'click',
				// columnOptions: {
				//   resizable: true,
				//   minWidth: 100
				// }
			};
			this.setGridOption({
				gridKey: this.gridName,
				// value: myOptions
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});

			const _this = this;
			let useFgSelectList = [];
			this.pageData.useFgList.forEach(item => {
				const it = { text: item.commCdNm, value: item.commCd };
				useFgSelectList.push(it);
			});
			let addInfoList = [];
			this.pageData.addInfoList.forEach(item => {
				const it = { text: item.addInfoNm, value: item.addInfoId };
				addInfoList.push(it);
			});
			let addInfoDataKindList = [];
			this.pageData.addInfoDataKindList.forEach(item => {
				const it = { text: item.commCdNm, value: item.commCd };
				addInfoDataKindList.push(it);
			});

			const myColumns = [
				{ header: '회사 ID', name: 'comId', hidden: true },
				{ header: '검침개소 번호', name: 'readPlcId', hidden: true },
				{ header: 'ERC NM', name: 'ercNm', align: 'center', hidden: true },
				{ header: 'TAG 명', name: 'tagNm', align: 'left' },
				{ header: 'TAG ID', name: 'tagId', align: 'center', hidden: true },
				{
					header: '에너지원',
					name: 'ercId',
					width: 100,
					formatter({ value }) {
						let retVal = '';
						const newValue = _this.pageData.ercNmList.filter(
							item => item.value == value,
						);
						if (newValue.length > 0) {
							retVal = newValue[0].text;
						}
						return retVal;
					},
				},
				{
					header: '분배율(1~100)',
					name: 'distRt',
					align: 'right',
					width: 100,
					// editor: {
					//   type: CustomNumberEditor,
					//   options: {
					//     min: 0,
					//     max: 100,
					//   }
					// }
				},
				{
					header: '대표 TAG 여부',
					name: 'reprTagFg',
					width: 100,
					// renderer: {
					//   type: CustomCheckbox,
					//   options: {
					//     onlyone: true,
					//     // disabled: true
					//   }
					// }
					formatter({ value }) {
						return value == '1' ? '예' : '아니오';
					},
				},
				{
					header: '사용여부',
					name: 'useFg',
					width: 100,
					formatter({ value }) {
						value = value === true ? '1' : '0';
						const newValue = _this.pageData.useFgList.filter(
							item => item.commCd == value,
						);
						return newValue[0].commCdNm;
					},
					// editor: {
					//   type: "select",
					//   options: {
					//     listItems: useFgSelectList
					//   }
					// }
				},
				{ header: '비고', name: 'rmrk', width: 100 },
				{ header: '등록 사용자', name: 'regUserNo', hidden: true },
				{ header: '등록 일자', name: 'regDttm', hidden: true },
				{ header: '수정 사용자', name: 'procUserNo', hidden: true },
				{ header: '수정 일자', name: 'procDttm', hidden: true },
			];

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

			this.loadGrid = true;
		},
		async getRowData(data, gridName) {
			if (data.rowStat === 'I') {
				this.detailReadPlcTagList[0].disabled = false;
				this.detailReadPlcTagList[1].disabled = false;
			} else {
				this.detailReadPlcTagList[0].disabled = true;
				this.detailReadPlcTagList[1].disabled = true;
			}
			this.setGridSelectData({
				gridKey: gridName,
				gridSelect: true,
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: Object.assign({}, data),
			});
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'add':
					const defaultRow = {
						tagId: '',
						tagNm: '',
						ercId: this.pageData.ercNmList[0].value,
						rmrk: null,
						distRt: '',
						reprTagFg: '1',
						useFg: true,
					};
					this.$refs[this.gridName].addRow(defaultRow);
					this.detailReadPlcTagList[0].disabled = false;
					this.detailReadPlcTagList[1].disabled = false;
					break;

				case 'remove':
					this.$refs[this.gridName].removeRow();
					this.detailReadPlcTagList[0].disabled = true;
					this.detailReadPlcTagList[1].disabled = true;
					break;

				case 'save':
					dataArr = this.$refs[this.gridName].save();
					// this.loadGrid = false;
					const newDataArr = dataArr.map(item => {
						const newData = {
							...item,
							comId: this.selectedComId,
							readPlcId: this.selectedReadPlcId,
						};
						newData.reprTagFg = newData.reprTagFg == true ? '1' : '0';
						newData.useFg = newData.useFg == true ? '1' : '0';
						return newData;
					});
					if (dataArr.length > 0) {
						var validCheck = true;
						dataArr.filter(item => {
							if (item.rowStat === 'I') {
								if (item.tagId == '' || item.distRt == '' || item.ercId == '') {
									alert('필수 입력값을 입력해주세요.');
									validCheck = false;
								}
							} else if (item.rowStat === 'U') {
								if (item.distRt == '' || item.ercId == '') {
									alert('필수 입력값을 입력해주세요.');
									validCheck = false;
								}
							}
						});

						if (validCheck) {
							const sendParam = {
								datas: {
									dsReadPlcTagRel: newDataArr,
								},
								params: {},
							};
							await this.postUpdateApi({
								apiKey: 'saveReadPlcTagRel',
								sendParam: sendParam,
							});
							// this.loadGrid = true;
							this.setPageData({ isFind: true });
						}
					} else {
						alert('저장할 내용이 없습니다.');
					}
					break;

				default:
					break;
			}
		},
		gridEditingFinish(data, bindingData) {
			this.$refs[this.gridName].editingFinish(data);
		},
		search() { },
	},
};

const myReadPlcTagDetail = [
	{
		type: 'EvtObjPop',
		labelContent: 'TAG',
		modalTitle: 'TAG 리스트',
		valueNm: 'tagId',
		valueNm2: 'tagNm',
		disabled: true,
		cols: 6,
		class: 'pr-4 pb-2 py-2 mt-2',
		required: true,
		labelCols: 12,
		textCols: 12,
		iconShow: true
	},

	{
		type: 'SelectBox',
		label: '에너지원',
		valueNm: 'ercId',
		disabled: false,
		cols: 6,
		class: 'pl-4 pb-2 py-3 mt-2',
		list: 'ercNmList',
		itemText: 'text',
		itemValue: 'value',
		required: true,
		labelCols: 12,
		textCols: 12,
		iconShow: true
	},
	{
		type: 'InputText',
		valueNm: 'tagNm',
		readonly: true,
		cols: 6,
		textCols: 12,
		class: 'pt-1 py-3 pr-4 mt-2',
		required: true,
	},
	{
		showValue: false,
	},
	{
		type: 'InputNumber',
		label: '분배율(1~100)',
		valueNm: 'distRt',
		disabled: false,
		cols: 6,
		class: 'py-3 pr-4 mt-2',
		inputType: 'number',
		min: 1,
		max: 100,
		required: true,
		labelCols: 12,
		textCols: 12,
		iconShow: true
	},
	{
		type: 'CheckBox',
		label: '대표 TAG 여부',
		valueNm: 'reprTagFg',
		disabled: false,
		cols: 6,
		class: 'py-3 pl-4 mt-2',
		value: { '1': true, '0': false },
		required: true,
		labelCols: 12,
		textCols: 12,
		iconShow: true
	},

	{
		type: 'CheckBox',
		label: '사용여부',
		valueNm: 'useFg',
		disabled: false,
		cols: 6,
		class: 'py-3 pr-4 mt-2',
		value: { '1': true, '0': false },
		required: true,
		labelCols: 12,
		textCols: 12,
		iconShow: true
	},
	{
		type: 'InputText',
		label: '비고',
		valueNm: 'rmrk',
		disabled: false,
		cols: 6,
		class: 'py-3 pl-4 mt-2',
		inputType: 'string',
		labelCols: 12,
		textCols: 12,
		iconShow: true
	},
];
</script>
