<template>
	<div>
		<div
			class="d-flex justify-space-between align-center"
			style="height: 80px;"
		>
			<span class="txt custom-title-4-new">공정 추가 정보</span>
			<Buttons
				:parentPrgmId="parentPrgmId"
				:bindingData="gridName"
				:btnActionsFnc="btnActions"
			/>
		</div>
		<div ref="gridParent" style="height: calc(100vh - 560px);">
			<Grid
				:ref="gridName"
				:is="loadGrid ? 'Grid' : null"
				:gridName="gridName"
				:parentPrgmId="parentPrgmId"
				:editorGrid="true"
				:innerTabGridInfo="innerTabGridInfo"
				@getRowsData="getRowData"
				: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 Utility from '~/plugins/utility';
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,
		Utility,
	},
	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: '추가 정보', name: 'readObjId', align: 'left' },
					{ header: 'Data 구분', name: 'readObjNm', align: 'left' },
					{ header: '추가 정보 값', name: 'readObjKind', 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;
		},
		selectedEccId() {
			return this.pageData.rowGridSelectData.eccId;
		},
	},
	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();
		},
		search() {},
		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.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');
					}
					// 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: '공정 번호', name: 'eccId', 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;
					},
				},
				{
					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: CustomRenderer,
					},
					editor: {
						type: CustomEditor,
						align: 'center',
					},
					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 getRowData(data, gridName) {
			this.setGridSelectData({
				gridKey: gridName,
				gridSelect: true,
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: Object.assign({}, data),
			});

			this.rowKey = data.rowKey;
			this.edtingFinishFlag = 'Y';
		},
		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();

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

					this.setPageData({ isFind: true });
					if (dataArr.length > 0) {
						// console.log(this.pageData)
						const sendParam = {
							datas: {
								dsEccAddInfo: dataArr.map(item => ({
									...item,
									comId: this.selectedComId,
									eccId: this.selectedEccId,
								})),
							},
							params: {},
						};
						await this.postUpdateApi({
							apiKey: 'saveEccAddInfoList',
							sendParam: sendParam,
						});
						this.loadGrid = true;
						this.setPageData({ isFind: true });
						this.edtingFinishFlag = 'Y';
					} else {
						this.loadGrid = true;
						alert('저장할 내용이 없습니다.');
					}
					break;

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

const dataPathDataExample = [
	{
	readObjId: 'OBJ001',
	readObjNm: '서울 본사',
	readObjKind: 'TYPE01',
	},
	{
	readObjId: 'OBJ002',
	readObjNm: '부산 지사',
	readObjKind: 'TYPE02',
	},
	{
	readObjId: 'OBJ003',
	readObjNm: '대전 공장',
	readObjKind: 'TYPE03',
	}
]
</script>
