
// 업무리스트 분류 선택
$(document).ready(function () {

    /* 업무일지 등록*/
    $('.plan-register').on("click",function(){
        var formData = new FormData($('#dailyTaskInput')[0]);
        let formType = $(this).attr('id');
        formData.append("mod", formType);

        if(!$("#pln_title").val()){
            alert('업무내용을 입력해 주세요.');
            $("#pln_title").focus();
            return;
        }

        // 파일첨부
        for (var i = 0; i < filesArr.length; i++) {
            // 삭제되지 않은 파일만 폼데이터에 담기
            if (!filesArr[i].is_delete) {
                formData.append("attach_file[]", filesArr[i]);
            }
        }

        // 로딩바
        $('#status').fadeIn();
        $('#preloader').delay(200).fadeIn();


        $.ajax({
            cache : false,
            url : "/html/process.html", // 요기에
            type : 'POST',
            async: true,
            data : formData,
            contentType: false,
            processData: false,
            headers: {'cache-control': 'no-cache', 'pragma': 'no-cache'},
            success : function(data) {
                if(data=='Success' || data == 'Auth'){
                    top.opener.location.reload();
                    self.close();
                }
                else {
                    alert(data);
                    $('#status').fadeOut();
                    $('#preloader').delay(200).fadeOut();
                }
            }, // success

            error : function(xhr, status) {
                alert(xhr + " : " + status);
            }
        }); // $.ajax */
    })

    /* 업무일지 등록 팝업*/
    $('.task-reg').on("click",function(){
        let plan_task_idx = $(this).data('idx');
        let month = $(this).data('month');
        popPlanTask(plan_task_idx,month);
    })

    /* 업무일지 수정 팝업*/
    $('.task-modify').on("click",function(){
        let plan_task_idx = $(this).data('idx');
        popPlanTask(plan_task_idx);
    })


    /* 업무일지 삭제*/
    $('.btn-delete').on("click",function(){
        let plan_task_idx = $(this).data('idx')
        let refpage = '/plan/daily.html';

        if(!plan_task_idx){
            alert('업무관리번호가 없습니다.');
            return;
        }

        if(!confirm('해당 업무를 삭제 하시겠습니까?')) return;

        $.ajax({
            cache : false,
            url : "/html/process.html",
            type : 'POST',
            data : {plan_task_idx:plan_task_idx,mod:'del',refpage:refpage },
            success : function(data) {
                if(data=='Success') location.reload();
                else alert(data);
            }, // success

            error : function(xhr, status) {
                alert(xhr + " : " + status);
            }
        }); // $.ajax */
    })


    /* 업무일지 완료처리*/
    $('.btn-complete').on("click",function(){
        let plan_task_idx = $(this).data('idx')
        let refpage = '/plan/daily.html';

        if(!plan_task_idx){
            alert('업무관리번호가 없습니다.');
            return;
        }

        if(!confirm('해당업무를 완료 하시겠습니까?')) return;

        $.ajax({
            cache : false,
            url : "/html/process.html",
            type : 'POST',
            data : {plan_task_idx:plan_task_idx,PLN_STATUS:'01',mod:'complete',refpage:refpage },
            success : function(data) {
                if(data=='Success') location.reload();
                else alert(data);
            }, // success

            error : function(xhr, status) {
                alert(xhr + " : " + status);
            }
        }); // $.ajax */
    })


    /* 반복업무 완료처리*/
    $('.btn-repeat').on("click",function(){
        let plan_task_idx = $(this).data('idx')
        let refpage = '/plan/daily.html';

        if(!plan_task_idx){
            alert('업무관리번호가 없습니다.');
            return;
        }

        if(!confirm('해당 반복업무를 완료 하시겠습니까?')) return;

        $.ajax({
            cache : false,
            url : "/html/process.html",
            type : 'POST',
            data : {plan_task_idx:plan_task_idx,PLN_STATUS:'01',mod:'repeat',refpage:refpage },
            success : function(data) {
                if(data=='Success') location.reload();
                else alert(data);
            }, // success

            error : function(xhr, status) {
                alert(xhr + " : " + status);
            }
        }); // $.ajax */
    })


    /* 추가진행현황 삭제 */
    $('.add-del').on("click",function(){
        let task_idx = $(this).data('idx');
        let parent = $(this).parent();
        let refpage = '/plan/daily.html';

        if(!task_idx){
            alert('업무관리번호가 없습니다.');
            return;
        }

        if(!confirm('해당 업무를 삭제 하시겠습니까?')) return;

        $.ajax({
            cache : false,
            url : "/html/process.html",
            type : 'POST',
            data : {task_idx:task_idx,mod:'add-del',refpage:refpage },
            success : function(data) {
                if(data=='Success') {
                    parent.remove();
                    opener.location.reload();
                }
                else alert(data);
            }, // success

            error : function(xhr, status) {
                alert(xhr + " : " + status);
            }
        }); // $.ajax */
    })


    /* 추가진행현황 추가 */
    $('#add-reg').on("click",function(){
        let task_idx = $(this).data('idx')
        let add_dttm = $('#add_dttm').val();
        let content = $('#add_content').val();
        let refpage = '/plan/daily.html';


        if(!task_idx){
            alert('업무관리번호가 없습니다.');
            return;
        }
        if(!content){
            return;
        }

        $.ajax({
            cache : false,
            url : "/html/process.html",
            type : 'POST',
            data : {task_idx:task_idx,add_dttm:add_dttm,add_content:content,mod:'add-reg',refpage:refpage },
            success : function(data) {
                if(data){
                    dataJson = JSON.parse(data);

                    let addHtml = "";
                    addHtml += "<div style=\"padding-top:5px;\">";
                    addHtml += "    <span style=\"color:black;font-weight: bold\">"+dataJson.ADD_DTTM+"</span> &nbsp;&nbsp; - &nbsp;&nbsp; "+dataJson.ADD_CONTENTS;
                    addHtml += "</div>";
                    $("#addBox").append(addHtml);
                    $('#add_dttm').val('');
                    $('#add_content').val('');
                    opener.location.reload();
                }
                else alert(data);
            }, // success

            error : function(xhr, status) {
                alert(xhr + " : " + status);
            }
        }); // $.ajax */
    })



    /* 작업자 삭제 */
    $(document).on('click', '.delWorker',function(e) {
        //해당 작업자 삭제
        $(this).parent().parent().remove();
    });

    /* 세부항목 추가 */
    var trLen = $('#worker_table > tbody > tr').length;
    $('.addWorker').on("click",function(){

        // 추가
        let workStatusId = $("#work-status-id").val();
        let workStatusVal = $("#work-status-val").val();
        let optionsId = workStatusId.split(',');
        let optionsVal = workStatusVal.split(',');

        let setHtml = '';
        setHtml += '<tr>';
        setHtml += '    <td>';
        setHtml += '        <input type="hidden" name="WB_NO[_N_]">';
        setHtml += '        <input class="form-control pull-left border-input databox" style="width:100%;" type="text" name="WORK_BRANCH[_N_]">';
        setHtml += '    </td>';
        setHtml += '    <td>';
        setHtml += '        <select class="form-control pull-left border-input databox" name="WORK_BRANCH_STATUS[_N_]">';
        for(let i=0;i<optionsId.length;i++) {
            setHtml += '            <option value="' + optionsId[i] + '">' + optionsVal[i] + '</option>';
        };
        setHtml += '        </select>';
        setHtml += '    </td>';
        setHtml += '    <td>';
        setHtml += '        <button type="button" class="btn btn-small btn-default delWorker" style="width:30px;margin: 1px;"> -';
        setHtml += '        </button>';
        setHtml += '    </td>';
        setHtml += '</tr>';

        setHtml = setHtml.replace(/_N_/g, trLen);

        //해당 작업자 추가
        $('#worker_table > tbody').append(setHtml);
        // datepicker 활성화
        $(".datepicker").datepicker({dateFormat: 'yy-mm-dd'});
        trLen++;
    })



    /* 기간 항시업무 설정 */
    $('#always').on("click",function(){
        let status = $(this).is(':checked');
        if(status){
            $("#REQ_DT").attr("disabled",true);
            $("#RFL_DT").attr("disabled",true);
            $('#no-limit').attr("disabled",true);
        }else{
            $("#REQ_DT").attr("disabled",false);
            $("#RFL_DT").attr("disabled",false);
            $('#no-limit').attr("disabled",false);
        }

    })
    /* 기간 미정 설정 */
    $('#no-limit').on("click",function(){
        let status = $(this).is(':checked');
        if(status){
            $("#RFL_DT").attr("disabled",true);
        }else{
            $("#RFL_DT").attr("disabled",false);
        }

    })



    /* 댓글 삭제 */
    $(document).on("click",'.cmt-del',function(){
        let cmt_idx = $(this).data('idx');
        let parent = $(this).parent();
        let refpage = '/plan/work_reg.html';

        if(!cmt_idx){
            alert('업무관리번호가 없습니다.');
            return;
        }

        if(!confirm('댓글을 삭제 하시겠습니까?')) return;

        $.ajax({
            cache : false,
            url : "/html/process.html",
            type : 'POST',
            data : {cmt_idx:cmt_idx,mod:'cmt-del',refpage:refpage },
            success : function(data) {

                if(data=='Success') {
                    parent.remove();
                }
                else alert(data);
            }, // success

            error : function(xhr, status) {
                alert(xhr + " : " + status);
            }
        }); // $.ajax */
    })

    /* 업무 : 댓글 등록 */
    $('#cmt-reg').on("click",function(){
        let task_idx = $(this).data('idx');
        let content = $('#cmt-content').val();
        let refpage = '/plan/work_reg.html';


        if(!task_idx){
            alert('업무관리번호가 없습니다.');
            return;
        }
        if(!content){
            return;
        }

        $.ajax({
            cache : false,
            url : "/html/process.html",
            type : 'POST',
            data : {task_idx:task_idx,cmt_content:content,mod:'cmt-reg',refpage:refpage },
            success : function(data) {
                if(data){
                    dataJson = JSON.parse(data);
                    console.log(dataJson);

                    let addHtml = "";
                    addHtml += "<div style=\"padding:5px 10px;\">";
                    addHtml += dataJson.CMT_NAME + " &nbsp;&nbsp; : &nbsp;&nbsp; " + dataJson.CMT_CONTENTS + " &nbsp;&nbsp; - &nbsp; " + dataJson.CMT_DTTM ;
                    addHtml += '<span class="btn-tiny btn-warning cmt-del" style="margin-left: 5px; line-height: 15px;" data-idx="' + dataJson.CMT_NO + '"> X </span>';
                    addHtml += "</div>";
                    $("#cmtBox").prepend(addHtml);
                    $('#cmt-content').val('');
                }
                else alert(data);
            }, // success

            error : function(xhr, status) {
                alert(xhr + " : " + status);
            }
        }); // $.ajax */
    })

});