/**
 * 获取校验失败字段
 * @param formSelector
 */
function getInvalidFields(formSelector) {
    const list = [];
    // 头部校验
    $(formSelector).find('.validatebox-invalid').each(function () {
        const $input = $(this);

        // 1️⃣ 找到当前 input 所在的 td
        const $td = $input.closest('td');

        // 2️⃣ 找前一个 td 里的标题
        const titleText = $td
            .prev('td')
            .find('.ui-form-item-title')
            .text()
            .trim();

        if (titleText) list.push(titleText);
    });
    return list;
}

/**
 * 绑定帮助图标提示
 * @param tableEl
 */
function bindHelpIconTips(tableEl) {
    let tipIndex = null;
    const $dg = $(tableEl);
    $dg.datagrid('getPanel').off('click.helpIcon').on('click.helpIcon', '.help-icon', function (e) {
        e.preventDefault();
        e.stopPropagation();

        if (tipIndex) {
            layer.close(tipIndex);
            tipIndex = null;
            return;
        }

        const helpMessage ='（1）合同需录入合同签订日期，按合同签订日期计算付款起算日期，比如预付款在合同签订1个月内付款，判断付款日期。<br>' +
            '（2）当资产验收申请流程审核通过后，将验收日期反写至SRM，才可以发起资产验收款。<br>' +
            '（3）合同需录入质保期限。';

        tipIndex = layer.tips(
            `
                        <div class="custom-tip">
                            <span class="custom-tip-close">×</span>
                            <div class="custom-tip-content">
                                ${helpMessage}
                            </div>
                        </div>
                        `,
            this,
            {
                tips: [1, '#ffffff'],
                time: 0,
                closeBtn: 0,
                maxWidth: 520,
                area: '520px',
                skin: 'custom-layer-tip'
            }
        );
    });

    // 点击其它地方关闭
    $(document).off('click.helpIconDoc').on('click.helpIconDoc', function () {
        if (tipIndex) {
            layer.close(tipIndex);
            tipIndex = null;
        }
    });
}

/**
 * 添加点击表格空白处结束编辑
 * @param tableEl
 */
function bindEndEditOnBlank(tableEl) {
    const $dg = $(tableEl);
    const $panel = $dg.datagrid('getPanel');
    const $body = $panel.find('.datagrid-body'); // ✅ 关键：绑定到 body

    // 先解绑，防止重复绑定
    $body.off('mousedown.endEditBlank').on('mousedown.endEditBlank', function (e) {
        // 1) 点在行上：不处理
        if ($(e.target).closest('tr.datagrid-row').length) return;

        // 2) 点在 editor 上：不处理（避免误结束编辑）
        if ($(e.target).closest('.textbox, .combo, input, textarea, select').length) return;

        let editIndex;
        if (tableEl === el.table_tb) {
            editIndex = el.tbEditIndex
        } else if (tableEl === el.table_pay) {
            editIndex = el.payEditIndex
        }
        if (editIndex === undefined) return;

        // 3) 校验通过才结束
        if (!endEditing(tableEl, editIndex)) {
            layer.msg("请填写表格必填字段");
        }
    });
}

/**
 * 金额格式化：千分位 + 两位小数
 * @param {number|string} value
 * @return {string}
 */
