require(['config'], function() {
    require([
        'kakao.map.util'
    ], function($) {
        pageObj.init();
    });
});

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

/*화면 변수*/
const OPER04010_GRID_ID     = '#ITP_OPER04010_jqGrid';
const OPER04010_GRID_LIST   = '#ITP_OPER04010_jqGrid_list';
const OPER04010_GRID_PAGER  = '#ITP_OPER04010_jqGridPager';
const OPER04010_GRID_EMPTY  = '#ITP_OPER04010_jqGridEmpty';

let ITP_FORM_OPER04010_DETAIL_IS_DUPLICATE = false;
let ITP_FORM_OPER04010_DETAIL_IS_WRITING = false;

/*API URL*/
let API_DETAIL_GRID_LIST        = '/api/srep/detail-grid-list';
let API_DETAIL_INFO             = '/api/srep/info-salemgr';
let API_DETAIL_SAVE             = '/api/srep/save-salemgr';
let API_CHECK_DUPLICATE         = '/api/srep/check-duplicate';
let API_INTI_USERPW             = '/api/srep/inti-salemgrpw';

/*화면 Grid Object*/
const gridColModel = {
    list: [
        {
            index: 'SALE_MGR_ID', name: 'saleMgrId',
            label: '영업담당자ID',
            width: '6', fixed: false, align: 'left',
            sortable: false, hidden: false
        },
        {
            index: 'SALE_MGR_NM', name: 'saleMgrNm',
            label: '영업담당자명',
            width: '10', fixed: false, align: 'left',
            sortable: false, hidden: false
        },
        {
            index: 'SALES_TYPE_NM', name: 'saleTypeNm',
            label: '영업타입',
            width: '6', fixed: false, align: 'center',
            sortable: false, hidden: false
        },
        {
            index: 'ST_NM', name: 'stNm',
            label: '상태',
            width: '6', fixed: false, align: 'center',
            sortable: false, hidden: false
        },
        {
            index: 'REG_DT', name: 'regDt',
            label: '가입일자',
            width: '8', fixed: false, align: 'center',
            sortable: false, hidden: false
        }
    ]
};

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

            // 공통코드 표시
            $('select').each(function() {
                if($(this).data('select-code')) {
                    fn_make_select(CODE_LIST, $(this).data('select-code'), $(this).attr('id'));
                }
            });

            // 조회일자 지정
            var now = new Date();
            $('#ITP_TAB_OPER04010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
            $('#ITP_FORM_OPER04010_SEARCH_FROM_DT').datepicker('setDate', new Date(now.setMonth(now.getMonth() - 1)));
            $('#ITP_FORM_OPER04010_SEARCH_TO_DT').datepicker('setDate', new Date());

            itp_fn_form_event.onKeyup('#ITP_FORM_OPER04010_DETAIL');

            // form alert message 주입
            $('input[data-alert-required="ONLYCHK"]').each(function() {
                if($(this).data('alert-msg') === 'address') {
                    $(this).data('alert-msg', ITP_MSG_LOCALE.message.form.emptyAddr);
                }
            });
        },
        form: function() {
    		itp_fn_form_event.onKeyup('#ITP_FORM_OPER04010_DETAIL');
    	},
        grid: function() { 
        },
        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_OPER04010_SRH'				: listObj.button.search();		break;	// 조회 버튼 클릭
                        case 'ITP_BTN_OPER04010_NEWREG'				: listObj.button.create(); 		break;	// 신규등록 버튼
                        case 'ITP_BTN_OPER04010_MODIFY'				: modifyObj.button.modify();	break;	// 수정 버튼
                        case 'ITP_BTN_OPER04010_CANCELLIST'			: listObj.search(); 	        break;	// 취소/목록 버튼
                        case 'ITP_BTN_OPER04010_DELETE'				: 								break;	// 삭제 버튼
                        case 'ITP_BTN_OPER04010_SAVE'				: createObj.button.save(); 		break;	// 저장 버튼
                        case 'ITP_BTN_OPER04010_RESET_PW'			: createObj.button.resetPass();	break;	// 상세:비밀번호 초기화
                        case 'ITP_FORM_OPER04010_DETAIL_DUP'		: createObj.button.duplicate();	break;	// 중복체크
                        case 'ITP_FORM_OPER04010_DETAIL_ADRES_SCH'	: createObj.button.address();	break;	// 신규등록 주소 찾기
                    }
                });
            });
        }
    },
    switchScreen: function(mode) {
        $('.itp_det_head').find('button[id^="ITP_BTN_OPER04010_"]').each(function(i) {
            $(this).hide();
        });
        $('#ITP_TAB_OPER04010').find('div[id$="_CONTAINER"]').each(function(i) {
            $(this).hide();
        });
        if(mode == 'LIST') { // 목록
            itp_fn_fire_window_resize();
            fn_show_btn_auth_array(['#ITP_BTN_OPER04010_SRH', '#ITP_BTN_OPER04010_NEWREG']);
            $('#ITP_AJAX_OPER04010_LIST_CONTAINER').show();
        } else if(mode == 'ADD') { // 등록
            ITP_FORM_OPER04010_DETAIL_IS_DUPLICATE = true;
            $('#ITP_AJAX_OPER04010_DETAIL_CONTAINER').show();
            fn_show_btn_auth_array(['#ITP_BTN_OPER04010_CANCELLIST', '#ITP_BTN_OPER04010_SAVE']);

            $('#ITP_FORM_OPER04010_DETAIL_SALE_MGR_ID').removeAttr('readonly');
            $('#ITP_FORM_OPER04010_DETAIL_DUP').removeAttr('disabled');

            $('.itp_modify_dt').hide();
			$('#ITP_FORM_OPER04010_DETAIL .itp_form_info').hide();
			$('#ITP_FORM_OPER04010_DETAIL .itp_form_change').show();

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

            $('#ITP_FORM_OPER04010_DETAIL_USER_PW').data('check-required', 'empty');
            $('#ITP_FORM_OPER04010_DETAIL_USER_PW_CONFIRM').data('check-required', 'empty');
            $('#ITP_FORM_OPER04010_DETAIL_EMAL_ADDR').data('check-required', 'empty');
        } else if(mode == 'MODIFY') { // 수정
            $('#ITP_AJAX_OPER04010_DETAIL_CONTAINER').show();
            fn_show_btn_auth_array(['#ITP_BTN_OPER04010_CANCELLIST', '#ITP_BTN_OPER04010_SAVE', '#ITP_BTN_OPER04010_RESET_PW']);

            $('.itp_modify_dt').show();
            $('.title').css({"border-bottom": "1px solid #ddd"});
			$('#ITP_FORM_OPER04010_DETAIL .itp_form_info').show();
			$('#ITP_FORM_OPER04010_DETAIL .itp_form_change').hide();

            $('#ITP_FORM_OPER04010_DETAIL_SALE_MGR_ID').attr('readonly', true);
            $('#ITP_FORM_OPER04010_DETAIL_DUP').attr('disabled', true);

            $('#ITP_FORM_OPER04010_DETAIL_USER_PW').data('check-required', '');
            $('#ITP_FORM_OPER04010_DETAIL_USER_PW_CONFIRM').data('check-required', '');
            $('#ITP_FORM_OPER04010_DETAIL_EMAL_ADDR').data('check-required', '');
        } else if(mode == 'VIEW') { // 보기
            $('#ITP_AJAX_OPER04010_VIEW_CONTAINER').show();
            fn_show_btn_auth_array(['#ITP_BTN_OPER04010_MODIFY', '#ITP_BTN_OPER04010_CANCELLIST']);
        }
    }
};

