require(['config'], function() {
    require([
        'jquery.bootstrap.fileUpload', //파일 업로드가 있는 페이지에서 로딩
        'kakao.map.util'
    ], function($) {
        pageObj.init();
    });
});

/********************************************************
 --------------------------------------------------------
 - Object 목록								            -
 --------------------------------------------------------
 * const gridColModel = {}	: 화면 Grid Object			*
 * let pageObj = {}			: 화면공통 Object			*
 * let listObj = {}			: 목록화면 Object			*
 * let viewObj = {}			: 상세화면 Object			*
 * let modifyObj = {}		: 수정화면 Object			*
 * let createObj = {}		: 신규화면 Object			*
 *******************************************************/

/*화면 변수*/
const STINFO01010_GRID_ID = '#ITP_STINFO01010_jqGrid';
const STINFO01010_GRID_LIST = '#ITP_STINFO01010_jqGrid_list';
const STINFO01010_GRID_PAGER = '#ITP_STINFO01010_jqGridPager';
const STINFO01010_GRID_EMPTY = '#ITP_STINFO01010_jqGridEmpty';

const STINFO01010_VIEW_GRID_ID = '#ITP_STINFO01010_VIEW_jqGrid';
const STINFO01010_VIEW_GRID_LIST = '#ITP_STINFO01010_VIEW_jqGrid_list';
const STINFO01010_VIEW_GRID_PAGER = '#ITP_STINFO01010_VIEW_jqGridPager';
const STINFO01010_VIEW_GRID_EMPTY = '#ITP_STINFO01010_VIEW_jqGridEmpty';

const STINFO01010_DETAIL_GRID_ID = '#ITP_STINFO01010_DETAIL_jqGrid';
const STINFO01010_DETAIL_GRID_LIST = '#ITP_STINFO01010_DETAIL_jqGrid_list';
const STINFO01010_DETAIL_GRID_PAGER = '#ITP_STINFO01010_DETAIL_jqGridPager';
const STINFO01010_DETAIL_GRID_EMPTY = '#ITP_STINFO01010_DETAIL_jqGridEmpty';

/*API URL*/
let API_DETAIL_GRID_LIST = '/api/brand/detail-grid-list';
let API_DETAIL_INFO = '/api/brand/info-brand';
let API_DETAIL_SAVE = '/api/brand/save-brand';

let ITP_FORM_STINFO01010_DETAIL_IS_DUPLICATE = false;
let ITP_FORM_STINFO01010_DETAIL_IS_WRITING = false;

/*화면 Grid Object*/
const gridColModel = {
    list: [
        {
            index: 'VIEW_CD', name: 'viewCd',
            label: ITP_MSG_LOCALE.label.viewCd,
            width: '10', fixed: false, align: 'center',
            sortable: false, hidden: true
        },
        {
            index: 'AFFL_SHOP_ID', name: 'afflShopId',
            label: ITP_MSG_LOCALE.label.afflShopId,
            width: '10', fixed: false, align: 'center',
            sortable: false, hidden: true
        },
        {
            index: 'AFFL_SHOP_NM', name: 'afflShopNm',
            label: ITP_MSG_LOCALE.label.afflShopNm, //브랜드그룹
            width: '10', fixed: false, align: 'center',
            sortable: false, hidden: false
        },
        {
            index: 'BRAND_ID', name: 'brandId',
            label: ITP_MSG_LOCALE.label.brandId,
            width: '10', fixed: false, align: 'center',
            sortable: false, hidden: false
        },
        {
            index: 'BRAND_NM', name: 'brandNm',
            label: ITP_MSG_LOCALE.label.brandNm, //브랜드명
            width: '13', fixed: false, align: 'center',
            sortable: false, hidden: false
        },
        {
            index: 'ST_NM', name: 'stNm',
            label: ITP_MSG_LOCALE.label.stNm, //상태
            width: '10', fixed: false, align: 'center',
            sortable: false, hidden: false
        },
        {
            index: 'BRAND_TYPE_NM', name: 'brandTypeNm',
            label: ITP_MSG_LOCALE.label.brandTypeNm, //브랜드 타입
            width: '13', fixed: false, align: 'center',
            sortable: false, hidden: false
        },
        {
            index: 'REG_DT', name: 'regDt',
            label: ITP_MSG_LOCALE.label.regDt, //등록일
            width: '10', fixed: false, align: 'center',
            sortable: false, hidden: false
        }],
    view: [],
    detail: []
};

