var el = {
    form : '#form',
    useState: '#useState',
    attachment: '#attachment',
    shareFlag: '#shareFlag',
    deductionType: '#deductionType',
    taxCode: '#taxCode',
    poCodeAndItemNo: '#poCodeAndItemNo',
    qualityNotice: '#qualityNotice',
    claimOrder: '#claimOrder',
    poItemNo: '#poItemNo',
    emptyTd: '.empty-td',
    poData: '.po_data',
    qualityNoticeData: '.quality_notice_data',
    claimOrderData1: '.claim_order_data1',
    poCodeAndItemNo: '#poCodeAndItemNo',
    poCode: '#poCode',
    qualityNoticeCode: '#qualityNoticeCode',
    claimOrderCode: '#claimOrderCode',
    deductionAmount: '#deductionAmount',
    dntAmount: '#dntAmount',
    taxValue: '#taxValue',
    currency: '#currency',
    purchaseGroup: '#purchaseGroup',
    supReplyAttachment: '#supReplyAttachment',
    supplierName: '#supplierName',
    supplierCode: '#supplierCode',
    currency: '#currency',
    deductionExecutionProcurement: '#deductionExecutionProcurement',
}


/**
 * 初始化页面特殊输入框
 */
$(function () {
    if (window.localStorage) {
        localStorage.userName =$('#userName').val();
    }
    var deductionType = $(el.deductionType).combobox('getValue');
    showHiddenRow(deductionType);


    // 扣款类型关联框
    $(el.poCodeAndItemNo).textbox({
        tipPosition: 'bottom',
        prompt: '请输入采购订单数据',
        required: false,
        width: 200,
    });
    $(el.qualityNotice).textbox({
        tipPosition: 'bottom',
        prompt: '请输入质量通知单数据',
        required: false,
        width: 200,
    });
    $(el.claimOrder).textbox({
        tipPosition: 'bottom',
        prompt: '请输入索赔单数据',
        required: false,
        width: 200,
    });
    // 初始化是否分摊下拉框
    $(el.shareFlag).combobox({
        valueField: 'value',
        textField: 'label',
        data: [
            {label: '需要', value: 1},
            {label: '不需要', value: 0},

        ],
        editable: false,
        prompt: '-- 请选择 --',
        panelHeight: 'auto'
    });
    // 初始化扣款类型下拉框
    $(el.deductionType).combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=back_type',
        panelHeight: 260,
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '-- 请选择 --',
        editable: false,
        onSelect: function (data) {
            showHiddenRow(data.code);
        }
    });
    // 初始化公司下拉框
    $('#companyCode').combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        url: g.ctx + 'pc/sys/company/rest/listAll',
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        panelWidth: 300,
        onSelect:function (data) {
            console.log(data)
            $('#companyName').val(data.companyName);
        }
    });
    // 初始化採購組织下拉框
    $('#purchaseOrg').combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        url: g.ctx + 'pc/sys/purchaseOrg/rest/listAll',
        editable: false,
        panelMaxHeight:180,
        prompt: '--- 请选择 ---',
        // panelHeight: 'auto',
        panelWidth: 300,
        // onSelect:function (data) {
        //     $('#companyName').textbox('setValue',data.companyName);
        // }
    });
    // 初始化採購組下拉框
    $('#deductionExecutionProcurement').combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll',
        editable: false,
        panelMaxHeight:180,
        prompt: '--- 请选择 ---',
        // panelHeight: 'auto',
        panelWidth: 300,
        // onSelect:function (data) {
        //     $('#companyName').textbox('setValue',data.companyName);
        // }
    });

    $('#purchaseGroup').combobox({
        valueField: 'purchaseGroupCode',
        textField: 'purchaseGroupName',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/createListAll',
        editable: false,
        panelMaxHeight:180,
        prompt: '--- 请选择 ---',
        // panelHeight: 'auto',
        panelWidth: 300,
        // onLoadSuccess:function (data) {
        //     $('#purchaseGroup').combobox('setValue',data[0].purchaseGroupCode);
        // }
        // onSelect:function (data) {
        //     $('#companyName').textbox('setValue',data.companyName);
        // }
    });

    // 初始化工厂下拉框
    $('#factory').combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        url: g.ctx + 'pc/sys/factory/rest/listAll',
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        panelWidth: 300,
        onLoadSuccess: function(data) {
            var defaultValue = '1000';
            $('#factory').combobox('setValue', defaultValue);
        }
        // onSelect:function (data) {
        //     $('#factory').textbox('setValue',1000);
        // }
    });
    // 初始化币种下拉框
    $(el.currency).combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=currency',
        panelHeight: 260,
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '-- 请选择 --',
        editable: false
    });
    // 初始化价格单位下拉框
    $(el.priceUnit).combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=price_unit_id',
        panelHeight: 260,
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '-- 请选择 --',
        editable: false
    });
    // 初始化税率下拉框
    // $(el.taxCode).combobox({
    //     url: g.ctx + 'pc/sys/dict/getDicByType?type=tax',
    //     panelHeight: 260,
    //     method: 'GET',
    //     valueField: 'code',
    //     textField: 'name',
    //     prompt: '-- 请选择 --',
    //     editable: false
    // });
    $('#taxCode').combobox({
        valueField: 'taxCode',
        textField: 'taxName',
        url: g.ctx + 'pc/sys/tax/rest/listAll',
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        panelWidth: 300,
        tipPosition: 'bottom',
        // onSelect: function (data) {
        //     var taxValue = data.taxName.match(/\d+/g)[0];
        //     $(el.taxValue).val(taxValue);
        //
        //     var deductionAmount = $(el.deductionAmount).numberbox('getValue');
        //     if(deductionAmount){
        //         var dntAmount = (Number(deductionAmount) / (Number(taxValue) / 100 + 1)).toFixed(2);
        //         $(el.dntAmount).numberbox('setValue', dntAmount);
        //     }
        // }
    });
    // 含税扣款金额变更
    // $(el.deductionAmount).numberbox({
    //     onChange: function (value, oldValue) {
    //         var taxValue = $(el.taxValue).val();
    //         if(taxValue){
    //             var dntAmount = (Number(value) / (Number(taxValue) / 100 + 1)).toFixed(2);
    //             $(el.dntAmount).numberbox('setValue', dntAmount);
    //         }
    //     }
    // });
});

