<template>
	<div class="l-layout">
		<v-row ref="searchFilter">
			<v-col :cols="12">
				<v-card class="searchFilter">
					<v-row>
						<v-col :cols="3">
							<component
								:is="'InputText'"
								:parentPrgmId="myPrgmId"
								valueNm="roleId"
								label="역할코드"
								:searchOption="true"
								:iconShow="true"
								customClass="input-large"
							/>
						</v-col>
						<v-col :cols="3">
							<component
								:is="'InputText'"
								:parentPrgmId="myPrgmId"
								valueNm="roleNm"
								label="역할명"
								:searchOption="true"
								:iconShow="true"
								customClass="input-large"
							/>
						</v-col>
						<v-col :cols="3">
							<component
								:is="'selectCodeList'"
								:parentPrgmId="myPrgmId"
								:label="'사용여부'"
								:dataKey="'useFg'"
								:sendParam="{ commGrpCd: 'CO_USEFG', useFg: '1' }"
								:addAll="true"
								:iconShow="true"
								customClass="select-large"
							/>
						</v-col>
						<v-col :cols="3" class="d-flex align-end justify-end text-right">
							<!-- <v-btn :ripple="false" @click="search()">조회</v-btn> -->
							<BtnSearch @click="search" size="large" />
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents">
			<v-col :cols="4" class="h100">
				<v-card class="pb-5">
					<div class="d-flex align-center justify-space-between pa-5">
						<v-card-title class="pa-0">역할 리스트</v-card-title>
						<div>
							<Buttons
								:parentPrgmId="myPrgmId"
								:bindingData="gridName"
								:btnActionsFnc="btnActions"
							/>
						</div>
					</div>
					<div class="h100 px-5" style="height:calc(100% - 70px)">
						<div ref="gridParent" class="w100 h100">
							<component
								:ref="gridName + myPrgmId"
								:is="loadGrid ? 'Grid' : null"
								:gridName="gridName"
								:parentPrgmId="myPrgmId"
								@getRowsData="getRowData"
								:dataPath="dataPathMock"
							/>
						</div>
					</div>
				</v-card>
			</v-col>
			<v-col :cols="8" class="h100">
				<v-card class="pb-5">
					<div class="d-flex align-center justify-space-between pa-5">
						<v-card-title class="pa-0">역할 상세</v-card-title>
					</div>
					<div class="px-5">
						<component
							:is="'Form'"
							:parentPrgmId="myPrgmId"
							:detailList="detailList"
							@gridEditingFinish="gridEditingFinish"
						/>
					</div>
				</v-card>
			</v-col>
		</v-row>
	</div>
</template>
<script>
import mixinGlobal from '@/mixin/global.js';
import { resize } from '@/mixin/resize.js';
import Utility from '~/plugins/utility';
import { mapState, mapMutations, mapActions } from 'vuex';
import Grid from '~/components/common/Grid';
import Buttons from '~/components/common/button/Buttons';
import selectCodeList from '@/components/common/select/selectCodeList';
import InputText from '@/components/common/input/InputText';
import Form from '~/components/common/form/Form';
import BtnSearch from '~/components/common/button/BtnSearch';

