$(function () {

    getCustomer('0','.allBuyer')
    getCustomer('1','.allSupplier')
    getPlatform()

    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 getPlatform() {
        $.ajax({
            url: '/platform/list' ,
            type: 'get',
            data: {},
            async: false,
            success: function (data) {
                if (data.success) {
                    $("[name=tradePlatform]").append('<option value="">请选择贸易平台</option>')
                    for (var i = 0; i < data.data.length; i++) {
                        if($('[name=tradePlatformBack]').length) {
                            if($('[name=tradePlatformBack]').val() == data.data[i].id) {
                                $("[name=tradePlatform]").append('<option selected value="'+data.data[i].id+'">'+data.data[i].platformName+'</option>')
                            }else {
                                $("[name=tradePlatform]").append('<option value="'+data.data[i].id+'">'+data.data[i].platformName+'</option>')
                            }

                        }else {
                            $("[name=tradePlatform]").append('<option value="'+data.data[i].id+'">'+data.data[i].platformName+'</option>')
                        }
                    }
                    ;
                    i = null;
                } else {
                    new $.zui.Messager('获取选项失败:' + data.msg, {
                        type: 'danger'
                    }).show();
                }
                ;
            },
            error: function (status) {
                new $.zui.Messager('获取选项出错:' + status, {
                    type: 'danger'
                }).show();
            }
        });
    }


    withSearchDropDownBox({
        allOptionSelector: '.allBuyer li',//所有的选项的选择器
        triggerSelector: '#buyer',//触发选择(显示下拉框)的表单的选择器(存放选择的name)
        resultIdSelector: '#buyerId',//表单元素选择器(存放选择的id)
        dropdownSelector: '.buyerListBox',//下拉框的选择器
        searchBtn:'.searchBuyer'
    });
    withSearchDropDownBox({
        allOptionSelector: '.allSupplier li',//所有的选项的选择器
        triggerSelector: '#supplier',//触发选择(显示下拉框)的表单的选择器(存放选择的name)
        resultIdSelector: '#supplierId',//表单元素选择器(存放选择的id)
        dropdownSelector: '#supplierListBox',//下拉框的选择器
        businessSpecial:'business',//特殊处理
        searchBtn:'#searchSupplier'
    });
    //修改页面
    if($('#updatePage').length) {
        $(".supplierListTbody").each(function (i,ele) {
            // withSearchDropDownBox({
            //     allOptionSelector: '.allSupplier li',//所有的选项的选择器
            //     triggerSelector: $(ele).find('.supplier'),//触发选择(显示下拉框)的表单的选择器(存放选择的name)
            //     resultIdSelector: $(ele).find('.supplierId'),//表单元素选择器(存放选择的id)
            //     dropdownSelector: $(ele).find('.supplierListBox'),//下拉框的选择器
            //     businessSpecial:'business',//特殊处理
            //     searchBtn:$(ele).find('.searchSupplier')
            // });
        })
    }else {
        $("[name=creatTime]").val(getCurrentDayTime())
    }

    // 排序
    function sortReceiptInfo(type){
            $(".supplierListTbody").each(function(i,ele){
                $(ele).find('td:first span').text(i+1);
            });
            if( $(".supplierListTbody").length <= 1 ){
                $('.supplierTable .negativeInformationReduce').hide();
            }else{
                $('.supplierTable .negativeInformationReduce').show();
            };
            if(type === 'update') {
                deleteListBtn()
            }
    };
    sortReceiptInfo();

    // 添加行
    $("#businessAddForm").on('click','.supplierTable .negativeInformationPlus',function(){
        var supplierTrClone = $(".supplierListTbody:first").clone();
        supplierTrClone.find('.supplier').removeAttr('id')
        supplierTrClone.find('.supplierId').removeAttr('id')
        supplierTrClone.find('.negativeInformationReduce').show();
        supplierTrClone.find('.error').hide();
        supplierTrClone.find('input').val('');
        $(this).parents('.supplierListTbody').after(supplierTrClone);
        withSearchDropDownBox({
            allOptionSelector: '.allSupplier li',//所有的选项的选择器
            triggerSelector: supplierTrClone.find('.supplier'),//触发选择(显示下拉框)的表单的选择器(存放选择的name)
            resultIdSelector: supplierTrClone.find('.supplierId'),//表单元素选择器(存放选择的id)
            dropdownSelector: supplierTrClone.find('.supplierListBox'),//下拉框的选择器
            businessSpecial:'business',//特殊处理
            searchBtn:supplierTrClone.find('.searchSupplier')
        });
        sortReceiptInfo('update');
    });
    // 修改时隐藏供应商列表删除
     function deleteListBtn() {
        const supplierIdList = $("#businessAddForm .supplierListTbody .supplierId")
        for (let i=0; i < supplierIdList.length; i++ ) {
            if( supplierIdList[i].defaultValue && $("#businessAddForm .supplierListTbody .supplierIdOldDate")[i].defaultValue === 'oldDate') {
                $("#businessAddForm .supplierListTbody .negativeInformationReduce")[i].style.display = 'none'
            }
        }
    }
    deleteListBtn()

    // 删除行
    $("#businessAddForm").on('click','.supplierTable .negativeInformationReduce',function(){
        $(this).parents('.supplierListTbody').remove();
        sortReceiptInfo('update');
    });


    // 附件相关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();
        };
    });

    // 选择附件
    $("#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(){
        console.log($(this).parents('.file-wrapper').find('.file-name').attr('originalid'), 8888)
        $(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('businessName',$("[name=businessName]").val());
        postdata.append('depositLimit',$("[name=depositLimit]").val());
        postdata.append('enterpriseCustomerInfoId',$("#buyerId").val());
        postdata.append('tradingPlatformId',$("[name=tradePlatform]").val());
        postdata.append('contents',$("[name=projectContent]").val());

        for(var i=0;i<$(".supplierListTbody").length;i++) {
            postdata.append('businessSupplierInfos['+i+'].supplierId',$(".supplierListTbody").eq(i).find('.supplierId').val());
            postdata.append('businessSupplierInfos['+i+'].supplierName',$(".supplierListTbody").eq(i).find('.supplier').val());
        }
        i=null;

        // 附件信息
        for( var m=0;m<$('.addFileList').data('filearray').length;m++ ){
            postdata.append('file['+m+']',$('.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 = '/business/management/add',tip='新增';
        if($("#updatePage").length) {
            url = '/business/management/update';
            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('/business/management/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 = {
        'businessName':{
            required:true
        },
        'buyer':{
            required:true
        },
        'tradePlatform':{
            required:true
        },
        'projectContent':{
            required:true,
            maxlength:500
        },
        'depositLimit':{
            required:true,
            maxlength:50
        },
    };

    var formMessages = {
        'businessName':{
            required:'请输入业务名称'
        },
        'buyer':{
            required:'请选择核心企业'
        },
        'tradePlatform':{
            required:'请选择贸易平台'
        },
        'projectContent':{
            required:'请输入项目内容',
            maxlength:'最多输入500个字符'
        },
        'depositLimit':{
            required:'请输入履约保证金上限'
        },
    };


    //验证供应商列表
    function suplierValid() {
        $('.supplierListTbody').each(function (i,ele) {
            if($(ele).find('.supplierId').val() !== '') {
                $(ele).find('.error').removeClass('shows').hide()
            }else {
                $(ele).find('.error').addClass('shows').show()
            }
        })
    }


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

        $("#businessAddForm").validate({
            promptPosition : "bottomLeft",
            submitHandler : function(form) {

                if( $('.error.shows').length>0 ){
                    $('.error.shows:first').prev().focus();
                    return;
                };

                var flagArr = [],flag=false;
                $('.supplierListTbody').each(function (i,ele) {
                    if($(ele).find('.supplierId').val() !== '') {
                        flagArr.push($(ele).find('.supplierId').val())
                    }
                })
                if(flagArr.length>1) {
                    var flagNewList = JSON.parse(JSON.stringify(flagArr))
                    for (let i = 0; i < flagNewList.length; i++) {
                        for (let j = i+1; j < flagNewList.length; j++) {
                          if(flagNewList[i] === flagNewList[j]) {
                            flagNewList.splice(j, 1)
                          }
                        }
                    }
                    if(flagNewList.length < flagArr.length) {
                        flag = true;
                    }
                    n=null;
                    if(flag) {
                        new $.zui.Messager('供应商重复选择。', {
                            type: 'warning'
                        }).show();
                        return false;
                    }
                }

                submitFunction(e);
            },
            rules:formRules,
            messages : formMessages
        });
    };

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

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


})
