/**
 * 对账模块-强制删除对账单明细页面JS
 *
 * Created by li.kui on 2020/8/24.
 */
'use strict';
var el = {
    dataDiv: '#dataDiv',
    id: '#id',
    orderType: '#orderType',
    taxAmount: '#taxAmount',
    notTaxAmount: '#notTaxAmount',
    dataTabs: '#dataTabs',
    tbDetails: '#tbDetails',
    tbDeduction: '#tbDeduction',
    tbRebate: '#tbRebate',
    tbApproveLog: '#tbApproveLog',
    delDetail: [],
    bodyHeight: document.documentElement.clientHeight
};


/**
 * 文档就绪
 */
$(function () {
    initTbDetails();

    initTbRebate();

    initTbDeduction();

    initTbApproveLog();
});


/**
 * 初始化入库明细表格
 */
function initTbDetails() {
    var dataDiv = $(el.dataDiv).outerHeight() + 45, orderType = $(el.orderType).val();

    $(el.tbDetails).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'fin/account/statement/detail/rest/find/by/statement/id',
        singleSelect: false,
        showFooter: true,
        rownumbers: true,
        pagination: false,
        queryParams: {
            asId: $(el.id).val()
        },
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'itemNo',
                    title: '对账单行号',
                    width: 80
                },
                {
                    field: 'invoiceCompleteFlag',
                    title: '开票标识',
                    width: 70,
                    formatter: function (value) {
                        if(Number(value) === 0){
                            return '未开票';
                        }
                        if(Number(value) === 1){
                            return '<span style="color: green;">已开票</span>';
                        }

                        return '';
                    }
                },
                {
                    field: 'receiveCode',
                    title: '入库凭证',
                    width: 90
                },
                {
                    field: 'receiveRowNo',
                    title: '行号',
                    width: 60
                },
                {
                    field: 'receiveDate',
                    title: '入库日期',
                    width: 100,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD');
                    }
                },
                {
                    field: 'voucherFlag',
                    title: '入库凭证标识',
                    width: 85,
                    formatter: function (value, row) {
                        if(!value){
                            return '';
                        }
                        if (value === 'H') {
                            return '<span style="color: red;">出库('+ row.sapMoveType +')</span>';
                        }else {
                            return '<span style="color: green;">入库('+ row.sapMoveType +')</span>';
                        }
                    }
                }
            ]
        ],
        columns: [
            [
                {
                    field: 'materialCode',
                    title: '物料编码',
                    width: 90
                },
                {
                    field: 'materialName',
                    title: '物料名称',
                    width: 180
                },
                {
                    field: 'materialUnit',
                    title: '单位',
                    width: 60
                },
                {
                    field: 'receiveNum',
                    title: '入库数量',
                    width: 70,
                    formatter: function (value) {
                        if (value < 0) {
                            return '<span style="color: red;">' + value + '</span>';
                        }else {
                            return value;
                        }
                    }
                },
                {
                    field: 'surplusNum',
                    title: '可用数量',
                    width: 70,
                    formatter: function (value) {
                        if (value < 0) {
                            return '<span style="color: red;">' + value + '</span>';
                        }else {
                            return value;
                        }
                    }
                },
                {
                    field: 'asQuantity',
                    title: '确认对账数量',
                    width: 90,
                    formatter: function (value) {
                        if (value < 0) {
                            return '<span style="color: red;">' + value + '</span>';
                        }else {
                            return value;
                        }
                    }
                },
                {
                    field: 'notTaxPrice',
                    title: '未税单价',
                    width: 90
                },
                {
                    field: 'taxPrice',
                    title: '对账含税单价',
                    width: 90
                },
                {
                    field: 'asDiffPrice',
                    title: '对账差异单价',
                    width: 90
                },
                {
                    field: 'notTaxAmount',
                    title: '对账未税金额',
                    width: 100,
                    formatter: function (value) {
                        if (value < 0) {
                            return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
                        }else {
                            return formatNumber(value, 2, 1);
                        }
                    }
                },
                {
                    field: 'taxDesc',
                    title: '对账税率',
                    width: 160,
                    formatter: function (value, row) {
                        if (!value) {
                            return '';
                        }
                        return '(' + row.taxCode + ')' + value;
                    }
                },
                {
                    field: 'taxAmount',
                    title: '对账含税金额',
                    width: 100,
                    formatter: function (value) {
                        if (value < 0) {
                            return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
                        }else {
                            return formatNumber(value, 2, 1);
                        }
                    }
                },
                {
                    field: 'asDiffAmount',
                    title: '对账差异含税金额',
                    width: 130,
                    formatter: function (value) {
                        if (value < 0) {
                            return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
                        }else {
                            return formatNumber(value, 2, 1);
                        }
                    }
                },
                {
                    field: 'diffTaxAmount',
                    title: '对账税额',
                    width: 90,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    // 累计开票金额 = 申请开票金额 + 采购确认金额 + 财务过账金额
                    field: 'invoicedAmount',
                    title: '累计开票金额',
                    width: 110,
                    formatter: function (value) {
                        if (!value) {
                            return '0.00';
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    // 剩余可开票金额 = (入库数量-对账数量) * 订单含税单价
                    field: 'surplusAmount',
                    title: '剩余可开票金额',
                    width: 120,
                    formatter: function (value) {
                        if (!value) {
                            return '0.00';
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'poCode',
                    title: 'SAP订单号',
                    width: 90
                },
                {
                    field: 'poItemNo',
                    title: '订单行号',
                    width: 70
                },
                {
                    field: 'seekPgName',
                    title: '询源采购组',
                    width: 110,
                    formatter: function (value, row) {
                        if (value) {
                            return '(' + row.seekPgCode + ')' + value;
                        }
                        return '';
                    }
                },
                {
                    field: 'orderNotTaxPrice',
                    title: '订单未税单价',
                    width: 90
                },
                {
                    field: 'orderTaxPrice',
                    title: '订单含税单价',
                    width: 90
                },
                {
                    field: 'orderTaxDesc',
                    title: '订单税率',
                    width: 160,
                    formatter: function (value, row) {
                        if(!value){
                            return '';
                        }
                        return '(' + row.orderTaxCode + ')' + value;
                    }
                },
                {
                    field: 'orderNotTaxAmount',
                    title: '订单未税金额',
                    width: 100,
                    formatter: function (value) {
                        if (value < 0) {
                            return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
                        }else {
                            return formatNumber(value, 2, 1);
                        }
                    }
                },
                {
                    field: 'orderTaxAmount',
                    title: '订单含税金额',
                    width: 100,
                    formatter: function (value) {
                        if (value < 0) {
                            return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
                        }else {
                            return formatNumber(value, 2, 1);
                        }
                    }
                },
                {
                    field: 'paymentTermName',
                    title: '付款条件',
                    width: 140,
                    formatter: function (value, row) {
                        if (value) {
                            return '(' + row.paymentTermCode + ')' + value;
                        }
                        return '';
                    }
                },
                {
                    field: 'paymentWayDesc',
                    title: '付款方式',
                    width: 140,
                    formatter: function (value, row) {
                        if (value) {
                            return '(' + row.paymentWayCode + ')' + value;
                        }
                        return '';
                    }
                },
                // 承运商对账
                {
                    field: 'materialSupplierCode',
                    title: '材料商编码',
                    hidden: Number(orderType) === 1,
                    width: 90,
                    sortable: true
                },
                {
                    field: 'materialSupplierName',
                    title: '材料商名称',
                    hidden: Number(orderType) === 1,
                    width: 180,
                    sortable: true
                },
                {
                    field: 'freightType',
                    title: '运费类型',
                    hidden: Number(orderType) === 1,
                    width: 80,
                    sortable: true
                },
                // 集采订单信息
                {
                    field: 'jcPoCode',
                    title: '集采SAP订单号',
                    width: 110,
                    sortable: true
                },
                {
                    field: 'jcPoItemNo',
                    title: '行号',
                    width: 70,
                    sortable: true
                },
                {
                    field: 'jcFactoryCode',
                    title: '集采工厂',
                    width: 80,
                    sortable: true
                }
            ]
        ],
        toolbar: [
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    delStatementItem();
                }
            }
        ],
        onLoadSuccess: function (data) {
            calculationAmount(data.rows);
        }
    });
}


