<template>
    <div class="ui--content-wrapper">
        <sdl-breadcrumb></sdl-breadcrumb>
        <!-- SEARCH Area -->
        <div class="ui--search-container clearfix">
            <div class="col-10 float-start">
                <div class="row">                    
                    <div class="col-6">
                        <div class="input-group">
                            <!-- dropdown -->
                            <select class="form-select" v-model="searchCondition">
                                <option value="parameterName">Parameter Name</option>
                                <option value="parameterType">Parameter Type</option>
                                <option value="parameterDesc">{{ $t('sdl.common.label.description') }}</option>
                            </select>
                            <input type="text" class="form-control" v-model.trim="searchKeyword"
                                @keyup.esc="searchKeyword = ''" @keyup.enter="getList()" />
                        </div>
                    </div>
                </div>
            </div>
            <!-- search button -->
            <div class="col-2 float-end text-end">
                <button class="btn btn-primary btn-search" type="button" @click="onSearch()">
                    {{ $t('sdl.common.label.search') }}
                </button>
            </div>
        </div>
        <!-- LIST Header & buttons -->
        <div class="ui--list-heading clearfix">
            <span class="ui--text-total"><strong>Total</strong> {{ $filters.numberFormat(records) }} </span>
            <div class="float-end">
                <button type="button" class="btn btn-primary btn-sm" :disabled="!hasRow" @click="downloadExcel()"
                    v-authorization="'execute'">
                    {{ $t('sdl.common.label.excelDownload') }}
                </button>
                <button type="button" class="btn btn-primary btn-sm" :disabled="!hasChecked" @click="deleteItem()"
                    v-authorization="'execute'">
                    {{ $t('sdl.common.label.delete') }}
                </button>
                <button type="button" class="btn btn-primary btn-sm" @click="moveRegistPage()"
                    v-authorization="'execute'">
                    {{ $t('sdl.common.label.register') }}
                </button>

            </div>
        </div>
        <div class="grid-wrap" style="height:" id="grd_main_div">
            <div class="realgrid" id="grid" style="width: 100%; height: 400px"></div>
        </div>
    </div>
    <pre>
    </pre>
</template>
<script>
import axios from 'axios';
import _ from 'lodash';
import { DateUtil, SDLUtil, StringUtil } from '@/utils';
import StoreParams from '@/mixin/StoreParams';
import SDLLocale from '@/mixin/SDLLocale';
import GridCommon from '@/mixin/GridCommon';
import RealGrid from 'realgrid';

