var el = {
    form: '#form',
    firstParty: '#firstParty',
    firstPartyPhone: '#firstPartyPhone',
    defaultAccount: '#defaultAccount',
    secondPartyPhone: '#secondPartyPhone',
    firstPartyUserName: '#firstPartyUserName',
    secondPartyUserName: '#secondPartyUserName',
    secondParty: '#secondParty',
    numberOfPages: '#numberOfPages',
    signOrder: '#signOrder',
    signatureType: '#signatureType',
    firstPartySignatureType: '#firstPartySignatureType',
    secondPartySignatureType: '#secondPartySignatureType',
    firstPartyAutoSign: '#firstPartyAutoSign',
    firstPartySignType: '#firstPartySignType',
    secondPartySignType: '#secondPartySignType',
    attachmentType: '#attachmentType',
    templateType: '#templateType',

};
$(function () {
    var summaryFileIdValue = $('#summaryFileId').val();
    console.log(summaryFileIdValue);
    initDict('sign_order,sign_type_two,sign_type')
    initNecessaryDatas('pc/sys/tax/rest/listAll')
    //页面初始化的时候进行汇总文件的id信息查询
    if(summaryFileIdValue !== "" && summaryFileIdValue !== null){
        var $div = $("#files");
        $div.attr("data-fileIds", summaryFileIdValue);
        //通过ajax查询订单上带的fileKey
       var businessId = $('#businessId').val();
        $.ajax({
            url: g.ctx+ "pc/order/purchaseOrder/rest/getPurchaseOrderById", type: 'get', data: {orderId:businessId},// ⑧告诉jQuery不要去处理发送的数据
            contentType: false,
            async: false, // 设置为同步请求
            success: function (obj) {
                console.log(obj.column2);
                if(obj.column2 !== '' && obj.column2 !== null){
                    $div.attr("data-fileKeys", obj.column2);
                }

            }, error: function (responseStr) {
                let message = responseStr['responseJSON']['message'];
                if (message) {
                    topWin.layer.msg(message);
                } else {
                    topWin.layer.msg('附件上传出错');
                }
            }
        });
    }
    initFileForm('sign-file-form')
    initFileForm('sign-create-file-form')
    // 加载页面输入或下拉框数据
    initPageInput();
    //通过订单号查询文件信息回填签署页面
// 假设你想赋的值是 '123,456,789'


});