/**
 * 初始化扣款信息表格
 */
function initTbDeduction() {
    var dataDiv = $(el.dataDiv).outerHeight() + 45;

    $(el.tbDeduction).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'fin/account/statement/rest/find/statement/deduction/list',
        singleSelect: false,
        rownumbers: true,
        pagination: false,
        queryParams: {
            asId: $(el.id).val()
        },
        frozenColumns: [
            [
                {
                    field: 'deductionNo',
                    title: '扣款编号',
                    width: 140
                },
                {
                    field: 'deductionTypeDesc',
                    title: '扣款类型',
                    width: 90
                },
                {
                    field: 'deductionAmount',
                    title: '含税扣款金额(元)',
                    width: 110,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'taxCodeDesc',
                    title: '税率',
                    width: 160
                }
            ]
        ],
        columns: [
            [
                {
                    field: 'deductionTime',
                    title: '扣款时间',
                    width: 90,
                    formatter: function (value) {
                        if (value) {
                            return moment(value).format("YYYY-MM-DD");
                        }
                        return '';
                    }
                },
                {
                    field: 'deductionReason',
                    title: '扣款原因',
                    width: 300
                },
                {
                    field: 'companyCode',
                    title: '公司代码',
                    width: 80
                },
                {
                    field: 'companyName',
                    title: '公司名称',
                    width: 180
                },
                {
                    field: 'supplierCode',
                    title: '供应商编码',
                    width: 90
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 270
                },
                {
                    field: 'associatedNo',
                    title: 'SRM业务单据',
                    width: 140,
                    formatter: function (value, row) {
                        if(!row.associatedRowNo){
                            return value;
                        }else {
                            return value + '|' + row.associatedRowNo;
                        }
                    }
                },
                {
                    field: 'associatedOaNo',
                    title: 'OA流程单号',
                    width: 120
                },
                {
                    field: 'createTime',
                    title: '创建时间',
                    width: 140,
                    formatter: function (value) {
                        if (value) {
                            return moment(value).format("YYYY-MM-DD HH:mm:ss");
                        }
                        return '';
                    }
                }
            ]
        ]
    });
}


