/**
 * 交付模块-标准预测计划首页JS
 *
 * Created by jt on 2019/9/16.
 */
'use strict';
var el = {
    searchForm: '#searchForm',
    isSupplier: '#isSupplier',
    fileId: '#fileId',
    title: '#title',
    createName: '#createName',
    tb: '#tb',
    chooseDate: '#chooseDate',
    excelFile: '#excelFile',
    uploadBoxHtml: '#uploadBoxHtml',
    planReleaseDialog: null,
    supplierReplyDialog: null,
    purchaseConfirmDialog: null,
    byDateShowDetailDialog: null,
    lookReplyProgressDialog: null,
    bodyHeight: document.documentElement.clientHeight
};

$(function () {
    // 是否为供应商用户 1:是 0:否
    var isSupplier = $(el.isSupplier).val();
    initDataGrid(isSupplier);
    // 初始化文件上传控件
    $(el.excelFile).filebox({
        buttonText: '选择文件',
        buttonAlign: 'right',
        accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
        multiple: false,
        prompt: ''
    });
    // 获取本月的第一天
    var firstDayOfMonth = moment().startOf('month');
    // 格式化为 yyyy-MM-dd
    var formattedDate = firstDayOfMonth.format('YYYY-MM-DD');
    $("#chooseDate").datebox("setValue", formattedDate)
});


/**
 * 初始化表格
 */
function initDataGrid(isSupplier) {
    var searchHeight = $(el.searchForm).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 40, 30);

    $(el.tb).datagrid({
        loadMsg: '数据远程载入中,请等待...',
        url: g.ctx + 'pc/order/shortagePlan/rest/list',
        height: el.bodyHeight - searchHeight,
        singleSelect: true,
        rownumbers: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        columns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'id',
                    hidden: true
                },
                {
                    field: 'createTime',
                    title: itableTitlei18n.cjsj,
                    width: 170
                },
                {
                    field: 'createName',
                    title: itableTitlei18n.cjr,
                    width: 200
                },
                {
                    field: 'startTime',
                    title: itableTitlei18n.jhqsrq,
                    width: 100,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD');
                    }
                },
                {
                    field: 'endTime',
                    title: itableTitlei18n.jhjsrq,
                    width: 100,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD');
                    }
                },
                {
                    field: 'title',
                    title: itableTitlei18n.jhwj,
                    width: 250,
                    formatter: function (value, row) {
                        // if (Number(isSupplier) === 1) {
                            return value;
                        // }
                        // if (row.filePath === '') {
                        //     return '<a href="' + g.ctx + 'pc/order/shortagePlan/rest/downloadSapData?planId=' + row.id + '" target="_blank">' + value + '</a>'
                        // } else {
                        //     return '<a href="javascript:void(0);" onclick="downloadFile(this)" data-type="basic" data-pid="' + row.id + '">' + value + '</a>'
                        // }
                    }
                },
                {
                    field: 'serialNumber',
                    title: itableTitlei18n.bb,
                    width: 80
                },
                {
                    field: 'status',
                    title: itableTitlei18n.jhzt,
                    width: 120,
                    formatter: function (value) {
                        //    NEW(0, "新建"),
                        //     RELEASE(1, "已发布"),
                        //     REPLY(2, "已回复"),
                        //     INVALID(3, "失效");
                        console.log(value === 0)
                        if (value === 0) {
                            return '新建';
                        } else if (value === 1) {
                            return '已发布'
                        } else if (value === 2) {
                            return '已回复'
                        } else if (value === 3) {
                            return '失效'
                        }
                        return ''
                    }
                },
                {
                    field: 'synStatus',
                    title: '数据同步状态',
                    width: 160
                }
            ]
        ],
        toolbar: [
            // {
            //     text: handlei18n.xzmb,
            //     id: 'btn_download_temp',
            //     iconCls: 'icon-download',
            //     handler: function () {
            //         downloadTemplate();
            //         /*  var fileId =$(el.fileId).val();
            //           window.open(g.ctx + 'pc/sys/file/rest/download/'+fileId);*/
            //     }
            // },
            // '-',
            // {
            //     text: handlei18n.sc,
            //     id: 'btn_upload',
            //     iconCls: 'icon-import',
            //     handler: function () {
            //         // 打开数据导入弹框
            //         $(el.uploadBoxHtml).dialog('open');
            //     }
            // },
            // '-',
            {
                text: handlei18n.fb,
                id: 'btn_release',
                iconCls: 'icon-accept',
                handler: function () {
                    planRelease();
                }
            },
            '-',
            {
                text: handlei18n.hf,
                id: 'btn_reply',
                iconCls: 'icon-tag',
                handler: function () {
                    supplierReply();
                }
            },
            '-',
            {
                text: '采购待回复',
                id: 'btn_replace_reply',
                iconCls: 'icon-find',
                handler: function () {
                    supplierReplaceReply();
                }
            },
            '-',
            {
                text: handlei18n.ck,
                id: 'btn_look',
                iconCls: 'icon-find',
                handler: function () {
                    showDetail();
                }
            },
            '-',
            {
                text: '删除',
                id: 'btn-remove',
                iconCls: 'icon-remove',
                handler: function () {
                    deleteDetail();
                }
            }
        ],
        onBeforeLoad: function () {
            displayButtonByUserRole("shortagePlan");
        },
        onLoadSuccess: function () {
            $(el.tb).datagrid('clearSelections');
        }
    });
}

