/**
 * 生成合同公用函数
 */
const BUSINESS_TYPE = {
    INQUIRY: "1",   // 询价
    TENDER: "2"     // 招标
};
const CONTRACT_TYPE = {
    COST: "01",   // 费用合同
    ASSET: "02"   // 资产合同
};

const CREATE_CONTRACT_COMMON = {
    /**
     * 生成合同
     * @param contractType 01-费用合同；02-资产合同
     * @param tableEl 创建合同重新渲染表格ID
     * @param businessType 业务单据类型 1-询价单；2-招标单
     * @param businessId 业务单据ID
     */
    lookCreateContract: function(contractType, tableEl, businessType, businessId) {
        let title = "选择数据";
        if (contractType === CONTRACT_TYPE.COST) {
            title = "生成费用合同";
        } else if (contractType === CONTRACT_TYPE.ASSET){
            title = "选择数据生成合同";
        }
        let selectPageUrl;
        if (businessType === BUSINESS_TYPE.INQUIRY) {
            selectPageUrl = '/pc/inquiry/hall/xjlistUI?xjId=' + businessId + '&optType=' + contractType;
        } else if(businessType === BUSINESS_TYPE.TENDER){
            selectPageUrl = '/pc/tender/page/zblistUI?zbId=' + businessId + '&optType=' + contractType;
        }
        
        const lookCreateContractDialog = openDialog("lookCreateContractDialog", selectPageUrl, {
            title: title,
            width: '60%',
            height: '60%',
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                lookCreateContractDialog.dialog('destroy');
            },
            buttons: [
                {
                    text:'提交',
                    iconCls:'icon-save',
                    handler:function() {
                        topWin.frames['lookCreateContractDialog'].submitLookCreatContra(function (rows) {
                            if (contractType === CONTRACT_TYPE.COST) {
                                // 创建费用合同
                                CREATE_CONTRACT_COMMON.createCostContract(rows, businessType, function(resultFLag) {
                                    if (resultFLag) {
                                        $(tableEl).datagrid('reload');
                                    }
                                });
                            } else if (contractType === CONTRACT_TYPE.ASSET) {
                                // 创建资产合同
                                const data = rows[0];
                                CREATE_CONTRACT_COMMON.createContract(data, tableEl);
                            }
                            lookCreateContractDialog.dialog('close');
                        });
                    }
                },
                {
                    text: '关闭',
                    handler: function () {
                        lookCreateContractDialog.dialog('close');
                    }
                }
            ]
        });
    },

    /**
     * 批量生成合同
     * @param contractType 合同类型；01-费用合同；02-资产合同
     * @param tableEl 批量创建合同重新渲染表格ID
     * @param businessType 业务单据类型 1-询价单；2-招标单
     */
    lookBatchCreateContract: function(contractType, tableEl, businessType){
        let title = "选择数据";
        if (contractType === CONTRACT_TYPE.COST) {
            title = "批量生成费用合同";
        } else if (contractType === CONTRACT_TYPE.ASSET){
            title = "批量选择数据生成合同";
        }
        let batchCreateUrl = '/pc/inquiry/hall/inquiryListUI?optType=' + contractType;
        const lookBatchCreateContractDialog = openDialog("lookBatchCreateContractDialog", batchCreateUrl, {
            title: title,
            width: '100%',
            height: '100%',
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                lookBatchCreateContractDialog.dialog('destroy');
            },
            buttons: [
                {
                    text:'提交',
                    iconCls:'icon-save',
                    handler:function() {
                        topWin.frames['lookBatchCreateContractDialog'].submitLookCreatContra(function (rows) {
                            if (contractType === CONTRACT_TYPE.COST) {
                                // 创建费用合同
                                CREATE_CONTRACT_COMMON.createCostContract(rows, businessType, function(resultFLag) {
                                    if (resultFLag) {
                                        $(tableEl).datagrid('reload');
                                    }
                                });
                            } else if(contractType === CONTRACT_TYPE.ASSET) {
                                // 创建资产合同
                                CREATE_CONTRACT_COMMON.batchCreateContract(rows);
                            }
                            lookBatchCreateContractDialog.dialog('close');
                        });
                    }
                },
                {
                    text: '关闭',
                    handler: function () {
                        lookBatchCreateContractDialog.dialog('close');
                    }
                }
            ]
        });
    },

    /**
     * 生成资产合同
     * @param data 创建合同数据
     * @param tableEl 重新渲染表格ID
     */
    createContract: function (data, tableEl){
        const createContractDialog = openDialog("createContractDialog",
            g.ctx+'pc/contract/mroManage/page/formDeatilById?supplierId='+data.supplierId+'&supplierCode='+data.supplierCode+'&supplierName='+data.supplierName+'&uuidKey='+data.uuidKey+'&check=1',
            {
                title: "生成合同",
                width: '90%',
                height:'100%',
                cache: false,
                modal: true,
                border: false,
                draggable: false,
                shadow: false,
                onClose: function () {
                    createContractDialog.dialog('destroy');
                },
                buttons: [
                    {
                        text:'暂存',
                        iconCls:'icon-save',
                        handler:function() {
                            topWin.frames['createContractDialog'].submitContractForm(0,function () {
                                createContractDialog.dialog('close');
                                $(tableEl).datagrid('reload');
                            });
                        }
                    },
                    {
                        text:'保存',
                        iconCls:'icon-save',
                        handler:function() {
                            topWin.frames['createContractDialog'].submitContractForm(1,function () {
                                createContractDialog.dialog('close');
                                $(tableEl).datagrid('reload');
                            });
                        }
                    },
                    {
                        text:'关闭',
                        iconCls:'icon-cancel',
                        handler:function() {
                            createContractDialog.dialog('close');
                        }
                    }
                ]
            }
        );
    },

    /**
     * 生成费用合同
     * @param rows 数据
     * @param businessType 业务单据类型 1-询价单；2-招标单
     * @param callback 回调
     */
    createCostContract: function(rows, businessType, callback) {
        let contractTotal = 0;
        rows.forEach(item => {
            contractTotal += item.detailAmount;
        });

        const data = {
            businessType: businessType,
            companyCode: rows[0].companyCode,               // 公司代码
            supplierId: rows[0].supplierId,                 // 供应商ID
            supplierCode: rows[0].supplierCode,             // 供应商代码
            supplierName: rows[0].supplierName,             // 供应商名称
            contractType: rows[0].contractType,             // 合同类型
            contractTotalAmount: contractTotal,             // 合同总金额
            invoiceType: rows[0].invoiceType,               // 发票类型
            createUserAccount: rows[0].createUserAccount,   // 申请人工号
            createUserName: rows[0].createUserName,         // 申请人姓名
            detail: rows                                    // 物料明细
        }
        $.ajax({
            url: g.ctx + "pc/sys/financialShare/rest/createCostContract",
            type: "POST",
            data: JSON.stringify(data),
            contentType: 'application/json',
            success: function () {
                topWin.layer.alert("生成成功", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    if (typeof callback === 'function') {
                        callback(true);
                    }
                });
            }, error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    },

    /**
     * 批量创建资产合同
     * @param data 批量创建合同数据
     * @param tableEl 重新渲染表格ID
     */
    batchCreateContract: function(data, tableEl){
        let idList = [];
        let supplierId = '';
        let materialCode = '';
        let supplierCode = '';
        let supplierName = '';
        let companyCode = '';
        let tmIdList = [];
        for(var i = 0; i < data.length; i++){
            idList.push(data[i].id);
            supplierId = data[i].supplierId;
            supplierCode = data[i].supplierCode;
            supplierName = data[i].supplierName;
            materialCode =data[i].materialCode;
            companyCode =data[i].companyCode;
            tmIdList.push(data[i].tmId);
        }
        const batchCreateContractDialog = openDialog("batchCreateContractDialog",
            g.ctx+'pc/contract/mroManage/page/formBatchDetailByIds?ids='+idList.join(',')+'&supplierId='+supplierId+'&tmIdList='+tmIdList.join(',')
            +'&supplierCode='+supplierCode+'&supplierName='+supplierName+'&companyCode='+companyCode+'&check=1',
            {
                title: "批量生成合同",
                width: '90%',
                height:'100%',
                cache: false,
                modal: true,
                border: false,
                draggable: false,
                shadow: false,
                onClose: function () {
                    batchCreateContractDialog.dialog('destroy');
                },
                buttons: [
                    {
                        text:'暂存',
                        iconCls:'icon-save',
                        handler:function() {
                            topWin.frames['batchCreateContractDialog'].submitContractForm(0,function () {
                                batchCreateContractDialog.dialog('close');
                                $(tableEl).datagrid('reload');
                            });
                        }
                    },
                    {
                        text:'保存',
                        iconCls:'icon-save',
                        handler:function() {
                            topWin.frames['batchCreateContractDialog'].submitContractForm(1,function () {
                                batchCreateContractDialog.dialog('close');
                                $(tableEl).datagrid('reload');
                            });
                        }
                    },
                    {
                        text:'关闭',
                        iconCls:'icon-cancel',
                        handler:function() {
                            batchCreateContractDialog.dialog('close');
                        }
                    }
                ]
            }
        );
    },

    /**
     * 获取合同编码显示
     * @param item
     * @returns {string|*|string}
     */
    getContractCode: function (item) {
        if (item.contractCode) {
            if (item.contractType === "费用合同") {
                // 费用类合同
                if (item.contractUrl) {
                    return '<a href="' + item.contractUrl + '" target="_blank" style="color: blue;text-decoration: underline;">'
                        + item.contractCode +
                        '</a>';
                } else {
                    return '<span style="color: #686802;">' + item.contractCode + '(获取链接失败)<span';
                }
            } else {
                // 资产类合同
                return item.contractCode;
            }
        } else {
            return '<span style="color: red">' + "未转合同" + '<span';
        }
    }
};