<template>
	<div>
		<div class="d-flex justify-space-between align-center mb-5" >
			<v-card-title class="txt custom-title-4 pa-0">
				설비 추가 정보
			</v-card-title>
			<Buttons
				:parentPrgmId="parentPrgmId"
				:bindingData="gridName"
				:btnActionsFnc="btnActions"
			/>
		</div>
		<div ref="gridParent" class="w100" style="height: calc(100vh - 520px);">
			<Grid
				:ref="gridName"
				:is="loadGrid ? 'Grid' : null"
				:gridName="gridName"
				:parentPrgmId="parentPrgmId"
				:editorGrid="true"
				:innerTabGridInfo="innerTabGridInfo"
				@getRowsData="getRowData"
			/>
		</div>
	</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import Buttons from '~/components/common/button/Buttons';
import Grid from '~/components/common/Grid';
import InputText from '~/components/common/input/InputText';
import Form from '~/components/common/form/Form';
import mixinGlobal from '@/mixin/global.js';
export default {
	mixins: [mixinGlobal],
	components: {
		Buttons,
		Grid,
		InputText,
		Form,
	},
	props: {
		parentPrgmId: {
			type: String,
			require: true,
		},
		innerTabGridInfo: {
			type: Object,
			default: null,
		},
	},
	data() {
		return {
			loadGrid: false,
			gridName: 'rowDetailGrid',
			rowKey: null,
			edtingFinishFlag: 'Y',
			dataPathMock: {
        'rowDetailGrid' : {
          column: [
            { header: '추가 정보', name: 'id', headerAlign: 'left', align: 'left', },
            { header: 'Data 구분', name: 'lable', headerAlign: 'left', align: 'left' },
            { header: '추가 정보 값', name: 'type', headerAlign: 'left', align: 'right' },
            // { header: '비고', name: 'note', headerAlign: 'left' }
          ],
          data: dataPathDataExample,
          defaultRow: dataPathDataExample,
          option: {}
        }
      },

		};
	},
	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;
		},
		selectedEqpmId() {
			return this.pageData.rowGridSelectData.eqpmId;
		},
	},
	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 - 30;

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

			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);
			});

			class CustomRenderer {
				constructor(props) {
					//const { min, max } = props.columnInfo.renderer.options;
					//console.log('props: %o', props);

					const el = document.createElement('input');
					if (
						props.grid.store.data.rawData[props.rowKey].addInfoDataKind == 'FG'
					) {
						el.type = 'checkbox';
					} else {
						el.type = 'text';
						$(el).addClass('tui-grid-cell-content');
						$(el).css('text-align', 'center');
					}
					// el.min = String(min);
					//el.max = String(max);
					//el.disabled = true;
					this.el = el;
					this.render(props);
				}

				getElement() {
					return this.el;
				}

				render(props) {
					if (this.el.type == 'checkbox') {
						if (props.value == 1) {
							this.el.checked = true;
						} else {
							this.el.checked = false;
						}
					}
					this.el.value = props.value;
				}
			}

			class CustomEditor {
				constructor(props) {
					const el = document.createElement('input');
					if (
						props.grid.store.data.rawData[props.rowKey].addInfoDataKind == 'FG'
					) {
						el.type = 'checkbox';
						if (props.value == 1) {
							el.checked = true;
						} else {
							el.checked = false;
						}
						el.addEventListener('change', this.change);
					} else {
						el.type = 'text';
						if (props.formattedValue == 'NUM') {
							el.oninput = function(event) {
								var regExp=/[^0-9]/g;
                if(event.data != null){
                  if(event.data.match(regExp)){
                    event.target.value = event.target.value.replace(regExp, '');
								  }
                }
							};
						}
						$(el).addClass('tui-grid-content-text');
					}
					this.el = el;

					this.render(props);
				}

				change(ev) {
					//console.log('props: %o', ev);
					if (ev.target.checked) {
						ev.target.value = 1;
					} else {
						ev.target.value = 0;
					}
				}

				getElement() {
					return this.el;
				}

				getValue() {
					return this.el.value;
				}

				render(props) {
					if (this.el.type == 'checked') {
						this.el.value = props.value;
					} else {
						this.el.value = String(props.value);
						// this.el.value = '';
					}
					//console.log('props: %o', props);
				}

				mounted() {
					if (this.el.type == 'checkbox') {
						$(this.el.parentElement).css('text-align', 'center');
					}
					this.el.select();
				}
			}

			const myColumns = [
				{ header: '회사 ID', name: 'comId', hidden: true },
				{ header: '설비 번호', name: 'eqpmId', hidden: true },
				{
					header: '추가 정보',
					name: 'addInfoId',
					align: 'left',
					formatter({ value }) {
						let retVal = '';
						const newValue = addInfoList.filter(item => item.value == value);
						if (newValue.length > 0) {
							retVal = newValue[0].text;
						}
						return retVal;
					},
					minWidth: 230,
				},
				{
					header: 'Data 구분',
					name: 'addInfoDataKind',
					align: 'left',
					formatter({ value }) {
						let retVal = '';
						const newValue = addInfoDataKindList.filter(
							item => item.value == value,
						);
						if (newValue.length > 0) {
							retVal = newValue[0].text;
						}
						return retVal;
					},
					minWidth: 330,
				},
				{
					header: '숫자 값',
					name: 'addInfoNumVal',
					align: 'right',
					editor: 'text',
					hidden: true,
				},
				{
					header: '문자 값',
					name: 'addInfoTxtVal',
					align: 'left',
					editor: 'text',
					hidden: true,
				},
				{
					header: '추가 정보 값',
					name: 'addInfoVal',
					align: 'left',
					renderer: {
						type: CustomRenderer,
					},
					editor: {
						type: CustomEditor,
						align: 'center',
					},
					formatter(data) {
						// console.log('test :', test);
						return data.row.addInfoDataKind;
					},
					minWidth: 330,
				},
				//{ header: "추가 정보 값", name: "addInfoVal", align: "center" , editor: "text",
				//},
				/*{
          header: "사용여부",
          name: "useFg",
          align: "center",
          formatter({ value }) {
            return value == "1" ? "사용" : "사용안함";
          },
          editor: {
            type: "select",
            options: {
              listItems: [
                {text:"사용", value:"1"},
                {text:"사용안함", value:"0"},
              ]
            }
          }
        },*/
				{ 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.$nextTick(() => {
				this.loadGrid = true;
			});
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'add':
					this.$refs[this.gridName].addRow();
					this.edtingFinishFlag = 'Y';
					break;

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

				case 'save':
					if (this.edtingFinishFlag == 'Y') {
						await this.$refs[this.gridName].editingFinish({
							rowKey: this.rowKey,
						});
					}
					dataArr = this.$refs[this.gridName].save();

					for (var i = 0; i < dataArr.length; i++) {
						if (
							dataArr[i].addInfoDataKind == 'NUM' &&
							dataArr[i].addInfoVal == ''
						) {
							dataArr[i].addInfoVal = null;
						}
					}

					if (dataArr.length > 0) {
						const sendParam = {
							datas: {
								dsReadPlcAddInfo: dataArr.map(item => ({
									...item,
									comId: this.selectedComId,
									eqpmId: this.selectedEqpmId,
								})),
							},
							params: {},
						};
						await this.postUpdateApi({
							apiKey: 'saveEqpmAddInfoList',
							sendParam: sendParam,
						});
						this.setPageData({ isFind: true });
						this.edtingFinishFlag = 'Y';
					} else {
						alert('저장할 내용이 없습니다.');
					}
					break;

				default:
					break;
			}
		},
		search() {},
		async getRowData(data) {
			this.rowKey = data.rowKey;
			this.edtingFinishFlag = 'Y';
		},
	},
};

import { getPathDataExample } from '@/const/const'
const dataPathDataExample = getPathDataExample({
	id: 'INCHEON.HVAC.EQP_HT_CH001.UT_CH101.CHI_AMP_1A_PV',
	lable: 'INCHEON 고온 냉동기 101호기 - 호로1',
	type: '사용', note: '-'
});
</script>
<style lang="scss" scoped> </style>
