{% load i18n common %}
<style>
  .pac-container {
    z-index: 1100 !important;
  }
</style>
<div style="padding-top: 5px;height: 490px;width: 900px;overflow: hidden;">
  <form class="layui-form action-form" action="" method="post" id="{{ model_name }}_{{ action_repr }}"
        enctype="multipart/form-data">
    {% csrf_token %}
    <div class="layui-row">
      <div class="layui-col-md5">

    {% with form.form as f %}
      <div class="layui-form-item" style="margin-bottom:-3px;">
          {% layui_inline f.client_id %}
          {% layui_inline f.company_name %}
      </div>
      <div class="layui-form-item" style="margin-bottom: -3px;">
          {% layui_inline f.branch %}
          {% layui_inline f.address %}
      </div>
      <div class="layui-form-item" style="margin-bottom:-3px;">
          {% layui_inline f.contact_person %}
          {% layui_inline f.mobile  %}
      </div>
      <div class="layui-form-item" style="margin-bottom: -3px;">
          {% layui_inline f.latitude %}
          {% layui_inline f.longitude %}
      </div>

      <div class="layui-form-item" style="margin-bottom: -3px;">
          <div style="display:none">
          {% layui_inline f.distance %}
          </div>
          {% layui_inline f.punch_location_radius %}
       </div>
      <div class="layui-form-item" style="margin-bottom:-3px;">
            <label for="" class="layui-form-label">{% trans 'client_company_logo' %}</label>
            <div class="layui-upload-drag" id="logo" style="width: 190px;height: 85px;padding: 1px;" title="{% trans 'client_title_clickToUploadLogo' %}">
                <img id="reviewLogoPhoto" src=" " style="width: 180px;height: 80px;" alt="Browse">
            </div>
              <div class="layui-form-item" style="margin-bottom:-3px;">
                <div class="layui-input-block layui-form-mid layui-word-aux">{% trans 'Only Supports .jpg and .png format' %}</div>
              </div>
            </div>


        </div>
        <div class="layui-col-md7" >

      <table>
        <tbody>
        <tr>
          <td style="vertical-align:top">
            <div class=layui-form-item">
              <div class="layui-inline" style="padding: 10px">
                <label for="id_search_map" style="margin: 0; width: 80px; font-weight: normal;">Search Map</label>
                <div class="layui-input-inline">
                  <input type="text" name="search_map" class="layui-input" id="id_search_map" autocomplete="on"
                         style="width: 340px; max-width: 340px">
                </div>
                <div class="layui-inline"><i onclick="formatAddress()" class="fa fa-fw fa-search"></i></div>
              </div>
            </div>
            <div id="map-canvas" style="height: 270px;width: 460px;"></div>
            <div style="padding-top:5px;">
              <div id="gps_add" style="width: 400px"></div>
              <br>
              <span id="gps_pos"></span>
            </div>
          </td>
        </tr>
        </tbody>
      </table>
        </div>
        </div>
    {% endwith %}
  </form>