function initPageInput() {
    $(el.firstPartyUserName).combobox({
        required: true,
        valueField: 'id',
        textField: 'username',
        // limitToList: 'true',
        panelHeight: 'auto',
        editable: false,
        method: 'GET',
        // prompt: '--- 请选择 ---',
        url: g.ctx+ 'pc/sys/digitalSealConfig/rest/listAll?sealType='+$(el.firstPartySignatureType).combobox('getValue')+'&companyCode='+$(el.firstParty).val(),
        onSelect: function (data) {
            $(el.firstPartyPhone).textbox('setValue', data.phone);
        },
        onLoadSuccess: function (data) {
            console.log(data)
            if (data.length > 0){
                var su = false;
                var defaultAccount = $(el.defaultAccount).val()
                if (defaultAccount){
                    data.forEach(function (item) {
                        if (item.signerAccount === defaultAccount){
                            $(el.firstPartyUserName).combobox('setValue', item.id);
                            $(el.firstPartyPhone).textbox('setValue', item.phone);
                            su = true;
                        }
                    });
                }
                if (!su){
                    $(el.firstPartyUserName).combobox('setValue', data[0].id);
                    $(el.firstPartyPhone).textbox('setValue', data[0].phone);
                }
            }
        },
    });
    $(el.secondPartyUserName).combobox({
        required: true,
        valueField: 'contactsName',
        textField: 'codeWithDesc',
        // limitToList: 'true',
        panelHeight: 'auto',
        editable: false,
        method: 'GET',
        // prompt: '--- 请选择 ---',
        url: g.ctx+ 'pc/supplier/contact/rest/getListBySupplierCodeAndType?supplierCode='+$(el.secondParty).val()+'&type=10',
        onSelect: function (data) {
            $(el.secondPartyPhone).textbox('setValue', data.contactsTel);
        },
        onLoadSuccess: function (data) {
            if (data.length > 0){
                $(el.secondPartyUserName).combobox('setValue', data[0].codeWithDesc);
                $(el.secondPartyPhone).textbox('setValue', data[0].contactsTel);
            }
        },
    });

    $(el.signOrder).combobox({
        required: true,
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        panelHeight: 'auto',
        method: 'GET',
        prompt: '--- 请选择 ---',
        data: getDictList('sign_order'),
        onSelect: function (data) {
            //单签甲方 
            if (data.code==='3'){
                $(el.secondPartyUserName).combobox({ disabled: true, required: false });
                $('#secondPartyDisplay').hide()
            }else {
                $(el.secondPartyUserName).combobox({ disabled: false, required: true });
                $('#secondPartyDisplay').show()
            }
        },
        onLoadSuccess:function (data,value) {
            //单签甲方
            if (data.code==='3'){
                $(el.secondPartyUserName).combobox({ disabled: true, required: false });
                $('#secondPartyDisplay').hide()
            }else {
                $(el.secondPartyUserName).combobox({ disabled: false, required: true });
                $('#secondPartyDisplay').show()
            }
        }
    });

    $(el.firstPartySignatureType).combobox({
        required: true,
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        panelHeight: 'auto',
        method: 'GET',
        prompt: '--- 请选择 ---',
        data: getDictList('sign_type'),
        onSelect: function (data) {
            $(el.firstPartyUserName).combobox({
                required: true,
                valueField: 'id',
                textField: 'username',
                // limitToList: 'true',
                panelHeight: 'auto',
                editable: false,
                method: 'GET',
                // prompt: '--- 请选择 ---',
                url: g.ctx+ 'pc/sys/digitalSealConfig/rest/listAll?sealType='+data.code+'&companyCode='+$(el.firstParty).val(),
                onSelect: function (result) {
                    $(el.firstPartyPhone).textbox('setValue', result.phone);
                },
                onLoadSuccess: function (result) {
                    if (result.length > 0){
                        var su = false;
                        var defaultAccount = $(el.defaultAccount).val()
                        if (defaultAccount){
                            result.forEach(function (item) {
                                if (item.signerAccount === defaultAccount){
                                    $(el.firstPartyUserName).combobox('setValue', item.id);
                                    $(el.firstPartyPhone).textbox('setValue', item.phone);
                                    su = true;
                                }
                            });
                        }
                        if (!su){
                            $(el.firstPartyUserName).combobox('setValue', result[0].id);
                            $(el.firstPartyPhone).textbox('setValue', result[0].phone);
                        }
                    }
                },
            });
        }
    });

    $(el.secondPartySignatureType).combobox({
        required: true,
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        panelHeight: 'auto',
        method: 'GET',
        prompt: '--- 请选择 ---',
        data: getDictList('sign_type')
    });

    if ($(el.templateType).length > 0){
        $(el.templateType).combobox({
            required: true,
            valueField: 'value',
            textField: 'label',
            limitToList: 'true',
            panelHeight: 'auto',
            prompt: '--- 请选择 ---',
            data: [
                {label: '材料购销合同', value: 0},
                {label: '加工费合同', value: 1}
            ],
            onChange: function (data) {
                console.log(data)
                let url = g.ctx + "pc/sys/esign/dialog?businessTypeCode=" + (data===0?'purchase_sale_contract' : 'purchase_sale_process_contract') + '&businessId=' + $('#businessId').val() + '&title=' + $('#title').val()
                    + '&firstParty=' + $('#firstParty').val() + '&firstPartyUserId=' + $('#firstPartyUserId').val() + '&firstPartyName=' + $('#firstPartyName').val()
                    + '&secondParty=' + $('#secondParty').val() + '&secondPartyName=' + $('#secondPartyName').val()+'&sumSignFlag=' + $('#sumSignFlag').val()+'&summaryFileId='+ $('#summaryFileId').val()
                window.location.href = url
            },
        });
    }

    $(el.firstPartyAutoSign).combobox({
        required: true,
        valueField: 'value',
        textField: 'label',
        limitToList: 'true',
        panelHeight: 'auto',
        prompt: '--- 请选择 ---',
        data: [
            {label: '否', value: '0'},
            {label: '是', value: '1'}
        ],
    });

    $(el.firstPartySignType).combobox({
        required: true,
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        multiple: true,
        panelHeight: 'auto',
        method: 'GET',
        prompt: '--- 请选择 ---',
        data: getDictList('sign_type_two'),
        onChange: function (data) {
            //如果是骑缝不是关键字
            if (data.indexOf("EDGE-SIGN") !== -1&&data.indexOf("KEYWORD-SIGN") === -1){
                $('.firstPartyKeywordDisplay').hide()
                $('.firstPartyEdgeDisplay').show()
            }else if (data.indexOf("EDGE-SIGN") === -1&&data.indexOf("KEYWORD-SIGN") !== -1){
                $('.firstPartyKeywordDisplay').show()
                $('.firstPartyEdgeDisplay').hide()
            }else {
                $('.firstPartyKeywordDisplay').show()
                $('.firstPartyEdgeDisplay').show()
            }
        },
        onLoadSuccess:function (data,value) {
            var code = $(el.firstPartySignType).combobox('getValues').join(',');
            if (code.indexOf("EDGE-SIGN") !== -1&&code.indexOf("KEYWORD-SIGN") === -1){
                $('.firstPartyKeywordDisplay').hide()
                $('.firstPartyEdgeDisplay').show()
            }else if (code.indexOf("EDGE-SIGN") === -1&&code.indexOf("KEYWORD-SIGN") !== -1){
                $('.firstPartyKeywordDisplay').show()
                $('.firstPartyEdgeDisplay').hide()
            }else {
                $('.firstPartyKeywordDisplay').show()
                $('.firstPartyEdgeDisplay').show()
            }
        }
    });

    $(el.secondPartySignType).combobox({
        required: true,
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        panelHeight: 'auto',
        multiple: true,
        method: 'GET',
        prompt: '--- 请选择 ---',
        data: getDictList('sign_type_two'),
        onChange: function (data) {
            //如果是骑缝不是关键字
            if (data.indexOf("EDGE-SIGN") !== -1&&data.indexOf("KEYWORD-SIGN") === -1){
                $('.secondPartyKeywordDisplay').hide()
                $('.secondPartyEdgeDisplay').show()
            }else if (data.indexOf("EDGE-SIGN") === -1&&data.indexOf("KEYWORD-SIGN") !== -1){
                $('.secondPartyKeywordDisplay').show()
                $('.secondPartyEdgeDisplay').hide()
            }else {
                $('.secondPartyKeywordDisplay').show()
                $('.secondPartyEdgeDisplay').show()
            }
        },
        onLoadSuccess:function (data,value) {
            var code = $(el.secondPartySignType).combobox('getValues').join(',');
            if (code.indexOf("EDGE-SIGN") !== -1&&code.indexOf("KEYWORD-SIGN") === -1){
                $('.secondPartyKeywordDisplay').hide()
                $('.secondPartyEdgeDisplay').show()
            }else if (code.indexOf("EDGE-SIGN") === -1&&code.indexOf("KEYWORD-SIGN") !== -1){
                $('.secondPartyKeywordDisplay').show()
                $('.secondPartyEdgeDisplay').hide()
            }else {
                $('.secondPartyKeywordDisplay').show()
                $('.secondPartyEdgeDisplay').show()
            }
        }
    });
}

