$(function () {

    //初始化日期
    function setDate(select,startDate,endDate){
        $(select).datetimepicker(
            {
                weekStart: 1,
                autoclose: 1,
                todayHighlight: 0,
                startView: 2,
                minView: 2,
                forceParse: 0,
                showMeridian: 1,
                startDate:startDate,
                endDate:endDate,
                format: "yyyy-mm-dd"
            }
        );
        $(select).datetimepicker('setStartDate',startDate);
        $(select).datetimepicker('setEndDate',endDate);
    };
    setDate('[name=cashDate]','1970-01-01','2116-12-31');

    function getCustomer(id,ele) {
        $.ajax({
            url: '/customer/findCoreBusiness?supplier=' + id,
            type: 'get',
            data: {},
            async: false,
            success: function (data) {
                if (data.success) {
                    for (var i = 0; i < data.data.length; i++) {
                        $(ele).append('<li class="companyli" value="' + data.data[i].id + '">' + data.data[i].enterpriseName + '</li>')
                    }
                    ;
                    i = null;
                } else {
                    new $.zui.Messager('获取选项失败:' + data.msg, {
                        type: 'danger'
                    }).show();
                }
                ;
            },
            error: function (status) {
                new $.zui.Messager('获取选项出错:' + status, {
                    type: 'danger'
                }).show();
            }
        });
    }

    function getBusiness(id) {
        $.ajax({
            url: '/cashFlow/getBusinessList?customerId='+id,
            type: 'get',
            data: {},
            async: false,
            success: function (data) {
                if (data.success) {
                    $('.allBus').empty();
                    for (var i = 0; i < data.data.length; i++) {
                        $('.allBus').append('<li class="companyli" value="' + data.data[i].businessName + '" code="' + data.data[i].businessNumber + '">' + data.data[i].businessName + '</li>')
                    }
                    ;
                    i = null;
                } else {
                    new $.zui.Messager('获取选项失败:' + data.msg, {
                        type: 'danger'
                    }).show();
                }
                ;
            },
            error: function (status) {
                new $.zui.Messager('获取选项出错:' + status, {
                    type: 'danger'
                }).show();
            }
        });
    }
    function getCompany() {
        $.ajax({
            url: '/cashFlow/getCompanyBelong' ,
            type: 'get',
            data: {},
            async: false,
            success: function (data) {
                if (data.success) {
                    $("[name=companyBelong]").empty();
                    $("[name=companyBelong]").append('<option value="">请选择</option>')
                    for (var i = 0; i < data.data.length; i++) {
                        $("[name=companyBelong]").append('<option value="'+data.data[i].companyBelong+'">'+data.data[i].companyName+'</option>')
                    }
                    ;
                    i = null;
                } else {
                    new $.zui.Messager('获取选项失败:' + data.msg, {
                        type: 'danger'
                    }).show();
                }
                ;
            },
            error: function (status) {
                new $.zui.Messager('获取选项出错:' + status, {
                    type: 'danger'
                }).show();
            }
        });
    }
    function getBank(id) {
        $.ajax({
            url: '/cashFlow/getBankName?companyBelong='+id ,
            type: 'get',
            data: {},
            async: false,
            success: function (data) {
                if (data.success) {
                    $("[name=bankName]").empty();
                    $("[name=bankName]").append('<option value="">请选择</option>')
                    for (var i = 0; i < data.data.length; i++) {
                        $("[name=bankName]").append('<option value="'+data.data[i]+'">'+data.data[i]+'</option>')
                    }
                    ;
                    i = null;
                } else {
                    new $.zui.Messager('获取选项失败:' + data.msg, {
                        type: 'danger'
                    }).show();
                }
                ;
            },
            error: function (status) {
                new $.zui.Messager('获取选项出错:' + status, {
                    type: 'danger'
                }).show();
            }
        });
    }
    function getBankNo(id) {
        $.ajax({
            url: '/cashFlow/getBankAccount?bankName='+id +'&companyBelong=' +$('[name=companyBelong]').val(),
            type: 'get',
            data: {},
            async: false,
            success: function (data) {
                if (data.success) {
                    $("[name=bankAccount]").empty();
                    $("[name=bankAccount]").append('<option value="">请选择</option>')
                    for (var i = 0; i < data.data.length; i++) {
                        $("[name=bankAccount]").append('<option value="'+data.data[i]+'">'+data.data[i]+'</option>')
                    }
                    ;
                    i = null;
                } else {
                    new $.zui.Messager('获取选项失败:' + data.msg, {
                        type: 'danger'
                    }).show();
                }
                ;
            },
            error: function (status) {
                new $.zui.Messager('获取选项出错:' + status, {
                    type: 'danger'
                }).show();
            }
        });
    }

    getCustomer('0','.allBuyer')//买方
    getCompany()//公司归属

    $(".buyerListBox").on("click","li.companyli",function(){
        if($(this).val() !== '') {
            getBusiness($(this).val())
            withSearchDropDownBox({
                allOptionSelector: '.allBus li',//所有的选项的选择器
                triggerSelector: '#businessName',//触发选择(显示下拉框)的表单的选择器(存放选择的name)
                resultIdSelector: '#businessNameId',//表单元素选择器(存放选择的id)
                dropdownSelector: '.busListBox',//下拉框的选择器
                //otherfn: '.exportAccountReceivableLists',
                searchBtn:'.searchBus',
                // isCallback: true,
                // callback: function (params) {
                //     $('[name=businessNumber]').val('')
                // }
            });
        }else {
            $(".allBus").empty();
        }
    })
    $(".busListBox").on("click","li.companyli",function(){
        if($(this).val() !== '') {
            $("[name=businessNumber]").val($(this).attr('code'));
        }else {
            $("[name=businessNumber]").empty();
        }
    })

    $('[name=companyBelong]').change(function () {
        if($(this).val() !== '') {
            getBank($(this).val())
        }else {
            $("[name=bankName]").empty();
        }
    })
    //$('[name=companyBelong]').change();

    $('[name=bankName]').change(function () {
        if($(this).val() !== '') {
            getBankNo($(this).val())
        }else {
            $("[name=bankAccount]").empty();
        }
    })
    //$('[name=bankName]').change();

    //类型改变
    $('[name=cashType]').change(function () {
        if($('[name=cashType] option:selected').text() == '票据贴现') {
            $(".actualAmountTr").show();
            $(".RecordedAmount").hide();
        }else {
            $(".actualAmountTr").hide();
            $(".RecordedAmount").show();
        }
    })


    withSearchDropDownBox({
        allOptionSelector: '.allBuyer li',//所有的选项的选择器
        triggerSelector: '#buyer',//触发选择(显示下拉框)的表单的选择器(存放选择的name)
        resultIdSelector: '#customerId',//表单元素选择器(存放选择的id)
        dropdownSelector: '.buyerListBox',//下拉框的选择器
        //otherfn: '.exportAccountReceivableLists',
        searchBtn:'.searchBuyer',
        isCallback: true,
        callback: function () {
            $('[name=businessName]').val('')
            $('[name=businessNumber]').val('')
        }
    });

    //修改页面
    if($('#updatePage').length) {

    }else {
        $("[name=cashDate]").val(getCurrentDayTime())
    }

    $('#businessAddForm').on("keyup",".amountInput",function(){
        $(this).val(commaDelimiter($(this).val()))
    })


    // 附件相关dom
    var fileWrapperbasic = '<div class="file-wrapper"><div class="file-icon" style="color: #5AC4FC;"><div class="file-icon-image"></div></div>'+
        '<div class="content"><div class="file-name"></div><div class="file-size small text-muted"></div></div>'+
        '<div class="actions" style="width:0.5rem"><a class="btn btn-link btn-delete-file">'+
        '<em>删除</em><i class="operateIconfont operateIcon-shanchu"></i></a></div></div>';

    // 在附件元素的data上存放选择的附件数据,初始为空
    $('.addFileList').each(function(i,ele){
        $(ele).data('filearray',[]);
        $(ele).data('deletefileid',[]);
    });

    // 展示原先有的附件
    function showOriginalFile(source, insert) {
        for (var j = 0; j < $(source).length; j++) {
            var originalFileWrapper = $(fileWrapperbasic).clone();
            originalFileWrapper.find('.file-name').text($(source).eq(j).find('.originalName').val());
            originalFileWrapper.find('.file-name').attr('originalid', $(source).eq(j).find('.originalId').val());
            if (parseFloat($(source).eq(j).find('.originalSize').val()) < 1048576) {
                originalFileWrapper.find('.file-size').text(($(source).eq(j).find('.originalSize').val() / 1024).toFixed(2) + "KB");
            } else {
                originalFileWrapper.find('.file-size').text(($(source).eq(j).find('.originalSize').val() / 1024 / 1024).toFixed(2) + "MB");
            }
            ;
            var originaltype = $(source).eq(j).find('.originalType').val().toUpperCase();
            if (originaltype == '.JPG' || originaltype == '.JPEG' || originaltype == '.PNG' || originaltype == '.BMP') {
                originalFileWrapper.find('.file-icon-image').css('background-image', 'url(' + $(source).eq(j).find('.originalUrl').val() + ')');
            } else {
                originalFileWrapper.find('.file-icon-image').append('<i class="icon icon-file-pdf"></i>');
            }
            ;
            originalFileWrapper.find('.btn-delete-file').addClass('btn-delete-originalfile').removeClass("btn-delete-file");

            originalFileWrapper.find('.btn-yulan-file').attr('href', '/fileStorage/preview?fileId=' + $(source).eq(j).find('.originalId').val());
            originalFileWrapper.find('.btn-xiazai-file').attr('href', '/fileStorage/downloadFile?fileId=' + $(source).eq(j).find('.originalId').val());
            $(insert).find('.fileContent').append(originalFileWrapper)
        }
        ;
        j = null;
        if ($(insert).find('.file-wrapper').length > 0) {
            $(insert).find('.spanHolder').remove();
        }
        ;
    };

    if($('#updatePage').length) {
        // 展示原附件
        showOriginalFile('.fileInfoListOriginal', '.addFileList');
    }


    // 触发选择附件
    $('#businessAddForm').on("click",".fileInfoListBox .choiceFile",function(){
        if ( !window.FileReader ) {
            new $.zui.Messager('您的浏览器版本过低，请升级您的浏览器', {
                type: 'danger'
            }).show();
            return;
        };
        $(this).parent().find('.fileinput').click();
    });

    // 触发选择附件
    $('#businessAddForm').on("click",".fileInfoListBox .fileContent",function(){
        if ( !window.FileReader ) {
            new $.zui.Messager('您的浏览器版本过低，请升级您的浏览器', {
                type: 'danger'
            }).show();
            return;
        };
        if( $(this).find(".spanHolder").length>0 ){
            $(this).parent().prev().click();
        };
    });

    // 富文本框
    var editor = new UE.ui.Editor({
		'fullscreen':false
	});
	editor.render('unifiedEditor');

    // 选择附件
    $("#businessAddForm").on("change",".fileInfoListBox .fileinput",function(e){
        var that = $(this);
        var choosefiles = e.target.files || e.dataTransfer.files;
        for( var i=0;i<choosefiles.length;i++ ){
            var file = e.target.files[i] || e.dataTransfer.files[i];//用于提交
            $(this).parent().data('filearray').push(file);
            fileWrapper = $(fileWrapperbasic).clone();
            var type = file.type;
            var indexof = type.indexOf("/"),fileType='';
            if( indexof != -1 ){
                var index = parseInt(indexof)+1;
                fileType = type.substring(index,type.length).toUpperCase();
            };
            fileWrapper.find('.file-name').text(file.name);
            if( parseFloat(file.size) < 1048576 ){
                fileWrapper.find('.file-size').text((file.size/1024).toFixed(2)+'KB');
            }else{
                fileWrapper.find('.file-size').text((file.size/1024/1024).toFixed(2)+'MB');
            };
            that.next().find(".fileContent").append(fileWrapper);
            // 有附件时去掉框框里的'上传附件'字样
            if( that.next().find('.file-wrapper').length>0 ){
                that.next().find('.spanHolder').remove();
            };
            detailpreview(fileType,fileWrapper,file);
        };
        i = null;
        function detailpreview(fileType,fileWrapper,file){
            var reader = new FileReader();
            reader.readAsDataURL(file);//转为base64(预览)
            reader.onload = function(e){
                e = e || window.event;
                if( fileType=='JPG' || fileType=='JPEG' || fileType=='PNG' || fileType=='BMP' || fileType=='JPG' ){
                    fileWrapper.find(".file-icon-image").css("backgroundImage",'url('+e.target.result+')')
                }else{
                    fileWrapper.find(".file-icon-image").append('<i class="icon icon-file-pdf"></i>')
                };
            };
        };
    });

    // 删除附件
    // $("#businessAddForm").on("click",".btn-delete-file",function(){
    //     var deleteindex = $(this).parents('td').find('.btn-delete-file').index($(this));
    //     $(this).parents('td').data('filearray').splice(deleteindex,1);
    //     $(this).parents(".uploaderFile").prev().val(null);
    //     if( $(this).parents('td').find('.file-wrapper').length == 1 ){
    //         $(this).parents(".file-wrapper").before('<span class="spanHolder">上传附件</span>');
    //     };
    //     $(this).parents(".file-wrapper").remove();
    //     return false;
    // });
    // 删除(原有的)附件
    // $("#businessAddForm").on("click",".btn-delete-originalfile",function(){
    //     $(this).parents('td').data('deletefileid').push($(this).parents('.file-wrapper').find('.file-name').attr('originalid'));
    //     $(this).parents(".uploaderFile").prev().val(null);
    //     if( $(this).parents('td').find('.file-wrapper').length == 1 ){
    //         $(this).parents(".file-wrapper").before('<span class="spanHolder">上传附件</span>');
    //     };
    //     $(this).parents(".file-wrapper").remove();
    //     return false;
    // });


    //保存
    function submitFunction(e){
        var postdata = new FormData();
        if($("#updatePage").length) {
            postdata.append('id',$("[name=basicId]").val());
        }
        postdata.append('cashFlowManageBaseVo.customerId',$("#customerId").val());
        postdata.append('cashFlowManageBaseVo.businessName',$("#businessNameId").val());
        postdata.append('cashFlowManageBaseVo.businessNumber',$("[name=businessNumber]").val());
        // postdata.append('cashFlowManageEntryInfo.entryParty',$("[name=entryParty]").val());
        postdata.append('cashFlowManageBaseVo.cashTypeDict.id',$("[name=cashType]").val());

        postdata.append('cashFlowManageEntryInfo.companyBelong',$("[name=companyBelong]").val());
        postdata.append('cashFlowManageEntryInfo.bankName',$("[name=bankName]").val());
        postdata.append('cashFlowManageEntryInfo.bankAccount',$("[name=bankAccount]").val());
        if($('[name=cashType] option:selected').text() == '票据贴现') {
            postdata.append('cashFlowManageBaseVo.amount',$("[name=amount]").val().split(',').join(''));
            postdata.append('cashFlowManageEntryInfo.billAmount',$("[name=billAmount]").val().split(',').join(''));
        }else {
            postdata.append('cashFlowManageBaseVo.amount',$("[name=amount2]").val().split(',').join(''));
        }
        postdata.append('cashFlowManageBaseVo.currencyDict.id',$("[name=currencyDictId]").val());
        postdata.append('cashFlowManageBaseVo.cashDate',$("[name=cashDate]").val());
        postdata.append('cashFlowManageEntryInfo.currExecutor',$("[name=currExecutor]").val());
        postdata.append('cashFlowManageBaseVo.remark',$("[name=remark]").val());
        postdata.append('cashFlowManageEntryInfo.fileText',UE.getEditor("unifiedEditor").getContent());


        // 附件信息
        // for( var m=0;m<$('.addFileList').data('filearray').length;m++ ){
        //     postdata.append('cashFlowEntryFile',$('.addFileList').data('filearray')[m]);
        // };
        // m = null;
        // 删除的附件信息
        // for( var m=0;m<$('.addFileList').data('deletefileid').length;m++ ){
        //     postdata.append('deleteFileIds['+m+']',$('.addFileList').data('deletefileid')[m]);
        // };
        // m = null;

        var url = '/cashFlow/doAdd',tip='新增';
        if($("#updatePage").length) {
            url = '/cashFlow/doUpdate';
            tip='修改';
        }

        $.ajax({
            url:url,
            type:'post',
            data:postdata,
            processData:false,
            contentType:false,
            success:function(data){
                if( data.success ){
                    new $.zui.Messager( tip+'现金流成功', {
                        type: 'success'
                    }).show();
                    $.get('/cashFlow/list',function(data){
                        $(".yk_rightcontent").empty().append(data);
                    });
                }else{
                    new $.zui.Messager(tip+'现金流失败:'+data.msg, {
                        type: 'danger'
                    }).show();
                }
            },
            error:function(status){
                new $.zui.Messager(tip+'现金流时发生错误:'+status, {
                    type: 'danger'
                }).show();
            }
        });
        return false;
    };

    var formRules = {
        'buyer':{
            required:true
        },
        'businessNameId':{
            required:true
        },
        'businessNumber':{
            required:true
        },
        'cashType':{
            required:true,
        },
        'companyBelong':{
            required:true
        },
        'bankName':{
            required:true
        },
        'bankAccount':{
            required:true,
        },
        'currencyDictId':{
            required:true,
        },
        'cashDate':{
            required:true
        },
        'amount':{
            required:true,
            checkAmount:true,
        },
        'amount2':{
            required:true,
            checkAmount2:true,
        },
        'billAmount':{
            required:true,
            checkBillAmount:true,
        },
        // 'entryParty':{
        //     required:true
        // },
        // 'currency':{
        //     required:true
        // },
    };

    var formMessages = {
        'buyer':{
            required:'请选择核心企业名称'
        },
        'businessName':{
            required:'请选择业务名称'
        },
        'businessNumber':{
            required:'请输入业务编号'
        },
        'cashType':{
            required:'请选择类型',
        },
        'companyBelong':{
            required:'请选择公司归属'
        },
        'bankName':{
            required:'请选择银行名称'
        },
        'bankAccount':{
            required:'请选择银行卡号',
        },
        'currencyDictId':{
            required:'请选择币种'
        },
        'cashDate':{
            required:'请选择日期'
        },
        'amount':{
            required:'请输入实际金额'
        },
        'amount2':{
            required:'请输入入账金额'
        },
        'billAmount':{
            required:'请输入票据金额'
        },
        // 'entryParty':{
        //     required:'请选择入账方'
        // },
        // 'currency':{
        //     required:'请选择币种'
        // },
    };

    //入账金额限制
    $.validator.addMethod("checkAmount2",function(value,element){
        value = value.replace(/,/gi,'')
        var score = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
        return this.optional(element) || (score.test(value));
    },"入账金额格式不正确");

    //实际金额限制
    $.validator.addMethod("checkAmount",function(value,element){
        value = value.replace(/,/gi,'')
        var score = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
        return this.optional(element) || (score.test(value));
    },"实际金额格式不正确");

    //票据金额限制
    $.validator.addMethod("checkBillAmount",function(value,element){
        value = value.replace(/,/gi,'')
        var score = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
        return this.optional(element) || (score.test(value));
    },"票据金额格式不正确");


    //表单验证
    function addNewCustomer(e){

        $("#businessAddForm").validate({
            promptPosition : "bottomLeft",
            submitHandler : function(form) {
                if( $('.error.shows').length>0 ){
                    $('.error.shows:first').prev().focus();
                    return;
                };

                //入账日期限制
                if(new Date($('[name=cashDate]').val()).getTime() > new Date(new Date(new Date().toLocaleDateString()).getTime() +24 * 60 * 60 * 1000 -1).getTime()) {
                    new $.zui.Messager('请选择小于等于当前日期' , {
                        type: 'danger'
                    }).show();
                    return false;
                }
                submitFunction(e);

                // var contentLen=UE.getEditor('unifiedEditor').getContentTxt();
				// if( contentLen.length>50000 ){
				// 	new $.zui.Messager('附件字数超出最大限度,请修改', {
				// 	    type: 'danger'
				// 	}).show();
				// 	return false
				// };
            },
            rules:formRules,
            messages : formMessages
        });
    };

    //提交按钮
    $(".yk_addNewMsg .submitBusiness").click(addNewCustomer);




    //关闭按钮
    $(".yk_addNewMsg .btn-cancel, .newBackBtn").click(function(){
        $.get('/cashFlow/list',function(data){
            $(".yk_rightcontent").empty().append(data);
        });
        return false;
    });


})
