/**
 * 交付模块-标准预测计划供应商回复页面JS
 *
 * @author jitong.zhang
 * @version 1.0
 */
var page = {
    editIndex: undefined,
    bodyHeight: document.documentElement.clientHeight,
    /**
     * 时间选中下边记录
     */
    replySelectInfo: {index: null, rows: null},
    saveOrUpdate: function () {
        page.replySelectInfo.rows = null;
        var data = page.replyDetailGrid.datagrid('getRows');
        var rows = page.replyDataGrid.datagrid("getSelections");
        var replySelectVal = page.replyDataGrid.datagrid('getSelected');

        var editIndex = page.replyDetailGrid.datagrid('getRowIndex', page.replyDetailGrid.datagrid('getSelected'));

        var detail_remark = $("#detail_remark").val();

        if (rows.length > 1) {
            topWin.layer.alert(tipsi18n.xzqzytcz, {icon: 2});
            return false;
        }

        if (editIndex >= 0) {
            page.replyDetailGrid.datagrid('endEdit', editIndex);
        }
        if (!data || !replySelectVal) {
            topWin.layer.alert(tipsi18n.cscw, {icon: 2});
            return false;
        }
        let tipMsg = []
        $.each(data, function (idx) {
            this['dataId'] = this.id;
            this['supplierCode'] = replySelectVal.supplierCode;
            if (this.distributeNum!=0&&this.adjustNum === '') {
                tipMsg.push("第" + (idx + 1) + "行，回复数量不能位空")
            }
        });
        if (tipMsg.length > 0) {
            topWin.layer.alert(tipMsg.join("</br>"), {icon: 2});
            return false;
        }
        var loadingIndex = topWin.layer.msg(tipsi18n.tjz, {icon: 16, shade: 0});
        $.ajax({
            url: g.ctx + 'pc/order/basicPlan/rest/save/reply/detail',
            data: {
                data: JSON.stringify(page.replyDetailGrid.datagrid('getRows')),
                isPurchaseReplace: isPurchaseReplace,
                detail_remark: detail_remark
            },
            type: 'POST',
            success: function () {
                topWin.layer.close(loadingIndex);
                topWin.layer.alert(tipsi18n.bccg, {icon: 1}, function (index) {
                    var dataIndex = page.replyDataGrid.datagrid('getRowIndex', page.replyDataGrid.datagrid('getSelected'));
                    if (dataIndex >= 0) {
                        page.refreshDetailDataTable(dataIndex);
                    }
                    page.replyDataGrid.datagrid('load');
                    topWin.layer.close(index)
                });
            },
            error: function (e) {
                topWin.layer.close(loadingIndex);
                topWin.layer.alert(JSON.parse(e.responseText).message || JSON.parse(e.responseText), {icon: 2});
            }
        });
    },
    /**
     * 一键匹配回复
     */
    matchReply: function () {
        var rows = page.replyDataGrid.datagrid("getSelections");

        if (rows.length > 1) {

            var replyDetail = page.replyDetailGrid.datagrid('getData');
            var replyDetailRows = replyDetail.rows;
            for (var n = 0; n < replyDetailRows.length; n++) {
                var rd = replyDetailRows[n];
                rd.adjustNum = rd.distributeNum;
            }

            parent.layer.confirm('是否多条数据一件匹配并保存？', function (index) {
                var loadingIndex = topWin.layer.msg(tipsi18n.tjz, {icon: 16, shade: 0});
                $.ajax({
                    url: g.ctx + 'pc/order/basicPlan/rest/save/reply/details',
                    data: {
                        data: JSON.stringify(rows),
                        isPurchaseReplace: isPurchaseReplace
                    },
                    type: 'POST',
                    complete: function () {
                        topWin.layer.close(loadingIndex);
                    },
                    success: function () {
                        var dataIndex = page.replyDataGrid.datagrid('getRowIndex', page.replyDataGrid.datagrid('getSelected'));
                        if (dataIndex >= 0) {
                            page.refreshDetailDataTable(dataIndex);
                        }
                        page.replyDataGrid.datagrid('load');
                        topWin.layer.close(index)
                    },
                    error: function (data) {
                        topWin.layer.alert(data.responseJSON.message, {icon: 2});
                    }
                });
            });

        } else {
            var replyDetail = page.replyDetailGrid.datagrid('getData');
            var replyDetailRows = replyDetail.rows;
            for (var n = 0; n < replyDetailRows.length; n++) {
                var rd = replyDetailRows[n];
                rd.adjustNum = rd.distributeNum;
            }
            page.replyDetailGrid.datagrid('loadData', replyDetailRows);
        }

    },
    /**
     * 时间明细 选中开始编辑
     */
    clickCell: function (index, field, value) {
        if (page.editIndex !== index) {
            if (page.isEndEditing()) {
                page.replyDetailGrid.datagrid('selectRow', index).datagrid('beginEdit', index);
                var ed = page.replyDetailGrid.datagrid('getEditor', {index: index, field: field});
                if (ed) {
                    ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
                }
                page.editIndex = index;
            } else {
                setTimeout(function () {
                    page.replyDetailGrid.datagrid('selectRow', page.editIndex);
                }, 0);
            }
        }
    },
    isEndEditing: function () {
        if (page.editIndex === undefined) {
            return true
        }
        if (page.replyDetailGrid.datagrid('validateRow', page.editIndex)) {
            page.replyDetailGrid.datagrid('endEdit', page.editIndex);
            page.editIndex = undefined;
            return true;
        } else {
            return false;
        }
    },
    /**
     * 父级选中
     *
     * @param rowIndex 物料表行索引
     */
    selectRow: function (rowIndex) {
        if (page.replySelectInfo.index === undefined) {
            page.refreshDetailDataTable(rowIndex);
        } else {
            if (rowIndex === page.replySelectInfo.index) {
                page.refreshDetailDataTable(rowIndex);
                //return
            } else {
                var editIndex = page.replyDetailGrid.datagrid('getRowIndex', page.replyDetailGrid.datagrid('getSelected'));
                page.replyDetailGrid.datagrid('endEdit', editIndex);

                //与之前保存的数据比对，检查数据是否修改过
                var isChange = false;
                var thisRowData = page.replyDetailGrid.datagrid('getRows');
                var oldRowData = JSON.parse(page.replySelectInfo.rows);
                if (oldRowData !== null) {
                    $.each((thisRowData || []), function (index) {
                        if (!isChange && Number(thisRowData[index]['adjustNum']) !== Number(oldRowData[index]['adjustNum'])) {
                            isChange = true;
                            return false;
                        }
                    });
                }
                if (isChange) {
                    topWin.layer.confirm(tipsi18n.yjggdsjbc, {icon: 3}, function () {
                        page.saveOrUpdate();
                    }, function () {
                        page.refreshDetailDataTable(rowIndex);
                    });
                } else {
                    page.refreshDetailDataTable(rowIndex);
                }
            }
        }
        //记录点击下标
        page.replySelectInfo.index = rowIndex;
    },
    /**
     * 刷新明细表格
     */
    refreshDetailDataTable: function (rowIndex) {

        $('#detail_remark').textbox({
            prompt: '请输入备注',
            multiline: true,
            width: '100%',
            height: '60px',
            value: ''
        });


        var rows = page.replyDataGrid.datagrid("getRows");
        var loadIndex = topWin.layer.msg(tipsi18n.jzz, {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'pc/order/basicPlan/rest/by/detail_id/get/plan_data',
            data: {detailId: rows[rowIndex].detailId, supplierCode: rows[rowIndex].supplierCode},
            type: 'POST', async: false,
            success: function (res) {
                topWin.layer.close(loadIndex);
                page.preDetailData = (res['perData'] || {});
                page.replyDetailGrid.datagrid("loadData", res.rows);
            },
            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});
            }
        });
    },
    initTable: function () {
        page.replyDataGrid = $('#tb').datagrid({
            url: g.ctx + 'pc/order/basicPlan/rest/get/reply/supplier?planId=' + planId,
            method:"GET",
            iconCls: 'icon-list', width: '100%', height: (page.bodyHeight - 80)/2,
            singleSelect: true, pagination: true, loadMsg: itablei8n.dataLoading, rownumbers: true,
            remoteSort: true, striped: true, page: 1, pageSize: 20, async: false,
            columns: [[
                {field: 'ck', checkbox: true},
                {field: 'id', hidden: true},
                {field: 'productCode', title: itableTitlei18n.wlbm, width: 120, align: 'left'},
                {field: 'productName', title: itableTitlei18n.wlms, width: 210, align: 'left'},
                {field: 'factoryCode', title: itableTitlei18n.gcbm, width: 120, align: 'left'},
                {field: 'supplierCode', title: itableTitlei18n.gysbm, width: 140, align: 'left'},
                {field: 'supplierName', title: itableTitlei18n.gysmc, width: 220, align: 'left'},
                {field: 'serialNumber', title: popupi18n.hfbb, width: 130, align: 'left'},
                {field: 'distributeNum', title: popupi18n.fpzs, width: 120, align: 'left'},
                {
                    field: 'status', title: itablei8n.status, width: 120, align: 'left',
                    formatter: function (val) {
                        switch (Number(val)) {
                            case 1:
                                return '<span style="color: #ffba00">' + statusi18n.dhf + '</span>';
                            case 10:
                                return '<span style="color: green">' + statusi18n.yhf + '</span>';
                            case 11:
                                return '<span style="color: red;">' + statusi18n.cgyjj + '</span>';
                            default:
                                return '';
                        }
                    }
                }
            ]],
            onSelect: page.selectRow,
            onLoadSuccess: function () {
                var rows = page.replyDataGrid.datagrid("getRows");
                if (page.replySelectInfo.index) {
                    page.replyDataGrid.datagrid('selectRow', page.replySelectInfo.index);
                } else {
                    if (rows.length > 0) {
                        page.replyDataGrid.datagrid('selectRow', 0);
                    } else {
                        page.replyDetailGrid.datagrid('loadData', {total: 0, rows: []});
                    }
                }
                //如果不是采购代答复  不显示风险物料
                if (!isPurchaseReplace) {
                    $('#tb').datagrid('hideColumn', 'isRisk');//列的field值
                }
            }
        });
        page.replyDetailGrid = $('#reply_data_table').datagrid({
            iconCls: 'icon-list',
            width: '100%',
            height: (page.bodyHeight - 80)/2,
            singleSelect: true,
            pagination: true,
            loadMsg: itablei8n.dataLoading,
            rownumbers: true,
            remoteSort: true,
            striped: true,
            page: 1,
            pageSize: 50,
            queryParams: {},
            columns: [[
                {field: 'ck', checkbox: true},
                {
                    field: 'dateType', title: popupi18n.rqlx, width: 50, align: 'left',
                    formatter: function (val) {
                        if (Number(val) === 1) {
                            return popupi18n.ri
                        } else if (Number(val) === 2) {
                            return popupi18n.zhou
                        } else if (Number(val) === 3) {
                            return popupi18n.yue
                        }
                        return ''
                    }
                },
                {field: 'dateTime', title: popupi18n.rq, width: 130, align: 'left'},
                {field: 'distributeNum', title: popupi18n.fpsl, width: 120, align: 'left'},
                {
                    field: 'adjustNum', title: handlei18n.hfsl, width: 120, align: 'left',
                    editor: {
                        type: 'numberbox', options: {
                            precision: 0,
                            editable: true
                        }
                    }
                },
                {
                    field: 'detailRemark', title: '回复日期', width: 120, align: 'left',
                    editor: {
                        type: 'textbox'
                    }
                },
                {
                    field: 'id', title: popupi18n.bh, width: 60, align: 'center',
                    formatter: function (val, row) {
                        var preReplyNum = row['distributeNum'] ? row['distributeNum'] : 0,
                            replyNum = row['adjustNum'] ? row['adjustNum'] : 0;
                        var attrHtml = ' data-pre_val="' + preReplyNum + '" data-this_val="' + replyNum + '" ';
                        if (Number(replyNum) > Number(preReplyNum)) {
                            return '<a href="javascript:void(0)" style="color: #090;font-size: 1.5em;" data-val="up" ' + attrHtml + ' onmouseenter="page.showChange(this)">▲</a>'
                        } else if (Number(replyNum) < Number(preReplyNum)) {
                            return '<a href="javascript:void(0)" style="color: #f54545;font-size: 1.5em;" data-val="down" ' + attrHtml + ' onmouseenter="page.showChange(this)">▼</a>'
                        } else {
                            return ''
                        }
                    }
                },
                // {field: 'refusalReason', title: '审批意见', width: 200, align: 'left'}
            ]],
            toolbar: [
                {
                    text: itablei8n.save,
                    iconCls: 'icon-save',
                    hidden: true,
                    handler: function () {
                        page.saveOrUpdate();
                    }
                },
                {
                    text: '一键匹配',
                    iconCls: 'icon-ok',
                    hidden: true,
                    handler: function () {
                        page.matchReply();
                    }
                }
            ],
            onClickCell: page.clickCell,
            onLoadSuccess: function () {
                page.replySelectInfo.rows = JSON.stringify(page.replyDetailGrid.datagrid('getRows'));
            }
        });
        /**
         * 导出
         */
        $('#export_btn').on('click', function () {
            if ($(this).linkbutton('options')['disabled']) {
                return
            }
            var status = $('#status').combobox('getValue');
            var supplierCode = $('#supplierCode').val();
            var purchaseGroup = $('#purchase_group').val();
            window.open(g.ctx + 'pc/order/basicPlan/rest/get/reply/export?planId=' + planId
                + "&status=1&status=" + status + "&supplier=" + supplierCode + "&purchaseGroup=" + purchaseGroup);
        });

        /**
         * 导入
         */
        $('#import_btn').on('click', function () {
            if ($(this).linkbutton('options')['disabled']) {
                return
            }
            $("#detailUpload .filebox-label").click();
        });

        if (!isSupplier && !isPurchaseReplace) {
            $('#export_btn').hide();
            $('#import_btn').hide();
            $('#if_reply_box').hide();
            $('#supplier_query_div').hide();
            $('#purchase_group_div').hide();
        } else {
        }
        if (isSupplier && !isPurchaseReplace) {
            $('#if_reply_box').hide();
            $('#supplier_query_div').hide();
            $('#purchase_group_div').hide();
        }
    },
    detailImport: function (v1, v2) {
        var filebox = $("#detailFileInput").filebox("files");
        if (filebox.length == 1) {
            var formData = new FormData();
            formData.append("file", filebox[0]);
            formData.append("planId", planId);
            var index = layer.load(1, {
                shade: [0.1, '#eee'] //0.1透明度的白色背景
            });
            $.ajax({
                url: g.ctx + 'pc/order/basicPlan/rest/reply/import',
                data: formData,
                type: 'post',
                async: false,
                contentType: false,
                processData: false,
                success: function (d) {
                    layer.close(index);
                    $("#detailFileInput").filebox("clear");
                    if (d) {
                        layer.alert('导入成功', {icon: 1}, function (alertIndex) {
                            layer.close(alertIndex);
                            page.initTable();
                            //page.refreshTable();
                            //page.replyDataGrid.datagrid('reload');
                            //重新加载表
                            //var dataIndex = page.replyDataGrid.datagrid('getRowIndex', page.replyDataGrid.datagrid('getSelected'));
                            //page.refreshDetailDataTable(dataIndex);
                            if (dataIndex >= 0) {
                                //page.refreshDetailDataTable(dataIndex);
                            }
                        });
                    } else {
                        layer.alert('导入失败', {icon: 2});
                    }
                },
                error: function (e) {
                    $("#detailFileInput").filebox("clear");
                    layer.close(index);
                    layer.alert(JSON.parse(e.responseText).message || (typeof (JSON.parse(e.responseText) === 'string') ? JSON.parse(e.responseText) : "出现错误"));
                }
            });
        }
    },
    /**
     * 上个版本数据
     */
    preDetailData: {},
    /**
     * 悬浮显示较上次上升or下降
     *
     * @param dom
     */
    showChange: function (dom) {
        var upOrDown = $(dom).data('val');
        var preVal = $(dom).data('pre_val');
        var thisVal = $(dom).data('this_val');
        if (upOrDown === 'up') {
            layer.tips('<div><p style="text-align: center;font-size: 1.2em;">' + tipsi18n.shs + '</p><p>' + tipsi18n.sgbbhfsl + '：' + preVal + '</p><p>' + tipsi18n.dqbbhfsl + '：' + thisVal + '</p></div>', dom, {
                tips: [4, '#090'],
                time: 4000
            });
        } else {
            layer.tips('<div><p style="text-align: center;font-size: 1.2em;">' + tipsi18n.xj + '</p><p>' + tipsi18n.sgbbhfsl + '：' + preVal + '</p><p>' + tipsi18n.dqbbhfsl + '：' + thisVal + '</p></div>', dom, {
                tips: [4, '#f54545'],
                time: 4000
            });
        }

    }
};
$(function () {
    // 1:已回复;2:未回复
    $('#status').combobox({
        valueField: 'value',
        textField: 'label',
        data: [
            {label: '全部', value: '0'},
            {label: '待回复', value: '1'},
            {label: '已回复', value: '10'}
        ],
        editable: false,
        panelHeight: 'auto',
        prompt: '-- 请选择 --'
    });
    page.initTable();
});