<template>
  <div>
    <Input
      :readonly="readonly"
      :placeholder="placeholder"
      :disabled="disabled"
      v-model="model"
    >
      <slot slot="prepend" name="prepend"></slot>
      <a href="javascript:;" slot="append" @click="onShowMap">
        <Icon type="md-locate" />
      </a>
    </Input>
    <position
      :position="position || defaultPosition"
      :city="defaultCity"
      @on-select="onSelect"
      :polygons="polygons"
      :show.sync="showMap"
    ></position>
  </div>
</template>
<script>
import position from "../position";
import emitter from "../mixins/emitter";
import { wgs84togcj02, gcj02towgs84 } from "../common/proj";
export default {
  components: { position },
  mixins: [emitter],
  props: {
    placeholder: {
      type: String
    },
    value: {
      type: String
    },
    defaultPosition: {
      type: String
    },
    defaultCity: {
      type: String
    },
    readonly: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    proj: {
      type: String,
      default: null
    },
    polygons: {
      type: Array,
      default: () => []
    }
  },
  name: "f-position-input",
  watch: {
    value(v) {
      this.model = this.value;
      this.position = this.model;
    },
    model() {
      this.$emit("input", this.model);
      this.position = this.model;
      this.dispatch("FormItem", "on-form-change", this.model);
    }
  },
  data() {
    return {
      model: this.value,
      position: this.value,
      showMap: false
    };
  },
  methods: {
    onSelect(pos) {
      this.model = pos.lnglat;
      this.$emit("on-select", pos);
      this.$emit("input", this.model);
    },
    onShowMap() {
      this.position = this.model;
      if ((this.proj == "wgs84" || this.proj == "gps") && this.model) {
        const ll = this.model.split(",").map(p => parseFloat(p));
        const r = wgs84togcj02(ll[0], ll[1]);
        this.position = r.join(",");
      }
      this.showMap = true;
    }
  }
};
</script>

<style scoped></style>
