<template>
  <div class="pt-editor">
    <Row :gutter="10">
      <Col :span="8">
        <div class="pt-editor__panel">
          <div
            v-if="pdfFile"
            class="pt-editor__controls"
          >
            <h3 class="pt-editor__title">
              {{ $t('PDF_PRINT_CONFIG.CREATE_NEW') }}
            </h3>

            <div class="pt-editor__group">
              <div class="pt-editor__field">
                <Input
                  v-model="configName"
                  :placeholder="$t('PDF_PRINT_CONFIG.ENTER_CONFIG_NAME')"
                />
              </div>
              <div class="pt-editor__block">
                <h3 class="pt-editor__group-title">
                  <span>{{ $t('PDF_PRINT_CONFIG.ADD_TEXT') }}</span>
                  <span class="pt-editor__group-switch">
                    <i-switch
                      v-model="configPayload.text.active"
                    />
                  </span>
                </h3>

                <Input
                  v-model="configPayload.text.content"
                  :placeholder="$t('PDF_PRINT_CONFIG.ENTER_TEXT')"
                />
                <div class="pt-editor__positions">
                  <Row :gutter="5">
                    <Col :span="24">
                      <div class="pt-editor__position">
                        <span class="pt-editor__label">{{ $t('PDF_PRINT_CONFIG.POSITION') }}:</span>
                        <Select
                          v-model="configPayload.text.position"
                          class="w-200"
                        >
                          <Option
                            v-for="option in positionOptions"
                            :key="option.value"
                            :value="option.value"
                          >
                            {{ option.emoji }} {{ $t(`PDF_PRINT_CONFIG.${option.label}`) }}
                          </Option>
                        </Select>
                      </div>
                    </Col>
                    <Col
                      :span="24"
                      class="mt-10"
                    >
                      <div class="pt-editor__position">
                        <span class="pt-editor__label">{{ $t('PDF_PRINT_CONFIG.FONT_SIZE') }}:</span>
                        <InputNumber
                          v-model="configPayload.text.fontSize"
                          class="w-200"
                        />
                      </div>
                    </Col>
                  </Row>
                  <div v-if="configPayload.text.position === 'custom'">
                    <Row :gutter="5">
                      <Col :span="12">
                        <div class="pt-editor__position">
                          <span class="pt-editor__label">{{ $t('PDF_PRINT_CONFIG.POSITION_X') }}:</span>
                          <InputNumber
                            v-model="configPayload.text.x"
                            :min="0"
                            :max="1000"
                          />
                        </div>
                      </Col>
                      <Col :span="12">
                        <div class="pt-editor__position">
                          <span class="pt-editor__label">{{ $t('PDF_PRINT_CONFIG.POSITION_Y') }}:</span>
                          <InputNumber
                            v-model="configPayload.text.y"
                            :min="0"
                            :max="1000"
                          />
                        </div>
                      </Col>
                    </Row>
                  </div>
                </div>
              </div>
              <div class="pt-editor__block">
                <h3 class="pt-editor__group-title">
                  <span>{{ $t('PDF_PRINT_CONFIG.ADD_IMAGE') }}</span>
                  <a
                    :href="openImageUrl"
                    target="_blank"
                    class="pt-editor__group-link"
                  >
                    <small>{{ $t('PDF_PRINT_CONFIG.OPEN_IMAGE_EXAMPLE') }}</small>
                  </a>
                  <span class="pt-editor__group-switch">
                    <i-switch
                      v-model="configPayload.image.active"
                    />
                  </span>
                </h3>

                <Row>
                  <Col
                    :span="24"
                    class="mb-10"
                  >
                    <Upload
                      action=""
                      accept="image/png,image/jpeg,image/jpg"
                      :before-upload="handleImageUpload"
                      :show-upload-list="false"
                    >
                      <Button icon="ios-image-outline">
                        {{ $t('PDF_PRINT_CONFIG.SELECT_IMAGE') }}
                      </Button>
                    </Upload>
                  </Col>
                  <Col
                    :span="24"
                  >
                    <div class="pt-editor__position">
                      <Select
                        v-model="configPayload.image.position"
                        class="w-200"
                      >
                        <Option
                          v-for="option in positionOptions"
                          :key="option.value"
                          :value="option.value"
                        >
                          {{ option.emoji }} {{ $t(`PDF_PRINT_CONFIG.${option.label}`) }}
                        </Option>
                      </Select>
                    </div>
                  </Col>
                </Row>
                <div
                  v-if="imagePreviewUrl"
                  class="pt-editor__image-preview"
                >
                  <img
                    :src="imagePreviewUrl"
                    alt="Preview"
                  >
                </div>
                <div class="pt-editor__positions">
                  <template v-if="configPayload.image.position === 'custom'">
                    <Row :gutter="5">
                      <Col :span="12">
                        <div class="pt-editor__position">
                          <span class="pt-editor__label">{{ $t('PDF_PRINT_CONFIG.POSITION_X') }}:</span>
                          <InputNumber
                            v-model="configPayload.image.x"
                            :min="0"
                            :max="1000"
                          />
                        </div>
                      </Col>
                      <Col :span="12">
                        <div class="pt-editor__position">
                          <span class="pt-editor__label">{{ $t('PDF_PRINT_CONFIG.POSITION_Y') }}:</span>
                          <InputNumber
                            v-model="configPayload.image.y"
                            :min="0"
                            :max="1000"
                          />
                        </div>
                      </Col>
                    </Row>
                  </template>
                  <Row :gutter="5">
                    <Col :span="12">
                      <div class="pt-editor__position">
                        <span class="pt-editor__label">{{ $t('PDF_PRINT_CONFIG.IMAGE_WIDTH') }}:</span>
                        <InputNumber
                          v-model="configPayload.image.width"
                          :min="10"
                          :max="1000"
                        />
                      </div>
                    </Col>
                    <Col :span="12">
                      <div class="pt-editor__position">
                        <span class="pt-editor__label">{{ $t('PDF_PRINT_CONFIG.IMAGE_HEIGHT') }}:</span>
                        <InputNumber
                          v-model="configPayload.image.height"
                          :min="10"
                          :max="1000"
                        />
                      </div>
                    </Col>
                  </Row>
                </div>

                <div class="pt-editor__actions">
                  <Row :gutter="10">
                    <Col :span="8 ">
                      <Button
                        type="info"
                        :disabled="btnDisabled"
                        @click="addContentToAllPages"
                      >
                        {{ $t('PDF_PRINT_CONFIG.PREVIEW') }}
                      </Button>
                    </Col>
                    <Col :span="16">
                      <Button
                        type="primary"
                        icon="md-save"
                        :disabled="!configName || btnDisabled"
                        @click="saveConfig"
                      >
                        {{ $t('PDF_PRINT_CONFIG.SAVE_CONFIG') }}
                      </Button>
                    </Col>
                  </Row>
                </div>
              </div>
            </div>
            <div
              v-if="listConfig.length && pdfFile"
              class="pt-editor__saved"
            >
              <h3 class="pt-editor__title">
                {{ $t('PDF_PRINT_CONFIG.SAVED_CONFIGS') }}
              </h3>

              <div
                class="pt-editor__saved-list"
              >
                <div
                  v-for="item in listConfig"
                  :key="item._id"
                  class="pt-editor__saved-item"
                >
                  <span class="pt-editor__saved-name">{{ item.name }}</span>
                  <div class="pt-editor__saved-actions">
                    <Button
                      type="primary"
                      size="small"
                      icon="md-play"
                      @click="previewConfig(item)"
                    />
                    <Button
                      type="error"
                      size="small"
                      icon="md-trash"
                      @click="deleteConfig(item)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </Col>
      <Col :span="16">
        <div
          v-if="pdfPreviewUrl"
          class="pt-editor__preview"
        >
          <h3 class="pt-editor__title">
            {{ $t('PDF_PRINT_CONFIG.PREVIEW') }}
          </h3>
          <iframe
            :src="pdfPreviewUrl"
            width="100%"
            height="800"
            frameborder="0"
          />

          <div class="pt-editor__preview-footer">
            <Row>
              <Col :span="12">
                <Select
                  v-model="selectedPlatform"
                  :placeholder="$t('SELECT_PLATFORM.PLACEHOLDER')"
                  class="w-100"
                  @on-change="loadSamplePdf"
                >
                  <Option
                    v-for="item in getListPlatform"
                    :key="item.value"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </Option>
                </Select>
              </Col>
              <Col
                :span="12"
                class="row-end"
              >
                <Upload
                  action=""
                  accept=".pdf"
                  :before-upload="handleFileUpload"
                  :show-upload-list="false"
                >
                  <Button icon="ios-cloud-upload-outline">
                    {{ $t('PDF_PRINT_CONFIG.SELECT_PDF') }}
                  </Button>
                </Upload>
              </Col>
            </Row>
          </div>
        </div>
      </Col>
    </Row>
  </div>