/**
 * 初始化返利信息表格
 */
function initTbRebate() {
    var dataDiv = $(el.dataDiv).outerHeight() + 45;

    $(el.tbRebate).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'fin/account/statement/rest/find/statement/rebate/list',
        rownumbers: true,
        singleSelect: false,
        pagination: false,
        queryParams: {
            asId: $(el.id).val()
        },
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'rebateNo',
                    title: '返利单号',
                    width: 140
                },
                {
                    field: 'rebateType',
                    title: '返利类型',
                    width: 120,
                    formatter: function (value) {
                        if(Number(value) === 1){
                            return '购方对供方返利';
                        }else {
                            return '供方对购方返利';
                        }
                    }
                },
                {
                    field: 'rebateAmount',
                    title: '含税返利金额(元)',
                    width: 110,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'taxCodeDesc',
                    title: '税率',
                    width: 160
                }
            ]
        ],
        columns: [
            [
                {
                    field: 'rebateTime',
                    title: '返利时间',
                    width: 110,
                    formatter: function (value) {
                        if (value) {
                            return moment(value).format("YYYY-MM-DD");
                        }
                        return '';
                    }
                },
                {
                    field: 'rebateReason',
                    title: '返利原因',
                    width: 300
                },
                {
                    field: 'companyCode',
                    title: '公司代码',
                    width: 80
                },
                {
                    field: 'companyName',
                    title: '公司名称',
                    width: 180
                },
                {
                    field: 'supplierCode',
                    title: '供应商编码',
                    width: 90
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 270
                },
                {
                    field: 'createTime',
                    title: '创建时间',
                    width: 140,
                    formatter: function (value) {
                        if (value) {
                            return moment(value).format("YYYY-MM-DD HH:mm:ss");
                        }
                        return '';
                    }
                }
            ]
        ]
    });
}


/**
 * 初始化审批记录表格
 */
