'use strict';

/**
 *
 *
 * @author Mai
 * @date 2019/3/20
 * @version
 */

function getTenderId() {
    return window.location.pathname.split('/')[2];
}

function getStageId() {
    return window.location.pathname.split('/')[5];
}

function loadUpdateDealPays(newPay, fields) {
    const newPays = newPay instanceof Array ? newPay : [newPay];
    for (const np of newPays) {
        const op = _.find(dealPay, {id: np.id});
        for (const prop in np) {
            if (!fields || fields.indexOf(prop) >= 0) {
                op[prop] = np[prop];
            }
        }
    }
}

function makeAttTable(id, attachment) {
    let html = '';
    if (attachment !== null) {
        for (const [index, att] of attachment.entries()) {
            const delhtml = uploadPermission && parseInt(att.uid) === parseInt(userID) ? '<a class="delete-att text-danger" href="javascript:void(0);" data-payid="'+ id +'" data-attindex="'+ index +'" title="删除"><i class="fa fa-remove "></i></a>' : '';
            html += '<tr><td style="width: 200px">' + att.filename + att.fileext + '</td><td>' + att.username + '</td><td>' + att.in_time + '</td>' +
                '<td><a href="/tender/'+ tender.id + '/measure/stage/' + tender.ledger_times +'/pay/download/file/'+ id +'/'+ index +'" title="下载"><i class="fa fa-download "></i></a> ' +
                delhtml +
                '</td></tr>';
        }
    }
    $('#pay-attList').html(html);
}