function save(call) {
    if($(el.form).form('validate')){
        var formData = $(el.form).serializeJson();
        console.log(formData.firstPartySignType)

        formData.firstPartySignType = Array.isArray(formData.firstPartySignType)?formData.firstPartySignType.join(','):formData.firstPartySignType
        formData.secondPartySignType = Array.isArray(formData.secondPartySignType)?formData.secondPartySignType.join(','):formData.secondPartySignType
        formData.signatureType = formData.firstPartySignatureType

        if(formData.firstPartySignType.indexOf("KEYWORD-SIGN") === -1 || formData.secondPartySignType.indexOf("KEYWORD-SIGN") === -1){
            layer.msg("双方签署类型请选择关键字！");
            return false;
        }

        if (!$('.sign-file-form').attr('data-fileKeys')&&!$('.sign-create-file-form').attr('data-fileKeys')){
            layer.msg("请上传或生成签署附件！");
            return false;
        }
        //获取乙方签章类型

        //获取签署文件类型
        var businessTypeCode = $('#businessTypeCode').val();
        var firstPartySignatureType = $(el.firstPartySignatureType).combobox('getValue') //甲方签章类型
        var secondPartySignatureType = $(el.secondPartySignatureType).combobox('getValue')//乙方签章类型
        if(businessTypeCode === "account_statement"){
            if(secondPartySignatureType == 1){
                layer.msg("对账单乙方签章类别只能选择财务章或者公章！");
                return false;
            }
            if(firstPartySignatureType !=3 ){
                layer.msg("对账单甲方签章类别只能选择财务章！");
                return false;
            }
        }
        if(businessTypeCode === "purchase_order"){
            if(secondPartySignatureType == 3){
                layer.msg("采购订单乙方签章类别只能选择合同章或者公章！");
                return false;
            }
            if(firstPartySignatureType !=1 ){
                layer.msg("对账单甲方签章类别只能选择合同章！");
                return false;
            }
        }


        //页数校验 邓京术
        var numberOfPages = $('#numberOfPages').val();
        var fileKeyList = [];
        if ($('.sign-file-form').attr('data-fileKeys')){
            $('.sign-file-form').attr('data-fileKeys').split(',').forEach(function (tem,index) {
                var file = {
                    fileKey:tem,
                    fileType:0,
                    fileId:$('.sign-file-form').attr('data-fileIds').split(',')[index],
                }
                fileKeyList.push(file)
            })
        }
        if ($('.sign-create-file-form').attr('data-fileKeys')){
            $('.sign-create-file-form').attr('data-fileKeys').split(',').forEach(function (tem,index) {
                var file = {
                    fileKey:tem,
                    fileType:1,
                    fileId:$('.sign-create-file-form').attr('data-fileIds').split(',')[index],
                }
                fileKeyList.push(file)
            })
        }

        formData.fileKeyList = fileKeyList;
        formData.numberOfPages = numberOfPages;
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/sys/esign/rest/sendSign',
            method: 'post',
            data: JSON.stringify(formData),
            contentType: 'application/json',
            success: function (data) {
                top.layer.close(loading);
                call();
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                top.layer.close(loading);
                if (JSON.parse(data.responseText).code===1702055){
                    parent.layer.alert('因骑缝签需要印章落在2个页面及以上，您所生成或上传的附件不满足，请在签署类型中取消骑缝签的选择',{icon: 2, shadeClose: true, title: '温馨提示'});
                }else {
                    parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                }
            }
        });
    }else{
        layer.msg("红色框为必输项，请填写！");
    }
}

