<template>
  <div class="row">
    <div class="col icon">
      <div class="icon-and-text">
        <div>
          <img class="link-icon" :src="new_icon || item.url" @click="change_icon"/>
        </div>
        <div>
          {{ new_text }}
        </div>
      </div>
    </div>
    <div class="col">
      <label>文字:</label>
      <input class="form-control mb-2" type="text" v-model="new_text" />
      <label>链接:</label>
      <input class="form-control mb-2" type="text" v-model="new_link" />
      <button :disabled="!updated" class="btn btn-secondary my-2" @click="save">更新</button>
    </div>
    <Modal title="选择图标" ref="icon_modal">
      <div class="select-img">
        <img v-for="(x, i) in iconset" :key="i" :src="x.url"
          :class="{active: x.url == selected_icon_url}"
          @click="selected_icon_url = x.url"/>
      </div>
    </Modal>
  </div>
</template>

<script>
export default {
  name: 'IconControl',
  props: ['item'],
  components: {
  },
  data: function () {
    return {
      new_icon: null,
      selected_icon_url: null,
      new_text: '',
      new_link: '',
    };
  },
  computed: {
    updated: function() {
      var ip = this.item.properties;
      return this.new_icon || this.new_text != ip.text || this.new_link != ip.link;
    },
    iconset: function() {
      var ret = [];
      for (var i = 1; i <= 60; i++) {
        var n = 1000 + i;
        ret.push({
          url: window.origin + '/icons/' + n + '.png',
        });
      }
      return ret;
    },
  },
  methods: {
    change_icon: function() {
      this.$refs.icon_modal.show((ok) => {
        if (ok) {
          this.new_icon = this.selected_icon_url;
        }
      });
    },
    save: async function() {
      var properties = {
        type: 'icon',
        position: this.item.properties.position,
        link: this.new_link,
        text: this.new_text,
      };
      var data = {
        url: this.new_icon || this.item.url,
        properties: JSON.stringify(properties),
        usage: 'mini-program-content',
      };
      if (this.item.id) {
        await this.$root.api_patch('/api/v1/asset-file/' + this.item.id + '/', data);
      } else {
        await this.$root.api_post('/api/v1/asset-file/', data);
      }
      this.$emit('updated');
    },
  },
  mounted() {
    this.new_link = this.item.properties.link;
    this.new_text = this.item.properties.text;
  },
}
</script>

<style scoped>
img.link-icon {
  width: 64px;
  height: 64px;
  cursor: pointer;
}
div.select-img img {
  margin: 4px;
}

div.select-img img.active {
  background-color: yellow;
  border: 2px inset green;
  margin: 2px;
}
.icon-and-text {
  margin: 2rem 0;
  width: 64px;
  text-align: center;
}
div.icon {
  min-width: 80px;
  max-width: 80px;
}
</style>