function formatMoney(value) {
    if (value === null || value === undefined || value === '') return '0.00';

    const num = Number(value);
    if (isNaN(num)) return '0.00';

    // 保留两位小数
    const fixed = num.toFixed(2);

    // 千分位
    return fixed.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

/**
 * 金额比例发生变换之后，重新计算金额
 * @param newValue
 */
function paymentRatioChange(newValue) {
    calculatePaymentAmount(newValue)
}

/**
 * 计算付款金额
 * @param value
 */
function calculatePaymentAmount(value) {
    const contractAmount = Number($("#contractAmount").textbox('getValue').replace(/,/g,''));
    const paymentAmount = value * contractAmount;
    const paymentAmountEditor = $(el.table_pay).edatagrid('getEditor', {
        index: el.payEditIndex,
        field: 'paymentAmount' // 确保字段名正确
    });
    if (paymentAmountEditor) {
        $(paymentAmountEditor.target).numberbox('setValue', parseFloat(paymentAmount.toFixed(2)));
    }
}

/**
 * 加载合计行
 * @param tableEl 表ID
 */
function loadFooter(tableEl) {
    const $dg = $(tableEl);
    const rows = $dg.datagrid('getRows');
    let price = new BigNumber(0),       // 含税单价
        num = new BigNumber(0),         // 数量
        noTaxPrice = new BigNumber(0),  // 未税单价
        amount = new BigNumber(0);      // 含税金额
    for (let i = 0; i < rows.length; i++) {
        price = price.plus(new BigNumber(rows[i].price));
        num = num.plus(new BigNumber(rows[i].num));
        noTaxPrice = noTaxPrice.plus(new BigNumber(rows[i].noTaxPrice));
        amount = amount.plus(new BigNumber(rows[i].amount));
    }
    $dg.datagrid('reloadFooter', [
        {
            price: price,
            num: num,
            noTaxPrice: noTaxPrice,
            amount: amount
        }
    ]);
}

/**
 * 加载付款合计行
 * @param tableEl
 */
function loadPayFooter(tableEl){
    const $dg = $(tableEl);
    const rows = $dg.datagrid('getRows') || [];

    let paymentRatio = new BigNumber(0);
    let paymentAmount = new BigNumber(0);

    for (let i = 0; i < rows.length; i++) {
        paymentAmount = paymentAmount.plus(new BigNumber(rows[i].paymentAmount || 0));
        paymentRatio  = paymentRatio.plus(new BigNumber(rows[i].paymentRatio  || 0));
    }

    $dg.datagrid('reloadFooter', [{
        paymentAmount: paymentAmount,
        paymentRatio: paymentRatio.toFixed(4)
    }]);
}

/**
 * 验证必填字段
 * @returns {boolean}
 */
function validateRequiredFields() {
    const rows = $('#table_tb').datagrid('getRows');
    let hasError = false;

    // 遍历所有行
    for (let i = 0; i < rows.length; i++) {
        const row = rows[i];

        if (!row.stockPoint || row.stockPoint.trim() === '') {
            layer.msg(`第 ${i + 1} 行：存放地点不能为空！`, {icon: 2});
            hasError = true;
            break;
        }
    }

    return !hasError; // 返回 true 表示校验通过
}

/**
 * 选择存放地点
 */
function selectStockPoint() {
    openDictSelectDialog('选择存放地点', 'stock_point', function (data) {
        let stockPoint = $(el.table_tb).edatagrid('getEditor', {
            index: editor,
            field: 'stockPoint'
        });
        if (stockPoint && stockPoint.target) {
            $(stockPoint.target).textbox("setValue", data.code || '');
        }
        let stockPointName = $(el.table_tb).edatagrid('getEditor', {
            index: editor,
            field: 'stockPointName'
        });
        if (stockPointName && stockPointName.target) {
            $(stockPointName.target).textbox("setValue", data.name || '');
        }
    })
}

/**
 * 采购明细-计算明细行金额
 * @param tableEl 表ID
 * @param rowIndex 行索引
 */
function calculateDetailAmount(tableEl, rowIndex) {
    const $dg = $(tableEl);
    // 税率
    const taxRateCodeEditor = $dg.edatagrid('getEditor', {
        index: rowIndex,
        field: 'taxRateCode'
    });
    const taxRateCode = $(taxRateCodeEditor.target).combobox('getValue');
    const taxRate = getTaxRate(taxRateCode);
    const priceEditor = $dg.edatagrid('getEditor', {
        index: rowIndex,
        field: 'price'
    });
    // 含税单价
    const price = $(priceEditor.target).numberbox('getValue');
    const numEditor = $dg.edatagrid('getEditor', {
        index: rowIndex,
        field: 'num'
    });
    // 数量
    const num = $(numEditor.target).numberbox('getValue');

    const canTax = (taxRate !== null);

    let newNoTaxPrice = null;
    let newAmount = null;
    if (canTax) {
        newNoTaxPrice = round2(price / (1 + taxRate));
        newAmount = round2(price * num);
    }
    const noTaxPriceEditor = $dg.datagrid('getEditor', { index: rowIndex, field: 'noTaxPrice' });
    if (noTaxPriceEditor) $(noTaxPriceEditor.target).numberbox('setValue', newNoTaxPrice);

    const amountEditor = $dg.datagrid('getEditor', { index: rowIndex, field: 'amount' });
    if (amountEditor) $(amountEditor.target).numberbox('setValue', newAmount);
}

/**
 * 获取税率
 * @param taxRateCode 税率代码
 * @returns {number|number}
 */
function getTaxRate(taxRateCode) {
    const taxData = getNecessaryDataList("pc/sys/tax/rest/listAll");
    const taxItem = taxData.find(item => item.code === taxRateCode);
    return taxItem ? (parseFloat(taxItem.taxValue)) : 0;
}

/**
 * 保留两位小数
 * @param n
 * @returns {number}
 */
function round2(n) {
    return Math.round(n * 100) / 100;
}

/**
 * 结束编辑
 * @param tableEl 表ID
 * @param index 行索引
 */
function endEditing(tableEl, index) {
    if (index === undefined) return true;
    const $dg = $(tableEl);
    if (!$dg.length) return true;

    if ($dg.datagrid('validateRow', index)) {
        $dg.datagrid('endEdit', index);
        $dg.datagrid('unselectRow', index);
        if (tableEl === el.table_tb) {
            el.tbEditIndex = undefined;
            loadFooter(tableEl);
            setMroTotalContractAmount();
        } else if (tableEl === el.table_pay) {
            el.payEditIndex = undefined;
            loadPayFooter(tableEl);
        }
        return true;
    } else {
        return false;
    }
}

//设置是mro合同总金额
function setMroTotalContractAmount(){
    let rowsTableTb = $('#table_tb').datagrid('getRows');
    let totalAmoutnt = 0;
    if (rowsTableTb && rowsTableTb.length > 0) {
        for (var i = 0; i < rowsTableTb.length; i++) {
            totalAmoutnt += parseFloat(rowsTableTb[i].price) * parseFloat(rowsTableTb[i].num);
        }
    }

    // 1. 更新合同总金额
    $("#contractAmount").textbox('setValue', formatMoney(totalAmoutnt));
    $('#contractAmountCapital').textbox('setValue', number_chinese(totalAmoutnt.toFixed(2)));

    // 2. 如果付款比例已填写，按比例计算付款金额
    let rows = $('#table_pay').datagrid('getRows');
    let hasPaymentRatio = false;
    rows.forEach(function(v) {
        if (v.paymentRatio !== null && v.paymentRatio !=='') {
            hasPaymentRatio = true;
        }
    });
    // 编辑中的不重新计算，关闭编辑后会自动计算
    rows = rows.filter(item => {
        return item.paymentRatio;
    })

    if (hasPaymentRatio) {
        // 检查所有付款比例是否都填写了
        let bl = 0;
        for (var i = 0; i < rows.length; i++) {
            bl += parseFloat(rows[i].paymentRatio);
        }

        // 按比例计算金额
        let je = new BigNumber(0);
        for (var i = 0; i < rows.length; i++) {
            rows[i].paymentAmount = new BigNumber(rows[i].paymentRatio).multipliedBy(new BigNumber(totalAmoutnt)).decimalPlaces(2, BigNumber.ROUND_HALF_UP);
            if (i < rows.length - 1) {
                je = je.plus(new BigNumber(rows[i].paymentAmount));
            }
        }
        // 最后一行 = 总金额 - 前 N-1 项和
        rows[rows.length - 1].paymentAmount = new BigNumber(totalAmoutnt).minus(je).decimalPlaces(2, BigNumber.ROUND_HALF_UP);

        // 更新表格
        rows.forEach(function(v, n) {
            $("#table_pay").datagrid('updateRow', {index: n, row: rows[n]});
            $('#table_pay').datagrid('refreshRow', n);
        });
        loadPayFooter(el.table_pay);
    }
}

/**
 * 付款明细-点击单元格
 * @param index 行索引
 * @param field 字段名
 */
function onClickCellPay(index, field) {
    if (endEditing(el.table_pay, el.payEditIndex)) {
        el.payEditIndex = index;
        const $dg = $(el.table_pay);

        $dg.datagrid('beginEdit', index);
        // 聚焦编辑器
        const editor = $dg.datagrid('getEditor', {index: index, field: field});
        if (editor && editor.target) $(editor.target).focus();
    }
}

/**
 * 采购明细-点击单元格
 * @param index 行索引
 * @param field 字段名
 */
function onClickCell(index, field) {
    // 步骤1：结束上一个单元格的编辑
    if (endEditing(el.table_tb, el.tbEditIndex)) {
        el.tbEditIndex = index;
        const $dg = $(el.table_tb);

        $dg.datagrid('beginEdit', index);
        // 聚焦编辑器
        const editor = $dg.datagrid('getEditor', {index: index, field: field});
        if (editor && editor.target) $(editor.target).focus();
    }
}

/**
 * 设置字段必填
 * @param $table
 * @param field
 * @param required
 * @param editIndex
 */
function setColumnRequired($table, field, required, editIndex) {
    // 1) 改 columns 配置（影响后续 beginEdit）
    var colOpt = $table.datagrid('getColumnOption', field);
    if (colOpt && colOpt.editor) {
        // editor 可能是字符串，也可能是对象
        if (typeof colOpt.editor === 'string') {
            colOpt.editor = { type: colOpt.editor, options: {} };
        }
        colOpt.editor.options = colOpt.editor.options || {};
        colOpt.editor.options.required = required;
    }

    // 2) 如果当前有正在编辑的行，把“当前 editor”也同步改掉（立刻生效）
    if (editIndex !== undefined && editIndex !== null) {
        const ed = $table.datagrid('getEditor', { index: editIndex, field: field });
        if (ed) {
            // textbox/combobox/numberbox 等底层都走 validatebox
            $(ed.target).validatebox({ required: required });

            // 如果刚关掉 required，把红框/invalid 状态清理掉
            if (!required) {
                $(ed.target).validatebox('validate'); // 重新验证一次，去掉 invalid
            }
        }
    }
}

/**
 * 新增采购明细
 */
function addDetail(){
    const rows = $(el.table_tb).datagrid('getRows');

    // 新增行：赋值必要字段，避免jQuery对象
    $(el.table_tb).datagrid('appendRow', {
        id: 0,
        customerCode: '',
        customerName: '',
        costCenterCode: '',
        costCenterName: '',
        stockPoint: '',
        stockPointName: ''
    });

    // 新增行后编辑
    onClickCell(rows.length - 1, "purchaseCode")
}

/**
 * 删除采购明细
 */
function delDetail() {
    let rows = $(el.table_tb).datagrid('getChecked');
    if (!rows || rows.length === 0) {
        layer.msg("请选中一条记录");
        return;
    }
    topWin.layer.confirm("是否删除", function (index) {
        rows.forEach(function (v,n) {
            var rowIndex = $(el.table_tb).datagrid('getRowIndex', v);
            $(el.table_tb).datagrid('deleteRow', rowIndex);
        });
        loadFooter(el.table_tb);
        setMroTotalContractAmount();
        topWin.layer.close(index);
    })
}

/**
 * 新增付款明细
 */
function addPay(){
    const rows = $(el.table_pay).datagrid('getRows');

    // 新增行：仅赋值必要字段，其他字段默认空（避免重复赋值）
    $(el.table_pay).datagrid('appendRow', {
        id: 0,
        paymentWay: 'B'
    });

    // 新增行后编辑
    onClickCellPay(rows.length - 1, "paymentStage")
}

/**
 * 删除付款明细
 */
// function delPay() {
//     let rows = $(el.table_pay).datagrid('getChecked');
//     if (!rows || rows.length === 0) {
//         layer.msg("请选中一条记录");
//         return;
//     }
//     topWin.layer.confirm("是否删除", function (index) {
//         rows.forEach(function (v) {
//             const rowIndex = $(el.table_pay).datagrid('getRowIndex', v);
//             $(el.table_pay).datagrid('deleteRow', rowIndex);
//         });
//         loadPayFooter(el.table_pay);
//         topWin.layer.close(index);
//     });
// }
function delPay() {
    const $dg = $(el.table_pay);
    const checked = $dg.datagrid('getChecked');

    if (!checked || checked.length === 0) {
        layer.msg("请选中一条记录");
        return;
    }

    topWin.layer.confirm("是否删除", function (index) {

        // 如果当前正在编辑，先结束编辑，避免删除正在编辑行导致内部状态异常
        endEditing(el.table_pay, el.payEditIndex);

        // 取索引并降序删除，防止索引漂移
        const idxs = checked
            .map(r => $dg.datagrid('getRowIndex', r))
            .filter(i => i >= 0)
            .sort((a, b) => b - a);

        idxs.forEach(i => $dg.datagrid('deleteRow', i));

        loadPayFooter(el.table_pay);
        topWin.layer.close(index);
    });
}

