/**
 * 打开发票云上传助手
 */
function loadKingdeeAssistant() {
    if (!$(el.accountStatementId).val()) {
        topWin.layer.alert('请先选择对账单');
        return false
    }
    const data = {
        // TODO 注释掉这几个还需要继续和金蝶人员确认，何时取到单据编码，怎么取
        // billId: billId,
        // billNo: billNo,
        // billType: "开票申请单",
        billId: $(el.accountStatementNo).textbox('getValue'),
        billNo: $(el.accountStatementNo).textbox('getValue'),
        billType: "er_tripreimbursebill",
        resource: "SRM",
        billTaxNo: billTaxNo,
        // userId: "13328993206",
        pushType: "socket",
        linkKey: $(el.accountStatementNo).textbox('getValue'),
        companyInfo: [
            {
                // taxNo: companyTaxNo,
                // name: companyName
                taxNo: '91440300582702079P',
                name: '深圳市智微智能科技股份有限公司'
            }
        ],
        salerInfo: [
            {
                // taxNo: companyTaxNo,
                taxNo: '91441900MA4UK7907R',
                // name: companyName
                name: '东莞高远兴精密螺丝有限公司'
            }
        ]
    };
    $.ajax({
        type: 'post',
        url: g.ctx + 'pc/sys/kingdeeInvoiceCloudAssistant/rest/getAssistantInfo',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: function (data) {
            const httpUrl = kingdeeHostUrl;
            const wssUrl = kingdeeSocketUrl;
            const accessToken = data.accessToken;
            const eventCode = data.eventCode;

            let socket = new WebSocket(wssUrl + "/msgwatch/?identifytype=" + $(el.accountStatementNo).textbox('getValue') + "&token=" + accessToken);
            //打开事件
            socket.onopen = function () {
                setInterval(function () {
                    socket.send("{\"handshake\":false}");
                }, 20000);
            };
            //获得消息事件
            socket.onmessage = async function (msg) {
                const obj = JSON.parse(msg.data);
                let invoiceData = obj.invoiceData;
                let allData = $(el.tbInvoice).datagrid("getRows");

                for (let i = 0; i < invoiceData.length; i++) {
                    let sameFlag = false;
                    for (let j = 0; j < allData.length; j++) {
                        if (allData[j].electronInvoiceNumber === invoiceData[i].invoiceNo || allData[j].invoiceCode === invoiceData[i].invoiceNo) {
                            sameFlag = true;
                            break;
                        }
                    }
                    if (sameFlag){
                        continue;
                    }
                }

                invoiceData = invoiceData.filter(item => {
                    let existFlag = false;
                    for (let i in allData) {
                        const data = allData[i];
                        if (data.electronInvoiceNumber === item.invoiceNo || data.invoiceCode === item.invoiceNo) {
                            existFlag = true;
                        }
                    }
                    return !existFlag;
                })
                if (invoiceData.length === 0) {
                    if (assistantUploadWindow) {
                        assistantUploadWindow.close();
                    }
                    return;
                }
                for (let index in invoiceData) {
                    if (index === "remove") continue;
                    const row = invoiceData[index];
                    console.log(row)
                    let taxData;
                    if (row.items && row.items.length !== 0) {
                        taxData = taxDict.filter(item => {
                            return item.itemValue == row.items[0].taxRate;
                        });
                    }
                    let fileId;
                    await $.ajax({
                        url: g.ctx + 'pc/sys/kingdeeInvoiceCloudAssistant/rest/downloadAndUploadFile',
                        method: 'POST',
                        data: {
                            downloadUrl: row.downloadUrl,
                            fileName: row.originalFileName
                        },
                        success: function (data) {
                            fileId = data.id;
                        },
                        error: function () {}
                    });
                    var deductionCodeType ;
                    if (row.deductionFlag){
                        deductionCodeType = Number(row.deductionFlag)===0?2:1;
                    }
                    let newRow = {
                        id: 0,
                        dutyParagraph: el.supplierBusinessRegisterNo,
                        currencyCode: el.supplierCurrencyCode,
                        invoiceDate: row.invoiceDate,
                        deductionCodeType: deductionCodeType,
                        taxRate: taxData[0].itemCode,
                        taxAmount: row.totalTaxAmount,
                        noTaxAmount: row.invoiceAmount,
                        diffTaxMoney: row.totalTaxAmount,
                        erpJson: JSON.stringify(row),
                        fileId: fileId
                    };
                    if (row.isElectricInvoice === "1") {
                        newRow.electronInvoiceNumber = row.invoiceNo;
                        newRow.invoiceCode = row.invoiceCode;
                    } else {
                        newRow.invoiceCode = row.invoiceCode;
                        newRow.invoiceNumber = row.invoiceNo;
                    }
                    $(el.tbInvoice).edatagrid('appendRow', newRow);
                    initFileForm('invoice-file-form');
                }
                if (assistantUploadWindow) {
                    assistantUploadWindow.close();
                }
            };
            //关闭事件
            socket.onclose = function () {
                console.log("连接关闭");
                if (assistantUploadWindow) {
                    assistantUploadWindow.close();
                }
            };
            //发生了错误事件
            socket.onerror = function () {
                topWin.layer.alert('发票云通讯失败, 请联系管理员', {icon: 0});
                if (assistantUploadWindow) {
                    assistantUploadWindow.close();
                }
            };
            const url = httpUrl + '/index.html?userId=Guest&formId=rim_fpzs_main&&eventCode=' + eventCode;
            assistantUploadWindow = window.open(url, '_blank');
            // IFrame的方式会被浏览器的安全机制，控制住Cookie导致无法访问，废弃
            // const reqUrl = encodeURIComponent(httpUrl + 'index.html?formId=rim_fpzs_main&&eventCode=' + eventCode);
            // const url = httpUrl + "accessTokenLogin.do?encode=true&access_token=" + accessToken + '&redirect=' + reqUrl;
            // let kingdeeAssistantDialog = openDialog("kingdeeAssistantDialog", url, {
            //     title: '发票上传',
            //     width: '1230px',
            //     height: '740px',
            //     cache: false,
            //     modal: true,
            //     border: false,
            //     draggable: true,
            //     shadow: false,
            //     onClose: function () {
            //         kingdeeAssistantDialog.dialog('destroy');
            //     },
            //     buttons: [{
            //         text: '关闭', iconCls: 'icon-cancel', handler: function () {
            //             kingdeeAssistantDialog.dialog('close');
            //         }
            //     }]
            // });
        },
        error: function (error) {
            topWin.layer.alert(error.responseJSON.message, {
                icon: 2,
                content: error.responseJSON.message
            });
        }
    });
}