jquery 点击弹窗内。勾选左侧右侧展示可删除。数据同步

19 阅读4分钟

//start======================================
// 部分1


  // 给定的数组数据
  var customerData = [

];

// 左侧多选的全量数据
var customerDataLeft = [
    {
        "key": "999",
        "val": "上海2222(22)",
        "optional_res": 0
    },
    {
        "key": "101160",
        "val": "上海ss展有限公司(3)",
        "optional_res": 0
    },
    {
        "key": "101154",
        "val": "江苏限公司(99)",
        "optional_res": 1
    },
    {
        "key": "2",
        "val": "北京(666)2",
        "optional_res": 0
    },
    {
        "key": "3",
        "val": "南京(444)2",
        "optional_res": 0
    },
    {
        "key": "4",
        "val": "重庆(9880890)",
        "optional_res": 0
    },
];
// 右侧列表展示数据
var customerRight = [];
// 左侧关键字和筛选数据

var filteredData =[]
// 部分1
//变更负责人
var  salesUser= []

//变更负责人

$(document).ready(function() {




$('input[name*="operating_account"]').on('click',function(){
    var $this=$(this);
    var mediaId=$this.parents('.medias-item').find('select[name*="media_id"]').val();
    var projectId=$('select[name="project_id"]').val();
    var customerId=$('select[name="customer_id"]').val();
    
    if($('select[name="customer_id"]').val()=='' || $('select[name="project_id"]').val()=='' || $this.parents('.medias-item').find('select[name*="media_id"]').val()==''){
        $this.attr('data-target','');
        return swal({
            title:"提示框",
            text: '请先选择客户、项目、投放媒体!',
            type:"warning",
            showCancelButton:"true",
            confirmButtonText:"确定",
            cancelButtonText:"取消"
        });
    }else{
        $.ajax({
            url:'/admin/project/account/operation_account',
            data:{media_id:mediaId,project_id:projectId,customer_id:customerId},
            type:'POST',
            complete:function(data){
                var result = JSON.parse(data.responseText);
                if(result.error_code === 0){
                    var list=result.list;
                    // customerDataLeft = list;
                    $this.parents('.wrapper').find('input.chosend_account_number').removeClass('chosend_account_number');
                    $this.addClass('chosend_account_number');
                    $this.parents('.wrapper').find('input.chosend_account_id').removeClass('chosend_account_id');
                    $this.parents('.accountModal').find('.operating_account_id').addClass('chosend_account_id');
                    let ceshidata= list
                    customerData=ceshidata
                    // customerDataLeft=ceshidata
                    console.log('ceshidata',ceshidata)
              
                    if(customerDataLeft&&customerDataLeft.length>0){
                        console.log('ceshidata',ceshidata)
                        var handInputHtml =''
                        $.each(customerDataLeft, function(index, customer) {
                            handInputHtml+=`<div class=${customer.key}><label class="everylabel"><input  style="margin:0px" class="everyInput"  type="checkbox" value=${customer.key}  ${customer.optional_res === 1 ? '' : 'disabled'}  ></input><div class="everySpan"> <div class="everySpanIn">${customer.val}</div> <div class="everySpanIn">${customer.val}</div> <div class="everySpanIn">${customer.val}</div></div></label></div>`
                        });
                        $('#selectOptions').html(handInputHtml);
                    }

                    selectEvery()
                    selectAllFn()
                      console.log('customerDataLeft',customerDataLeft)
                }else{

                    $('.handoverCustomers').hide()
                    return swal({
                        title:"提示框",
                        text:result.error_msg,
                        type:"warning",
                        showCancelButton:"true",
                        confirmButtonText:"确定",
                        cancelButtonText:"取消"
                    });
                }
            }
        });
    }
    $this.attr('data-target','#chosenAccountModal');
})

    function selectAllFn(){
          // 全选功能
    $('#selectAllCheckbox').change(function() {
        if ($(this).prop('checked')) {
            // 如果全选被选中,则将所有复选框设置为选中状态
           // 遍历每个复选框,检查 disabled 属性
            $('#selectOptions input[type="checkbox"]').each(function() {
                // 检查 disabled 属性是否为 false,如果是,则选中
                if (!$(this).prop('disabled')) {
                 $(this).prop('checked', true);
                }else {
                    $(this).prop('checked', false);
                }
            }); 
            console.log('customerDataLeft',customerDataLeft)
            // 筛选的不为1的数据。 不置灰的值
            let customerDisData = customerDataLeft.filter(item => item.optional_res === 1);
            console.log('customerDisData',customerDisData)
            //筛选数据如果大于0 则右侧需要更新的数据是筛选数据。否则更新数据是。 左侧非置灰的数据
            let dataToMerge=[]
            if(filteredData && filteredData.length > 0){
                dataToMerge=filteredData
            }else {
                dataToMerge= customerDisData
            }
            //合并数据。是右侧本来的数据。 和左侧选中的数据
            let mergedData = [...customerRight, ...dataToMerge];  
         
            // 合并数据去重
            mergedData = mergedData.filter((item, index, self) =>
                index === self.findIndex((t) => (
                    t.key === item.key
                ))
            );
            customerRight=mergedData
            console.log('customerRight',customerRight)
            // 去重后数据展示在右侧
            displayRight(mergedData);
          // 遍历 customerDataLeft 。如果有筛选数据。则筛选数据选中。如果无筛选数据。则非disabled数据选中
                $.each(customerDataLeft, function(index, leftItem) {
                    const leftKey = leftItem.key;
                    // 初始化复选框状态为 false
                    let isChecked = false;
                    // 遍历 mergedData
                    $.each(mergedData, function(index, mergedItem) {
                        const mergedKey = mergedItem.key;
                        // 比较每一项的 key 是否相等
                        if (leftKey === mergedKey) {
                            // 如果相等,则设置复选框状态为 true
                            isChecked = true;
                            return false; 
                        }
                    });
                    // 找到左侧数据中的相应项,设置复选框状态
                    $('#selectOptions .' + leftKey).find('input[type="checkbox"]').prop('checked', isChecked);
                });

        } else {
            // 如果没有筛选的数据(即 filteredData 为空或未定义),则清空右侧数据  
            let remainingData = filteredData && filteredData.length > 0 ?   
            customerRight.filter(item => !filteredData.some(filteredItem => filteredItem.key === item.key)) : [];  
            console.log('filteredData',filteredData)
            //更新右侧数据 
            customerRight= JSON.parse(JSON.stringify(remainingData))
          displayRight(remainingData);
          // 处理左侧数据
        // 取消 filteredData 中对应的复选框的勾选状态(如果有 filteredData)  
        if (filteredData && filteredData.length > 0) {  
            $.each(filteredData, function(index, filteredItem) {  
                $('#selectOptions .'+filteredItem.key).find('input[type="checkbox"]').prop('checked', false);  
            });  
        } else {
            $('#selectOptions input[type="checkbox"]').prop('checked', false);
            filteredData=[]
        }
       }
    });
    }
  


  

function selectEvery(){
        $('#selectOptions').find('input[type="checkbox"]').on('change', function() {
        // 处理右侧数据展示
            var key = $(this).val();
            var checkboxdata =$(this)
        
            if(checkboxdata.prop('checked')){
                  // 在左侧勾选状态。 右侧数据追加
                  const addIndex = customerDataLeft.find(item => item.key === key); // 查找要删除的元素的索引
                    if(addIndex){
                        customerRight.push(JSON.parse(JSON.stringify(addIndex))); // 将数据追加到 customerRight 数组中
                    }
                   
            }else {
                // 在左侧勾选状态。 右侧数据删除
                const index = customerRight.findIndex(item => item.key === key); // 查找要删除的元素的索引
                if (index !== -1) {
                    customerRight.splice(index, 1); // 从右侧数据中删除指定的元素
                }
            }
            // 更新右侧数据展示
            displayRight(customerRight);
            allCheckedFn()
            
   });
}

// 更新全选复选框状态
    function allCheckedFn(){
        var allChecked = $('#selectOptions input[type="checkbox"]:checked').length;
        var totalCheckboxes = $('#selectOptions input[type="checkbox"]').length;
               
        if (allChecked === totalCheckboxes) {
            $('#selectAllCheckbox').prop('indeterminate', false); // 取消半选中状态
            $('#selectAllCheckbox').prop('checked', true); // 设置全选为选中状态
        } else if (allChecked > 0) {
            $('#selectAllCheckbox').prop('checked', false); // 设置全选为未选中状态
            $('#selectAllCheckbox').prop('indeterminate', true); // 设置为半选中状态
        } else {
            $('#selectAllCheckbox').prop('indeterminate', false); // 取消半选中状态
            $('#selectAllCheckbox').prop('checked', false); // 设置全选为未选中状态
        }
    }
     
    // 点击删除按钮时移除对应数据
    $('#changeOptions').on('click', '.delete-span', function() {
        var deletedData = $(this).prev().text(); // 获取要删除的数据
        var prevClass = $(this).prev().attr('class');
        console.log(deletedData,prevClass)
        const indexRight = customerRight.findIndex(item => item.key === prevClass); // 查找要删除的元素的索引
        console.log('indexRight',indexRight)
        if (indexRight !== -1) {
            customerRight.splice(indexRight, 1); // 从右侧数据中删除指定的元素
            displayRight(customerRight)
            $('#selectOptions .' + prevClass).find('input[type="checkbox"]').prop('checked', false);;
        }
        // 更新复选框状态    
        allCheckedFn()
    });

      // 当手动过滤输入框内容发生变化时触发事件
      $('#handFilterInput').on('input', function() {
        var keyword = $(this).val().trim().toLowerCase(); // 获取搜索关键字并转为小写
        // 如果搜索关键字为空,则将左侧数据设置为全量数据 
        searchButton(keyword)
    });

    // 查询数据的筛选。筛选符合条件的客户主体
    function searchButton(keyword) {
        if (keyword === '') {
            for (var n=0;n<customerDataLeft.length;n++){
                $('#selectOptions .' + customerDataLeft[n].key).show()
            }
            filteredData=[]
        } else {
             filteredData = customerDataLeft.filter(function(item) {
                // console.log('item',item['val'].toLowerCase().includes(keyword))
                if(item['val'].toLowerCase().includes(keyword)){
                    return item ;
                }
            });
            console.log('filteredData',filteredData)
            // 如果有搜索结果,则展示搜索结果;如果没有搜索结果,则展示全量数据 customerData
            if (filteredData.length > 0) {
                   // 使用一个对象来跟踪应该显示的key  
                    var keysToShow = {};  
                    // 遍历filteredData,记录所有应该显示的key  
                    for (var m = 0; m < filteredData.length; m++) {  
                        keysToShow[filteredData[m].key] = true;  
                    }  
                    // 遍历customerDataLeft,根据keysToShow对象来决定显示或隐藏元素  
                    for (var n = 0; n < customerDataLeft.length; n++) {  
                        var key = customerDataLeft[n].key;  
                        // 如果keysToShow中存在这个key,则显示元素,否则隐藏元素  
                        if (keysToShow[key]) {  
                            $('#selectOptions .' + key).show();  
                        } else {  
                            $('#selectOptions .' + key).hide();
                        }  
                    }  
                    console.log('filteredData', filteredData, 'customerDataLeft', customerDataLeft);
            } else {
                for (var n=0;n<customerDataLeft.length;n++){
                    $('#selectOptions .' + customerDataLeft[n].key).hide()
                }
            }
        }
    }

    

      // 右侧数据重置展示
      function displayRight(data) {
        // 清空右侧展示区域
        // $('#changeOptions').empty();
        var changeOptionsDiv = $('#changeOptions'); 
        changeOptionsDiv.empty();
    
        // 根据 customerRight 数组中的数据显示右侧内容
        for (var i = 0; i < data.length; i++) {
            var val = data[i].val;
            var dataDiv = $('<div>').addClass('rightDiv').append(
                $('<span style="display:inline-block">').text(val).addClass(data[i].key), // 添加类以设置样式
                $('<span>').text('x').addClass('delete-span') // 添加类以设置样式
            );
            changeOptionsDiv.append(dataDiv);
        }
    }
    




  

function  clearHandOverForm (){
        // 清空表单中所有勾选的值
        $('.hand-over-form input[type="checkbox"]').prop('checked', false);
        $('.hand-over-form input[type="text"]').val('');
        $('.hand-over-form textarea').val('');
        $('.hand-over-form select').val('');


        customerDataLeft=[]
        filteredData=[]
        customerRight=[]
        displayRight([])
          $('.save-hand-over-btn').prop('disabled', false).css({
                'background-color':'#18a689',
                'border-color': '#18a689'
            });
}
// 点击取消

$('.cancel-hand-over-btn').click(function() {
    // 关闭弹窗 // 恢复初始化
    clearHandOverForm()

});


// 监听模态框关闭事件
$('#handoverCustomers').on('hidden.bs.modal', function () {
    clearHandOverForm()
});

// 点击关闭按钮也清空表单内容
$('.closeOverCustomer').on('click', function() {
    clearHandOverForm()
});




  
   
//     }
// })
    // 点击发起审批按钮
    $('.save-hand-over-btn').click(function() {
        // 点击按钮后首先禁用按钮
            $('.save-hand-over-btn').prop('disabled', true).css({
                'background-color': '#cccccc',
                'border-color': '#cccccc'
            })

        if($(".hand-over-form").valid()){
            console.log(' // 如果校验通过')
                 var formData = {};
                 $('.hand-over-form').serializeArray().forEach(function(item) {
                     formData[item.name] = item.value;
                 });
                 // 获取右侧数据的所有key
                 let customerIdsFilter = customerRight.map(item => item.key);
                 let objSubmit = {
                    customerIds:[],
                    receiver:formData.receiver,
                    year:formData.year,
                    remarks:''
                 }
                 //拦截交接客户不能为空为必选项
                 if(customerIdsFilter.length==0){
                    return  swal({
                        title:"提示框",
                        text:'客户为必填项,请完善信息!',
                        type:"warning",
                        showCancelButton:"true",
                        confirmButtonText:"确定",
                        cancelButtonText:"取消",
                    },function(isConfirm){
                       
                        if(isConfirm){
                        }else {
                            console.log('取消了吗')
                          
                        }

                        $('.save-hand-over-btn').prop('disabled', false).css({
                            'background-color':'#18a689',
                            'border-color': '#18a689'
                        });
                        
                    });
                 }else {
                    objSubmit.customerIds=customerIdsFilter
                 }

                 // 判断是否为其他。其他将输入理由替换选择理由
                 if(formData.remarks==3){
                    objSubmit.remarks=formData.remark
                 }else {
                    remarkdata.map((item) => {
                        if (item.key == formData.remarks) {
                            objSubmit.remarks = item.val;
                        }
                        return objSubmit;
                    })
                 }
            // 交接接口
                 saveHandOverCheck(objSubmit)

        }else {
            $('.save-hand-over-btn').prop('disabled', false).css({
                'background-color':'#18a689',
                'border-color': '#18a689'
            });
        }
     

    });

    



    //  客户交接-检测提交数据
    function saveHandOverCheck (data){
        console.log('校验datadata',data)
        let subdata=data
      
        $.ajax({
            url: '/admin/crm/customer/handover/check', // 接口地址
            type: 'POST', 
            data:data,
            dataType: 'json', 
            complete: function(response) {
                // 请求成功时执行的操作
                let data= response.responseJSON
                if(data.error_code==0){
                    if( data.result.remind_msg!=''){
                        swal({
                            title: "提示框",
                            text: data.result.remind_msg,
                            type: "warning",
                            showCancelButton: true,
                            allowOutsideClick :false,
                            confirmButtonColor: "#1ab394",
                            confirmButtonText: "是",
                            cancelButtonText:"否",
                            closeOnConfirm: true,
                        },function(isConfirm){
                            if(isConfirm){
                               
                            $('.save-hand-over-btn').prop('disabled', false).css({
                                    'background-color':'#18a689',
                                    'border-color': '#18a689'
                                });
                            }else {
                                HandOverSubmit(subdata)
                            }
                            
                        })
                    }else {
                        HandOverSubmit(subdata)
                    }
                }else {
                    $('.save-hand-over-btn').prop('disabled', false).css({
                        'background-color':'#18a689',
                        'border-color': '#18a689'
                    });
                    return   swal({
                        title:"提示框",
                        text: data.error_msg,
                        type:"warning",
                        showCancelButton:"true",
                        confirmButtonText:"确定",
                        cancelButtonText:"取消",
                    });
                }
                
            },
            error: function(xhr, status, error) {
                console.error('请求失败', error);
            }
        });
    }

  });


// 提交接口参数
  function HandOverSubmit(subdata){
    $.ajax({
        url: '/admin/crm/customer/handover/submit',
        type: 'POST',
        data: subdata,
        dataType: 'json',
        complete: function(response){
            // $('.save-hand-over-btn').prop('disabled', false).css({
            //     'background-color':'#18a689',
            //     'border-color': '#18a689'
            // });
            var data = JSON.parse(response.responseText);
            if (data.error_code === 0) {
                window.location.href = '/admin/work/check/list?tab=2';
                clearHandOverForm()
            } else if (data.error_code === 200) {
                location.reload();
            } else {
                setTimeout(function () {
                    swal({
                        title: "提示框",
                        text: data.error_msg,
                        type: "warning",
                        showCancelButton: "true",
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                    });
                }, 100);
            }
        }
    })
  }



    

// end======================================