<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">
                        <!-- form -->
                        <div class="row">
                            <label class="col-3 col-form-label text-end">Type</label>
                            <div class="col-9">
                                <div class="input-group">
                                    <select class="form-select" v-model="kpiModuleType">
                                        <option value="">All</option>
                                        <option :value="itemType.code" v-for="itemType in itemTypeList"
                                            :key="itemType.codeId">
                                            {{ getLabel(itemType) }}
                                        </option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="input-group">
                            <!-- dropdown -->
                            <select class="form-select" v-model="searchCondition">
                                <option value="kpiModuleName">Module Name</option>
                                <option value="kpiModuleId">Module Id</option>
                                <option value="kpiModuleDesc">{{ $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: "module/moduleList",
    mixins: [StoreParams, SDLLocale, GridCommon],
    data() {
        return {
            searchItemType: '',
            searchCondition: 'kpiModuleName',
            searchKeyword: '',
            itemTypeList: SDLUtil.getCommCodeList({ commCodeTypeId: 'EMBO_KPI_MODULE_TYPE' }),
            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.kpiModuleType = storeParams.kpiModuleType;
                this.searchCondition = storeParams.searchCondition;
                this.searchKeyword = storeParams.searchKeyword;
                this.onSearch();
            } else {
                this.onSearch();
            }
            // console.log(this.$route);
        },
        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: 'kpiModuleId' },
                { fieldName: 'kpiModuleType' },
                { fieldName: 'kpiModuleName' },
                { fieldName: 'kpiModuleDesc' },
                { fieldName: 'kpiModuleProgram' },
                { fieldName: 'createdBy' },
                { fieldName: 'createdAt' },
                { fieldName: 'updatedBy' },
                { fieldName: 'updatedAt' },
            ]);

            this.gridView.setColumns([
                {
                    fieldName: 'kpiModuleId',
                    header: 'Module ID',
                    width: 100,
                },
                { fieldName: 'kpiModuleType', header: 'Type', width: 150 },
                { fieldName: 'kpiModuleName', header: 'Name', width: 300, styleName: 'rgsample-blue-column cursor' },
                { fieldName: 'kpiModuleDesc', header: 'Description', width: 300 },
                { fieldName: 'kpiModuleProgram', header: 'Program', width: 150 },
                { 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 == 'kpiModuleName') {
                    let row = this.dataProvider.getJsonRow(clickData.dataRow);
                    this.moveRegistPage(row.kpiModuleId);
                }
            };

            this.gridView.onItemChecked = (grid, itemIndex, checked) => {
                //console.log('onItemChecked: ' + checked + ' at ' + itemIndex);
                this.checkedItems = checked ? this.grid_getCheckedRowArray(grid) : [];
            };

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

            let listApi = `${SDLUtil.API_URL}/embo/module/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/module/moduleView/` + key);
            } else {
                this.$router.push(`${this.$CONTEXT}/embo/module/moduleEdit/`);
            }
        },
        downloadExcel() {
            this.grid_getGridExcel(this.gridView, { fileName: 'testItemList' });
        },
        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/module/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 Page');

            // connection type
            /*axios.get(`${SDLUtil.API_URL}/commcode/groupcodes/itemType/commcodes`).then(({ data }) => {
              this.itemTypeList = data;
            });*/
        });
    },
    unmounted() {
        //alert('The component is removed (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>