/**
 *
 * 父画面调用时，按钮需要校验时参考如下代码，在onOpen加入回调
 *      openDialog("attachmentFileDetailDialog", url, {
 *           title: '送货单附件',
 *           ...
 *           onOpen: function() {
 *               // dialog打开后，等待iframe加载完成
 *               const iframe = $(this).find('iframe')[0];
 *               iframe.onload = async function() {
 *                   // 按钮需要校验时参考如下代码：
 *                   iframe.contentWindow.uploadValidation = accountStatementExistValidation;
 *                   ...
 *               };
 *           }
 *       });
 * @author Chen Tianshi
 * @version 1.0
 */
// let el = {
//     businessAttachment: '#businessAttachment'
// }
let uploadAttachmentFileDialog;
var businessTypeCode1 = businessCode2==null?"contract_payment_apply":businessCode2;

$(function () {
    // 初始化附件类型字典数据-businessFileTypeNecessaryData
    initDict("businessFileType");
    initOrderFileTb();
});

/**
 * 初始化表格
 */
function initOrderFileTb () {
    const column = [[
        {
            field: 'ck', checkbox: true
        }, {
            field: 'type', title: "附件类型", width: '10%', formatter: function (value) {
                return getNameByCode(businessFileTypeNecessaryData, value);
            }
        },
        {
            field: 'billCode', title: "单据编号", width: '15%'
        },
        {
            field: 'fileName', title: "附件名称", width: '20%'
        }, {
            field: 'deleteFlag', title: "删除标记", formatter: function (value) {
                if (value === 1) {
                    return "<span style='color: red;'>是</span>"
                }
                return "否"
            }
        }, {
            field: 'remark', title: "备注", width: '20%'
        }, {
            field: 'updateUser', title: "最近修改人"
        }, {
            field: 'updateTime', title: "最近修改时间"
        }, {
            field: 'fileId', title: BJGL.BJGL__XZ, width: '10%', formatter: function (value, row) {
                return '<a href="#" onclick="previewFileForm(undefined,\'' + row.fileName + '\',\'' + row.fileId + '\')">预览</a>'+"&nbsp;&nbsp;<a href='" + g.ctx + "pc/sys/file/rest/download/" + value + "' title='" + row.fileName + "'>下载</a>"
            }
        }
    ]];

    let toolbar = [
        // {
        //     text: "导入合同附件及送货单附件", iconCls: 'icon-add', hidden: true, handler: importAttachmentFile
        // }, "-",
        {
            text: BJGL.BJGL__SC, iconCls: 'icon-add', hidden: true, handler: uploadAttachmentFile
        }, "-", {
            text: BJGL.BJGL__SHANC, iconCls: 'icon-remove', handler: deleteAttachmentFile
        }, "-", {
            text: "设置备注", iconCls: 'icon-remove', handler: remarkAttachmentFile
        }
    ];
    if (optType === 2) {
        toolbar = [
        ];
    }


    const url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentList?businessId=' + businessId + '&businessTypeCodes=contract_payment_apply&billCode=' + contractTempCode;
    // 加载附件列表
    $(el.tbAttachment).datagrid({
        url: url,
        height: document.documentElement.clientHeight - 10,
        method: "GET",
        width: gridwidth,
        singleSelect: true,
        pagination: true,
        autoHeight: true,
        loadMsg: ALLCOMMON.LOADING,
        rownumbers: true,
        fitColumns: false,
        nowrap: true,
        remoteSort: false,
        striped: true,
        columns: column,
        toolbar: toolbar,
        loadFilter: tbAttachmentFilter,
        onLoadSuccess: async function (data) {
            var rows = $(el.tb).datagrid('getRows');
            var contractNo ="";
            var contractType = "";
            var paymentType = "";
            for (var i = 0; i < rows.length; i++) {
                var obj = {}, item = rows[i];
                contractNo = item.contractNo;
                //合同类型 模具与非模具
                contractType = item.contractType;
                //付款阶段
                paymentType = item.paymentAround;
                break;
            }
            var grid = $("#tbAttachment");
            const allRows = await getAllBusinessData(data.rows);
            for (let ii = 0; ii < allRows.length; ii++) {
                debugger
                var sysCheck = 0;
                // for(var i = 0
                // 判断对账单是否有附件
                if (allRows[ii].type==='escrow_agreement') {
                    el.tbEscrowAgreementFileRowsExt = true;
                }
                // 判断对账单是否有附件
                if (allRows[ii].type==='contract_delivery') {
                    el.tbDeliveryFileRowsExt = true;
                }
                //判断购销合同是否有附件
                if (allRows[ii].type==='contractType') {
                    el.tbContractFileRowsExt = true;
                    //设置合同编号
                    allRows[ii].billCode = contractNo;
                    grid.datagrid('refreshRow', ii);
                    // var rows = grid.datagrid('getRows');
                    // if (rowIndex < 0 || rowIndex >= rows.length) {
                    //     console.error("无效的行索引：" + rowIndex);
                    //     return false;
                    // }

                    // $("#tbAttachment").datagrid('updateRow', {
                    //     index: ii,
                    //     row: {
                    //         billNo: contractNo
                    //     }
                    // });

                }
                //进度报告判断
                if (allRows[ii].type==='progress_report'){
                    el.tbProgressReportFileRowsExt = true;
                }
            }

            // if ($(el.id).val() != null && $(el.id).val() > 0) {

                var queryType = "contract_payment_apply";
                if (contractType && contractType !== "03") {
                    if (paymentType === "01") {
                        queryType = "contract_payment_no_model_one_check";
                    } else if (paymentType === "02") {
                        queryType = "contract_payment_no_model_two_check";
                    } else if (paymentType === "03") {
                        queryType = "contract_payment_no_model_three_check";
                    } else {
                        queryType = "contract_payment_no_model_four_check";
                    }
                } else if (contractType) {
                    if (paymentType === "01") {
                        queryType = "contract_payment_model_one_check";
                    } else if (paymentType === "02") {
                        queryType = "contract_payment_model_two_check";
                    } else if (paymentType === "03") {
                        queryType = "contract_payment_model_three_check";
                    } else {
                        queryType = "contract_payment_model_four_check";
                    }
                }
                $(el.tbAttachmentManualCheck).datagrid('options').queryParams = {
                    businessType: 4,
                    // currencyCode: $(el.currencyCode).textbox('getValue'),
                    // paymentWay: $(el.paymentWay).combobox('getValue'),
                    businessId: businessId,
                    businessCode: businessTypeCode1,
                    paymentWay: queryType
                };
                $(el.tbAttachmentManualCheck).datagrid('options').url = g.ctx + 'pc/finance/attachment/manual/check/rest/list';
                $(el.tbAttachmentManualCheck).datagrid('load');
            // }
        }
    });
}