/*목록화면 Object*/
let listObj = {
    init: function () {
        itp_fn_jqgrid_resize(OPER04010_GRID_ID, OPER04010_GRID_LIST, 'lg');
        this.search();
    },
    itp_OPER04010_param: {},
    itp_OPER04010_search: false,
    button: {
        search: function() {
            listObj.itp_OPER04010_search = true;
            let param = $('#ITP_FORM_OPER04010_SEARCH').serializeObject();
            param.gridSize = $.jgrid.defaults.rowNum;
            param.gridPage = $.jgrid.defaults.page;
            $(OPER04010_GRID_ID).data('grid-param',param);
            $(OPER04010_GRID_ID).setGridParam({'postData': JSON.stringify(param)}).trigger('reloadGrid');
        },
        create: function() {
            pageObj.switchScreen('ADD');
            itp_fn_form_clear_validate(null, '#ITP_FORM_OPER04010_DETAIL');
            kakaoMap.init('ITP_FORM_OPER04010_DETAIL', '');
        }
    },
    search: function() {
        pageObj.switchScreen('LIST');
        this.grid.init();
    },
    grid: {
        init: function () {
            this.unload();
            this.load();
        },
        colModel: gridColModel.list,
        load: function() {
            let param = $('#ITP_FORM_OPER04010_SEARCH').serializeObject();
            param.gridSize = $.jgrid.defaults.rowNum;

            var option = {
                gridId: OPER04010_GRID_ID,
                colModel: gridColModel.list,
                param: param,
                url: DOMAIN + API_DETAIL_GRID_LIST,
                pager: OPER04010_GRID_PAGER,
                onCellSelect: function(rowId, cellIdx, cellValue) {
                    var cm = $(this).jqGrid('getGridParam', 'colModel');
                    var colNm = cm[cellIdx].name;
                    if (colNm == 'saleMgrNm') {
                        const saleMgrIdVal = $(this).jqGrid('getCell', rowId, 'saleMgrId');
                        const key = {saleMgrId: saleMgrIdVal, viewCd: 'R'};
                        var param = $.param(key);
                        viewObj.init(param);
                    }
                },
                loadComplete: function(data) {
                    // console.log(data);
                    itp_fn_grid_load_complete(data, OPER04010_GRID_ID, true, 'number', 'OPER04010', listObj.itp_OPER04010_search, listObj.empty, true, data.gridRecords, true);
                    var ids = $(OPER04010_GRID_ID).getDataIDs();
                    $.each(ids, function(idx, rowId) {
                        $(OPER04010_GRID_ID).jqGrid('setCell', rowId, 'saleMgrNm', '', ITP_GRID_COL_STYLE.link);
                    });
                },
                onPaging: function(action) {
                    itp_fn_grid_paging(OPER04010_GRID_ID, action, param);
                }
            };
            itp_fn_grid_make_remote(option);
        },
        reload : function() {
        },
        clearData : function() {
            $(OPER04010_GRID_ID).jqGrid('clearGridData', true);
            $(OPER04010_GRID_LIST).find('.ui-jqgrid-bdiv').css('min-height', '100px');
            $(OPER04010_GRID_EMPTY).html(ITP_MSG_LOCALE.message.grid.noData);
            $(OPER04010_GRID_EMPTY).show();
        },
        unload : function() {
            $.jgrid.gridUnload(OPER04010_GRID_ID);
        }
    },
    empty: {
        init: function() {
        },
        push: function() {
        },
        back: function() {
        }
    }
};