/**
 * @param call
 * 编辑和保存
 */

function saveOrUpdate(call) {
    if($(el.form).form('validate')){
        var formData = $(el.form).serializeJson();
        var attachData = $(el.attachment).attr('data-fileIds')
        formData.attachment = attachData
        var supAttachData = $(el.supReplyAttachment).attr('data-fileIds')
        formData.supReplyAttachment = supAttachData
        // 获取 textarea 元素
        var textarea = document.getElementById('deductionReason');
// 获取 textarea 的值并去除首尾空格
        var deductionReason = textarea.value.trim();
        if (deductionReason=== null || deductionReason === undefined || deductionReason === "") {
            layer.msg("请填写扣款原因");
            return;
        }
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            contentType: 'application/json',
            url: g.ctx + 'pc/finance/deduction/rest/saveOrUpdate',
            method: 'post',
            data: JSON.stringify(formData),
            success: function (data) {
                call();
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                layer.alert(JSON.parse(data.responseText).message);
            }
        });
    }else{
        layer.msg("红色框为必输项，请填写！");
    }
}

// function saveOrUpdate(call) {
//     if($(el.form).form('validate')){
//         var formData = $(el.form).serializeJson();
//         var attachData = $(el.attachment).attr('data-fileIds')
//         formData.attachment = attachData
//         var supAttachData = $(el.supReplyAttachment).attr('data-fileIds')
//         formData.supReplyAttachment = supAttachData
//         var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
//         $.ajax({
//             contentType: 'application/json',
//             url: g.ctx + 'pc/finance/deduction/rest/saveOrUpdate',
//             method: 'post',
//             data: JSON.stringify(formData),
//             success: function (data) {
//                 call();
//             },
//             complete: function(data) {
//                 top.layer.close(loading);
//             },
//             error: function (data) {
//                 layer.alert(JSON.parse(data.responseText).message);
//             }
//         });
//     }else{
//         layer.msg("红色框为必输项，请填写！");
//     }
// }

function submit(call) {
    if($(el.form).form('validate')){
        var formData = $(el.form).serializeJson();
        var flag = formData.flag
        var attachData = $(el.attachment).attr('data-fileIds')
        formData.attachment = attachData
        console.log("formData.attachment"+ formData.attachment)
        console.log(1457863)
        if(formData.attachment == null || formData.attachment == ''){
            layer.msg("请上传附件");
            return;
        }
        var supAttachData = $(el.supReplyAttachment).attr('data-fileIds')
        formData.supReplyAttachment = supAttachData
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            contentType: 'application/json',
            url: g.ctx + 'pc/finance/deduction/rest/submit?flag=' + flag,
            method: 'post',
            data: JSON.stringify(formData),
            success: function (data) {
                call();
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                layer.alert(JSON.parse(data.responseText).message);
            }
        });
    }else{
        layer.msg("红色框为必输项，请填写！");
    }
}
/**
 * 选择用户
 */
