$(function () {
    $('#creditReportingUpdateBtn').removeClass("loadingCircle");

    //日期的处理
    $('[name=establishDate],[name=bizEndDate]').each(function (i, ele) {
        $(ele).val($(ele).attr('value').substring(0, 4) + '-' + $(ele).attr('value').substring(4, 6) + '-' + $(ele).attr('value').substring(6, 8));
    });

    // 获取字典项数据
    function getDictCode(paramName) {
        var dictOptionsData = {};
        $.ajax({
            url: '/dictionary/do_findByParentCode',
            type: 'get',
            data: {
                'parentCode': paramName
            },
            async: false,
            success: function (data) {
                dictOptionsData = data.data;
            },
            error: function (status) {
                new $.zui.Messager('获取字典项时出错:' + status, {
                    type: 'danger'
                }).show();
            }
        });
        return dictOptionsData;
    };
    // 获取行业分类
    function getEntDictCode(paramName) {
        var dictOptionsData = {};
        $.ajax({
            url: '/creditEntBusiness/doFindDictCode',
            type: 'get',
            data: {
                'paramName': paramName
            },
            async: false,
            success: function (data) {
                dictOptionsData = data;
            },
            error: function (status) {
                new $.zui.Messager('获取字典项时出错:' + status, {
                    type: 'danger'
                }).show();
            }
        });
        return dictOptionsData;
    };

    //组织机构类型
    var selectTypeOptions = getDictCode('entOrgType');
    if (selectTypeOptions) {
        $("[name=orgType]").append('<option value="">请选择</option>')
        for (var i=0; i<selectTypeOptions.length; i++ ) {
            $("[name=orgType]").append('<option value="' + selectTypeOptions[i].id + '" code="' + selectTypeOptions[i].code + '">' + selectTypeOptions[i].name + '</option>')
        }
        i=null;
        if($("[name=orgTypeBack]").val() !== '') {
            $("[name=orgType]").find('option[value=' + $("[name=orgTypeBack]").val() + ']').prop('selected', true);
        }

    }
    $("[name=orgType]").change(function () {
        if($(this).val() !== '') {
            var selectTypeOptions = getDictCode($(this).find('option:selected').attr('code'));
            $("[name=orgSubType]").empty();
            $("[name=orgSubType]").append('<option value="">请选择</option>')
            if (selectTypeOptions) {
                for (var i=0; i<selectTypeOptions.length; i++ ) {
                    $("[name=orgSubType]").append('<option value="' + selectTypeOptions[i].id + '">' + selectTypeOptions[i].name + '</option>')
                };
                i=null;
                if($("[name=orgSubTypeBack]").val() !== '') {
                    $("[name=orgSubType]").find('option[value=' + $("[name=orgSubTypeBack]").val() + ']').prop('selected', true);
                }

            }
        }
    })
    $("[name=orgType]").change();

    // '登记注册号类型' / '客户类型' / '国别' / '注册资本(币种)' / '组织机构类别' / '组织机构类别细分' / '经济行业分类' / '经济类型' / '基本户状态' / '企业规模' / '机构状态'
    // $('[name=regNoType],[name=custType],[name=countryCode],[name=capitalCurrency],[name=economicType],[name=accountStatus],[name=entScope],[name=orgStatus]').each(function(i,ele){
    // 	var selectTypeOptions = getDictCode($(ele).attr('name'));
    // 	if( selectTypeOptions ){
    // 		for( var i in selectTypeOptions){
    // 			$(ele).append('<option value="'+i+'">'+selectTypeOptions[i]+'</option>')
    // 		};
    // 		$(ele).find('option[value='+$(ele).attr('orival')+']').prop('selected',true);
    // 	};
    // });

    //'经济行业分类'--处理为带搜索项的
    var industryOptions = getEntDictCode('industry');
    $('.allIndustry').empty();
    for( var i in industryOptions ){
    		$('.allIndustry').append('<li class="companyli" value="'+i+'">'+industryOptions[i]+'</li>');
    		if( $('#ecoIndusCateBack').val() == i ){
    			$('#ecoIndusCate').val(industryOptions[i])
    		}
    };
    // for (var i=0; i<industryOptions.length; i++ ) {
    //     $('.allIndustry').append('<option value="' + industryOptions[i].code + '">' + industryOptions[i].name + '</option>')
    // };
    // i=null;
    withSearchDropDownBox({
    	allOptionSelector:'.allIndustry li',//所有的选项的选择器
    	triggerSelector:'#ecoIndusCate',//触发选择(显示下拉框)的表单的选择器(存放选择的name)
    	resultIdSelector:'#ecoIndusCateBack',//表单元素选择器(存放选择的id)
    	dropdownSelector:'.industryListBox',//下拉框的选择器
    	searchBtn:'.industryListBox button'// 查询按钮选择器
    });

    // 选择reg行政区划
    $('#regAreaCode').click(function () {
        chooseProvinceEtc({
            triggerId: '#regAreaCode',// 触发选择元素的选择器, 即存放最终选择结果的选择器, 该元素需要至少有相对定位属性
            originalId: '.originalVal'// 原先的纯文字元素的选择器, 选填
        })
    });
    // 选择con行政区划
    $('#conAreaCode').click(function () {
        chooseProvinceEtc({
            triggerId: '#conAreaCode',// 触发选择元素的选择器, 即存放最终选择结果的选择器, 该元素需要至少有相对定位属性
            originalId: '.originalValue'// 原先的纯文字元素的选择器, 选填
        })
    });

    // 日期
    $('[name=establishDate],[name=bizEndDate]').datetimepicker(
        {
            weekStart: 1,
            autoclose: 1,
            todayHighlight: 0,
            startView: 2,
            minView: 2,
            forceParse: 0,
            showMeridian: 1,
            startDate: '1970-01-01',
            endDate: '2999-12-31',
            format: "yyyy-mm-dd"
        }
    );
    $('[name=establishDate],[name=bizEndDate]').datetimepicker('setStartDate', '1970-01-01');
    $('[name=establishDate],[name=bizEndDate]').datetimepicker('setEndDate', '2999-12-31');

    //日期输入框可删除
    $('.deleteTime').each(function (i, ele) {
        $(ele).parent().find('input').change(function () {
            if ($(this).val() !== '') {
                var transDate = $(this).val().split('-')[0] + $(this).val().split('-')[1] + $(this).val().split('-')[2];
                $(this).val(transDate)
                $(ele).show();
                //日期有值时去掉验证效果
                $(ele).parent().find('input').removeClass('error');
                $("#" + $(ele).parent().find('input').attr('name') + "-error").hide();
            } else {
                $(ele).hide();
            }
        });
        $(ele).parent().find('input').change();
    });
    $('.deleteTime').click(function () {
        $(this).parent().find('input').val('');
        $(this).hide();
    });

    // 注册资本输入时添加分隔符
    $('[name=regCap]').val(commaDelimiter($('[name=regCap]').val()))
    $('[name=regCap]').keyup(function(){
    	$(this).val( commaDelimiter($(this).val()));
    });

    // 取消
    $('#creditReportingBackBtn').click(function () {
        $(".yk_businessTabContentBox").load('/creditEntBusiness/basic/viewCreditEntBasic?entBusInfoId=' + enterPriseBusinessQuery.enterPriseDomesticCompanyId);
        return false;
    });

    function updateOrgbaseInfoNewValid(e) {
        $("#updatecreditEntBasicNew").validate({
            promptPosition: "bottomLeft",
            submitHandler: function (form) {
                // if ($('#regAreaCode').find('.originalVal').length <= 0 && $('#regAreaCode').find('.resultcounty').length <= 0) {
                //     new $.zui.Messager('登记地行政区划请选择到区县', {
                //         type: 'danger'
                //     }).show();
                //     return;
                // }
                // if ($('#conAreaCode').find('.originalValue').length <= 0 && $('#conAreaCode').find('.resultcounty').length <= 0) {
                //     new $.zui.Messager('联系地行政区划请选择到区县', {
                //         type: 'danger'
                //     }).show();
                //     return;
                // }
                var postdata = {};
                postdata['entBusInfo.id'] = enterPriseBusinessQuery.enterPriseDomesticCompanyId;
                postdata['id'] = $('#basicId').val();
                postdata['entName'] = $('[name=entName]').val();
                postdata['institution'] = $('[name=institution]').val();
                postdata['subjectSocialCreditCode'] = $('[name=subjectSocialCreditCode]').val();
                postdata['entCertType.id'] = $('[name=entCertType]').val();
                postdata['entCertNum'] = $('[name=entCertNum]').val();
                // postdata['cimoc'] = $('[name=cimoc]').val();

                postdata['customerType'] = $('[name=customerType]').val();
                postdata['etpStatus.id'] = $('[name=etpStatus]').val();
                postdata['orgType.id'] = $('[name=orgType]').val();
                postdata['orgSubType.id'] = $('[name=orgSubType]').val();
                postdata['nationality'] = $('[name=nationality]').val();
                postdata['regAdd'] = $('[name=regAdd]').val();
                postdata['admDivOfReg'] = $('[name=admDivOfReg]').val();
                postdata['establishDate'] = $('[name=establishDate]').val();
                postdata['bizEndDate'] = $('[name=bizEndDate]').val();
                postdata['bizRange'] = $('[name=bizRange]').text();
                //postdata['orgAttr.regCapital'] = $('[name=regCapital]').val().split(',').join('');
                if ($("#ecoIndusCateBack").val() != '') {
                    postdata['ecoIndusCate'] = $("#ecoIndusCateBack").val();
                }
                postdata['ecoType.id'] = $('[name=ecoType]').val();
                postdata['regCapCurrency.id'] = $('[name=regCapCurrency]').val();
                postdata['regCap'] = $('[name=regCap]').val().split(',').join('');
                postdata['regCapStr'] = $('[name=regCapStr]').val();
                postdata['entScale'] = $('[name=entScale]').val();
                postdata['conAdd'] = $('[name=conAdd]').val();
                postdata['conPhone'] = $('[name=conPhone]').val();
                postdata['finConPhone'] = $('[name=finConPhone]').val();

                if ($('#regAreaCode').find('.originalVal').length <= 0) {
                    if($('#regAreaCode').find('.resultcounty').attr('deptCode')) {
                        postdata['admDivOfReg'] = $('#regAreaCode').find('.resultcounty').attr('deptCode');
                    }else {
                        postdata['admDivOfReg'] = $('#regAreaCode').find('.resultcity').attr('deptCode');
                    }
                } else {
                    postdata['admDivOfReg'] = $('#regAreaCode').attr('originalcode');
                }
                if ($('#conAreaCode').find('.originalValue').length <= 0) {
                    if($('#conAreaCode').find('.resultcounty').attr('deptCode')) {
                        postdata['conAddDistrictCode'] = $('#conAreaCode').find('.resultcounty').attr('deptCode');
                    }else {
                        postdata['conAddDistrictCode'] = $('#conAreaCode').find('.resultcity').attr('deptCode');
                    }
                } else {
                    postdata['conAddDistrictCode'] = $('#conAreaCode').attr('originalcode');
                }

                $('#creditReportingSaveBtn').addClass("loadingCircle");

                $.ajax({
                    url: '/creditEntBusiness/basic/doUpdateCreditEntBasic',
                    type: 'post',
                    data: postdata,
                    success: function (data) {
                        if (data.success) {
                            if (data.data) {
                                new $.zui.Messager('修改基本信息成功', {
                                    type: 'success'
                                }).show();
                                $(".yk_businessTabContentBox").load('/creditEntBusiness/basic/viewCreditEntBasic?entBusInfoId=' + enterPriseBusinessQuery.enterPriseDomesticCompanyId);
                                return false;
                            } else {
                                new $.zui.Messager('修改基本信息失败', {
                                    type: 'danger'
                                }).show();
                            }
                            ;
                        } else {
                            new $.zui.Messager('修改基本信息请求失败:' + data.msg, {
                                type: 'danger'
                            }).show();
                        }
                        ;
                        $('#creditReportingSaveBtn').removeClass("loadingCircle");
                    },
                    error: function (status) {
                        new $.zui.Messager('修改基本信息时出错:' + status, {
                            type: 'danger'
                        }).show();
                        $('#creditReportingSaveBtn').removeClass("loadingCircle");
                    }
                })

            },
            rules: {
                // "orgChnName": {
                //     maxlength: 120
                // },
                // "orgEngName": {
                //     maxlength: 80
                // },
                // "loanCardNo": {
                //     maxlength: 16
                // },
                // "regNo": {
                //     maxlength: 20
                // },
                // 'orgCreditCode': {
                //     maxlength: 18
                // },
                // 'accountPermitNo': {
                //     maxlength: 20
                // },
                // 'regAddr': {
                //     maxlength: 120
                // },
                // 'bizScope': {
                //     maxlength: 200
                // },
                // 'regCapital': {
                //     decimalLengthValid2: true,
                //     decimalNumberValid3: true,
                //     decimalPointValid: true
                // },
                // 'officeAddr': {
                //     maxlength: 120
                // },
                // 'phoneNo': {
                //     maxlength: 35
                // },
                // 'financePhoneNo': {
                //     maxlength: 35
                // }
            },
            messages: {
                // "orgChnName": {
                //     maxlength: '最多不超过120个字符'
                // },
                // "orgEngName": {
                //     maxlength: '最多不超过80个字符'
                // },
                // "loanCardNo": {
                //     maxlength: '最多不超过16个字符'
                // },
                // "regNo": {
                //     maxlength: '最多不超过20个字符'
                // },
                // 'orgCreditCode': {
                //     maxlength: '最多不超过18个字符'
                // },
                // 'accountPermitNo': {
                //     maxlength: '最多不超过20个字符'
                // },
                // 'regAddr': {
                //     maxlength: '最多不超过120个字符'
                // },
                // 'bizScope': {
                //     maxlength: '最多不超过200个字符'
                // },
                // 'officeAddr': {
                //     maxlength: '最多不超过120个字符'
                // },
                // 'phoneNo': {
                //     maxlength: '最多不超过35个字符'
                // },
                // 'financePhoneNo': {
                //     maxlength: '最多不超过35个字符'
                // }
            }
        });
    }
    updateOrgbaseInfoNewValid();

    // 保存
    $('#creditReportingSaveBtn').click(updateOrgbaseInfoNewValid);


})