export default {
    name: "parameter/parameterList",
    mixins: [StoreParams, SDLLocale, GridCommon],
    data() {
        return {
            
            searchCondition: 'parameterName',
            searchKeyword: '',            
            records: 0,

            //-- grid
            dataProvider: null,
            gridView: null,
            gridList: [],
            checkedItems: [],
        };
    },
    computed: {
        hasChecked: function () {
            return !_.isEmpty(this.checkedItems);
        },
        hasRow: function () {
            return !_.isEmpty(this.gridList);
        },
    },
    methods: {
        init() {
            const storeParams = this.getStoreParameter();
            if (storeParams) {                
                this.searchCondition = storeParams.searchCondition;
                this.searchKeyword = storeParams.searchKeyword;
                this.onSearch();
            } else {
                this.onSearch();
            }            
        },
        initGrid() {
            this.dataProvider = new RealGrid.LocalDataProvider(); // LocalDataProvider 사용
            this.gridView = new RealGrid.GridView('grid'); // GridView 사용
            this.gridView.setDataSource(this.dataProvider); // setDataSource 사용

            //set grid edit option
            const options = { options: { checkBar: { visible: true, showAll: true } }, displayOptions: { columnMovable: true, rowHeight: 25 } };
            this.grid_setGridOptions(this.gridView, options);
            //this.gridView.setCopyOptions({enabled: false});
            //this.gridView.setPasteOptions({enabled: false});
            /*this.gridView.setDisplayOptions({
              columnMovable: false,rowHeight: 20,
            });*/
            // 그리드 데이터 설정
            this.dataProvider.setFields([
                
                { fieldName: 'parameterType' },
                { fieldName: 'parameterName' },
                { fieldName: 'parameterDesc' },
                { fieldName: 'parameterProgram' },
                { fieldName: 'multi' },
                { fieldName: 'createdBy' },
                { fieldName: 'createdAt' },
                { fieldName: 'updatedBy' },
                { fieldName: 'updatedAt' },
            ]);

            this.gridView.setColumns([
                {
                    fieldName: 'parameterType',
                    header: 'Parameter Type',
                    width: 100,
                },
                
                { fieldName: 'parameterName', header: 'Name', width: 300, styleName: 'rgsample-blue-column cursor' },
                { fieldName: 'parameterDesc', header: 'Description', width: 300 },
                { fieldName: 'parameterProgram', header: 'Program', width: 150 },
                { fieldName: 'multi', header: 'Multi', width: 50 },
                { fieldName: 'createdBy', header: 'Created By', width: 150 },
                { fieldName: 'createdAt', header: 'Created Date', width: 150 },
                { fieldName: 'updatedBy', header: 'Updated By', width: 150 },
                { fieldName: 'updatedAt', header: 'Updated Date', width: 150 },
            ]);

            // set grid event
            this.gridView.onCellClicked = (grid, clickData) => {
                //전체 데이타 this.checkedItems = this.grid_getCheckedRowArray(grid);
                if (clickData.column == 'parameterName') {
                    let row = this.dataProvider.getJsonRow(clickData.dataRow);
                    this.moveRegistPage(row.parameterType);
                }
            };

            this.gridView.onItemChecked = (grid, itemIndex, checked) => {                
                this.checkedItems = checked ? this.grid_getCheckedRowArray(grid) : [];
            };

            this.gridView.onItemAllChecked = (grid, checked) => {                
                this.checkedItems = checked ? this.grid_getCheckedRowArray(grid) : [];
            };
        },
        onSearch() {
            // eslint-disable-next-line no-underscore-dangle       
            const params = {                
                searchCondition: this.searchCondition,
                searchKeyword: this.searchKeyword,
            };
            this.setStoreParameter(params);

            let listApi = `${SDLUtil.API_URL}/embo/parameter/main.do?method=search`;
            SDLUtil.showLoadingBar(true);
            axios
                .post(listApi, JSON.stringify(params), {
                    headers: { 'Content-Type': `application/json` },
                })
                .then(response => {
                    this.gridList = _.map(response.data.result, r => {
                        r.createdAt = this.$filters.dateFormat(r.createdAt);
                        r.updatedAt = this.$filters.dateFormat(r.updatedAt);
                        return r;
                    });

                    this.dataProvider.setRows(this.gridList);
                    // hide Loading bar
                    SDLUtil.showLoadingBar(false);
                })
                .catch(error => {
                    SDLUtil.showLoadingBar(false);
                    SDLUtil.errorAlert(error);
                    console.log(error);
                });
        },
        moveRegistPage(key = '') {
            console.log('moveRegistPage key:' + key);
            if (key) {
                this.$router.push(`${this.$CONTEXT}/embo/parameter/parameterView/` + key);
            } else {
                this.$router.push(`${this.$CONTEXT}/embo/parameter/parameterEdit/`);
            }
        },
        downloadExcel() {
            this.grid_getGridExcel(this.gridView, { fileName: 'parameterList' });
        },
        deleteItem() {
            SDLUtil.confirm({
                msg: 'sdl.common.message.doDelete',
                // title: 'confirm title',
                // okLabel: 'ok label',
                // cancelLabel: 'Cancel',
                onOkEvt: () => this.doDeleteFormula(),
            });
        },
        doDeleteFormula() {
            var rows = this.grid_getCheckedRowArray(this.gridView);
            axios
                .post(`${SDLUtil.API_URL}/embo/parameter/main.do?method=delete`, { items: rows })
                .then(({ data }) => {
                    SDLUtil.showLoadingBar(false);
                    SDLUtil.alert('sdl.common.message.deleted');
                    this.onSearch();
                })
                .catch(err => {
                    SDLUtil.showLoadingBar(false);
                    SDLUtil.errorAlert(err);
                });
        },
    }, //--method
    created() {
        this.init();
    },
    mounted() {
        this.initGrid();

        this.$nextTick(() => {
            console.info('initialize parameter Page');         
        });
    },
    unmounted() {
       
        this.dataProvider.clearRows();
        this.gridView.destroy();
        this.dataProvider.destroy();
        this.gridView = null;
        this.dataProvider = null;
    },
};
</script>
<style scoped>
button:disabled,
button[disabled] {
    border: 1px solid #999999;
    background-color: #cccccc;
    color: #666666;
}
</style>