function importAttachmentFile() {
    debugger
    var paymentType = $(el.paymentType).combobox('getValue');
    //如果是质保款，则返回， 如果是模具类的进度度，则返回
    if (paymentType === "04") {
        return;
    }
    var rows = $(el.tb).datagrid('getRows');
    if (rows.length === 0) {
        // topWin.layer.alert('请添加付款合同明细数据', {icon: 0});
        // return false;
    }
    var itemList = [];
    for (var i = 0; i < rows.length; i++) {
        var obj = {}, item = rows[i];
        //如果是模具类的进度款，则返回
        if (item.contractType === "03" && paymentType === "02") {
            //return;
        }

        obj.contractNo = item.contractNo;
        obj.id = businessId;
        //合同类型 模具与非模具
        obj.contractType = item.contractType;
        //付款阶段
        obj.paymentAround = paymentType;
        //0新增 1修改 2查看不查后台
        obj.optType = optType;
        itemList.push(obj);
    }

    $.ajax({
        url: g.ctx + 'pc/contract/payment/rest/data/importAttachement',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(itemList),
        success: function () {
            // topWin.layer.msg('导入成功', {icon: 1});
            $(el.tbAttachment).datagrid('reload');
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });


}

/**
 * 上传
 */
function uploadAttachmentFile() {
    var rows = $(el.tb).datagrid('getRows');
    if (rows.length === 0) {
        topWin.layer.alert('请添加付款合同明细数据', {icon: 0});
        return false;
    }
    //businessTypeCode1 需要动态设置
    //根据模具非模具，根据01预付款，02进度款 03验收款 04质保款，去数据库配置查询要上传的类型
    var paymentType = $(el.paymentType).combobox('getValue');
    var contractType = $(el.paymentType).combobox('getValue');
    for (let i = 0; i < rows.length; i++) {
        var item = rows[i]
        //合同类型 模具与非模具
        contractType = item.contractType;
    }
    //03非模具类型合同
    var businessTypeCode22 = "contract_payment_apply";
    if (contractType !== "03") {
        if (paymentType === "01") {
            businessTypeCode22 = "contract_payment_no_model_one";
        } else if (paymentType === "02") {
            businessTypeCode22 = "contract_payment_no_model_two";
        } else if (paymentType === "03") {
            businessTypeCode22 = "contract_payment_no_model_three";
        } else {
            businessTypeCode22 = "contract_payment_no_model_four";
        }
    } else {
        if (paymentType === "01") {
            businessTypeCode22 = "contract_payment_model_one";
        } else if (paymentType === "02") {
            businessTypeCode22 = "contract_payment_model_two";
        } else if (paymentType === "03") {
            businessTypeCode22 = "contract_payment_model_three";
        } else {
            businessTypeCode22 = "contract_payment_model_four";
        }
    }


    openCommonFileDialog('commonFileDialog',{
        //业务类型编码
        title:'附件上传',
        //业务类型编码
        businessTypeCode:businessTypeCode22,
        businessCode:businessTypeCode1,
        //业务唯一id
        businessId:businessId,
        callBack : function () {
            $(el.tbAttachment).datagrid('reload');
        },
    });
}

/**
 * 上传完文件的回调
 * @param data 上传文件服务器后的文件数据
 */
function receiveFileUploadData(data) {
    data.forEach(item => {
        item["businessId"] = businessId;
        item["businessCode"] = businessTypeCode1;
        item["businessTypeCode"] = businessTypeCode;
    })
    $.ajax({
        url: g.ctx + 'pc/contract/payment/rest/data/importAttachement',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function () {
            topWin.layer.msg('保存成功', {icon: 1});
            $(el.tbAttachment).datagrid('reload');
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });

    uploadAttachmentFileDialog.dialog('close');
}

/**
 * 删除
 */
function deleteAttachmentFile() {
    const rows = $(el.tbAttachment).datagrid("getChecked");
    if (rows.length > 0) {
        // if (!validation(window.deleteValidation, rows, businessId)) return;
        // if (!validation(window.deleteInvoiceValidation, rows, businessId)) return;
        const id = rows[0].id;

        var loading = topWin.layer.msg('数据操作中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'pc/sys/businessAttachment/rest/deleteCheck',
            type: 'POST',
            data: {
                id: id
            },
            success: function (result) {
                topWin.layer.close(loading);
                topWin.layer.prompt({
                    formType: 2, value: '', title: '请输入删除备注',
                }, function (value, index) {
                    $.ajax({
                        type: 'post',
                        url: g.ctx + 'pc/sys/businessAttachment/rest/delete',
                        data: {
                            id: id,
                            remark: value,
                            businessTypeCode: 'contract_payment_apply'
                        },
                        async: false,
                        success: function () {
                            $(el.tbAttachment).datagrid('reload');
                            topWin.layer.close(index);
                        }, error: function (data) {
                            topWin.layer.close(index);
                            topWin.layer.alert(data.responseJSON.message, {icon: 2});
                        }
                    });
                });
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    } else {
        layer.msg('请选择一条数据');
    }
}

/**
 * 备注
 */
function remarkAttachmentFile() {
    const rows = $(el.tbAttachment).datagrid("getChecked");
    if (rows.length > 0) {
        if (!validation(window.remarkValidation, rows, businessId)) return;
        const id = rows[0].id;
        topWin.layer.prompt({
            formType: 2, value: '', title: '请输入备注',
        }, function (value, index) {
            $.ajax({
                type: 'post',
                url: g.ctx + 'pc/sys/businessAttachment/rest/remark',
                data: {
                    id: id,
                    remark: value
                },
                async: false,
                success: function () {
                    $(el.tbAttachment).datagrid('reload');
                    topWin.layer.close(index);
                }, error: function (data) {
                    topWin.layer.close(index);
                    topWin.layer.alert(data.responseJSON.message, {icon: 2});
                }
            });
        });
    } else {
        layer.msg('请选择一条数据');
    }
}

/**
 * 根据code获取对应的name
 * @param {Array} list - 文件类型列表
 * @param {string} code - 要查找的code
 * @returns {string|null} 对应的name，找不到返回null
 */
function getNameByCode(list, code) {
    const item = list.find(item => item.code === code);
    return item ? item.name : null;
}

/**
 * 按钮校验
 * @param parentValidationFunction 父画面的校验回调
 * @param rows 选中的行数据
 * @param businessId 业务ID
 * @returns {boolean} 结果
 */
function validation(parentValidationFunction, rows, businessId) {
    if (typeof parentValidationFunction === 'function') {
        /**
         * result: {
         *     isError: false/true
         *     message: 校验信息
         * }
         */
        const result = parentValidationFunction(rows, businessId);
        if (result.isError) {
            topWin.layer.alert(result.message, {icon: 2});
            return false;
        }
    }
    return true;
}

/**
 * 附件清单个根据单据编码去重复
 * @param data
 */
function tbAttachmentFilter(data) {
    const rows = data.rows;
    const uniqueRows = [];
    const seenCodes = new Set();

    for (const row of rows) {
        if (!seenCodes.has(row.businessCode)) {
            seenCodes.add(row.businessCode);
            uniqueRows.push(row);
        }
    }

    data.rows = uniqueRows;
    return data;
}

/**
 * 获取所有业务附件
 */
async function getAllBusinessData(rows) {
    if (rows.length === 0) return [];
    const url = $(el.tbAttachment).datagrid('options').url;
    if (isBlank(url)) return [];
    const detailRows = await new Promise((resolve, reject) => {
        $.ajax({
            url: url,
            type: "GET",
            success: resolve,
            error: reject
        });
    });
    return detailRows.rows;
}