/**
 * 删除
 */

function deleteDetail() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert(itablei8n.plselect, {icon: 0});
        return false;
    }
    // if (row.status === 0) {
    //     topWin.layer.alert(tipsi18n.jhysx, {icon: 0});
    //     return false;
    // }
    // if (row.status === 1) {
        //ajax 请求删除数据

        topWin.layer.confirm(tipsi18n.sfsc, {icon: 3}, function (index) {
            $.ajax({
                url: g.ctx + 'pc/order/shortagePlan/rest/remove',
                data: {id: row.id},
                type: "POST",
                success: function (data) {
                    topWin.layer.alert("删除成功", {icon: 1}, function (idx) {
                        topWin.layer.close(idx);
                        $(el.tb).datagrid('load');
                    });
                },
                error: function (data) {
                    topWin.layer.close(idx);
                    topWin.layer.alert(data.responseJSON.message, {icon: 2});
                }
            })
        })
    // } else {
    //     topWin.layer.alert("只允许状态为新建的数据可以删除", {icon: 0});
    //     return false;
    // }
}

/**
 * 下载文件
 *
 * @param ele 当前操作DOM节点
 */
function downloadFile(ele) {
    var type = $(ele).data('type'), pid = $(ele).data('pid');
    var href = g.ctx + 'pc/order/shortagePlan/rest/download/plan/file?type=' + type + '&planId=' + pid;
    window.open(href);
}


/**
 * 查看供应商回复
 *
 * @param id 计划ID
 */