$(document).ready(() => {
    autoFlashHeight();

    const paySpread = SpreadJsObj.createNewSpread($('#pay-spread')[0]);
    const paySpreadSetting = {
        cols: [
            {title: '名称', colSpan: '1', rowSpan: '1', field: 'name', hAlign: 0, width: 150, formatter: '@', readOnly: 'readOnly.name'},
            {title: '扣款', colSpan: '1', rowSpan: '1', field: 'minus', hAlign: 1, width: 50, cellType: 'checkbox', readOnly: 'readOnly.minus'},
            {title: '本期金额（表达式）', colSpan: '1', rowSpan: '1', field: 'tp', hAlign: 2, width: 100, readOnly: 'readOnly.tp', /*cellType: 'tip', getTip: function (data) {return data ? data.expr : '';}*/},
            {title: '截止上期金额',  colSpan: '1', rowSpan: '1', field: 'pre_tp', hAlign: 2, width: 100, readOnly: true},
            {title: '截止本期金额',  colSpan: '1', rowSpan: '1', field: 'end_tp', hAlign: 2, width: 100, readOnly: true},
            {title: '起扣金额',  colSpan: '1', rowSpan: '1', field: 'sprice', hAlign: 2, width: 100, readOnly: 'readOnly.sprice', /*cellType: 'tip', getTip: function (data) {return data ? data.sexpr : '';}*/},
            {title: '付（扣）款限额',  colSpan: '1', rowSpan: '1', field: 'rprice', hAlign: 2, width: 100, readOnly: 'readOnly.rprice', /*cellType: 'tip', getTip: function (data) {return data ? data.rexpr : '';}*/},
            {
                title: '附件', colSpan: '1', rowSpan: '1', field: 'attachment', hAlign: 0, width: 60, readOnly: true, cellType: 'imageBtn',
                normalImg: '#rela-file-icon', hoverImg: '#rela-file-hover', getValue: 'getValue.attachment'
            },
            {title: '状态', colSpan: '1', rowSpan: '1', field: '', hAlign: 0, width: 120, readOnly: true, getValue: 'getValue.state', foreColor: 'red', font: '8px 宋体'},
        ],
        emptyRows: 0,
        headRows: 1,
        headRowHeight: [50],
        defaultRowHeight: 30,
        readOnly: readOnly,
        pos: SpreadJsObj.getObjPos($('#pay-spread')[0]),
    };
    paySpreadSetting.imageClick = function (data) {
        makeAttTable(data.id, data.attachment);
        $('#file').modal('show');
    };
    paySpreadSetting.getColor = function (data, col, defaultColor) {
        if (data) {
            if (data.pause) {
                return '#f2f2f2';
            } else if (!data.is_yf) {
                return '#d6d8db';
            } else if (data.csorder == getStageId() && data.uid > 0) {
                return '#FFFFE1';
            } else {
                return defaultColor;
            }
        } else {
            return defaultColor;
        }
    };
    const payCol = {
        getValue: {
            attachment: function (data) {
                return data.attachment ? data.attachment.length : 0;
            },
            state: function (data) {
                const value = [];
                if (data.pause) {
                    value.push('停用');
                }
                if (!data.is_yf) {
                    value.push('不参与本期应付');
                }
                return value.join('\n');
            },
        },
        readOnly: {
            isNonZero: function (num) {
                return !(!num || num === 0)
            },
            isYF: function (data) {
                return data.ptype === 2;
            },
            isSpecial: function (data) {
                return data.ptype !== 1;
            },
            isOld: function (data) {
                if (data.csorder === 0) {
                    return stage.order > 1 || stage.times > 1 || stage.curOrder > 0;
                } else {
                    return stage.order > data.csorder || stage.times > data.cstimes || stage.curOrder > data.csaorder;
                }
            },
            isYB: function (data) {
                return (stage.status === 1 || stage.status === 4);
            },
            isStarted: function (data) {
                return ((payCol.readOnly.isNonZero(data.end_tp) || payCol.readOnly.isNonZero(data.tp)) && data.tp !== data.end_tp) || payCol.readOnly.isNonZero(data.pre_tp);
            },
            name: function (data) {
                return payCol.readOnly.isSpecial(data); //所有人，轮到自己时，均可修改
            },
            minus: function (data) {
                if (payCol.readOnly.isOld(data)) { // 上报或审批后，仅原报，在未开始计量前，可修改
                    return payCol.readOnly.isSpecial(data) || payCol.readOnly.isStarted(data) || !payCol.readOnly.isYB(data);
                } else { // 新增时，新增人可修改
                    return payCol.readOnly.isSpecial(data);
                }
            },
            tp: function (data) {
                return data.ptype === 2 || data.ptype === 4; // 仅本期完成计量、本期应付，不可修改
            },
            sprice: function (data) {
                if (payCol.readOnly.isOld(data)) { // 上报或审批后，仅原报，在未开始计量前，可修改
                    return payCol.readOnly.isYF(data) || payCol.readOnly.isStarted(data) || !payCol.readOnly.isYB(data);
                } else { // 新增时，新增人可修改
                    return payCol.readOnly.isSpecial(data);
                }
            },
            rprice: function (data) {
                return payCol.readOnly.sprice(data); // 同起扣金额
            },
        }
    };
    SpreadJsObj.initSpreadSettingEvents(paySpreadSetting, payCol);
    SpreadJsObj.initSheet(paySpread.getActiveSheet(), paySpreadSetting);
    SpreadJsObj.loadSheetData(paySpread.getActiveSheet(), SpreadJsObj.DataType.Data, dealPay);

    const paySpreadObj = {
        _checkExpr: function (text, data, priceField, exprField) {
            if (text) {
                const num = _.toNumber(text);
                if (num) {
                    data[priceField] = num;
                    data[exprField] = null;
                } else {
                    data[exprField] = text.replace('=', '');
                    data[priceField] = null;
                }
            } else {
                data[priceField] = null;
                data[exprField] = null;
            }
        },
        refreshActn: function () {
            const setObjEnable = function (obj, enable) {
                if (enable) {
                    obj.removeClass('disabled');
                } else {
                    obj.addClass('disabled');
                }
            };
            const sheet = paySpread.getActiveSheet();
            const select = SpreadJsObj.getSelectObject(sheet);
            setObjEnable($('#add'), !readOnly);
            setObjEnable($('#del'), !readOnly && select);
            setObjEnable($('#up-move'), !readOnly && select && select.ptype === 1 && dealPay.indexOf(select) > 3);
            setObjEnable($('#down-move'), !readOnly && select && select.ptype === 1 && dealPay.indexOf(select) < dealPay.length - 1);
            setObjEnable($('#unlock'), !readOnly);
        },
        add: function () {
            const sheet = paySpread.getActiveSheet();
            postData(window.location.pathname + '/save', {type: 'add'}, function (result) {
                if (result) {
                    dealPay.push(result);
                    sheet.addRows(dealPay.length - 1, 1);
                    SpreadJsObj.reLoadRowData(sheet, dealPay.length - 1);
                    sheet.setSelection(dealPay.length - 1, 0, 1, 1);
                    paySpreadObj.refreshActn();
                }
            });
        },
        del: function () {
            const sheet = paySpread.getActiveSheet();
            const select = SpreadJsObj.getSelectObject(sheet);
            postData(window.location.pathname + '/save', {type: 'del', id: select.pid}, function (result) {
                const index = dealPay.indexOf(select);
                dealPay.splice(index, 1);
                sheet.deleteRows(index, 1);
                loadUpdateDealPays(result);
                SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
                const sel = sheet.getSelections();
                sheet.setSelection(index > 0 ? index - 1 : 0, sel.length > 0 ? sel[0].col : 0, 1, 1);
                paySpreadObj.refreshActn();
            });
        },
        upMove: function () {
            const sheet = paySpread.getActiveSheet();
            const cur = SpreadJsObj.getSelectObject(sheet);
            const up = dealPay[dealPay.indexOf(cur) - 1];
            postData(window.location.pathname + '/save', {type: 'changeOrder', id1: cur.pid, id2: up.pid}, function () {
                const order = cur.order;
                cur.order = up.order;
                up.order = order;
                dealPay.sort(function (a, b) {
                    return a.order - b.order
                });
                SpreadJsObj.reLoadSheetData(sheet);
                const sel = sheet.getSelections();
                const index = dealPay.indexOf(cur);
                sheet.setSelection(index, sel.length > 0 ? sel[0].col : 0, 1, 1);
                paySpreadObj.refreshActn();
            });
        },
        downMove: function () {
            const sheet = paySpread.getActiveSheet();
            const cur = SpreadJsObj.getSelectObject(sheet);
            const down = dealPay[dealPay.indexOf(cur) + 1];
            postData(window.location.pathname + '/save', {
                type: 'changeOrder',
                id1: cur.pid,
                id2: down.pid
            }, function () {
                const order = cur.order;
                cur.order = down.order;
                down.order = order;
                dealPay.sort(function (a, b) {
                    return a.order - b.order
                });
                SpreadJsObj.reLoadSheetData(sheet);
                const sel = sheet.getSelections();
                const index = dealPay.indexOf(cur);
                sheet.setSelection(index, sel.length > 0 ? sel[0].col : 0, 1, 1);
                paySpreadObj.refreshActn();
            });
        },
        selectionChanged: function (e, info) {
            paySpreadObj.refreshActn();
            const sel = info.sheet.getSelections()[0];
            const col = info.sheet.zh_setting.cols[sel.col];
            const data = SpreadJsObj.getSelectObject(info.sheet);
            if (col.field === 'tp') {
                $('#expr').val(data.expr).attr('field', 'expr').attr('org', data.expr)
                    .attr('readOnly', readOnly|| payCol.readOnly.isSpecial(data));
            } else if (col.field === 'sprice') {
                $('#expr').val(data.sexpr).attr('field', 'sexpr').attr('org', data.sexpr)
                    .attr('readOnly', readOnly|| payCol.readOnly.isSpecial(data) || payCol.readOnly.isOld(data));
            } else if (col.field === 'rprice') {
                $('#expr').val(data.rexpr).attr('field', 'rexpr').attr('org', data.rexpr)
                    .attr('readOnly', readOnly|| payCol.readOnly.isSpecial(data) || payCol.readOnly.isOld(data));
            } else {
                $('#expr').val('').attr('readOnly', true);
            }
        },
        editEnded: function (e, info) {
            if (info.sheet.zh_setting) {
                const select = SpreadJsObj.getSelectObject(info.sheet);
                const col = info.sheet.zh_setting.cols[info.col];
                if (col.field === 'minus') {
                    return;
                }
                // 未改变值则不提交
                const validText = info.editingText ? info.editingText.replace('\n', '') : null;
                let orgValue;
                if (col.field === 'tp') {
                    orgValue = _.toNumber(validText) ? select.tp : select.expr;
                } else if (col.field === 'sprice') {
                    orgValue = _.toNumber(validText) ? select.sprice : select.sexpr;
                } else if (col.field === 'rprice') {
                    orgValue = _.toNumber(validText) ? select.rexpr : select.rexpr;
                } else {
                    orgValue = select[col.field];
                }
                if (orgValue == validText || ((!orgValue || orgValue === '') && (validText === ''))) {
                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
                    return;
                }
                // 获取更新信息
                const data = {
                    type: (col.field === 'tp' || col.field === 'name') ? 'stage' : 'info',
                    updateData: {}
                };
                // 获取更新数据
                if (col.field === 'tp') {
                    data.updateData.pid = select.pid;
                    paySpreadObj._checkExpr(validText, data.updateData, 'tp', 'expr');
                } else if (col.field === 'name') {
                    data.updateData.pid = select.pid;
                    data.updateData.name = validText;
                } else {
                    data.updateData.id = select.pid;
                    if (validText) {
                        if (col.field === 'sprice') {
                            paySpreadObj._checkExpr(validText, data.updateData, 'sprice', 'sexpr');
                        } else if (col.field === 'rprice') {
                            paySpreadObj._checkExpr(validText, data.updateData, 'rprice', 'rexpr');
                        } else {
                            data.updateData[col.field] = validText;
                        }
                    } else {
                        data.updateData[col.field] = null;
                    }
                }
                // 更新至服务器
                postData(window.location.pathname + '/save', data, function (result) {
                    loadUpdateDealPays(result, col.field === 'name' ? ['name'] : null);
                    SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
                });
            }
        },
        buttonClicked: function (e, info) {
            if (info.sheet.zh_setting) {
                const select = SpreadJsObj.getSelectObject(info.sheet);
                const col = info.sheet.zh_setting.cols[info.col];
                if (payCol.readOnly.minus(select)) {
                    return;
                }
                if (col.field === 'minus') {
                    if (info.sheet.isEditing) {
                        info.sheet.endEdit(true);
                    }
                    // 获取更新数据
                    // 获取更新信息
                    const data = {
                        type: 'info',
                        updateData: {id: select.pid},
                    };
                    data.updateData.minus = info.sheet.getValue(info.row, info.col) || false;
                    // 更新至服务器
                    postData(window.location.pathname + '/save', data, function (result) {
                        loadUpdateDealPays(result);
                        SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
                    });
                }
            }
        },
        editStarting: function (e, info) {
            const col = info.sheet.zh_setting.cols[info.col];
            if (col.field === 'tp') {
                const select = SpreadJsObj.getSelectObject(info.sheet);
                if (select.expr && select.expr !== '') {
                    info.sheet.getCell(info.row, info.col).text(select.expr);
                }
            } else if (col.field === 'sprice') {
                const select = SpreadJsObj.getSelectObject(info.sheet);
                if (select.sexpr && select.sexpr !== '') {
                    info.sheet.getCell(info.row, info.col).text(select.sexpr);
                }
            } else if (col.field === 'rprice') {
                const select = SpreadJsObj.getSelectObject(info.sheet);
                if (select.rexpr && select.rexpr !== '') {
                    info.sheet.getCell(info.row, info.col).text(select.rexpr);
                }
            }
        },
        deletePress: function (sheet) {
            if (sheet.zh_setting && sheet.zh_data) {
                const sel = sheet.getSelections()[0];
                if (!sel) return;

                const col = sheet.zh_setting.cols[sel.col];
                if (col.readOnly === true) { return; }
                if (sel.colCount > 1) {
                    toast('请勿同时删除多列数据', 'warning');
                }

                const data = {type: col.field === 'tp' ? 'stage' : 'info', updateData: []};
                for (let iRow = sel.row; iRow < sel.row + sel.rowCount; iRow++) {
                    const node = sheet.zh_data[iRow];
                    if (node && (node.ptype === 1 || node.ptype === 3)) {
                        const updateData = {};
                        if (col.field === 'tp') {
                            updateData.pid = node.pid;
                            updateData.tp = null;
                            updateData.expr = null;
                        } else {
                            updateData.id = node.pid;
                            if (col.field === 'sprice') {
                                updateData.sprice = null;
                                updateData.sexpr = null;
                            } else if (col.field === 'rprice') {
                                updateData.rprice = null;
                                updateData.rexpr = null;
                            } else {
                                updateData[col.field] = null;
                            }
                        }
                        data.updateData.push(updateData);
                    }
                }
                if (data.updateData.length > 0) {
                    if (data.updateData.length === 1 && sel.rowCount === 1) {
                        data.updateData = data.updateData[0];
                    }
                    postData(window.location.pathname + '/save', data, function (result) {
                        loadUpdateDealPays(result, col.field === 'name' ? ['name'] : null);
                        SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
                    })
                }
            }
        },
        clipboardPasted: function (e, info) {
            if (info.sheet.zh_setting && info.sheet.zh_data) {
                const col = info.sheet.zh_setting.cols[info.cellRange.col];
                if (col.readOnly === true) {
                    SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
                    return;
                }
                if (info.cellRange.colCount > 1) {
                    toast('请勿同时复制粘贴多列数据', 'warning');
                }

                const sortData = info.sheet.zh_data;
                const data = {type: col.field === 'tp' ? 'stage' : 'info', updateData: []};

                for (let iRow = 0; iRow < info.cellRange.rowCount; iRow++) {
                    const curRow = info.cellRange.row + iRow;
                    const node = sortData[curRow];
                    if (node && (node.ptype === 1 || node.ptype === 3)) {
                        const validText = info.sheet.getText(curRow, info.cellRange.col).replace('\n', '');
                        const updateData = {};
                        if (col.field === 'tp') {
                            updateData.pid = node.pid;
                            paySpreadObj._checkExpr(validText, updateData, 'tp', 'expr');
                        } else {
                            updateData.id = node.pid;
                            if (validText) {
                                if (col.field === 'sprice') {
                                    paySpreadObj._checkExpr(validText, updateData, 'sprice', 'sexpr');
                                } else if (col.field === 'rprice') {
                                    paySpreadObj._checkExpr(validText, updateData, 'rprice', 'rexpr');
                                } else {
                                    updateData[col.field] = validText;
                                }
                            } else {
                                updateData[col.field] = null;
                            }
                        }
                        data.updateData.push(updateData);
                    }
                    if (data.updateData.length > 0) {
                        postData(window.location.pathname + '/save', data, function (result) {
                            loadUpdateDealPays(result, col.field === 'name' ? ['name'] : null);
                            SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
                        }, function () {
                            SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
                        });
                    }
                }
            }
        },
    };
    paySpreadObj.refreshActn();
    if (!readOnly) {
        paySpread.bind(spreadNS.Events.EditEnded, paySpreadObj.editEnded);
        paySpread.bind(spreadNS.Events.SelectionChanged, paySpreadObj.selectionChanged);
        paySpread.bind(spreadNS.Events.ButtonClicked, paySpreadObj.buttonClicked);
        paySpread.bind(spreadNS.Events.EditStarting, paySpreadObj.editStarting);
        paySpread.bind(spreadNS.Events.ClipboardPasted, paySpreadObj.clipboardPasted);
        SpreadJsObj.addDeleteBind(paySpread, paySpreadObj.deletePress);
        $('#add').click(paySpreadObj.add);
        $('#del').click(paySpreadObj.del);
        $('#up-move').click(paySpreadObj.upMove);
        $('#down-move').click(paySpreadObj.downMove);
        $('#expr').change(function () {
            const expr = $(this);
            const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
            const field = expr.attr('field'), orgValue = expr.attr('org'), newValue = expr.val();
            if (orgValue === newValue) { return; }

            const data = {};
            if (field === 'expr') {
                data.type = 'stage';
                data.updateData = { pid: select.pid, tp: null, expr: newValue }
            } else if (field === 'sexpr') {
                data.type = 'info';
                data.updateData = {id: select.pid, sprice: null, sexpr: newValue};

            } else if (field === 'rexpr') {
                data.type = 'info';
                data.updateData = {id: select.pid, rprice: null, rexpr: newValue};
            } else {
                expr.val('');
                return;
            }
            // 更新至服务器
            postData(window.location.pathname + '/save', data, function (result) {
                loadUpdateDealPays(result);
                SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
            });
        })
    }

    const deadlineObj = {
        initView(pay) {
            // 模式
            $('[name=dl-type][value=' + pay.dl_type +']')[0].checked = true;
            // 计量期数
            $('#stage-count').val(pay.dl_count ? pay.dl_count : getStageId()).attr('min', getStageId());
            // 计量金额类型
            const tpType = pay.dl_tp_type ? pay.dl_tp_type : 'gather';
            $('[value=' + tpType + ']')[0].checked = true;
            // 计量金额
            $('#tp').val(pay.dl_tp ? pay.dl_tp : 0);
            if (pay.dl_type === 1) {
                $('[dl-type=1]').show();
                $('[dl-type=2]').hide();
                deadlineObj.getStageCountHint();
                $('#dl-hint').show();
            } else if (pay.dl_type === 2) {
                $('[dl-type=1]').hide();
                $('[dl-type=2]').show();
                deadlineObj.getTotalPriceHint();
                $('#dl-hint').show();
            } else {
                $('[dl-type=1]').hide();
                $('[dl-type=2]').hide();
                $('#dl-hint').hide();
            }
        },
        getStageCountHint() {
            $('#range-hint').text('当 计量期数 >= ' + $('#stage-count').val() + ' 时');
        },
        getTotalPriceHint() {
            const tpType = $('[name=tp-type]:checked').attr('id');
            const tpName = $('[for='+ tpType +']').text();
            const tpRange = $('#tp').val();
            $('#range-hint').text('当 ' + tpName + ' >= ' + (tpRange !== '' ? tpRange : 0) + ' 时');
        },
        changeDeadlineType() {
            const type = $(this).val();
            if (type == 1) {
                $('[dl-type=1]').show();
                deadlineObj.getStageCountHint();
            } else {
                $('[dl-type=1]').hide();
            }
            if (type == 2) {
                $('[dl-type=2]').show();
                deadlineObj.getTotalPriceHint();
            } else {
                $('[dl-type=2]').hide();
            }
            if (type == 0) {
                $('#dl-hint').hide();
            } else {
                $('#dl-hint').show();
            }

        }
    };
    // 右键菜单
    $.contextMenu({
        selector: '#pay-spread',
        build: function ($trigger, e) {
            const target = SpreadJsObj.safeRightClickSelection($trigger, e, paySpread);
            return target.hitTestType === GC.Spread.Sheets.SheetArea.viewport || target.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
        },
        items: {
            'detail': {
                name: '明细',
                icon: 'fa-list',
                callback: function (key, opt) {
                    if ($('#detail-list').children().length === 0) {
                        postData(window.location.pathname + '/detail', null, function (result) {
                            const html = [], decimal = result.decimal.tp;
                            for (const cd of result.detail) {
                                html.push('<tr>');
                                html.push('<td>', cd.name, '</td>');
                                html.push('<td class="text-right">', _.round(cd.contract_tp, decimal), '</td>');
                                html.push('<td class="text-right">', _.round(cd.qc_tp, decimal), '</td>');
                                html.push('<td class="text-right">', _.round(cd.gather_tp, decimal), '</td>');
                                html.push('<td class="text-right">', _.round(cd.end_gather_tp, decimal), '</td>');
                                html.push('</tr>');
                            }
                            $('#detail-list').html(html.join(''));
                            $('#detail').modal('show');
                        });
                    } else {
                        $('#detail').modal('show');
                    }
                },
                visible: function(key, opt){
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    return select.ptype === 4;
                }
            },
            'start': {
                name: '启用',
                icon: 'fa-play',
                callback: function (key, opt) {
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    const data = {
                        type: 'stage',
                        updateData: {
                            pid: select.pid,
                            pause: false
                        }
                    };
                    // 更新至服务器
                    postData(window.location.pathname + '/save', data, function (result) {
                        loadUpdateDealPays(result);
                        SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
                    });
                },
                visible: function (key, opt) {
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    return select.ptype === 1 && select.pause;
                },
                disabled: function (key, opt) {
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    return readOnly || payCol.readOnly.minus(select);
                }
            },
            'stop': {
                name: '停用',
                icon: 'fa-pause',
                callback: function (key, opt) {
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    const data = {
                        type: 'stage',
                        updateData: {
                            pid: select.pid,
                            pause: true
                        }
                    };
                    // 更新至服务器
                    postData(window.location.pathname + '/save', data, function (result) {
                        loadUpdateDealPays(result);
                        SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
                    });
                },
                visible: function (key, opt) {
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    return select.ptype === 1 && !select.pause;
                },
                disabled: function (key, opt) {
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    return readOnly || payCol.readOnly.minus(select);
                }
            },
            'setDeadline': {
                name: '设置计提期限',
                icon: 'fa-clipboard',
                visible: function (key, opt) {
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    const stageId = getStageId();
                    return select.ptype === 1 && (select.csorder == stageId || stageId == 1);
                },
                callback: function (key, opt) {
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    deadlineObj.initView(select);
                    if (select.rprice) {
                        $('#deadline').modal('show');
                    } else {
                        toast('计提期限用于达到条件时，即刻计量至付(扣)款限额，应先设置付(扣)款限额', 'warning');
                    }
                },
                disabled: function (key, opt) {
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    return readOnly || payCol.readOnly.minus(select);
                }
            },
            'dropYF': {
                name: '不参与本期应付计算',
                icon: 'fa-chain-broken',
                visible: function (key, opt) {
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    const stageId = getStageId();
                    return select.ptype === 1 && select.is_yf && (select.csorder == stageId || stageId == 1);
                },
                callback: function (key, opt) {
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    const data = {
                        type: 'info',
                        updateData: {
                            id: select.pid,
                            is_yf: false
                        }
                    };
                    // 更新至服务器
                    postData(window.location.pathname + '/save', data, function (result) {
                        loadUpdateDealPays(result);
                        SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
                    });
                },
                disabled: function (key, opt) {
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    return readOnly || payCol.readOnly.minus(select);
                }
            },
            'belongYF': {
                name: '参与本期应付计算',
                icon: 'fa-chain',
                visible: function (key, opt) {
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    const stageId = getStageId();
                    return select.ptype === 1 && !select.is_yf && (select.csorder == stageId || stageId == 1);
                },
                callback: function (key, opt) {
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    const data = {
                        type: 'info',
                        updateData: {
                            id: select.pid,
                            is_yf: true
                        }
                    };
                    // 更新至服务器
                    postData(window.location.pathname + '/save', data, function (result) {
                        loadUpdateDealPays(result);
                        SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
                    });
                },
                disabled: function (key, opt) {
                    const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
                    return readOnly || payCol.readOnly.minus(select);
                }
            }
        }
    });
    $('[name=dl-type]').click(deadlineObj.changeDeadlineType);
    $('[name=tp-type]').click(deadlineObj.getTotalPriceHint);
    $('#stage-count').change(deadlineObj.getStageCountHint);
    $('#tp').change(deadlineObj.getTotalPriceHint);
    $('#deadline-ok').click(function () {
        const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
        const data = {
            type: 'info',
            updateData: {
                id: select.pid,
            }
        };
        data.updateData.dl_type = parseInt($('[name=dl-type]:checked').val());
        data.updateData.dl_count = parseInt($('#stage-count').val());
        data.updateData.dl_tp_type = $('[name=tp-type]:checked').val();
        data.updateData.dl_tp = parseFloat($('#tp').val());
        postData(window.location.pathname + '/save', data, function (result) {
            loadUpdateDealPays(result);
            SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
            $('#deadline').modal('hide');
        });
    });

    // 上传附件
    $('#upload-file').change(function () {
        const files = this.files;
        const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
        const formData = new FormData();
        // const sizes = [];
        formData.append('pay_id', select.id);
        for (const file of files) {
            if (file === undefined) {
                toast('未选择上传文件！', 'error');
                return false;
            }
            const filesize = file.size;
            if (filesize > 10 * 1024 * 1024) {
                toast('存在上传文件大小过大！', 'error');
                return false;
            }
            const fileext = '.' + file.name.toLowerCase().split('.').splice(-1)[0];
            if (whiteList.indexOf(fileext) === -1) {
                toast('只能上传指定格式的附件！', 'error');
                return false;
            }
            // sizes.push(filesize);
            formData.append('size', filesize);
            formData.append('file[]', file);
        }
        // formData.append('size', sizes.join(','));
        postDataWithFile('/tender/' + tender.id + '/measure/stage/' + tender.ledger_times + '/pay/upload/file', formData, function (data) {
            if (select.attachment === null) {
                select.attachment = data;
            } else {
                select.attachment = data.concat(select.attachment);
            }
            makeAttTable(select.id, select.attachment);
            const index = dealPay.indexOf(select);
            dealPay.splice(index, 1, select);
            SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
        }, function () {
            toast('附件上传失败', 'error');
        });
        $('#upload-file').val('');
    });

    // 删除附件
    $('body').on('click', '.delete-att' ,function () {
        const id = $(this).attr('data-payid');
        const index = $(this).attr('data-attindex');
        const data = {
            id,
            index,
        };
        const select = SpreadJsObj.getSelectObject(paySpread.getActiveSheet());
        postData('/tender/' + tender.id + '/measure/stage/' + tender.ledger_times + '/pay/delete/file', data, function (result) {
            select.attachment.splice(index, 1);
            makeAttTable(id, select.attachment);
            const pay_index = dealPay.indexOf(select);
            dealPay.splice(pay_index, 1, select);
            SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
        });
    })
});
