<template>
  <div>
    <div class="editor">
      <PageEditorTiny ref="tiny" :id="id"/>
    </div>
    <div class="alert alert-secondary my-3">
      <div class="mb-1">
        页面背景色:
      </div>
      <div>
        <input class="color" type="color" v-model="options.page_bg_color" />
      </div>
    </div>
    <button class="btn btn-primary btn-sm" :disabled="saving" @click="save">保存</button>
    <button class="btn btn-secondary btn-sm mx-1" @click="$router.go(-1)">返回</button>
    <div class="alerts">
      <CAlert v-if="saving" color="info">正在保存</CAlert>
      <CAlert v-if="saved" color="success">已保存</CAlert>
      <CAlert v-if="save_failed" color="danger">保存失败</CAlert>
    </div>
    <Modal ref="overwrite_modal">
      确定要用模板内容覆盖现有数据吗？
    </Modal>
  </div>
</template>

<script>
import PageEditorTiny from './page-editor-tiny'

export default {
  name: 'PageEditor',
  props: ['uri', 'id', 'fieldname'],
  components: {
    PageEditorTiny,
  },
  data: function () {
    return {
      data: '',
      options: {},
      saving: false,
      saved: false,
      save_failed: false,
      use_tiny: localStorage.getItem("preferred_editor") == 'tiny',
    };
  },
  computed: {
    editor: function() {
      return this.$refs.tiny;
    },
  },
  methods: {
    reload: async function() {
      var r = await this.$root.api_get(this.uri);
      this.data = r.data[this.fieldname];
      this.editor.set_data(this.data);
      if (r.data.options) {
        try {
          this.options = JSON.parse(r.data.options);
        } catch {
          this.options = {};
        }
      }
      if (!this.options.page_bg_color) {
        this.options.page_bg_color = '#ffffff';
      }
    },
    save: function() {
      this.do_save(this.editor.get_data());
    },
    do_save: async function(html) {
      var k = this.fieldname;
      var data = {};
      data[k] = html;
      data.options = JSON.stringify(this.options);
      this.saving = true;
      this.save_failed = false;
      this.saved = false;
      try {
        await this.$root.api_patch(this.uri, data);
        this.saved = true;
      } catch (e) {
        this.save_failed = true;
      } finally {
        this.saving = false;
      }
    },
  },
  mounted() {
    this.reload();
  },
}
</script>

<style scoped>
div.editor {
  max-width: 500px;
}
div.alerts {
  max-width: 500px;
  margin: 1rem 0;
}
input.color {
  height: 4rem;
  width: 4rem;
}
</style>