function initTbApproveLog() {
    var dataDiv = $(el.dataDiv).outerHeight() + 45;

    $(el.tbApproveLog).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'fin/account/statement/detail/rest/find/as/approve/log',
        singleSelect: false,
        rownumbers: true,
        pagination: false,
        queryParams: {
            asId: $(el.id).val()
        },
        columns: [
            [
                {
                    field: 'approveNode',
                    title: '审批节点描述',
                    width: 120,
                    formatter: function (value) {
                        if(Number(value) === 1){
                            return '对账确认';
                        }else {
                            return '财务节点';
                        }
                    }
                },
                {
                    field: 'approveResult',
                    title: '审批结果',
                    width: 120,
                    formatter: function (value) {
                        switch (Number(value)){
                            case 0:
                                return '<span style="color: red;">拒绝</span>';
                            case 1:
                                return '<span style="color: green;">同意</span>';
                            case 2:
                                return '<span style="color: orange;">采购撤销</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'approveOpinion',
                    title: '审批意见',
                    width: 300
                },
                {
                    field: 'approveUserName',
                    title: '审批用户姓名',
                    width: 130
                },
                {
                    field: 'approveTime',
                    title: '审批时间',
                    width: 140,
                    formatter: function (value) {
                        if (value) {
                            return moment(value).format("YYYY-MM-DD HH:mm:ss");
                        }
                        return '';
                    }
                }
            ]
        ]
    });
}


/**
 * 删除入库凭证数据
 */
function delStatementItem() {
    var rows = $(el.tbDetails).datagrid('getSelections');
    if(rows.length === 0){
        topWin.layer.alert('请选择您要删除的入库明细', {icon: 0});
        return false;
    }

    for(var j = 0; j < rows.length; j++){
        var row = rows[j];
        if(Number(row.invoiceCompleteFlag) === 1){
            topWin.layer.alert('选择删除的行项目: ' + row.itemNo + '已经开票完成, 不能被删除', {icon: 0});
            return false;
        }
    }

    topWin.layer.confirm('您确定要删除选中的入库明细吗?', {icon: 3}, function (index) {
        topWin.layer.close(index);
        for(var i = 0; i < rows.length; i++){
            var item = rows[i];

            el.delDetail.push(item);
            var rowIndex = $(el.tbDetails).datagrid('getRowIndex', item);
            $(el.tbDetails).datagrid('deleteRow', rowIndex);
        }

        var dataRows = $(el.tbDetails).datagrid('getRows');
        calculationAmount(dataRows);
    });
}


/**
 * 数据保存
 *
 * @param callback 回调函数
 */
function confirmDel(callback) {
    var id = $(el.id).val(), taxAmount = $(el.taxAmount).textbox('getValue'), notTaxAmount = $(el.notTaxAmount).val();

    // 对账单明细
    var detail = $(el.tbDetails).datagrid('getRows'), dsiId = [];

    // 明细删除
    for(var i2 = 0; i2 < el.delDetail.length; i2++){
        dsiId.push(el.delDetail[i2].id);
    }

    topWin.layer.confirm('您确定要提交刚才删除的入库明细吗?', {icon: 3}, function (index) {
        topWin.layer.close(index);

        var loading = topWin.layer.msg('数据提交中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            type: 'POST',
            url: g.ctx + 'fin/account/statement/rest/force/del/detail',
            data: {
                id: id,
                taxAmount: Number(taxAmount.replace(/,/g,'')),
                notTaxAmount: Number(notTaxAmount.replace(/,/g,'')),
                delSiIds: dsiId.length === 0 ? '' : JSON.stringify(dsiId),
                delStatementFlag: detail.length === 0 ? 1 : 0
            },
            success: function () {
                topWin.layer.close(loading);
                callback();
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    });
}


/**
 * 计算页面相关金额
 */
function calculationAmount(rows) {
    var taxAmount = 0, notTaxAmount = 0, asDiffAmount = 0;
    for (var j = 0; j < rows.length; j++) {
        taxAmount = accAdd(taxAmount, rows[j].taxAmount);
        notTaxAmount = accAdd(notTaxAmount, rows[j].notTaxAmount);
        asDiffAmount = accAdd(asDiffAmount, rows[j].asDiffAmount);
    }

    $(el.taxAmount).textbox('setValue', formatNumber(taxAmount, 2, 1));
    $(el.notTaxAmount).val(formatNumber(notTaxAmount, 2, 1));

    // 更新页脚行的值并刷新
    var footers = $(el.tbDetails).datagrid('getFooterRows');
    footers[0]['taxAmount'] = formatNumber(taxAmount, 2, 1);
    footers[0]['notTaxAmount'] = formatNumber(notTaxAmount, 2, 1);
    footers[0]['diffTaxAmount'] = formatNumber(Number(taxAmount) - Number(notTaxAmount), 2, 1);
    footers[0]['asDiffAmount'] = formatNumber(asDiffAmount, 2, 1);
    $(el.tbDetails).datagrid('reloadFooter');
}