{% extends 'obj_form.html' %}
{% load i18n %}
{% load tj_filters %}

{% block css %}
    {{ block.super }}
    #obj_form .datepicker{
        width:100px
    }
    #obj_form select.adm{
        min-width:100px;
        margin-left:5px;
    }
    #product_label{
        min-width:380px;
        margin-left:15px;
        margin-right:7px;
    }
    #obj_form .btn-del{
        float:right;
    }  

    #obj_form .checkbox { 
        padding-left:20px;
    }
{% endblock %}



{% block js %}
    {{ block.super }}

     $("#obj_form input[type='checkbox']").removeClass('form-control');


    var dt1,dt2;
    dt1=new Date();
    dt2=new Date();
    dt2.setFullYear(dt1.getFullYear(),11,31);
    $('.datepicker').datepicker({dateFormat: 'yy-mm-dd'});
    $('#dt1,#dt1_product').datepicker('setDate',dt1);
    $('#dt2,#dt2_product').datepicker('setDate',dt2);
    setDatePickerZh();

    var my_adm_1,my_adm_2,my_adm_3;
    my_adm_1={'id':'{{myadms.province.0}}','name':'{{myadms.province.1}}'};
    my_adm_2={'id':'{{myadms.city.0}}','name':'{{myadms.city.1}}'};
    my_adm_3={'id':'{{myadms.county.0}}','name':'{{myadms.county.1}}'};

  

    var phtml='';
    $('#id_province_gis_id').append("<option value=''>-----------------</option>");
    {% for p in provinces %}
        phtml=phtml+"<option value='{{p.0}}'>{{p.1}}</option>";
    {% endfor %}
    $('#id_province_gis_id').append(phtml);

    
    


    $('#product_label').autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: '/obj/ajax/autocomplete/product/',
                    dataType: "json",
                    data: {
                        term:   $("#product_label").val() ,//搜索栏里的内容
                        company_id:  $('#id_company').val() ,//额外参数
                    },
                    success: function(data) {
                        response(data);
                    }
                });
            },
            select: function (event, ui) {
                $("#product_id").val(ui.item.value);
                $("#product_label").val(ui.item.label);
                return false;
            }
    });

    
    {% ifequal request.user.company.level.sn 0 %}
        $('#parent_label').autocomplete({
            //source: {{children|safe}},
            source: function(request, response) {
                $.ajax({
                    url: '/obj/ajax/autocomplete/parent/',
                    dataType: "json",
                    data: {
                        term:   $("#parent_label").val() ,//搜索栏里的内容
                        company_id:  $('#id_company').val() ,//额外参数
                    },
                    success: function(data) {
                        response(data);
                    }
                });
            },
            select: function (event, ui) {      
                $("#id_parent").val(ui.item.value);
                $("#parent_label").val(ui.item.label);                
                $('#lv').text(ui.item.level.name); 
                $('#plv').val(ui.item.plv); 
				$('#id_level').val(ui.item.level.id);
                return false;
            }
        });
		$("#btn_custom_level").show();
		$("#btn_custom_level").click(function(){
			$("#levelSelect").show();
		})
		
		$("#levelSelect").change(function(){
			var checkText=$(this).find("option:selected").text();  //获取Select选择的Text
			var checkValue=$(this).val();           
			if(checkValue!==''){
				$('#lv').text(checkText); 
				$('#id_level').val(checkValue);
			}
		})
    {% endifequal %}
	
	


    $('.add-product').click(function(){
            var id=$('#product_id').val();
            var label=$('#product_label').val();
            if(id==''){
                toastr.error("请先选择产品！", "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;
            }else{
                var e=false;
                $("#sel-product option").each(function(){
                    if($(this).val() == id){
                        e=true;
                        return false;
                    }
                });
                if(e){
                    toastr.error(label+"已在列表中！", "操作错误：",
                        {timeOut: 800, positionClass: "toast-center-center"}
                    );
                    return;
                }else{
                    $('#sel-product').append("<option value='"+id+"'>"+label+"</option>");
                }
            };
    });

    
    
    //2021-09-25
    $('.add-parent').click(function(){
        var id=$('#id_parent').val();
        var label=$('#parent_label').val();
        if(id==''){
            toastr.error("请先选择所属公司(上级经销商)！", "操作错误：",
                {timeOut: 800, positionClass: "toast-center-center"}
            );
            return;
        }else{
            var e=false;
            $("#sel-parents option").each(function(){
                if($(this).val() == id){
                    e=true;
                    return false;
                }
            });
            if(e){
                toastr.error(label+"已在列表中！", "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;
            }else{
                $('#sel-parents').append("<option value='"+id+"'>"+label+" ["+$('#plv').val()+"]</option>");
            }
        };
    });



    //2020-09-04
    $('.btn-geo-agent').click(function(){
        event.preventDefault();        
        var url='/inventory/ajax/geo/agent/';
        {% if form.instance.id %}
            url=url+'{{form.instance.id}}/';
        {% endif %}
        url=url+"?adm1_id="+$("#id_province_gis_id").val()+
            "&adm2_id="+$("#id_city_gis_id").val()+
            "&adm3_id="+$("#id_county_gis_id").val();
           
        
            $.OpenUrlCfmDlg(url,"{{form.instance.name}}：","保存","取消");
    });   
    $('.btn-geo-store').click(function(){
        event.preventDefault();        
        var url='/inventory/ajax/geo/store/';
        {% if form.instance.id %}
            url=url+'{{form.instance.id}}/';
        {% endif %}
        url=url+"?adm1_id="+$("#id_province_gis_id").val()+
            "&adm2_id="+$("#id_city_gis_id").val()+
            "&adm3_id="+$("#id_county_gis_id").val();   

        $.OpenDlg(url,"经销商仓库位置：",1100,700);

    });        




    $('.add-adm').click(function(){
            var me=$(this);
            var id=$(me).parent().parent().find('select').val();
            var lv=$(this).attr('lv');
            var adm='';

            var label="";
            switch (lv){
                case '1':
                    adm='省份';
                    label=$('#province').find("option:selected").text();
                    break;
                case '2':
                    adm='城市';
                    label=$('#province').find("option:selected").text()+$('#city').find("option:selected").text();
                    break;
                case '3':
                    adm='区县';
                    label=$('#city').find("option:selected").text()+$('#county').find("option:selected").text();
                    break;   
            };           
            if(id==''){
                toastr.error("请先选择"+adm+"名称！", "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;
            }else{
                var e=false;
                $("#sel-adm option").each(function(){
                    if($(this).val() == id){
                        e=true;
                        return false;
                    }
                });
                if(e){
                    toastr.error(label+"已在列表中！", "操作错误：",
                        {timeOut: 800, positionClass: "toast-center-center"}
                    );
                    return;
                }else{
                    $('#sel-adm').append("<option value='"+id+"'>"+label+"</option>");
                }
            };
    });


    $("#province,#id_province_gis_id").change(function() {
        var sel;
        if($(this).attr('id')=='province'){
            sel=$('#city');        
        }else{
            sel=$('#id_city_gis_id');
        }        
        var province_id = $(this).val();
        getCity(province_id,sel);
    });
    $("#city,#id_city_gis_id").change(function() {
        var city_id = $(this).val();
        var sel;
        if($(this).attr('id')=='city'){
            sel=$('#county');        
        }else{
            sel=$('#id_county_gis_id');
        };        
        getCounty(city_id,sel);
    });
    function getCity(province_id,sel) {
        var me=sel;
        $.ajax({
            url: "/gis/adm/2/"+province_id+"/",
            success: function(data) {
                $(me).empty();
                $('#area').empty();
                $.each(data,function(i,d){$(me).append("<option value='"+d[0]+"'>"+d[1]+"</option>")});
                $(me).append("<option value='' selected='selected'>---------</option>");
            },
            dataType: 'jsonp',
            jsonp: 'callback'
        });
    };
    function getCounty(city_id,sel) {
        var me=sel;
        $.ajax({
            url: "/gis/adm/3/"+city_id+"/",
            success: function(data) {
                $(me).empty();
                $.each(data,function(i,d){$(me).append("<option value='"+d[0]+"'>"+d[1]+"</option>")});
                $(me).append("<option value='' selected='selected'>---------</option>");
            },
            dataType: 'jsonp',
            jsonp: 'callback'
        });
    };

    

    $('#tb_auth input[type="checkbox"]').removeClass('form-control');


    $('.select2_multiple').on('dblclick','option',function(){
            $(this).remove();
    });




    $('#obj_form .select2_multiple option').tooltip({
		title:'双击删除',
		placement:'left',
		animation:'true',
		container:'#obj_form',
		trigger:'hover'
	});

    $('#obj_form .add-parent').tooltip({
        title:'点击添加两个或以上的上级经销商',
		placement:'left',
		animation:'true',
		container:'#obj_form',
		trigger:'hover'
	});

    $('.btn-save').click(function(){
        $('.btn').hide();
        
        var a=[];
        $("#sel-product option").each(function (){ a.push($(this).val()); });
        if(a.length>0){   
            $('#id_products').val(a.join(',')); 
        }else{
            $('#id_products').val('');
        };

        var a=[];
        $("#sel-adm option").each(function (){ a.push($(this).val()); });
        if(a.length>0){ 
            $('#id_adm_ids').val(a.join(','));
        }else{
            $('#id_adm_ids').val('');
        };       
             

        //2021-09-25
        a=[];
        $("#sel-parents option").each(function (){ 
            a.push({
                "id":$(this).val(),
                "name":$(this).text()
            })
        });
        if(a.length>0){   
            $('#id_parents').val(JSON.stringify(a)); 
        }else{
            $('#id_parents').val('[]');
        }
		
		if($("#ySelectSeries")){
			var series= $("#ySelectSeries").ySelectedValues(",");
			$("#id_series_more").val(series);
		}
		
		if($("#ySelectChannelLevels")){
			var series= $("#ySelectChannelLevels").ySelectedValues(",");
			$("#id_channel_level_ids").val(series);
		}
		
	
        
        
        $.SubmitForm('#obj_form form','{{request.path}}');
    });

    //经销商可以设置其下经销商为终端店
    $('#is_terminal').change(function(){
        if($(this).prop("checked") == true){
            $('#id_level').val('3');
        }else{
            $('#id_level').val('');
        }
    });
    {% ifequal level.id 3 %}
        $('#is_terminal').prop('checked',true);
    {% endifequal %}   
   


    $('#id_division').change(function(){
        var me=$('#id_sub_division');
        var d=$(this).val();
        $('#id_sub_division').empty();
        if (d!=''){
            $.ajax({
                url: "/company/json/subdivision/"+d+"/",
                success: function(data) {
                    data=data.details;
                    $.each(data,function(i,d){$(me).append("<option value='"+d[0]+"'>"+d[1]+"</option>")});
                    $(me).append("<option value='' selected='selected'>---------</option>");
                }
            });
        }
    });


    //2020-09-14
    $('#id_province_gis_id').val(my_adm_1.id);
    if(my_adm_2.id>0){
        $('#id_city_gis_id').append("<option  value='"+my_adm_2.id+"'>"+my_adm_2.name+"</option>");
        $('#id_city_gis_id').val(my_adm_2.id);
    };    
    if(my_adm_3.id>0){
        $('#id_county_gis_id').append("<option value='"+my_adm_3.id+"'>"+my_adm_3.name+"</option>");
        $('#id_county_gis_id').val(my_adm_3.id);
    };    


    {% if jg_ty %}
        $('[name="sync_ty"]').closest('label').removeClass('active');
        {% ifequal sync_ty '1' %}
            $("#ty_yes")
                .prop('checked', true)
                .closest('label').addClass('active');
        {% else %}
            $('#ty_no')
                .prop('checked', false)
                .closest('label').addClass('active');
        {% endifequal %}
    {% endif %}
    {% if form.instance %}
        {% if form.instance.parent %}
            $('#id_parent').val({{form.instance.parent_id}});
            $('#parent_label').val('{{form.instance.parent.name}}');
        {% else %}
            $('#id_parent').val({{parent.id}});
            $('#parent_label').val('{{parent.name}}');
        {% endif %}
        {% if form.instance.id %}
            $('#plv').val('{{form.instance.parent.level.name}}');
        {% endif %}
    {% endif %}

    //2020-11-24
    $('#data-content .btn-delete').click(function(){
        $.ajax({
            url:'/obj/delete/agent/{{form.instance.id}}/',                             
            success: function(data) {
                if(data.cnt>0){  
                    toastr.success('当前经销商已删除!', '操作成功：',
                        {timeOut: 800, positionClass: "toast-center-center"}
                    );
                    $.RefreshContent("/obj/list/agent/");                   
                };
            },

        });       
    
    });     
	$('#ySelectSeries').ySelect(
          {
            placeholder: '选择系列',
            searchText: '搜索',
            showSearch: true,
            numDisplayed: 5,
            overflowText: '已选中 {n}项',
            isCheck:false
          }
    );
	
	$('#ySelectChannelLevels').ySelect(
          {
            placeholder: '选择等级',
            searchText: '搜索',
            showSearch: true,
            numDisplayed: 5,
            overflowText: '已选中 {n}项',
            isCheck:false
          }
    );


   
{% endblock %}

 
{% block subtitle-1 %}
    {% trans '经销商管理' %}
{% endblock %}
{% block subtitle-2 %}
    {% trans '经销商信息' %}
{% endblock %}   

    


{% block form_content %}
    {{ block.super }}

    
    <div class="form-group ">
        <label class="col-sm-2 control-label ">{% trans '经销商名称:' %} </label>
        <div class="col-sm-10">{{ form.name }}</div>
    </div>
    
    {% if request.user.company.is_microboss %}
    {% else %}
        {% ifequal request.user.company.level.sn 0 %}            
             {% if user.company.cfg_company.multi_parents %}
                <div class="form-group" style='margin-bottom:0;'>
                    <label class="col-sm-2 control-label ">{% trans '所属公司(上级经销商):' %} </label>
                    <div class="col-sm-10">
                        <div class="input-group" style='margin-bottom:0;'>
                            <input id="parent_label">
                            <span class="input-group-btn"><button  type="button" class="btn btn-success add-parent">
                                <span class='glyphicon glyphicon-arrow-down'></span>
                            </button></span>
                        </div>
                    </div>
                </div>
                <div class='col-sm-10 col-md-offset-2' style='margin-bottom:10px;'>
                    <select class="select2_multiple form-control" id="sel-parents" multiple="multiple" style='margin-top:0px;'>
                        {% for o in form.instance.parents %}
                            <option value='{{o.id}}'>{{o.name}}</option>
                        {% endfor %}
                    </select>
                </div>   
             {% else %}        
                <div class="form-group ">
                    <label class="col-sm-2 control-label ">{% trans '所属公司(上级经销商):' %} </label>
                    <div class="col-sm-10"><input id="parent_label"></div>
                </div>
            {% endif %}

            {% if parent.has_external_code %}
                <div class="form-group ">
                    <label class="col-sm-2 control-label ">{% trans '外部编码:' %}</label>
                    <div class="col-sm-4">{{ form.external_code }}</div>       
                    <label class="col-sm-2 control-label ">{% trans '客户状态:' %}</label>
                    <div class="col-sm-4">{{ form.status }}</div>
                </div> 
            {% endif %}


            <div class="form-group ">
                <label class="col-sm-2 control-label ">{% trans '经销商层级:' %} </label>
                <div class="col-sm-2 control-label">
                    <span id='lv' class="pull-left">
                    {% if form.instance.id %}
                        {{ form.instance.level.name }}
                    {% else %}   
                        {{parent.child_level.name}}
                    {% endif %}
					</span>
					<input id='plv' type='hidden' value='公司'/>
					<a id="btn_custom_level" style="display:none;margin-left:5px;text-decoration: underline;cursor: pointer;">自定义层级</a>
					<select id="levelSelect" style="display:none">
						<option value="">请选择</option>
						<option value="2">一级</option>
						<option value="4">二级</option>
						<option value="5">三级</option>
						<option value="6">四级</option>
					</select>
				
				</div>
                <label class="col-sm-2 control-label ">{% trans '所属战区:' %} </label>
                <div class="col-sm-2">{{ form.division }}</div>

                <label class="col-sm-2 control-label ">{% trans '所属分区:' %} </label>
                <div class="col-sm-2">{{ form.sub_division }}</div>
            </div>
			
        {% else %}
            <div class="form-group ">
                <label class="col-sm-2 control-label ">{% trans '经销商层级:' %} </label>
                <div class="col-sm-10">
                    <label class="form-inline">
                        <input style='margin-top:-3px;margin-right:5px;' type="checkbox" id="is_terminal"/>
                        {% trans '此经销商为销售终端店' %}
                    </label>
                    <!--
                    <input type="hidden" name="level" id="id_level"  />
                    -->
                </div>
            </div>
        {% endifequal %}     
    
    {% endif %}


    
    <!--2020-09-14-->
    <div class="form-group ">
        <label class="col-md-2 control-label ">{% trans '省份:' %}</label>  
        <div class='col-md-2'>
            {{form.province_gis_id}}
        </div>
        <label class="col-md-2 control-label">{% trans '城市:' %}</label>  
        <div class='col-md-2'>    
            {{form.city_gis_id}}
        </div>   
        <label class="col-md-2 control-label">{% trans '区县:' %}</label>  
        <div class='col-md-2'>    
            {{form.county_gis_id}}
        </div>   
            
    </div>

    <div class="form-group ">
        <label class="col-sm-2 control-label">{% trans '联系人电话:' %}</label>
        <div class="col-sm-2">{{ form.cell_phone }} </div>
        <label class="col-sm-2 control-label">{% trans '联系人姓名:' %}</label>
        <div class="col-sm-2">{{ form.contacts }} </div>
        <label class="col-sm-2 control-label">{% trans '是否为终端店:' %}</label>
        <div class="col-sm-2">{{ form.is_terminal }} </div>
		
    </div>

    {% ifequal request.user.company.id 19651 %}
            <label class="col-sm-2 control-label">金牌客户</label>
            <div class='col-sm-2'>{{ form.is_golden}}</div>
        {% else %}
            <label class="col-sm-2 control-label"></label>
        {% endifequal %}


	<div class="form-group">
        <label class="col-sm-2 control-label"></label>
		<div class='col-sm-8'>
            <div class='col-sm-4'>
                <label>{% trans '是否为公司派出机构' %}</label>
                {{ form.is_expense_account}}
            </div>
            <div class='col-sm-4'>
                <label>{% trans '是否专卖店' %}</label>
                {{ form.is_franchised}}
            </div> 
        </div>  
	</div>



    <div class="form-group ">
        <label class="col-sm-2 control-label">{% trans '渠道:' %}</label>
        <div class="col-sm-2">{{ form.channel }} </div>
        <label class="col-sm-2 control-label">{% trans '等级:' %}</label>
        <div class="col-sm-4"> 
                <select id="ySelectChannelLevels" multiple="multiple">
                    {% for s in channel_levels %}
						{% ifequal s.2 1 %}
							<option value='{{s.0}}' selected="selected">{{s.1}}</option>
						{% else %}
							<option value='{{s.0}}'>{{s.1}}</option>
						{% endifequal %}
                    {% endfor %}
                </select>
		</div>
    </div>
    
    <!--
    <div class="form-group ">
        <label class="col-sm-2 control-label">{% trans '是否为终端店:' %}</label>
        <div class="col-sm-1">
            {{form.is_terminal}}
        </div>
    </div>
    -->

    <div class="form-group ">
        <label class="col-sm-2 control-label">{% trans '经销商地址:' %}</label>
        <div class="col-sm-10">{{ form.address }} </div>
    </div>


    



    <div class="form-group " style="margin-bottom:0">
        {% ifequal user.company.cfg_company.auth_product 1 %}
            <label class="col-sm-2 control-label">产品经销授权</label>
            <div class='col-sm-4'>
                <div class="input-group" style="margin-bottom:0">
                    <input  class=' form-control' id="product_label" placeholder='所有产品'/>
                    <input type="hidden" id="product_id" />
                    <span class="input-group-btn"><button type="button" class="btn btn-success add-product">
                        <span class='glyphicon glyphicon-arrow-down'></span></button></span>
                </div>
            </div>
        {% endifequal %}
        {% ifequal user.company.cfg_company.auth_area 1 %}
            <label class="col-md-2 control-label">区域经销授权</label>
            <div class='col-md-4'>
                <div class="input-group" style="margin-bottom:0">
                    <select id="province"  lv="1" class="form-control adm">
                    {% for p in prs %}
                        <option value="{{p.0}}">{{p.1}}</option>
                    {% endfor %}
                    <option value="" selected="selected">所有区域</option>
                </select>
                <span class="input-group-btn"><button lv="1" type="button" class="btn  btn-success add-adm">
                        <span class='glyphicon glyphicon-arrow-down'></span></button></span>
                </div>
            </div>
            <div class='col-md-3'>
                <div class="input-group" style="margin-bottom:0">
                    <select id="city"  lv="2" class="form-control adm">
                        <option value="" selected="selected">---------</option>
                    </select>
                    <span class="input-group-btn"><button lv="2"  type="button" class="btn btn-success add-adm">
                        <span class='glyphicon glyphicon-arrow-down'></span></button></span>
                </div>
            </div>
            <div class='col-md-3'>
                <div class="input-group" style="margin-bottom:0">
                    <select id="county"  lv="3" class="form-control adm">
                        <option value="" selected="selected">---------</option>
                    </select>
                    <span class="input-group-btn"><button  lv="3" type="button" class="btn btn-success add-adm">
                        <span class='glyphicon glyphicon-arrow-down'></span></button></span>
                </div>
            </div>
        {% endifequal %}
    </div>

    <div class="form-group" >
        {% ifequal user.company.cfg_company.auth_product 1 %}
            <div class='col-sm-4 col-md-offset-2'>
                <select class="select2_multiple form-control" id="sel-product" multiple="multiple">
                    {% for o in products %}
                        <option value='{{o.0}}'>{{o.1}}</option>
                    {% endfor %}
                </select>
            </div>
        {% endifequal %}

        {% ifequal user.company.cfg_company.auth_area 1 %}
            <div class='col-sm-10 col-md-offset-2'>
                <select class="select2_multiple form-control" id="sel-adm" multiple="multiple">
                    {% for o in adms %}
                        <option value='{{o.0}}'>{{o.1}}</option>
                    {% endfor %}
                </select>
            </div>
        {% endifequal %}
    </div>


	<div class="form-group">
            <label class="col-md-2 control-label">产品系列授权</label>
			<div class='col-sm-4'>
                <select id="ySelectSeries" multiple="multiple">
                    {% for s in series %}
						{% ifequal s.2 1 %}
							<option value='{{s.0}}' selected="selected">{{s.1}}</option>
						{% else %}
							<option value='{{s.0}}'>{{s.1}}</option>
						{% endifequal %}
                    {% endfor %}
                </select>
            </div>
			
	</div>


    <div  style="margin-top:20px;">
        {% if form.instance.id %}
            <a class="btn btn-danger btn-delete" type="button"  >{% trans '删除' %}</a>
        {% endif %}
       
        <a type="button" class='btn btn-primary btn-geo-agent'>
            <span class='glyphicon glyphicon-map-marker'  style='padding-right:5px;float:right;'></span>{% trans '定位' %}
        </a>
            
        <a type="button" class='btn btn-primary btn-save' style="float:right;">
            <span class='glyphicon glyphicon-floppy-disk' style='padding-right:5px;'></span>{% trans '保存' %}
        </a>
    </div>    

{% endblock %}