</template>

<script>
import { PdfService } from '@/lib/pdf/service';
import { ConfigPdfPrinter } from '@/models/config';
import { usePrinterStore } from '@/vue/pinia/printer';
import { loggerVue } from '@/plugins/logger';

const printerStore = usePrinterStore();

export default {
  name: 'PdfPrinterConfig',
  data() {
    /** @type {PrintPdfConfigOverlay} */
    const configPayload = {
      text: {
        active: true,
        content: '',
        position: 'top-center',
        x: 100,
        y: 100,
        fontSize: 20,
        isBold: true,
      },
      image: {
        active: true,
        data: null,
        base64: '',
        position: 'bottom-center',
        x: 100,
        y: 100,
        width: 180,
        height: 50,
      },
    };

    /** @type {PrintPdfConfigList[]} */
    const listConfig = [];

    const pdfService = new PdfService();

    const openImageUrl = 'https://drive.google.com/drive/u/0/folders/1btOrjBYtfLblWo6_5IpttwYmKn69edqI';

    return {
      pdfService,
      pdfFile: null,
      pdfBytes: null,
      pdfPreviewUrl: '',
      imagePreviewUrl: '',
      selectedPlatform: 'shopee',
      configName: '',
      configPayload,
      listConfig,
      positionOptions: printerStore.listPosition,
      openImageUrl,
    };
  },
  methods: {
    async handleFileUpload(file) {
      if (!file) {
        return false;
      }
      await this.pdfService.loadPdfFromFile(file);

      this.pdfFile = this.pdfService.getPdfFile();
      this.pdfBytes = this.pdfService.getPdfBytes();
      this.updatePdfPreview();
    },
    async handleImageUpload(file) {
      if (!file) {
        return false;
      }

      this.configPayload.image.data = file;
      this.configPayload.image.base64 = await this.fileToBase64(file);

      this.imagePreviewUrl = URL.createObjectURL(file);
    },
    updatePdfPreview() {
      this.pdfPreviewUrl = this.pdfService.getPdfPreviewUrl(this.pdfBytes);
    },
    async addContentToAllPages() {
      try {
        this.pdfBytes = await this.pdfService.addConfigContent(this.configPayload);

        this.updatePdfPreview();
      } catch (error) {
        loggerVue.error({
          msg: 'PDF_PREVIEW_CONFIG_ERROR',
          error,
        });

        this.$Message.error(this.$t('PDF_PRINT_CONFIG.CONTENT_ADDED_ERROR'));
      }
    },
    async loadSamplePdf(platform) {
      try {
        await this.pdfService.loadPdfFromUrl(`/platform/${platform}/order.pdf`);

        this.pdfFile = this.pdfService.getPdfFile();
        this.pdfBytes = this.pdfService.getPdfBytes();
        this.updatePdfPreview();
      } catch (error) {
        this.$Message.error(this.$t('PDF_PRINT_CONFIG.SAMPLE_LOADED_ERROR'));
      }
    },
    loadExampleConfig() {
      const imageUrl = '/example/pdf_sign.png';
      fetch(imageUrl)
        .then((res) => res.blob())
        .then((blob) => {
          const file = new File([blob], 'pdf_sign.png', { type: blob.type });
          this.handleImageUpload(file);
        }).catch((error) => {
          loggerVue.error({
            msg: 'PDF_LOAD_EXAMPLE_IMAGE_ERROR',
            error,
          });
        });
    },
    fileToBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
      });
    },
    async loadSavedConfigs() {
      this.listConfig = await ConfigPdfPrinter.findAll();
    },
    async saveConfig() {
      try {
        const payloadConfig = {
          name: this.configName,
          config: this.configPayload,
        };

        payloadConfig.config.image.base64 = await this.fileToBase64(this.configPayload.image.data);

        await ConfigPdfPrinter.insert(payloadConfig);

        this.$Message.success(this.$t('PDF_PRINT_CONFIG.CONFIG_SAVED_SUCCESS'));
        this.configName = '';
        this.loadSavedConfigs();
      } catch (error) {
        loggerVue.error({
          msg: 'PDF_SAVE_CONFIG_ERROR',
          error,
        });
        this.$Message.error(this.$t('PDF_PRINT_CONFIG.CONFIG_SAVED_ERROR'));
      }
    },
    async previewConfig({ name, config }) {
      try {
        this.pdfBytes = await this.pdfService.addConfigContent(config);
        this.updatePdfPreview();
        this.$Message.success(this.$t('PDF_PRINT_CONFIG.CONFIG_APPLIED_SUCCESS', { name }));
      } catch (error) {
        loggerVue.error({
          msg: 'PDF_PREVIEW_CONFIG_ERROR',
          error,
        });
        this.$Message.error(this.$t('PDF_PRINT_CONFIG.CONFIG_APPLIED_ERROR', { name }));
      }
    },
    async deleteConfig({ _id, name }) {
      this.$Modal.confirm({
        content: name,
        title: this.$t('REMOVE_CONFIRM'),
        onOk: async () => {
          await ConfigPdfPrinter.removeId(_id);
          this.loadSavedConfigs();
          this.$Message.success(this.$t('PDF_PRINT_CONFIG.CONFIG_DELETED_SUCCESS', { name }));
        },
      });
    },
  },
  async created() {
    this.loadExampleConfig();
    this.loadSamplePdf(this.selectedPlatform);
    this.loadSavedConfigs();

    ConfigPdfPrinter.syncRemote();
  },
  computed: {
    btnDisabled() {
      if (this.configPayload.text.content || this.configPayload.image.data) {
        return false;
      }

      return true;
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/vue/styles/tokens.scss';

.pt-editor {
  padding: 20px;

  &__panel {
    position: sticky;
    top: 20px;
  }

  &__controls {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  &__title {
    margin-bottom: 15px;
    font-size: 15px;
    font-weight: 600;
    color: $c-text-strong;
  }

  &__group {
    padding: 15px;
    border: 1px solid $c-border-strong;
    border-radius: $radius-card;
    background-color: $c-surface;

    .ivu-btn {
      width: 100%;
      margin-top: 10px;
    }
  }

  &__group-title {
    margin-bottom: 15px;
    font-size: 15px;
    font-weight: 600;
    color: $c-text-strong;
  }

  &__group-link {
    margin-left: 5px;
    color: $c-link;

    &:hover {
      color: $c-link-hover;
    }
  }

  &__group-switch {
    display: flex;
    justify-content: flex-end;
  }

  &__field {
    margin-bottom: 20px;
  }

  &__block {
    margin: 10px 0;
  }

  &__positions {
    display: flex;
    flex-direction: column;
    gap: 15px;
    margin: 15px 0;
  }

  &__position {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    margin-right: 15px;
  }

  &__label {
    min-width: 70px;
    color: $c-text;
  }

  &__preview {
    border: 1px solid $c-border-strong;
    border-radius: $radius-card;
    padding: 15px;
    background-color: $c-surface;
    height: 100%;

    iframe {
      border: 1px solid $c-border;
      border-radius: $radius-item;
      background-color: $c-surface-alt;
    }
  }

  &__preview-footer {
    margin-top: 5px;
  }

  &__saved {
    padding: 15px;
    border: 1px solid $c-border-strong;
    border-radius: $radius-card;
    background-color: $c-surface;
  }

  &__saved-list {
    margin-top: 20px;
  }

  &__saved-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px;
    border: 1px solid $c-border;
    border-radius: $radius-item;
    margin-bottom: 8px;
    transition: border-color $motion-fast, background-color $motion-fast;

    &:hover {
      border-color: $c-border-strong;
      background-color: $c-surface-soft;
    }
  }

  &__saved-name {
    font-size: 14px;
    color: $c-text-strong;
    @include ellipsis;
  }

  &__saved-actions {
    display: flex;
    gap: 8px;
    flex-shrink: 0;
  }

  &__image-preview {
    margin: 10px 0;
    text-align: center;

    img {
      max-width: 200px;
      max-height: 200px;
      object-fit: contain;
      border: 1px solid $c-border-strong;
      border-radius: $radius-item;
      padding: 5px;
    }
  }
}
</style>
