// 选择或时复选框禁用
function checkBoxDisabled() {
    $('.goodsListTbody').each(function ( i, ele) {
        if($(ele).attr('id')){
            setTimeout(() => {
                var nameVal = `jqg_chooseGoodsList_${$(ele).attr('id')}`
                $(`[name=${nameVal}]`).attr('checked', false)
                $(`[name=${nameVal}]`).attr('disabled',true)
                console.log( $(`[name=${nameVal}]`))
            }, 300);
        }
    })
}
// 排序-货物
function sortIGoodsnfo() {
    $(".goodsListTbody").each(function (i, ele) {
        $(ele).find('td:first span').text(i);
    });
    if ($(".goodsListTbody").length <= 1) {
        $('.goodsTable .negativeInformationReduce').hide();
    } else {
        $('.goodsTable .negativeInformationReduce').show();
    }
};

// 删除 -货物
$("#contractSign-form").on('click', '.goodsTable .negativeInformationReduce', function () {
    $(this).parents('.goodsListTbody').remove();
    sortIGoodsnfo();
});

function chooseGoods(id) {
    var chooseData = $('#chooseGoodsList').jqGrid('getRowData', id);
    var trStr = `<tr class="choosedGoodsTbody">
                        <td width="5%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;"></td>
                        <td width="14%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.goodsName + `</td>
                        <td width="14%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.goodsFactory + `</td>
                        <td width="14%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.modelNumber + `</td>
                        <td width="13%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.units + `</td>
                        <td width="13%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.quantity + `</td>
                        <td width="13%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.salesPrice + `</td>
                        <td style="display: none">` + chooseData.id + `</td>
                        <td style="display: none" class="remark">` + chooseData.remark + `</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;border-right: 1px solid #E8F0F3;"><span class="relaseGoods" style="color: #5AC4FC;cursor: pointer">释放</span></td>
                    </tr>`
    $(".choosedGoodsList").append(trStr);
    $("#myModal-chooseGoods").resize();
    sortChooseGoodsInfo();
}

//paixu
function sortChooseGoodsInfo() {
    $(".choosedGoodsTbody").each(function (i, ele) {
        $(ele).find('td:first').text(i + 1);
    });
}

/* 贸理通3.1 - 开始  */
$('[name=approval]').on('change', function () {
    if($('[name=approval]:checked').val() == '1') {
        $('.approvalHide').show()
        $('[name=addGoods]').change()
        $('.approvalTd').attr('colspan', 0)
        $('.approvalTd').attr('width', '35%')
        $('.approvalChange').hide()
    }else {
        $('.approvalChange').show()
        $('.approvalHide').hide()
        $('.goodsTable').hide()
        $('.approvalTd').attr('colspan', 3)
        $('.approvalTd').attr('width', '85%')
    }
})

$('[name=addGoods]').on('change', function () {
    if($('[name=addGoods]:checked').val() == '1') {
        $('.goodsTable').show()
    }else {
        $('.goodsTable').hide()
    }
})

// 选择货物的时候后端计算暂定单价
function calcGoodsTempPrice(goodsList, type) {
    if(!$("[name=accrualMarginCalcMethod]").val()) {
        if(type !== 'noMessage') {
            new $.zui.Messager('请选择利差计算方式', {
                type: 'danger'
            }).show();
        }
        return
    }
    var postdata = new FormData();


    goodsList.forEach((item, index) => {
        postdata.append(`salesGoodsIds[${index}].id`, item.id);
        postdata.append(`salesGoodsIds[${index}].quantity`, item.quantity);
        postdata.append(`salesGoodsIds[${index}].supplement`, item.supplement);
    })
    postdata.append(`priceRule.accrualMarginCalcMethod`, $("[name=accrualMarginCalcMethod]").val());
    if($("[name=accrualMarginCalcMethod]").attr('code') === 'purchAccrualMarginCalcMethod_fixedInterest') {
        if(!$("[name=factoringFinanceDeadline]").val()) {
            if(type !== 'noMessage') {
                new $.zui.Messager('请输入预估保理融资期限', {
                    type: 'danger'
                }).show();
            }

            return
        }
        if(!$("[name=monthlyInterestRate]").val()) {
            if(type !== 'noMessage') {
                new $.zui.Messager('请输入月利率', {
                    type: 'danger'
                }).show();
            }

            return
        }
        postdata.append(`priceRule.factoringFinanceDeadline`, $("[name=factoringFinanceDeadline]").val());
        postdata.append(`priceRule.monthlyInterestRate`, $("[name=monthlyInterestRate]").val());
    }else {
        if(!$("[name=differAmount]").val()) {
            if(type !== 'noMessage') {
                new $.zui.Messager('请输入差额', {
                    type: 'danger'
                }).show();
            }
            return
        }
        postdata.append(`priceRule.differAmount`, $("[name=differAmount]").val().split(',').join(''));
    }
    $.ajax({
        url: '/purchContract/calculateGoods',
        type: 'post',
        processData: false,
        contentType: false,
        data: postdata,
        success: function (data) {
            if (data.success) {
                const list = data.data
                // 这是用于价格规则发生变化生效的
                // if(type === 'noMessage') {
                //     $('.goodsListTable').empty()
                // }
                list.forEach(item => {
                    var supplierTrClone2 = $(".goodsListTbody:first").clone();
                    supplierTrClone2.find('.negativeInformationReduce').show();
                    supplierTrClone2.find('.error').hide();
                    supplierTrClone2.find('input').val('');
                    supplierTrClone2.find('select').val('');
                    supplierTrClone2.find('td').eq(1).find('input').attr('supplement', item.supplement)
                    supplierTrClone2.find('td').eq(1).find('input').val(item.goodsName)
                    supplierTrClone2.find('td').eq(2).find('input').val(item.goodsFactory)
                    supplierTrClone2.find('td').eq(3).find('input').val(item.modelNumber)
                    supplierTrClone2.find('td').eq(4).find('input').val(item.units)
                    supplierTrClone2.find('td').eq(5).find('input').val(item.quantity)
                    supplierTrClone2.find('td').eq(6).find('input').val(item.price === '不明确' ? item.price : Number(item.price).toFixed(2))
                    supplierTrClone2.find('td').eq(7).find('input').val(item.remark)
                    supplierTrClone2.find('td').eq(1).find('input').attr('goodsId', item.id)
                    supplierTrClone2.attr('id', item.id)
                    supplierTrClone2.show();
                    $('.goodsListTable').append(supplierTrClone2);
                    sortIGoodsnfo();
                })
                $("#myModal-chooseGoods").modal("hide");
            } else {
                new $.zui.Messager('暂定单价失败:' + data.msg, {
                    type: 'danger'
                }).show();
            }
        },
        error: function (status) {
            new $.zui.Messager('暂定单价发生错误:' + status, {
                type: 'danger'
            }).show();
        }
    });
}

/* 贸理通3.1 - 结束  */


$(function () {
    // 贸理通3.1 - 开始
    // 是否需要审核默认值
    if(!$('[name=approval]:checked').val()) {
        $('[name=approval]').get(1).checked = true
    }
    if(!$('[name=addGoods]:checked').val()) {
         // 是否新增货物默认值
        $('[name=addGoods]').get(1).checked = true
    }


    $('[name=approval]').change()
    uploadFileMethod({
        mainDom: '#contractSign-form',
        delegateDom: '.choiceFile',
        insideDelegateDom: '.fileContent',
        delegateDomInput: '.fileListBox .fileinput',
        depositDataDom: '.fileListBox',
        delegateLabel: '.fileListBox',
        displayListDom: '.uploaderFile',
        isCustomUploadBtn: false,
    })
    if($('.contractBoxUploadTdFileStorage').length) {
        showOriginalFile($('.contractBoxUploadTdFileStorage'), $('.contractBoxUploadTd').find('.fileListBox'), 'delete')
    }

    sortIGoodsnfo()

    // 贸理通3.1 - 结束

    //初始化日期
    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=contractEffectDate]','1970-01-01','2116-12-31');

    //提交
    function submitFunction(e){
        // $(".newTabAddUpdateBtnBox .save,.newTabAddUpdateBtnBox .btn-cancel").addClass("loadingCircle");
        var postdata = new FormData(),tipword="变更";
        postdata.append('taskId',$('[name=taskId]').val() === 'null' ? '' : $('[name=taskId]').val())
        postdata.append('businessKey',$('[name=businessKey]').val())
        postdata.append('contractSupplementInfo.approval',$('[name=approval]:checked').val())
        postdata.append('contractSupplementInfo.id',$('[name=purchContractSupplementInfoId]').val())


        if($('[name=approval]:checked').val() == '1') {
            postdata.append('contractSupplementInfo.addGoods',$('[name=addGoods]:checked').val())
            postdata.append('contractSupplementInfo.supplementContractNumber',$('[name=supplementContractNumber]').val())
            postdata.append('contractSupplementInfo.contractEffectDate',$('[name=contractEffectDate]').val())
            postdata.append('contractSupplementInfo.priceRuleDetail',$('[name=priceRuleDetail]').val())
            postdata.append('contractSupplementInfo.otherConvention',$('[name=otherConvention]').val())
            if($('[name=addGoods]:checked').val() == '1') {
                // 货物信息
                for (var i = 1; i < $(".goodsListTbody").length; i++) {
                    postdata.append('purchContractGoodsInfo[' + (i - 1) + '].supplement', $(".goodsListTbody").eq(i).find('td').eq(1).find('input').attr('supplement'));
                    postdata.append('contractGoodsInfo[' + (i - 1) + '].goodsName', $(".goodsListTbody").eq(i).find('td').eq(1).find('input').val());
                    postdata.append('contractGoodsInfo[' + (i - 1) + '].goodsFactory', $(".goodsListTbody").eq(i).find('td').eq(2).find('input').val());
                    postdata.append('contractGoodsInfo[' + (i - 1) + '].modelNumber', $(".goodsListTbody").eq(i).find('td').eq(3).find('input').val());
                    postdata.append('contractGoodsInfo[' + (i - 1) + '].units', $(".goodsListTbody").eq(i).find('td').eq(4).find('input').val());
                    postdata.append('contractGoodsInfo[' + (i - 1) + '].quantity', $(".goodsListTbody").eq(i).find('td').eq(5).find('input').val());
                    postdata.append('contractGoodsInfo[' + (i - 1) + '].price', $(".goodsListTbody").eq(i).find('td').eq(6).find('input').val());
                    postdata.append('contractGoodsInfo[' + (i - 1) + '].remark', $(".goodsListTbody").eq(i).find('td').eq(7).find('input').val());
                    postdata.append('purchContractGoodsInfo[' + (i - 1) + '].salesContractGoodsInfoId', $(".goodsListTbody").eq(i).find('td').eq(1).find('input').attr('goodsId'));
                }
            }
        }else {
            // 合同文件
            let file = $('.contractBoxUploadTd').find('.fileListBox').data('filearray')
            let fileId = $('.contractBoxUploadTd').find('.fileListBox .file-name').attr('originalId')
            let deleteFiles = $('.contractBoxUploadTd').find('.fileListBox').data('deletefileid')
            if(!file.length && !fileId) {
                new $.zui.Messager('请上传附件', {
                    type: 'success'
                }).show();
                return
            }
            for (let i = 0; i < file.length; i++) {
                postdata.append(`contractSupplementInfo.files[${i}]`, file[i])
            }
            for (let i = 0; i < deleteFiles.length; i++) {
                postdata.append(`contractSupplementInfo.deleteFiles[${i}]`, deleteFiles[i])
            }
        }



        // 说明
        postdata.append('contractSupplementInfo.remark',$('[name=remark]').val())
        $.ajax({
            url:'/purchContract/change/doChange',
            type:'post',
            data:postdata,
            processData:false,
            contentType:false,
            success:function(data){
                if( data.success ){
                    new $.zui.Messager(tipword+'成功', {
                        type: 'success'
                    }).show();

                    $(".yk_rightcontent").load('/purchContract/list');

                }else{
                    new $.zui.Messager(tipword+'失败:'+data.msg, {
                        type: 'danger'
                    }).show();
                    // $(".newTabAddUpdateBtnBox .save,.newTabAddUpdateBtnBox .btn-cancel").removeClass("loadingCircle");
                }
            },
            error:function(){
                new $.zui.Messager(tipword+'时发生错误:'+status, {
                    type: 'danger'
                }).show();
                // $(".newTabAddUpdateBtnBox .save,.newTabAddUpdateBtnBox .btn-cancel").removeClass("loadingCircle");
            }
        });
        return false;
    };

    var formRules = {
        // supplementContractNumber: {
        //     required:true
        // },
        contractEffectDate: {
            required:true
        },
        priceRuleDetail: {
            required:true
        },
        addGoods: {
            required:true
        }
    };

    var formMessages = {
        approvalConclusion:{
            required:'请输入补充合同编号'
        },
        contractEffectDate: {
            required:'请选择合同生效日'
        },
        priceRuleDetail: {
            required: '请输入价格计算规则'
        },
        addGoods: {
            required: '请选择是否新增货物'
        }
    };


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

        $("#contractSign-form").validate({
            promptPosition : "bottomLeft",
            submitHandler : function(form) {
                //货物必填验证
                if($('[name=approval]:checked').val() == '1' && $('[name=addGoods]:checked').val() == '1') {
                    if ($(".goodsListTable .goodsListTbody").length) {
                        $('.goodsListTable .validInput').change();
                    } else {
                        new $.zui.Messager('请添加货物信息。', {
                            type: 'danger'
                        }).show();
                        return false;
                    }
                }
                submitFunction(e);
            },
            rules:formRules,
            messages : formMessages
        });
    };

    // 提交按钮
    $(".yk_addNewMsg .save").click(function(e){
        if( !$(this).hasClass('loadingCircle') ){
            addNewCustomer(e);
        };
    });

    // 关闭按钮
    $(".yk_addNewMsg .btn-cancel,.newBackBtn").click(function(){
        if( !$(this).hasClass('loadingCircle') ){
            $(".yk_rightcontent").load('/purchContract/list');
        };
        return false;
    });


    //释放
    $("#myModal-chooseGoods").on('click', '.chooseGoodsTable .relaseGoods', function () {
        $(this).parents('.choosedGoodsTbody').remove();
        sortChooseGoodsInfo();
        //return false;
    });

    function hideSelectAll() {
        $("#cb_chooseGoodsList").hide();
        return (true);
    }

    function operate(cellValue, options, rowObject) {
        var btnstr = '';
        btnstr += '<p><span>选择</span><i class="icon-check" onclick="chooseGoods(' + rowObject.id + ')"></i></p>';
        return '<div class="operateIcon noHover">' + btnstr + '</div>';
    };

    function tablefunction(tableid) {
        var tipword = '', pageid = '', pageNo = 1, postData = {};
        url = '', colNamesArray = [], colModelArray = [];
        switch (tableid) {
            case '#chooseGoodsList':
                tipword = '货物';
                pageid = '#chooseGoodsListPage';
                postData = {
                    'businessKey': $("[name=businessKey]").val(),
                    'taskId': $("[name=taskId]").val()
                };
                url = '/purchContract/selectGoods';
                colNamesArray = ['ID', '销售备注', 'supplement', '编号', '名称', '厂家', '型号', '单位', '数量', '销售单价'];
                colModelArray = [
                    {name: 'id', label: 'ID', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'remark', label: '销售备注', hidedlg: true, hidden: true, sortable: false, title: false},
                     {name: 'supplement', label: 'supplement', hidedlg: true, hidden: true, sortable: false, title: false},
                    {name: 'orderNumber', label: '编号', hidedlg: true, width: 50, sortable: false, title: false},
                    {name: 'goodsName', label: '名称', sortable: false, align: 'left', title: false},
                    {name: 'goodsFactory', label: '厂家', sortable: false, align: 'left', title: false},
                    {name: 'modelNumber', label: '型号', sortable: false, align: 'left', title: false},
                    {name: 'units', label: '单位', sortable: false, align: 'left', title: false},
                    {name: 'quantity', label: '数量', sortable: false, align: 'left', title: false},
                    {name: 'salesPrice', label: '销售单价', sortable: false, align: 'left', title: false},
                    // {name: 'operate', label: '操作',sortable:false,align:'left',title:false,formatter:operate},
                ];
                break;
        }
        ;
        sxUtil.jqGrid(tableid, {
            colNames: colNamesArray,
            colModel: colModelArray,
            height: 'auto',
            mtype: 'GET',
            url: url,
            // pager: pageid,
            rowNum: 0,
            rowList: [],
            multiselect: true,
            multiboxonly: true,
            beforeSelectRow: function (rowid, e) {
                var $myGrid = $(this),
                    i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
                    cm = $myGrid.jqGrid('getGridParam', 'colModel');
                return (cm[i].name == 'cb')
            },
            onSelectAll: function(aRowids,status) {
                checkBoxDisabled()
            },
            rownumbers: false,
            postData: postData,
            page: pageNo,
            loadError: function () {
                new $.zui.Messager(tipword + '列表加载失败', {
                    type: 'warning'
                }).show();
            }
        }, true);
        $(tableid).trigger('reloadGrid');
    };

    tablefunction('#chooseGoodsList');

    $("#chooseButton").click(function () {

        $('#chooseGoodsList').setGridParam({
            mtype: 'GET',
            url: '/purchContract/selectGoods',
            datatype: 'json',
            postData: {
                'businessKey': $("[name=basicId]").val(),
                'taskId': $("[name=taskId]").val()
            },
            page: 1
        });
        $('#chooseGoodsList').trigger('reloadGrid');
        $("#myModal-chooseGoods").modal("show");
        $("#myModal-chooseGoods").on('shown.zui.modal', function () {
            $(window).resize();
            $("#chooseGoodsList_cb").css({'width': '45', 'padding': '0 0.12rem'})
            $('#chooseGoodsList .jqgfirstrow td:first').css('width', '45')

            $(".choosedGoodsList").empty();
        })
        checkBoxDisabled()
        return false;
    });

    // 选择货物提交按钮
   /*  $(".chooseSure").click(function () {
        var ids = $('#chooseGoodsList').jqGrid('getGridParam', 'selarrrow');
        if (ids.length > 0) {
            for (var i = 0; i < ids.length; i++) {
                var chooseData = $('#chooseGoodsList').jqGrid('getRowData', ids[i]);
                var trStr = `<tr class="choosedGoodsTbody">
                        <td width="5%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;"></td>
                        <td width="14%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.goodsName + `</td>
                        <td width="14%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.goodsFactory + `</td>
                        <td width="14%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.modelNumber + `</td>
                        <td width="13%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.units + `</td>
                        <td width="13%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.quantity + `</td>
                        <td width="13%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;">` + chooseData.salesPrice + `</td>
                        <td style="display: none">` + chooseData.id + `</td>
                        <td style="display: none" class="remark">` + chooseData.remark + `</td>
                        <td width="10%" style="background-color:#fff;border-bottom: 1px solid #E8F0F3;border-right: 1px solid #E8F0F3;"><span class="relaseGoods" style="color: #5AC4FC;cursor: pointer">释放</span></td>
                    </tr>`
                $(".choosedGoodsList").append(trStr);
            }
        }

        $(".choosedGoodsTbody").each(function (i, ele) {

            var supplierTrClone2 = $(".goodsListTbody:first").clone();
            supplierTrClone2.find('.negativeInformationReduce').show();
            supplierTrClone2.find('.error').hide();
            supplierTrClone2.find('input').val('');
            supplierTrClone2.find('select').val('');

            supplierTrClone2.find('td').eq(1).find('input').val($(ele).find('td').eq(1).text())
            supplierTrClone2.find('td').eq(2).find('input').val($(ele).find('td').eq(2).text())
            supplierTrClone2.find('td').eq(3).find('input').val($(ele).find('td').eq(3).text())
            supplierTrClone2.find('td').eq(4).find('input').val($(ele).find('td').eq(4).text())
            supplierTrClone2.find('td').eq(5).find('input').val($(ele).find('td').eq(5).text())
            supplierTrClone2.find('td').eq(6).find('input').val($(ele).find('td.remark').text())
            supplierTrClone2.find('td').eq(1).find('input').attr('goodsId',$(ele).find('td').eq(7).text())

            supplierTrClone2.show();
            $('.goodsListTable').append(supplierTrClone2);
            sortIGoodsnfo();

        })
        $("#myModal-chooseGoods").modal("hide");
    }) */

     // 贸理通V3.1货物点击确定逻辑
     $(".chooseSure").click(function () {
        var ids = $('#chooseGoodsList').jqGrid('getGridParam', 'selarrrow');
        if(ids.length) {
            let goodsListTbodyId = []
            $('.goodsListTbody').each(function ( j, ele) {
                goodsListTbodyId.push($(ele).attr('id'))
            })
            const goodList = []
            for (var i = 0; i < ids.length; i++) {
                const goodsListTbodyIdStatus = goodsListTbodyId.every(item => item !== ids[i])
                if(goodsListTbodyIdStatus) {
                    const { quantity } = $('#chooseGoodsList').jqGrid('getRowData', ids[i])
                    // const pattern = /\d+(\.\d+)?/;
                    // const match = quantity.match(pattern);
                    const match = quantity.replace(/<[^>]+>/g, '')
                    goodList.push({
                        ...$('#chooseGoodsList').jqGrid('getRowData', ids[i]),
                        quantity: match
                    })
                }
                // if(goodsListTbodyIdStatus) {
                //     goodList.push($('#chooseGoodsList').jqGrid('getRowData', ids[i]))
                // }else {
                //     new $.zui.Messager('请选择货物', {
                //         type: 'danger'
                //     }).show();
                //     return
                // }
            }

            if(goodList.length) {
                calcGoodsTempPrice(goodList, 'noMessage')
            }else {
                new $.zui.Messager('货物已全部选择', {
                    type: 'danger'
                }).show();
            }


        }else {
            new $.zui.Messager('请选择货物', {
                type: 'danger'
            }).show();
        }
    })
})