/*상세화면 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_OPER04010_VIEW #ITP_FORM_OPER04010_VIEW_SALE_MGR_ID').val(result.saleMgrId);
        $('#ITP_FORM_OPER04010_VIEW .fnSaleMgrId').text(result.saleMgrId);
        $('#ITP_FORM_OPER04010_VIEW .fnSaleMgrNm').text(result.saleMgrNm);
        $('#ITP_FORM_OPER04010_VIEW .fnSaleType').text(result.saleTypeNm);
        $('#ITP_FORM_OPER04010_VIEW .fnStCd').text(result.stNm);
        $('#ITP_FORM_OPER04010_VIEW .fnTelNo').text(result.rprstTelNo);
        $('#ITP_FORM_OPER04010_VIEW .fnFaxNo').text(result.rprstFaxNo);
        $('#ITP_FORM_OPER04010_VIEW .fnEmail').text(result.rprstEmal);
        $('#ITP_FORM_OPER04010_VIEW .fnZipNo').text(result.zipNo);
        $('#ITP_FORM_OPER04010_VIEW .fnLoadAddr').text(result.addr1);
        $('#ITP_FORM_OPER04010_VIEW .fnDtlAddr').text(result.addr2);

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

        var adres = result.addr1 + ' ' + result.addr2;
        kakaoMap.init('ITP_FORM_OPER04010_VIEW', adres);
    }
};

/*수정화면 Object*/
let modifyObj = {
    init: function (param) {
    },
    button: {
        modify: function (param) {
            itp_fn_form_clear_validate(null, '#ITP_FORM_OPER04010_DETAIL');
            const saleMgrIdVal = $('#ITP_FORM_OPER04010_VIEW_SALE_MGR_ID').val();
            const key = {saleMgrId: saleMgrIdVal, 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_OPER04010_DETAIL #ITP_FORM_OPER04010_DETAIL_VIEW_CD').val('U');
        $('#ITP_FORM_OPER04010_DETAIL #ITP_FORM_OPER04010_DETAIL_SALE_MGR_ID').val(result.saleMgrId);

        $('#ITP_FORM_OPER04010_DETAIL .fnSaleMgrId').text(result.saleMgrId);
        $('#ITP_FORM_OPER04010_DETAIL #ITP_FORM_OPER04010_DETAIL_SALE_MGR_NM').val(result.saleMgrNm);
        $('#ITP_FORM_OPER04010_DETAIL #ITP_FORM_OPER04010_DETAIL_SALES_TYPE_CD').val(result.saleType);
        $('#ITP_FORM_OPER04010_DETAIL #ITP_FORM_OPER04010_DETAIL_USE_STAT_CD').val(result.stCd);
        $('#ITP_FORM_OPER04010_DETAIL #ITP_FORM_OPER04010_DETAIL_TEL_NO').val(result.rprstTelNo);
        $('#ITP_FORM_OPER04010_DETAIL #ITP_FORM_OPER04010_DETAIL_FAX_NO').val(result.rprstFaxNo);
        $('#ITP_FORM_OPER04010_DETAIL #ITP_FORM_OPER04010_DETAIL_EMAL_ADDR').val(result.rprstEmal);

        $('#ITP_FORM_OPER04010_DETAIL #ITP_FORM_OPER04010_DETAIL_ZIPNO').val(result.zipNo);
        $('#ITP_FORM_OPER04010_DETAIL #ITP_FORM_OPER04010_DETAIL_ADRES').val(result.addr1);
        $('#ITP_FORM_OPER04010_DETAIL #ITP_FORM_OPER04010_DETAIL_ADRES_DTL').val(result.addr2);

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

        kakaoMap.init('ITP_FORM_OPER04010_DETAIL', $('#ITP_FORM_OPER04010_DETAIL_ADRES').val());
    }
};

/*신규화면 Object*/
let createObj = {
    init: function () {
    },
    button: {
        duplicate: function() {
            const formId = '#ITP_FORM_OPER04010_DETAIL';
            itp_fn_form_clear_validate(null, formId);
            var vali_salesUserId = itp_fn_form_validate(formId, formId + '_TMP_SALE_MGR_ID', ['empty'], undefined);
            if (vali_salesUserId) {
                var dupFn = function(result) {
                    if (result.code == 'N') {
                        ITP_FORM_OPER04010_DETAIL_IS_DUPLICATE = false;
                        $(formId + '_SALE_MGR_ID').val($(formId + '_TMP_SALE_MGR_ID').val());
                    } else {
                        ITP_FORM_OPER04010_DETAIL_IS_DUPLICATE = true;
                    }
                };
                const key = {'saleMgrId':  $(formId + '_TMP_SALE_MGR_ID').val()};
                const param = $.param(key);
                fn_ajax_call(API_CHECK_DUPLICATE, param, dupFn, 'GET');
            }
        },
        resetPass: function() {
            var resetPwFn = {
                callBack: function(args) {
                    const key = {'saleMgrId':  $('#ITP_FORM_OPER04010_DETAIL_SALE_MGR_ID').val()};
                    const param = $.param(key);
                    fn_ajax_call(API_INTI_USERPW, param, undefined, 'GET');
                }
            };
            itp_fn_modal_confirm(ITP_MSG_LOCALE.message.ajax.askResetUserPw, resetPwFn, null);
        },
        address: function() {
            new daum.Postcode({
                oncomplete: function(data) {
                    // 전체주소 리턴
                    // console.log(data);
                    document.getElementById('ITP_FORM_OPER04010_DETAIL_ZIPNO').value = data.zonecode;
                    document.getElementById('ITP_FORM_OPER04010_DETAIL_ADRES').value = data.roadAddress;
                    document.getElementById('ITP_FORM_OPER04010_DETAIL_LOTS_ADDRESS').value = !!data.autoJibunAddress ? data.autoJibunAddress : data.jibunAddress;
                    document.getElementById('ITP_FORM_OPER04010_DETAIL_STREET_ADDRESS').value = data.roadAddress;
                    document.getElementById('ITP_FORM_OPER04010_DETAIL_HJ_DONG').value = !!data.hname ? data.hname : data.bname;
                    document.getElementById('ITP_FORM_OPER04010_DETAIL_BJ_DONG').value = data.bname;

                    kakaoMap.init('ITP_FORM_OPER04010_DETAIL', data.roadAddress);
                    document.getElementById('ITP_FORM_OPER04010_DETAIL_ADRES_DTL').focus();
                }
            }).open();
        },
        save: function() {
            const formId = '#ITP_FORM_OPER04010_DETAIL';
            itp_fn_form_event.removeChar('#ITP_FORM_OPER04010_DETAIL');
            itp_fn_form_clear_validate(null, formId);

            if (itp_fn_form_event.isValid(formId)) {
                if($(formId + ' #ITP_FORM_OPER04010_DETAIL_USER_PW').val() !== $(formId + ' #ITP_FORM_OPER04010_DETAIL_USER_PW_CONFIRM').val()) {
                    var element = '#ITP_FORM_OPER04010_DETAIL_USER_PW';
                    $(element).closest('.itp_ip').addClass('has-error');
                    var error_msg = $('<span class="help-block">' + ITP_MSG_LOCALE.message.form.wrongPwd + '</span>');
                    error_msg.insertAfter($(element));
                    return;
                }
                if (ITP_FORM_OPER04010_DETAIL_IS_DUPLICATE) {
                    itp_fn_modal_duplicate('영업담당자 ID 중복체크를 해주세요.', formId + '_SALES_USER_ID');
                } else {
                    let param = $(formId).serializeObject();
                    var searhFn = function() {
                        ITP_FORM_OPER04010_DETAIL_IS_WRITING = false;
                        listObj.search();
                    };
                    // console.log(JSON.stringify(param));
                    fn_ajax_call(API_DETAIL_SAVE, JSON.stringify(param), searhFn, 'POST');
                }
            }
        }
    }
};
