(()=>{
    'use strict';

    window.G = window.G||{};

    $(()=>{

        // 공지사항 알림 발송
        $('.sub_cont .board_list').on('click', 'span.edit>.btn-send', (e) => {
            e.stopPropagation();

            sendNoticeAlarm($(e.currentTarget).closest('a.type-notice').data('uid')); 
        });

        //공지사항 수정
        $('.sub_cont .board_list').on('click', 'span.edit>.btn-edit', (e) => {
            e.stopPropagation();
            $('.foot_btn .foot_btn_back_history').data('target', 'list');
            $('.foot_btn .foot_btn_back_history').data('uid', '');
            openEditNotice($(e.currentTarget).closest('a.type-notice').data('uid'));
        });

        //공지사항 삭제
        $('.sub_cont .board_list').on('click', 'span.edit>.btn-delete', (e) => {
            e.stopPropagation();
            deleteNotice($(e.currentTarget).closest('a.type-notice').data('uid'), function(notice_id){
                $(`.board_list>li:has(a[data-uid=${notice_id}])`).remove();
            });
        });

        //공지알림대상
        $('.board_edit input[type=radio][name=edit_notice_target]').on('change', (e) =>{
            if($(e.currentTarget).val() == 'DEPT'){
				$('#btn_edit_open_dept, .edit_trgt_dept').removeClass('none')
            }else{
				$('#btn_edit_open_dept, .edit_trgt_dept').addClass('none');
            }
        });
    });

    // 공지사항 알림 발송
    function sendNoticeAlarm(notice_id, callback){
        popConfirm('해당 공지를 발송하시겠습니까?', function(){
            requestAstro(`${server_host}/astroapi/mdial/v1/notice/alarm/send`, {notice_id : notice_id}, 'post')
            .then(response => {
                console.log('sendNoticeAlert',"공지사항 발송 성공" , response);
                popAlert("발송되었습니다.", callback);
            })
            .catch(reason => {
                console.log('sendNoticeAlert',"공지사항 발송 실패" , reason);
                popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
            });
        });
    }

    function deleteNotice(notice_id, callback){
        popConfirm('삭제하시겠습니까?\n삭제한 데이터는 복구 할 수 없습니다.', function(){
            requestAstro(`${server_host}/astroapi/notice/v1/notice/${notice_id}`, {}, 'delete')
            .then(response => {
                console.log('deleteNotice',"공지사항 삭제 성공" , response);
                if(callback) callback(notice_id);
                popAlert("삭제되었습니다.");
            })
            .catch(reason => {
                console.log('deleteNotice',"공지사항 삭제 실패" , reason);
                popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
            });
        })
    }

    function openEditNotice(notice_id){

        function drawEditNotice(data){

            $('.view_cont .for_board_edit').removeClass('none');
            $('.view_cont .for_board_view').addClass('none');
            $('.foot_btn .foot_btn_save').data("notice_uid", notice_id||'');
            $('.for_board_edit .edit_trgt_dept').empty();

            $('#edit_board_title').val(data?.title||'');

            if(data){
                let start_time = data.start_time?gformatter.date(new Date(data.start_time),'y.M.d'):'',
                    end_time = data.end_time?gformatter.date(new Date(data.end_time),'y.M.d'):''
                ;
                $('#edit_board_term').text(`${start_time} ~ ${end_time}`);
                $('#term_pop_start_date').val(`${start_time} `)
                $('#term_pop_end_date').val(`${end_time} `)
                
                if((data.start_time == undefined || data.start_time == '') && (data.end_time == undefined || data.  end_time == '')){
                    $('#term_pop_limitless').prop('checked', true).trigger('change');
                }
            }else{
                setNoticeTermDefault()
            }

            $(`div.board_edit input[type=radio][name=edit_notice_type][value=${data?.category||'N'}]`).prop('checked', true);

            $(`div.board_edit input[type=radio][name=edit_notice_target][value=${data?.trgt||'ALL'}]`).prop('checked', true).trigger('change');

            if(data?.trgt == 'DEPT'){
                let group_codes = (data.trgt_dept_codes||'').split(','), names = (data.trgt_dept_names||'').split(',');
                group_codes.forEach((groupcode, idx) => {
                    $('.for_board_edit .edit_trgt_dept').append(
                        $('#selected_notice_dept_template').text()
                        .replace(/{{group-code}}/g, groupcode)   
                        .replace(/{{name}}/g, names[idx]||'알수없음')   
                    );
                });
            }
            
            $('#edit_board_cont').empty();
            $("#edit_board_cont").summernote({minHeight: 200}).summernote('code', data?.contents||'');

            initFooter('notice_edit');
            $('.view_cont').removeClass('none');
        }

        if(notice_id){
            requestAstro(`notice/v1/notice/${notice_id}`, {}, 'get')
            .then(r => {
                console.log(`notice/v1/notice/${notice_id} response code :: `, r.code);
                
                if(r.code == '0000'){
                    drawEditNotice(r.data);
                }
            });
        }else{
            drawEditNotice();
        }
    }

    window.G = {
        ...window.G,
        openEditNotice : openEditNotice,
        sendNoticeAlarm : sendNoticeAlarm
    };

})();