</div>
<script>

  var circle, map, marker, zoomUpdate, mapDistance;
  var tmp_google, tmp_circle, tmp_map, tmp_marker, tmp_zoomUpdate, tmp_mapDistance;
  var initLat = '12.9891657',
      initLon = '77.6885258',
      check_submit = 0,
      noPos = false;

  function checkSubmit() {
    if (check_submit) {
      check_submit = 0;
      circle = tmp_circle;
      google = tmp_google;
      map = tmp_map;
      marker = tmp_marker;
      zoomUpdate = tmp_zoomUpdate;
      mapDistance = tmp_zoomUpdate
    }
  }

  function initData() {
    var autocomplete = new google.maps.places.Autocomplete(document.getElementById('id_search_map'));
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
      var place = autocomplete.getPlace();
      zoomUpdate = 18;
      if (place !== undefined) {
        if (place.formatted_address === undefined) {
          formatAddress();
        } else {
          showInMap(place.geometry.location);
        }
      } else {
        showInMap(new google.maps.LatLng(initLat, initLon), true);
      }
    });
    initMap();
  }

  function formatAddress() {
    var geocoder = new google.maps.Geocoder();
    var address = document.getElementById('id_search_map').value;
    geocoder.geocode({'address': address}, function (results, status) {
      if (status === 'OK') {
        geometryLocation = results[0].geometry.location;
        geometryAddress = results[0].formatted_address;
        if (typeof (map) == "undefined") {
          map = new google.maps.Map(document.getElementById("map-canvas"), {center: geometryLocation, zoom: 6});
          marker = new google.maps.Marker({
            position: geometryLocation,
            map: map,
            draggable: true
          });

          google.maps.event.addListener(marker, 'dragend', function () {
            checkSubmit();
          });
        } else {
          map.setOptions({center: geometryLocation, zoom: map.getZoom()});
          marker.setPosition(geometryLocation);
        }
        geocodePosition(marker.getPosition());
      }
      else{
        layer.alert(gettext('invalid_location'), {title: gettext("layer_title"), icon: 5, btn: gettext("btn_confirm")});
      }
    });
  }

  function showInMap(pos, noPos) {
    checkSubmit();
    if (typeof (map) == "undefined") {
      var mapOption = {
        center: pos,
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      if (noPos) {
        mapOption['zoom'] = 5;
        zoomUpdate = 5
      } else {
        zoomUpdate = 18
      }

      map = new google.maps.Map(document.getElementById("map-canvas"), mapOption);
      marker = new google.maps.Marker({
        position: pos,
        map: map,
        draggable: true
      });
      marker.addListener('click', function () {
        map.setZoom(zoomUpdate);
        map.setCenter(marker.getPosition());
      });

      google.maps.event.addListener(marker, 'dragend', function () {
        checkSubmit();
        geocodePosition(marker.getPosition());
      });
    } else {
      map.setOptions({center: pos, zoom: 12});
      marker.setPosition(pos);
    }
    geocodePosition(marker.getPosition(), noPos);
  }

  function geocodePosition(pos, noPos) { // noPos means first time to add
    geocoder = new google.maps.Geocoder();
    geocoder.geocode
    ({latLng: pos}, function (responses) {
      if (responses && responses.length > 0) {
        geometryLocation = pos;
        geometryAddress = responses[0].formatted_address;
        document.getElementById('gps_add').innerText = geometryAddress;
        $('#id_address').val(geometryAddress);
        if (!noPos) {
          document.getElementById('id_latitude').value = pos.lat();
          document.getElementById('id_longitude').value = pos.lng()
        }
      }
      if (!(circle === undefined)) {
        circle.setOptions({center: pos, radius: parseFloat(mapDistance)});
      } else {
        circle = new google.maps.Circle({
          strokeColor: "#7ac143",
          strokeOpacity: 0.8,
          strokeWeight: 1.5,
          fillColor: "#7ac143",
          fillOpacity: 0.35,
          map: map,
          center: pos,
          radius: parseFloat(mapDistance)
        })
      }
    });
  }

  function updateDistannce() {
    circle.setOptions({center: marker.getPosition(), radius: parseFloat(mapDistance)});
  }

  function initMap() {
    mapDistance = document.getElementById('id_punch_location_radius').value;
    if (!mapDistance || isNaN(mapDistance)) {
      mapDistance = 0
    }
    var tempLat = document.getElementById('id_latitude').value;
    var tempLon = document.getElementById('id_longitude').value;
    if (tempLat === '' || tempLon === '') {
      showInMap(new google.maps.LatLng(initLat, initLon), true);
    } else {
      showInMap(new google.maps.LatLng(tempLat, tempLon));
    }
  }

  layui.use(['form','upload'], function () {
    var form = layui.form;
    upload = layui.upload;
    form.render();
    upload.render({
          elem: "#logo"
          //,url: ''
          ,auto: false
          ,field: "logo"
          ,exts: "jpg|png"
          ,choose: function(obj){
            obj.preview(function(index, file, result){
              $('#reviewLogoPhoto').attr('src', result); //图片链接（base64）
            });
          }
          ,error: function(index, upload){

          }
      });
    $(function () {
      $.getScript("https://maps.googleapis.com/maps/api/js?key={% MAPS_API_KEY %}&v=3.31&libraries=places", function () {
        initData()
      });
      $('#id_punch_location_radius').on("input", function () {
        //change distance need change circle also.
        if (!isNaN(this.value)) {
          mapDistance = this.value
        } else {
          mapDistance = 0
        }
        updateDistannce()
      });
      $('#id_punch_location_radius').change(function () {
        var distance = $('#id_punch_location_radius').val();
        if (distance < 0) {
          layer.alert(gettext('gps_distance_invalid'), {
            title: gettext('system_exception')
            , icon: 5
            , btn: gettext('btn_confirm')
          })
        }
      });
    });

    $(".layui-layer-btn0, .layui-layer-close1, .layui-layer-btn1").click(function () {
      if (google !== undefined) {
        check_submit = 1;
        tmp_google = google;
        tmp_circle = circle;
        tmp_map = map;
        tmp_marker = marker;
        tmp_zoomUpdate = zoomUpdate;
        tmp_mapDistance = mapDistance;
        google = circle = map = marker = zoomUpdate = mapDistance = undefined;
      }
    });
  });
</script>