function userSearch (type) {
    if(type == 1){
        var roleCodes = "apply_accounting";
    }else if(type == 2){
        var roleCodes = "CZ replace";
    }
    var userDialogElement = openDialog("userDialog", g.ctx + "pc/sys/user/index?select=1&single=0&roleCodes=" + roleCodes, {
        title: "用户选择",
        width: '80%',
        height: '80%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            userDialogElement.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.save,
            handler: function () {
                topWin.frames['userDialog'].chooseRow(function (rows) {
                    //数组得用rows[0]
                    if(type===1){
                        //应付会计
                        $('#apAccountantName').textbox('setValue', rows[0].username);
                        $('#apAccountant').val(rows[0].id);
                    }else if(type===2){
                        //扣款执行采购
                        $('#deductionExecutionProcurementName').textbox('setValue', rows[0].username);
                        $('#deductionExecutionProcurement').val(rows[0].id);
                    }
                    userDialogElement.dialog('close');
                });
            }
        }, {
            text: '关闭', iconCls: 'icon-cancel', handler: function () {
                userDialogElement.dialog('close');
            }
        }]
    })
}
function userSearch1 () {
    userSearch(1)
}
function userSearch2 () {
    userSearch(2)
}
/**
 * 选择不同扣款类型 隐藏显示不同输入框
 *
 * @param deductionType 扣款类型 1:质量扣款 2:延期扣款 3:索赔扣款 4:其他
 */
function showHiddenRow(deductionType) {
    if(1 === Number(deductionType) || 2 === Number(deductionType) || 3 === Number(deductionType) || 4 === Number(deductionType)){
        $(el.emptyTd).hide();
    }

    var poData = $(el.poData), qualityNoticeData = $(el.qualityNoticeData), claimOrderData1 = $(el.claimOrderData1);
    if (Number(deductionType) === 1) {
        $(el.poCode).val('');
        $(el.poItemNo).val('');

        qualityNoticeData.css('display', 'table-cell');
        poData.css('display', 'none');
        claimOrderData1.css('display', 'none');
    }
    if (Number(deductionType) === 2) {
        $(el.qualityNoticeCode).val('');

        poData.css('display', 'table-cell');
        qualityNoticeData.css('display', 'none');
        claimOrderData1.css('display', 'none');
    }
    if (Number(deductionType) === 3) {
        $(el.claimOrderCode).val('');
        claimOrderData1.css('display', 'table-cell');
        poData.css('display', 'none');
        qualityNoticeData.css('display', 'none');
    }
    if (Number(deductionType) === 4) {
        $(el.poCode).val('');
        $(el.poItemNo).val('');
        $(el.qualityNoticeCode).val('');
        $(el.claimOrderCode).val('');
        poData.css('display', 'none');
        qualityNoticeData.css('display', 'none');
        claimOrderData1.css('display', 'none');
        $(el.emptyTd).show();
    }
}


/**
 * 选择供应商
 */
function choseSupplier() {
    var url = g.ctx + "pc/supplier/purchaseCategory/page/selector?single=1";
    var userOrgyDialog = openDialog('userOrgyDialog', url, {
        title: "选择供应商",
        width: '80%',
        height: '70%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            userOrgyDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.confirm,
                handler: function () {
                    topWin.frames['userOrgyDialog'].chooseRow(function (cbox) {console.log(cbox)
                        $(el.supplierName).textbox('setValue', cbox[0].supplierName);
                        $(el.supplierCode).val(cbox[0].supplierCode);
                        $(el.currency).combobox('setValue',cbox[0].currencyCode);
                        // 初始化创建采购组下拉框
                        $('#purchaseGroup').combobox({
                            valueField: 'purchaseGroupCode',
                            textField: 'purchaseGroupName',
                            url: g.ctx + 'pc/sys/purchaseGroup/rest/createListAll?supplierId='+cbox[0].supplierId,
                            editable: false,
                            panelMaxHeight:180,
                            prompt: '--- 请选择 ---',
                            // panelHeight: 'auto',
                            panelWidth: 300,
                            onLoadSuccess:function (data) {
                                $('#purchaseGroup').combobox('setValue',data[0].purchaseGroupCode);
                            }
                            // onSelect:function (data) {
                            //     $('#companyName').textbox('setValue',data.companyName);
                            // }
                        });
                        // $(el.purchaseGroup).combobox('setValue',cbox[0].createId);
                        $(el.deductionExecutionProcurement).combobox('setValue',cbox[0].purchaseGroupCode);
                        $(el.paymentWayCode).combobox('setValue',cbox[0].paymentMethod);
                        $(el.taxCode).combobox('setValue',cbox[0].taxCode);
                        // findSupBankDataBySupplierCode(cbox[0].supplierId);
                        //清空表格数据
                        $('#tb').datagrid('loadData', {total: 0, rows: []})
                        userOrgyDialog.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                handler: function () {
                    userOrgyDialog.dialog('close');
                }
            }
        ]
    });
}
function searchSupplier(){
    var userOrgyDialog = openDialog('userDeductionDialog', g.ctx + 'pc/supplier/supplierSelect?single=1', {
        title: "选择供应商",
        width: '800px',
        height: '500px',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            userOrgyDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.confirm,
                handler: function () {
                    topWin.frames['userDeductionDialog'].chooseRow(function (cbox) {console.log(cbox)
                        $('#supplierId').val(cbox.id);
                        $('#supplierCode').val(cbox.supplierCode);
                        $('#supplierName').textbox('setValue', cbox.supplierName);
                        userOrgyDialog.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                handler: function () {
                    userOrgyDialog.dialog('close');
                }
            }
        ]
    });
}