<template>
	<div>
		<div
			class="d-flex justify-space-between align-center"
			style="height: 80px;"
		>
			<span class="txt">검침 대상 추가 정보</span>
			<Buttons
				:parentPrgmId="parentPrgmId"
				:bindingData="gridName"
				:btnActionsFnc="btnActions"
			/>
		</div>
		<div ref="gridParent" style="height: calc(100vh - 520px);">
			<Grid
				:ref="gridName"
				:is="loadGrid ? 'Grid' : null"
				:gridName="gridName"
				:parentPrgmId="parentPrgmId"
				:editorGrid="true"
				:innerTabGridInfo="innerTabGridInfo"
				@getRowsData="getRowData"
				:selectedRowDataWatchFlag="true"
				:dataPath="dataPathMock"
			/>
		</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';
import { NewCustomRenderer } from '~/plugins/gridUtility';
import { NewCustomEditor } from '~/plugins/gridUtility';
export default {
	mixins: [mixinGlobal],
	components: {
		Buttons,
		Grid,
		InputText,
		Form,
	},
	props: {
		parentPrgmId: {
			type: String,
			require: true,
		},
		innerTabGridInfo: {
			type: Object,
			default: null,
		},
	},
	data() {
		return {
			loadGrid: true,
			gridName: 'rowDetailGrid',
			rowKey: null,
			edtingFinishFlag: 'Y',
			dataPathMock: {
				"rowDetailGrid": {
				column: [
					{ header: '검침 대상 ID', name: 'readObjId', align: 'left' },
					{ header: '검침 대상 명', name: 'readObjNm', align: 'left' },
					{ header: '검침 대상 유형', name: 'readObjKind', align: 'left' },
					{ header: '그룹', name: 'grpCd', align: '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;
		},
		selectedReadObjId() {
			return this.pageData.rowGridSelectData.readObjId;
		},
	},
	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: 28,
				},
				rowHeight: 29,
				minRowHeight: 29,
				selectionUnit: 'row',
				editingEvent: 'click',
			};
			this.setGridOption({
				gridKey: this.gridName,
				value: 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);
			});

			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.keyDown = "this.value=this.value.replace(/[^0-9]/g,'');"
							el.onkeydown = function(event) {
								var code = event.keyCode;
								if (
									(code > 47 && code < 58) ||
									event.ctrlKey ||
									event.altKey ||
									code == 8 ||
									code == 9 ||
									code == 46
								) {
									if (event.ctrlKey && event.keyCode == 86) {
										event.preventDefault();
									}
									return;
								}
								event.preventDefault();
							};
						}
						$(el).addClass('tui-grid-content-text');
					}
					// console.log('props: %o', props);
					// console.log('el: %o', el);
					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);
					}
					//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: '검침 대상 ID', name: 'readObjId', 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;
					},
				},
				{
					header: 'Data 구분',
					name: 'addInfoDataKind',
					align: 'center',
					formatter({ value }) {
						let retVal = '';
						const newValue = addInfoDataKindList.filter(
							item => item.value == value,
						);
						if (newValue.length > 0) {
							retVal = newValue[0].text;
						}
						return retVal;
					},
					// editor: {
					//   type: "select",
					//   options: {
					//     listItems: addInfoDataKindList
					//   }
					// }
				},
				{
					header: '숫자 값',
					name: 'addInfoNumVal',
					align: 'right',
					editor: 'text',
					hidden: true,
				},
				{
					header: '문자 값',
					name: 'addInfoTxtVal',
					align: 'left',
					editor: 'text',
					hidden: true,
				},
				{
					header: '추가 정보 값',
					name: 'addInfoVal',
					align: 'center',
					renderer: {
						type: NewCustomRenderer,
					},
					editor: {
						type: NewCustomEditor,
					},
					formatter(data) {
						return data.row.addInfoDataKind;
					},
				},
				//{ header: "추가 정보 값", name: "addInfoVal", align: "center" , editor: "text",
				// formatter({ value, row , column}) {
				//   console.log("addInfoVal row : ", row);
				//   console.log("addInfoVal state : ", column);
				//   if(row.addInfoDataKind === "NUM"){
				//     column.align = "right";
				//   }else{
				//     column.align = "left";
				//   }
				//   return value;
				// }
				//},
				/*{
          header: "사용여부",
          name: "useFg",
          align: "center",
          formatter({ value }) {
            return value == "1" ? "사용" : "사용안함";
          },
          editor: {
            type: "select",
            options: {
              // listItems: useFgSelectList
              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.loadGrid = true;
		},
		async getRowData2(data, gridName) {
			this.setGridSelectData({
				gridKey: gridName,
				gridSelect: true,
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: Object.assign({}, data),
			});
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'add':
					this.$refs[this.gridName].addRow();
					this.edtingFinishFlag = 'Y';
					break;

				case 'remove':
					await this.$refs[this.gridName].editingFinish({
						rowKey: this.rowKey,
					});
					this.$refs[this.gridName].removeRow();
					this.edtingFinishFlag = 'N';
					break;

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

					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: {
								dsReadObjAddInfo: dataArr.map(item => ({
									...item,
									comId: this.selectedComId,
									blocId: this.selectedBlocId,
									readObjId: this.selectedReadObjId,
								})),
							},
							params: {},
						};
						await this.postUpdateApi({
							apiKey: 'saveReadObjAddInfoList',
							sendParam: sendParam,
						});
						this.loadGrid = true;
						this.setPageData({ isFind: true });
						this.edtingFinishFlag = 'Y';
					} else {
						this.loadGrid = true;
						alert('저장할 내용이 없습니다.');
					}
					break;

				default:
					break;
			}
		},
		async getRowData(data) {
			this.rowKey = data.rowKey;
			this.edtingFinishFlag = 'Y';
		},
		gridEditingFinish2(data, bindingData) {
			this.$refs[bindingData].editingFinish(data);
		},
		search() {},
	},
};
const dataPathDataExample = [
	{
	readObjId: 'OBJ001',
	readObjNm: '서울 본사',
	readObjKind: 'TYPE01',
	grpCd: 'GRP01',
	},
	{
	readObjId: 'OBJ002',
	readObjNm: '부산 지사',
	readObjKind: 'TYPE02',
	grpCd: 'GRP02',
	},
	{
	readObjId: 'OBJ003',
	readObjNm: '대전 공장',
	readObjKind: 'TYPE03',
	grpCd: 'GRP01',
	}
];

</script>