function showSupplierReply(id) {
    var url = g.ctx + 'pc/order/shortagePlan/look/reply/progress?id=' + id;
    el.lookReplyProgressDialog = openDialog('lookReplyProgress', url, {
        title: handlei18n.hfjd,
        width: '65%',
        height: '75%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            el.lookReplyProgressDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.close,
                iconCls: 'icon-cancel',
                handler: function () {
                    el.lookReplyProgressDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 计划发布
 */
function planRelease() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert(itablei8n.plselect, {icon: 0});
        return false;
    }
    if (row.status === 3) {
        topWin.layer.alert(tipsi18n.jhysx, {icon: 0});
        return false;
    }

    var url = g.ctx + 'pc/order/shortagePlan/release/adjustmentUI?id=' + row.id;
    el.planReleaseDialog = openDialog('planRelease', url, {
        title: handlei18n.fb,
        width: '100%',
        height: '100%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            el.planReleaseDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.fb,
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['planRelease'].saveReleaseData(function () {
                        // $(el.tb).datagrid('load');
                        //el.planReleaseDialog.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                iconCls: 'icon-cancel',
                handler: function () {
                    el.planReleaseDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 供应商回复
 */
function supplierReply() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert(itablei8n.plselect, {icon: 0});
        return false;
    }
    if (row.status === 0) {
        topWin.layer.alert(tipsi18n.jhysx, {icon: 0});
        return false;
    }

    var url = g.ctx + 'pc/order/shortagePlan/supplier/replyUI?id=' + row.id;
    el.supplierReplyDialog = openDialog('supplierReply', url, {
        title: itablei8n.hfqr,
        width: '100%',
        height: '100%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            el.supplierReplyDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '暂存',
                iconCls: 'icon-save',
                // hidden: true,
                handler: function () {
                    topWin.frames['supplierReply'].page.saveOrUpdate(function () {
                    });
                }
            },
            {
                text: '保存并提交',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['supplierReply'].confirmReply(function () {
                        // $(el.tb).datagrid('load');
                        // topWin.frames['supplierReply'].confirmReply();
                        //el.planReleaseDialog.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                iconCls: 'icon-cancel',
                handler: function () {
                    el.supplierReplyDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * 采购代回复
 */
function supplierReplaceReply() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert(itablei8n.plselect, {icon: 0});
        return false;
    }
    if (row.status === 0) {
        topWin.layer.alert(tipsi18n.jhysx, {icon: 0});
        return false;
    }

    var url = g.ctx + 'pc/order/shortagePlan/supplier/replyUI?isPurchaseReplace=true&id=' + row.id;
    el.supplierReplyDialog = openDialog('supplierReply', url, {
        title: itablei8n.hfqr,
        width: '100%',
        height: '100%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            el.supplierReplyDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '暂存',
                iconCls: 'icon-save',
                // hidden: true,
                handler: function () {
                    topWin.frames['supplierReply'].page.saveOrUpdate(function () {
                    });
                }
            },
            {
                text: '保存并提交',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['supplierReply'].confirmReply(function () {
                        // $(el.tb).datagrid('load');
                        // topWin.frames['supplierReply'].confirmReply();
                        //el.planReleaseDialog.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                iconCls: 'icon-cancel',
                handler: function () {
                    el.supplierReplyDialog.dialog('close');
                }
            }
        ]
    });
}


function isToday(dateString) {
    var currentDate = new Date();
    var currentYear = currentDate.getFullYear();
    var currentMonth = currentDate.getMonth() + 1; // 月份从0开始，因此需要加1
    var currentDay = currentDate.getDate();

    var yStr = dateString.substring(0,4);
    var mStr = dateString.substring(4,6);
    var dStr = dateString.substring(6,8);
    var year = parseInt(yStr, 10);
    var month = parseInt(mStr, 10);
    var day = parseInt(dStr, 10);

    if (year !== currentYear || month !== currentMonth || day !== currentDay) {
        return false;
    }
    return true;
}


/**
 * 采购确认供应商回复
 */
function purchaseConfirm() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert(itablei8n.plselect, {icon: 0});
        return false;
    }
    if (row.status === 0) {
        topWin.layer.alert(tipsi18n.jhysx, {icon: 0});
        return false;
    }

    var url = g.ctx + 'pc/order/shortagePlan/confirm/replyUI?id=' + row.id;
    el.purchaseConfirmDialog = openDialog('purchaseConfirm', url, {
        title: itablei8n.qrgyshf,
        width: '80%',
        height: '90%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            el.purchaseConfirmDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.close,
                iconCls: 'icon-cancel',
                handler: function () {
                    el.purchaseConfirmDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 明细查看
 */
function showDetail() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert(itablei8n.plselect, {icon: 0});
        return false;
    }

    var loadIndex = topWin.layer.msg(itablei8n.dataLoading, {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'pc/order/shortagePlan/rest/getReplyData',
        type: 'POST',
        data: {planId: row.id},
        success: function (res) {
            topWin.layer.close(loadIndex);
            if (!res || res.length === 0) {
                topWin.layer.alert(tipsi18n.fbsjwk, {icon: 0});
                return false;
            }
            var url = g.ctx + 'pc/order/shortagePlan/show/date?type=basic&id=' + row.id;
            el.byDateShowDetailDialog = openDialog('settingDialog', url, {
                title: handlei18n.ck,
                width: '90%',
                height: '98%',
                cache: false,
                modal: true,
                border: false,
                draggable: false,
                shadow: false,
                onClose: function () {
                    el.byDateShowDetailDialog.dialog('destroy');
                },
                buttons: [{
                    text: itablei8n.close,
                    iconCls: 'icon-cancel',
                    handler: function () {
                        el.byDateShowDetailDialog.dialog('close');
                    }
                }]
            });
        },
        error: function (e) {
            topWin.layer.close(loadIndex);
            topWin.layer.alert(JSON.parse(e.responseText).message || (typeof (JSON.parse(e.responseText) === 'string') ? JSON.parse(e.responseText) : "出现错误"), {icon: 2});
        }
    });
}


/**
 * 确认导入
 */
function confirmImport() {
    var fileBox = $(el.excelFile).filebox('files'), chooseDate = $(el.chooseDate).datebox('getValue');
    if (fileBox.length === 1) {
        var formData = new FormData();
        formData.append('file', fileBox[0]);
        var index = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'pc/order/shortagePlan/rest/import?startDate=' + chooseDate,
            data: formData,
            type: 'POST',
            contentType: false,
            processData: false,
            success: function () {
                topWin.layer.close(index);
                topWin.layer.msg('数据导入成功', {icon: 1});

                $(el.excelFile).filebox('clear');
                $(el.uploadBoxHtml).dialog('close');
                $(el.tb).datagrid('load');
            },
            error: function (e) {
                console.log(e);
                $(el.excelFile).filebox('clear');
                topWin.layer.close(index);
                topWin.layer.alert(JSON.parse(e.responseText).message, {icon: 2});
            }
        });
    }
}


/**
 * 关闭导入弹框
 */
function closeImportDialog() {
    $(el.uploadBoxHtml).dialog('close');
}


/**
 * 数据查询
 */
function dataQuery() {
    var queryParams = $(el.tb).datagrid('options').queryParams;
    queryParams.title = $.trim($(el.title).val());
    queryParams.createName = $.trim($(el.createName).val());
    $(el.tb).datagrid('load');
}


/**
 * 重置查询条件
 */
function resetQuery() {
    $(el.title).val('');
    $(el.createName).val('');
    dataQuery();
}

// 下载导入模板
function downloadTemplate() {
    window.location.href = g.ctx + "static/excel/shortage_plan_list.xlsx";

}