let myTitle;
let myPrgmId;
export default {
	mixins: [mixinGlobal, resize],
	async asyncData(context) {
		const myState = context.store.state;
		myPrgmId = context.route.query.prgmId;
		await context.store.commit('setActiveMenuInfo', myState.menuData[myPrgmId]);
		myTitle = await myState.activeMenuInfo.menuNm;
	},
	meta: {
		title: () => {
			return myTitle;
		},
		prgmId: myPrgmId,
		closable: true,
	},
	components: {
		BtnSearch,
		Grid,
		Buttons,
		selectCodeList,
		InputText,
		Form,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			gridName: 'rowGrid',
			loadGrid: true,
			detailList: myDetail,
			dataPathMock : {
				rowGrid: {
					column: [
						{ header: '추가 정보 그룹', name: 'addGrpId', align: 'left' },
						{ header: '추가 정보 ID', name: 'addInfoId', align: 'left' },
						{ header: '추가 정보 명', name: 'addInfoNm', align: 'left' },
						{ header: 'Data 형식', name: 'addInfoDataKind', align: 'center' },
						{ header: '사용여부', name: 'useFg', align: 'center' },
					],
					data: dataMockExample,
					defaultRow: dataMockExample,
					option: {},
				},
			},
		};
	},
	computed: {
		...mapState({
			pageData: state => state.pageData[myPrgmId],
		}),
		loadFlag() {
			var init1 = this.pageData.useFgList.length > 0 ? true : false;

			return init1;
		},
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkUseFg() {
			// 사용여부 선택 감지
			return this.pageData.useFg;
		},
	},
	watch: {
		chkIsFind(val) {
			if (val) this.search();
		},
		async loadFlag(val) {
			if (val) {
				await this.gridInit();
			}
			// await this.gridInit();
		},
		chkUseFg() {
			this.setPageData({ isFind: true });
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
		await this.$store.dispatch('chkOpenTabList', {
			key: 'create',
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	mounted() {
		if (this.loadFlag) {
			this.gridInit();
		}
		// this.init();
	},
	methods: {
		init() {
			// this.gridInit();
		},
		search() {
			if (this.loadFlag == false) {
				return;
			}
			this.getRowGridData();
		},
		gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 36;

			const myOptions = {
				scrollX: false,
			};

			this.setGridOption({
				gridKey: this.gridName,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});

			const _this = this;
			const myColumns = [
				{ header: '역할ID', name: 'roleId', align: 'center' },
				{ header: '역할명', name: 'roleNm' },
				{
					header: '사용여부',
					name: 'useFg',
					align: 'center',
					formatter({ value }) {
						value = value === true ? '1' : '0';
						const newValue = _this.pageData.useFgList.filter(
							item => item.commCd == value,
						);
						return newValue[0].commCdNm;
					},
				},
			];

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

			this.getRowGridData();
		},
		// 메뉴리스트 조회
		async getRowGridData() {
			let res = await this.postApiReturn({
				apiKey: 'selectRole',
				resKey: 'roleData',
				sendParam: {
					roleId: this.pageData.roleId,
					roleNm: this.pageData.roleNm,
					useFg: this.pageData.useFg,
				},
			});
			res = res.map(item => {
				const newItem = {
					...item,
					rowStat: null,
					useFg: item.useFg === '1' ? true : false, // 화면 개발 편의를 위해 boolean 타입으로 교체, 저장시 "1", "0" 으로 바꿔 보내야 함
				};
				return newItem;
			});
			this.xlsDataBind(res);
			this.loadGrid = true;

			this.setGridData({
				gridKey: this.gridName,
				value: res,
			});

			// 첫번째 row 선택상태
			this.$nextTick(() => {
				this.$refs[this.gridName + this.myPrgmId].focus({
					//rowKey: 0,
					rowKey:
						this.pageData.rowGridSelectKey == '' ||
						this.pageData.rowGridSelectKey == null
							? 0
							: this.pageData.rowGridSelectKey ==
							  this.$refs[this.gridName + this.myPrgmId].getData().length - 1
							? this.pageData.rowGridSelectKey
							: 0,
					columnName: 'roleId',
					setScroll: true,
				});
				this.setPageData({ isFind: false });
			});
		},
		async getRowData(data) {
			this.setPageData({
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: data,
			});
		},
		async btnActions(action) {
			let dataArr = [];
			switch (action) {
				case 'add':
					this.$refs[this.gridName + this.myPrgmId].addRow();
					break;

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

				case 'save':
					dataArr = this.$refs[this.gridName + this.myPrgmId].save();
					var validCheck = true;
					if (dataArr.length > 0) {
						dataArr.forEach(item => {
							if (item.roleNm == '' || item.roleNm == null) {
								validCheck = false;
								alert('필수 입력값을 입력해주세요.');
							}
						});
						if (validCheck) {
							const sendParam = {
								datas: {
									dsRole: dataArr.map(item => ({
										...item,
										useFg: item.useFg ? '1' : '0',
									})),
								},
								params: {},
							};
							await this.postUpdateApi({
								apiKey: 'saveRole',
								sendParam: sendParam,
							});

							this.$nextTick(() => {
								this.setPageData({ isFind: true });
							});
						}
					} else {
						alert('저장할 내용이 없습니다.');
					}
					break;

				default:
					break;
			}
		},
		xlsDataBind(res) {
			const xlsRowData = res.map(item => {
				const obj = {
					...item,
					useFg: item.useFg == '1' ? '사용' : '사용안함',
				};
				return obj;
			});
			this.setPageData({
				xlsFileInfo: {
					[this.gridName]: {
						rowData: xlsRowData,
					},
				},
			});
		},
		gridEditingFinish(data) {
			this.$refs[this.gridName + this.myPrgmId].editingFinish(data);
		},
	},
};

const defaultData = {
	isFind: false, // true 경우 조회

	/* 검색옵션 */
	roleId: '',
	roleNm: '',
	useFg: '',
	useFgList: [],

	// 선택된 그룹코드 상세 데이터
	rowGridSelectKey: 0,
	rowGridSelectData: null,

	/* data 세팅 */
	rowGrid: {
		data: [],
		column: [],
		option: {},
		defaultRow: {
			roleId: null,
			roleNm: null,
			useFg: 1,
			rmrk: null,
			regUserNo: null,
			regDttm: null,
			procUserNo: null,
			procDttm: null,
			rowStat: null,
		},
		buttonAuth: {
			add: true,
			remove: true,
			save: true,
			excel: true,
		},
	},

	xlsFileInfo: {
		// 출력하려는 grid 와 같은 이름으로 세팅
		rowGrid: {
			// rowData: [],
			fileName: null, // 갑이 없으면 해당 페이지 메뉴명
			sheetName: null, //  갑이 없으면 'Sheet1'
		},
	},
};
const myDetail = [
	{
		type: 'InputText',
		label: '역할코드',
		valueNm: 'roleId',
		readonly: true,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pr-4',
		required: false,
		placeholder: '시스템 자동입력',
	},
	{
		type: 'InputText',
		label: '역할명',
		valueNm: 'roleNm',
		disabled: false,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pl-4',
		required: true,
	},
	{
		type: 'CheckBox',
		label: '사용여부',
		valueNm: 'useFg',
		disabled: false,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pr-4',
		value: { '1': true, '0': false },
		required: true,
	},
	{
		type: 'InputText',
		label: '비고',
		valueNm: 'rmrk',
		disabled: false,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pl-4',
	},
	// {
	//   type: "InputText",
	//   label: "정렬순서",
	//   valueNm: "sortSeq",
	//   disabled: false,
	//   cols: 6,
	//   class: "py-2"
	// },
	{
		type: 'InputText',
		label: '등록자No',
		valueNm: 'regUserNo',
		disabled: true,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pr-4',
		placeholder: '시스템 자동입력',
	},
	{
		type: 'InputText',
		label: '등록일시',
		valueNm: 'regDttm',
		disabled: true,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pl-4',
		placeholder: '시스템 자동입력',
	},
	{
		type: 'InputText',
		label: '수정자No',
		valueNm: 'procUserNo',
		disabled: true,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pr-4',
		placeholder: '시스템 자동입력',
	},
	{
		type: 'InputText',
		label: '수정일시',
		valueNm: 'procDttm',
		disabled: true,
		cols: 6,
		labelCols: 12,
		textCols: 12,
		iconShow: true,
		class: 'py-2 pl-4',
		placeholder: '시스템 자동입력',
	},
];

const dataMockExample = [
  {
    addGrpId: 'GRP001',
    addInfoId: 'INFO001',
    addInfoNm: '온도 센서',
    addInfoDataKind: 'DATA01',
    useFg: true,
  },
  {
    addGrpId: 'GRP002',
    addInfoId: 'INFO002',
    addInfoNm: '압력 센서',
    addInfoDataKind: 'DATA02',
    useFg: false,
  },
  {
    addGrpId: 'GRP003',
    addInfoId: 'INFO003',
    addInfoNm: '압력 센서',
    addInfoDataKind: 'DATA03',
    useFg: false,
  },
  {
    addGrpId: 'GRP004',
    addInfoId: 'INFO004',
    addInfoNm: '압력 센서',
    addInfoDataKind: 'DATA04',
    useFg: false,
  },
  {
    addGrpId: 'GRP005',
    addInfoId: 'INFO005',
    addInfoNm: '압력 센서',
    addInfoDataKind: 'DATA05',
    useFg: false,
  },
];

</script>
