/**
 * 交付模块-标准预测计划首页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: ''
    });
    setDatePickerToFirstDayOfMonth();

});

/**
 * 初始化上传导入标准预测开始日期为当月一号
 */
function setDatePickerToFirstDayOfMonth(){
    var now = new Date();
    now.setDate(1);
    var formattedDate = now.getFullYear() + '-' + (now.getMonth() + 1).toString().padStart(2, '0') + '-01';
    $(el.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/basicPlan/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,
                    formatter: function (value) {
                        if(!value){
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm:ss');
                    }
                },
                {
                    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/basicPlan/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) {
                        if (Number(value) === 1) {
                            return '<span style="color: #00ee00">' + statusi18n.xinj + '</span>'
                        } else if (Number(value) === 0) {
                            return '<span style="color: red;">' + statusi18n.sx + '</span>'
                        } else if (Number(value) === 10) {
                            return '<span style="color: blue;">' + statusi18n.yfb + '</span>'
                        } else if (Number(value) === 11) {
                            return '<span style="color: #00e0ee">' + statusi18n.yhf + '</span>'
                        }
                        return ''
                    }
                },
                {
                    field: 'replySum',
                    title: isSupplier ? handlei18n.yhfzt : handlei18n.hfjd,
                    width: 80,
                    formatter: function (value, row) {
                        if (Number(isSupplier)) {
                            return '<span>' + row['replySum'] + '/' + row['replySumAll'] + '</span>'
                        } else {
                            return '<a href="javascript:void(0)" onclick="showSupplierReply(' + row.id + ')">' + row['suppSum'] + '/' + row['suppSumTotal'] + '</a>'
                        }
                    }
                }
            ]
        ],
        toolbar: [
            {
                text: handlei18n.xzmb,
                id: 'btn_download_temp',
                iconCls: 'icon-download',
                handler: function () {
                    downloadTemplate();
                }
            },
            '-',
            {
                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.qr,
                id: 'btn_confirm',
                iconCls: 'icon-confirm',
                handler: function () {
                    purchaseConfirm();
                }
            },
            '-',
            {
                text: handlei18n.ck,
                id: 'btn_look',
                iconCls: 'icon-find',
                handler: function () {
                    showDetail();
                }
            },
            '-',
            {
                text: '删除',
                id: 'btn-remove',
                iconCls: 'icon-remove',
                handler: function () {
                    deleteDetail();
                }
            }
        ],
        onLoadSuccess: function () {
            displayButtonByUserRole('MediumLongForecast');
            $(el.tb).datagrid('clearSelections');
        }
    });
}


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


/**
 * 查看供应商回复
 *
 * @param id 计划ID
 */
function showSupplierReply(id) {
    var url = g.ctx + 'pc/order/basicPlan/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 === 0){
        topWin.layer.alert(tipsi18n.jhysx, {icon: 0});
        return false;
    }

    var load = topWin.layer.load(1);
    $.ajax({
        type: 'GET',
        url: g.ctx + 'pc/order/basicPlan/rest/check/plan/release/reply/situation',
        data: {
            planId: row.id,
            checkType: 1
        },
        success: function () {
            topWin.layer.close(load);
            var url = g.ctx + 'pc/order/basicPlan/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');
                        }
                    }
                ]
            });
        },
        error: function (data) {
            topWin.layer.close(load);
            topWin.layer.alert(data.responseJSON.message, {icon: 0});
        }
    });
}


/**
 * 供应商回复
 */
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/basicPlan/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: 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/basicPlan/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: itablei8n.close,
                iconCls: 'icon-cancel',
                handler: function () {
                    el.supplierReplyDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 采购确认供应商回复
 */
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 load = topWin.layer.load(1);
    $.ajax({
        type: 'GET',
        url: g.ctx + 'pc/order/basicPlan/rest/check/plan/release/reply/situation',
        data: {
            planId: row.id,
            checkType: 2
        },
        success: function () {
            topWin.layer.close(load);
            var url = g.ctx + 'pc/order/basicPlan/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');
                        }
                    }
                ]
            });
        },
        error: function (data) {
            topWin.layer.close(load);
            topWin.layer.alert(data.responseJSON.message, {icon: 0});
        }
    });
}


/**
 * 明细查看
 */
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/basicPlan/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/basicPlan/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 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/basicPlan/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;
    }

}
/**
 * 确认导入
 */
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/basicPlan/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/basic_plan_list.xlsx";

}