/*화면공통 Object*/
let pageObj = {
    init: function () {
        this.ui.init();
        this.event.init();
    },
    ui: {
        init: function () {
            this.view();
            this.grid();
            this.ready();
        },
        view: function() {
            // 버튼 권한설정
            fn_proc_btn_auth('STINFO01010');

            // 공통코드 표시
            $('select').each(function() {
                if($(this).data('select-code')) {
                    fn_make_select(CODE_LIST, $(this).data('select-code'), $(this).attr('id'));
                }
            });
        },
        grid: function() {
            itp_fn_jqgrid_resize(STINFO01010_GRID_ID, STINFO01010_GRID_LIST, 'lg');
            listObj.empty.init();
            itp_fn_fire_window_resize();
        },
        ready: function() {
            listObj.init();
        }
    },
    event: {
        init: function () {
            this.button();
        },
        button: function () {
            // 버튼 클릭 이벤트
            $('button').each(function() {
                var id = $(this).attr('id');
                $(this).on('click', function() {
                    switch (id) {
                        case 'ITP_BTN_STINFO01010_SRH'				    : listObj.button.search();		break;	// 조회 버튼 클릭
                        case 'ITP_BTN_STINFO01010_NEWREG'				: listObj.button.create(); 		break;	// 신규등록 버튼
                        case 'ITP_BTN_STINFO01010_MODIFY'				: modifyObj.button.modify();	break;	// 수정 버튼
                        case 'ITP_BTN_STINFO01010_CANCELLIST'			: createObj.button.cancel(); 	break;	// 취소/목록 버튼
                        case 'ITP_BTN_STINFO01010_DELETE'				: 								break;	// 삭제 버튼
                        case 'ITP_BTN_STINFO01010_SAVE'				    : createObj.button.save(); 		break;	// 저장 버튼
                        case 'ITP_FORM_STINFO01010_DETAIL_DUP'		    : createObj.button.duplicate();	break;	// 중복체크
                        case 'ITP_BTN_STINFO01010_RESET_PW'			    : createObj.button.resetPass();	break;	// 상세:비밀번호 초기화
                        case 'ITP_BTN_STINFO01010_DETAIL_ADDROW'		: afflShopObj.button.addRow();	break;	// 상세:추가버튼
                        case 'ITP_BTN_STINFO01010_DETAIL_DELROW'		: afflShopObj.button.delRow();	break;	// 상세:삭제버튼
                    }
                });
            });
        }
    },
    fileUpload: function() {
        //파일업로드(수정화면)
        var id = 'STINFO01010';
        $('#ITP_' + id + '_DETAIL_UPLOAD').empty();
        const fileArgs = {
            'fileNo': $('#ITP_FORM_' + id + '_DETAIL_FILE_NO').val(),
            'viewCd': $('#ITP_FORM_' + id + '_DETAIL_VIEW_CD').val(),
            'showYn': $('#ITP_' + id + '_DETAIL_UPLOAD').attr('data-show-yn'),
            'fileId': '#ITP_FORM_' + id + '_DETAIL_FILE_NO' //파일번호를 서버에서 받아서 넣을 파일번호 인풋박스 아이디
        };
        itp_fn_set_file_upload('ITP_' + id + '_DETAIL_UPLOAD', 'notice', true, false, id, fileArgs);
    },
    switchScreen: function(mode) {
        $('.itp_det_head').find('button[id^="ITP_BTN_STINFO01010_"]').each(function(i) {
            $(this).hide();
        });
        $('#ITP_TAB_STINFO01010').find('div[id$="_CONTAINER"]').each(function(i) {
            $(this).hide();
        });
        if(mode == 'LIST') { // 목록
            $('#ITP_AJAX_STINFO01010_LIST_CONTAINER').show();
            fn_show_btn_auth_array(['#ITP_BTN_STINFO01010_SRH', '#ITP_BTN_STINFO01010_NEWREG']);
        } else if(mode == 'ADD') { // 등록
            ITP_FORM_STINFO01010_DETAIL_IS_DUPLICATE = true;
            $('#ITP_AJAX_STINFO01010_DETAIL_CONTAINER').show();
            fn_show_btn_auth_array(['#ITP_BTN_STINFO01010_CANCELLIST', '#ITP_BTN_STINFO01010_SAVE']);

            $('#ITP_FORM_STINFO01010_DETAIL').find('input, textarea, select, checkbox').each(function(i, elem) {
                $(this).attr('id') === 'ITP_FORM_STINFO01010_DETAIL_VIEW_CD' ? $(this).val('C') : $(this).val('');
                if(elem.type === 'select') {
                    $(this).val('').prop('selected', true);
                }
            });

            $('#ITP_FORM_STINFO01010_DETAIL_AFFL_SHOP_ID').val(fn_make_user_info.get('afflShopId'));
            $('#ITP_FORM_STINFO01010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));
            $('#ITP_FORM_STINFO01010_DETAIL_BRAND_ID').removeAttr('readonly');
            $('#ITP_FORM_STINFO01010_DETAIL_DUP').removeAttr('disabled');
        } else if(mode == 'MODIFY') { // 수정
            $('#ITP_AJAX_STINFO01010_DETAIL_CONTAINER').show();
            fn_show_btn_auth_array(['#ITP_BTN_STINFO01010_CANCELLIST', '#ITP_BTN_STINFO01010_SAVE', '#ITP_BTN_STINFO01010_RESET_PW']);

            $('#ITP_FORM_STINFO01010_DETAIL_AFFL_SHOP_ID').val(fn_make_user_info.get('afflShopId'));
            $('#ITP_FORM_STINFO01010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));
            $('#ITP_FORM_STINFO01010_DETAIL_BRAND_ID').attr('readonly', true);
            $('#ITP_FORM_STINFO01010_DETAIL_DUP').attr('disabled', true);
        } else if(mode == 'VIEW') { // 보기
            $('#ITP_AJAX_STINFO01010_VIEW_CONTAINER').show();
            fn_show_btn_auth_array(['#ITP_BTN_STINFO01010_MODIFY', '#ITP_BTN_STINFO01010_CANCELLIST']);
        }
    }
};

/*목록화면 Object*/
let listObj = {
    init: function () {
        this.grid.init();
    },
    itp_STINFO01010_param: {},
    itp_STINFO01010_search: false,
    button: {
        search: function() {
            listObj.itp_STINFO01010_search = true;
            let param = $('#ITP_FORM_STINFO01010_SEARCH').serializeObject();
            param.gridSize = $.jgrid.defaults.rowNum;
            param.gridPage = $.jgrid.defaults.page;
            $(STINFO01010_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
        },
        create: function() {
            pageObj.switchScreen('ADD');
            itp_fn_form_clear_validate(null, '#ITP_FORM_STINFO01010_DETAIL');
            // 권한정보 리스트 조회
            createObj.init();
        }
    },
    empty: {
        init: function() {
            var _this = this;
            this.push();
            $(STINFO01010_GRID_EMPTY).on('click', function() {
                _this.back();
                listObj.itp_STINFO01010_param.gridSize = $.jgrid.defaults.rowNum;
                $(STINFO01010_GRID_ID).setGridParam({'postData': JSON.stringify(listObj.itp_STINFO01010_param)}).trigger('reloadGrid');
            });
        },
        push: function() {
            let param = $('#ITP_FORM_STINFO01010_SEARCH').serializeObject();
            listObj.itp_STINFO01010_param = param;
        },
        back: function() {
            $('#ITP_FORM_STINFO01010_SERVICE_BRAND_TYPE').val(listObj.itp_STINFO01010_param.brandType);
            $('#ITP_FORM_STINFO01010_SERVICE_ST_CD').val(listObj.itp_STINFO01010_param.stCd);
            $('#ITP_FORM_STINFO01010_SEARCH_BRAND_NM').val(listObj.itp_STINFO01010_param.brandNm);
        }
    },
    grid: {
        init: function () {
            // 데이터 없을때
            listObj.empty.push();
            this.search();
        },
        colModel: gridColModel.list,
        search: function() {
            pageObj.switchScreen('LIST');
            this.unload();
            this.load();
        },
        load: function() {
            let param = $('#ITP_FORM_STINFO01010_SEARCH').serializeObject();
            param.gridSize = $.jgrid.defaults.rowNum;

            var option = {
                gridId: STINFO01010_GRID_ID,
                colModel: gridColModel.list,
                param: param,
                url: DOMAIN + API_DETAIL_GRID_LIST,
                pager: STINFO01010_GRID_PAGER,
                onCellSelect: function(rowId, cellIdx, cellValue) {
                    var cm = $(this).jqGrid('getGridParam', 'colModel');
                    var colNm = cm[cellIdx].name;
                    if (colNm === 'brandId') {
                        const brandIdVal = $(this).jqGrid('getCell', rowId, 'brandId');
                        const key = {brandId: brandIdVal, viewCd: 'R'};
                        var param = $.param(key);
                        viewObj.init(param);
                    }
                },
                loadComplete: function(data) {
                    //console.log(JSON.stringify(data));
                    itp_fn_grid_load_complete(data, STINFO01010_GRID_ID, true, 'number', 'STINFO01010', listObj.itp_STINFO01010_search, listObj.empty, true, data.gridRecords, true);
                    var ids = $(STINFO01010_GRID_ID).getDataIDs();
                    $.each(ids, function(idx, rowId) {
                        $(STINFO01010_GRID_ID).jqGrid('setCell', rowId, 'brandId', '', ITP_GRID_COL_STYLE.link);
                    });
                },
                onPaging: function(action) {
                    itp_fn_grid_paging(STINFO01010_GRID_ID, action, param);
                }
            };
            itp_fn_grid_make_remote(option);
        },
        clearData : function() {
            $(STINFO01010_GRID_ID).jqGrid('clearGridData', true);
            $(STINFO01010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
            $(STINFO01010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
            $(STINFO01010_GRID_EMPTY).show();
        },
        unload : function() {
            $.jgrid.gridUnload(STINFO01010_GRID_ID);
        }
    }
};

/*상세화면 Object*/
let viewObj = {
    init: function (param) {
        this.load(param);
    },
    load: function(param) {
        fn_ajax_call(API_DETAIL_INFO, param, this.callback, 'GET');
    },
    callback: function (result) {
        // console.log(result);
        pageObj.switchScreen('VIEW');
        $('#ITP_FORM_STINFO01010_VIEW #ITP_FORM_STINFO01010_VIEW_AFFL_SHOP_ID').val(result.afflShopId);
        $('#ITP_FORM_STINFO01010_VIEW #ITP_FORM_STINFO01010_VIEW_BRAND_ID').val(result.brandId);
        $('#ITP_FORM_STINFO01010_VIEW .fnBrandUnitUnqNo').text(result.brandId);
        $('#ITP_FORM_STINFO01010_VIEW .fnStCd').text(result.stCd);
        $('#ITP_FORM_STINFO01010_VIEW .fnBrandNm').text(result.brandNm);
        $('#ITP_FORM_STINFO01010_VIEW .fnBrandType').text(result.brandType);
        $('#ITP_FORM_STINFO01010_VIEW .fnTelNo').text(result.telNo);
        $('#ITP_FORM_STINFO01010_VIEW .fnFaxNo').text(result.faxNo);
        $('#ITP_FORM_STINFO01010_VIEW .fnEmalAddr').text(result.email);
        $('#ITP_FORM_STINFO01010_VIEW .fnDpstBnkCd').text(result.bnkCd);
        $('#ITP_FORM_STINFO01010_VIEW .fnRcvAcctNo').text(result.acctNo);
        $('#ITP_FORM_STINFO01010_VIEW .fnOwacNm').text(result.owacNm);
        $('#ITP_FORM_STINFO01010_VIEW .fnZipNo').text(result.zipNo);
        $('#ITP_FORM_STINFO01010_VIEW .fnLoadAddr').text(result.addr1);
        $('#ITP_FORM_STINFO01010_VIEW .fnDtlAddr').text(result.addr2);
        $('#ITP_FORM_STINFO01010_VIEW .fnRegId').text(result.sysRegId);
        $('#ITP_FORM_STINFO01010_VIEW .fnRegDt').text(result.sysRegDttm);
        $('#ITP_FORM_STINFO01010_VIEW .fnChgId').text(result.sysChgId);
        $('#ITP_FORM_STINFO01010_VIEW .fnChgDt').text(result.sysChgDttm);
        // $('#ITP_FORM_STINFO01010_VIEW .fnBrandLogo').text(result.lastLoginDt);
    }
};

/*수정화면 Object*/
let modifyObj = {
    button: {
        modify: function () {
            itp_fn_form_clear_validate(null, '#ITP_FORM_STINFO01010_DETAIL');
            const brandIdVal = $('#ITP_FORM_STINFO01010_VIEW_BRAND_ID').val();
            const key = {brandId: brandIdVal, viewCd: 'R'};
            var param = $.param(key);
            modifyObj.load(param);
        }
    },
    load: function(param) {
        fn_ajax_call(API_DETAIL_INFO, param, this.callback, 'GET');
    },
    callback: function (result) {
        console.log(result);
        pageObj.switchScreen('MODIFY');
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_VIEW_CD').val('U');

        $('#ITP_FORM_STINFO01010_DETAIL .fnBrandId').text(result.brandId);
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_BRANDP_ID').val(result.brandId);
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_ST_CD').val(result.stCd);
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_BRAND_NM').val(result.brandNm);
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_BRAND_TYPE').val(result.brandType);
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_BSNS_REG_NO').val(result.bsnsRegNo);
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_CORP_REG_NO').val(result.corpRegNo);
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_TEL_NO').val(result.telNo);
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_FAX_NO').val(result.faxNo);
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_EMAL_ADDR').val(result.emalAddr);
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_DPST_BNK_CD').val(result.dpstBnkCd);
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_RCV_ACCT_NO').val(result.acctNo);
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_OWAC_NM').val(result.owacNm);
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_ZIPNO').val(result.zipNo);
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_LOAD_ADDR').val(result.addr1);
        $('#ITP_FORM_STINFO01010_DETAIL #ITP_FORM_STINFO01010_DETAIL_DTL_ADDR').val(result.addr2);

        $('#ITP_FORM_STINFO01010_DETAIL .fnAddDt').text(result.sysRegDttm);
        $('#ITP_FORM_STINFO01010_DETAIL .fnChgDt').text(result.sysChgDttm);

        let locate = result.addr1 + ' ' + result.addr2;
        kakaoMap.init('ITP_FORM_STINFO01010_DETAIL_MAP', locate);

    }
};

/*신규화면 Object*/
let createObj = {
    init: function () {
        pageObj.fileUpload();
        $('#ITP_FORM_STINFO01010_DETAIL_BRAND_ID').val(fn_make_user_info.get('brandId'));
        kakaoMap.init('ITP_FORM_STINFO01010_DETAIL_MAP', '');
    },
    button: {
        address: function() {
            new daum.Postcode({
                oncomplete: function(data) {
                    // 전체주소 리턴
                    document.getElementById('ITP_FORM_STINFO01010_DETAIL_ZIPNO').value = data.zonecode;
                    document.getElementById('ITP_FORM_STINFO01010_DETAIL_ADRES').value = data.roadAddress;
                    document.getElementById('ITP_FORM_STINFO01010_DETAIL_LOTS_ADDRESS').value = !!data.autoJibunAddress ? data.autoJibunAddress : data.jibunAddress;
                    document.getElementById('ITP_FORM_STINFO01010_DETAIL_STREET_ADDRESS').value = data.roadAddress;
                    document.getElementById('ITP_FORM_STINFO01010_DETAIL_HJ_DONG').value = !!data.hname ? data.hname : data.bname;
                    document.getElementById('ITP_FORM_STINFO01010_DETAIL_BJ_DONG').value = data.bname;

                    kakaoMap.init('ITP_FORM_STINFO01010_DETAIL_MAP', data.roadAddress);
                    document.getElementById('ITP_FORM_STINFO01010_DETAIL_ADRES_DTL').focus();
                }
            }).open();
        },
        save: function() {
            const formId = '#ITP_FORM_STINFO01010_DETAIL';
            itp_fn_form_clear_validate(null, formId);

            if (createObj.isValid(formId)) {
                if (ITP_FORM_STINFO01010_DETAIL_IS_DUPLICATE) {
                    itp_fn_modal_duplicate(ITP_MSG_LOCALE.label.brandId, formId + '_BRAND_ID');
                } else {
                    let param = $(formId).serializeObject();

                    var searhFn = function() {
                        ITP_FORM_STINFO01010_DETAIL_IS_WRITING = false;
                        listObj.grid.search();
                    };
                    fn_ajax_call(API_DETAIL_SAVE, JSON.stringify(param), searhFn, 'POST');
                }
            }
        },
        cancel: function () {
            listObj.grid.search();
        }
    }
};
