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: 'center',
            sortable: false, hidden: false
        },
        {
            index: 'SALE_MGR_NM', name: 'saleMgrNm',
            label: '영업담당자명',
            width: '10', fixed: false, align: 'center',
            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.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'));
                }
            });

            // 조회일자 지정
            $('#ITP_TAB_OPER04010 .input-group.date').datepicker(ITP_DATE_LANGUAGE);
        },
        grid: function() {
            itp_fn_jqgrid_resize(OPER04010_GRID_ID, OPER04010_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_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') { // 목록
            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);
                }
            });
        } 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();
			$('#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);
        } 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 () {
        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).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() {
            var _this = this;
            this.push();
            $(OPER04010_GRID_EMPTY).on('click', function() {
                _this.back();
                listObj.itp_OPER04010_param.gridSize = $.jgrid.defaults.rowNum;
                $(OPER04010_GRID_ID).setGridParam({'postData': JSON.stringify(listObj.itp_OPER04010_param)}).trigger('reloadGrid');
            });
        },
        push: function() {
            let param = $('#ITP_FORM_OPER04010_SEARCH').serializeObject();
            listObj.itp_OPER04010_param = param;
        },
        back: function() {
            $('#ITP_FORM_OPER04010_DEVI_TP_CD').val(listObj.itp_OPER04010_param.deviTpCd);
            $('#ITP_FORM_OPER04010_ORDER_YN').val(listObj.itp_OPER04010_param.orderYn);
            $('#ITP_FORM_OPER04010_ADT_AUTH_CD').val(listObj.itp_OPER04010_param.adtAuthCd);
            $('#ITP_FORM_OPER04010_EMAIL_RCV_YN').val(listObj.itp_OPER04010_param.emailRcvYn);
            $('#ITP_FORM_OPER04010_SMS_RCV_YN').val(listObj.itp_OPER04010_param.smsRcvYn);
            $('#ITP_FORM_OPER04010_MEMB_EXIT_DT').val(listObj.itp_OPER04010_param.membExitDt);
            $('#ITP_FORM_OPER04010_FROM_DT').val(listObj.itp_OPER04010_param.fromDt);
            $('#ITP_FORM_OPER04010_TO_DT').val(listObj.itp_OPER04010_param.toDt);
            $('#ITP_FORM_OPER04010_KEYWORD').val(listObj.itp_OPER04010_param.keyword);
        }
    }
};

/*상세화면 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.stCd);
        $('#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 #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 + '_DETAIL');
            var vali_salesUserId = itp_fn_form_validate(formId + '_DETAIL', formId + '_SALE_MGR_ID', ['empty'], undefined);
            if (vali_salesUserId) {
                var dupFn = function(result) {
                    if (result.code == 'N') {
                        ITP_FORM_OPER04010_DETAIL_IS_DUPLICATE = false;
                    } else {
                        ITP_FORM_OPER04010_DETAIL_IS_DUPLICATE = true;
                    }
                };
                const key = {'saleMgrId':  $(formId + '_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_clear_validate(null, formId);
            var vali_salesUserId = itp_fn_form_validate(formId, formId + '_SALE_MGR_ID', ['empty'], undefined);
            var vali_salesTypeCd = itp_fn_form_validate(formId, formId + '_SALES_TYPE_CD', ['empty'], undefined);
            var vali_useStatCd = itp_fn_form_validate(formId, formId + '_USE_STAT_CD', ['empty'], undefined);
            var vali_salesUserNm = itp_fn_form_validate(formId, formId + '_SALE_MGR_NM', ['empty'], undefined);
            var vali_telNo = itp_fn_form_validate(formId, formId + '_TEL_NO', ['empty'], undefined);
            var vali_email = itp_fn_form_validate(formId, formId + 'EMAIL', ['empty'], undefined);

            var vali_userPw = true;
            var vali_userPwConfirm = true;
            if($('#ITP_FORM_OPER04010_DETAIL_VIEW_CD').val() == 'C') { // 신규
                vali_userPw = itp_fn_form_validate(formId, formId + '_USER_PW', ['empty'], undefined);
                vali_userPwConfirm = itp_fn_form_validate(formId, formId + '_USER_PW_CONFIRM', ['empty'], undefined);
            }

            if (vali_salesUserId && vali_salesTypeCd && vali_useStatCd && vali_salesUserNm && vali_userPw && vali_userPwConfirm && vali_telNo && vali_email) {

                if($('#ITP_FORM_OPER04010_DETAIL_ZIPNO').val() == '' || $('#ITP_FORM_OPER04010_DETAIL_ADRES').val() == '') {
                    itp_fn_modal_alert('주소 검색을 통해 회사 주소를 입력하세요.');
                    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');
                }
            }
        }
    }
};
