<template>
  <!-- SUB Contents -->
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <!--Contents Area -->
    <div class="ui--form-container">
      <form class="needs-validation" novalidate="" @submit.prevent>
        <div class="mb-4">
          <label>Key <span class="ui--text-required">&#42;</span></label>
          <input
            type="text"
            class="form-control"
            v-model="htmlDoc.templateKey"
            :readonly="!modifyFlag"
            v-validation="{
              groupId: '',
              valids: [
                {
                  validFuncs: () => {
                    return checkKey(htmlDoc.templateKey);
                  },
                  errorMessage: 'sdl.template.message.invalidKey.alphaNumeric',
                },
              ],
            }"
            errorMessage="sdl.samsung.validate.required"
          />
        </div>
        <div class="mb-4">
          <label>{{ $t('sdl.approval.label.title') }} <span class="ui--text-required">&#42;</span></label>
          <input type="text" class="form-control" v-model="htmlDoc.title" v-validation="" errorMessage="sdl.samsung.validate.required" />
        </div>
        <div class="mb-4">
          <label>{{ $t('sdl.board.label.classificationDesc') }} <span class="ui--text-required">&#42;</span></label>
          <input type="text" class="form-control" v-model="htmlDoc.description" v-validation="" errorMessage="sdl.samsung.validate.required" />
        </div>
        <div class="mb-4">
          <label>{{ $t('sdl.common.label.attachments') }} <span class="ui--text-required">&#42;</span></label>
          <button
            class="btn btn-outline-secondary ui--btn-xs ms-2"
            type="button"
            @click="onPreview(htmlDoc.id)"
            v-if="!modifyFlag"
          >
            {{ $t('sdl.board.label.preView') }}
          </button>
          <div class="mt-1">
            <input type="file" class="form-control" @change="onChange" v-if="modifyFlag || reUploadFlag" />
            <button
              class="btn btn-outline-primary ui--btn-xs"
              type="button"
              @click="reUploadFlag = true"
              v-if="!modifyFlag && !reUploadFlag"
            >
              reUpload
            </button>
          </div>
        </div>
      </form>
    </div>
    <hr class="mb-4" />
    <div class="ui--button-container">
      <button class="btn btn-secondary btn-lg" type="button" @click="goBackToList">
        {{ $t('sdl.common.label.list') }}
      </button>
      <button class="btn btn-secondary btn-lg" type="button" v-if="!modifyFlag" @click="delEvent">
        {{ $t('sdl.common.label.delete') }}
      </button>
      <button class="btn btn-primary btn-lg" type="button" @click="onBeforeSave">
        {{ $t('sdl.common.label.save') }}
      </button>
    </div>

    <!--//Contents Area -->
  </div>
</template>

<script>
import axios from 'axios';
import _ from 'lodash';
import { SDLUtil } from '@/utils';
import StoreParams from '@/mixin/StoreParams';
import HtmlPreviewPopup from './popup/HtmlTemplatePreview.vue';

export default {
  data() {
    return {
      modifyFlag: true,
      htmlDoc: {},
      templateGroupCode: '',
      checkFlag: false,
      files: [],
      reUploadFlag: false,
    };
  },
  mixins: [StoreParams],
  methods: {
    init() {
      // eslint-disable-next-line prefer-destructuring
      this.templateGroupCode = _.replace(this.$route.path, `${this.$CONTEXT}/`, '').split('/')[2];
      if (this.$route.params.templateKey) {
        this.loadHtmlDoc();
      }
    },
    checkKey(templateKey) {
      const regId = /^[A-Za-z0-9]{1,50}$/;
      if (!regId.test(templateKey)) {
        return false;
      }
      return true;
    },
    async checkDupKey() {
      const r = await axios.get(
        `${SDLUtil.API_URL}/html-templates/dup-check/group/${this.templateGroupCode}/key/${this.htmlDoc.templateKey}`,
      );
      return r.data;
    },
    /**
     * param: event
     * return:
     * exception:
     * Description : Select attachment
     */
    onChange(e) {
      this.files = e.target.files || e.dataTransfer.files;

      const getFileExt = fileName => fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLowerCase();
      const extList = 'html|htm'.split('|');

      Object.keys(this.files).forEach(x => {
        if (!extList.includes(getFileExt(this.files[x].name))) {
          SDLUtil.alert(
            SDLUtil.getMsgProp('sdl.common.message.extensionCannotBeAttached', [`${getFileExt(this.files[x].name)}`]),
          );
          this.files = [];
          e.target.value = '';
        }
      });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : event before deleting
     */
    delEvent() {
      SDLUtil.confirm({
        msg: 'sdl.common.message.doDelete',
        title: 'sdl.common.label.delete',
        onOkEvt: () => {
          this.onDelete();
        },
      });
    },
    /**
     * param:
     * return:
     * exception:
     * Description : delete htmlTemplate
     */
    onDelete() {
      SDLUtil.showLoadingBar(true);
      axios
        .delete(`${SDLUtil.API_URL}/html-templates/${this.htmlDoc.id}`)
        .then(() => {
          // hide Loading bar
          SDLUtil.showLoadingBar(false);
          this.$router.replace({
            path: `${this.$CONTEXT}/admin/htmlTemplate/${this.templateGroupCode}/list`,
          });
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          console.log(error);
          SDLUtil.errorAlert(error);
        });
    },
    // 저장 btn click
    async onBeforeSave() {
      if (SDLUtil.onSubmitValidation()) return;

      if (this.modifyFlag && this.files.length === 0) {
        SDLUtil.alert('sdl.common.message.selectFile');
        return;
      }

      if (this.modifyFlag) {
        if (await this.checkDupKey()) {
          SDLUtil.alert('sdl.common.message.duplicatedKey');
          return;
        }
      }

      SDLUtil.confirm({
        msg: 'sdl.common.message.doSave',
        title: 'sdl.common.label.save',
        onOkEvt: () => {
          this.onSave();
        },
      });
    },
    onSave() {
      const param = new FormData();
      if (this.files.length > 0) {
        param.append('templateFile', this.files[0]);
      }

      param.append('templateKey', this.htmlDoc.templateKey);
      param.append('title', this.htmlDoc.title);
      param.append('description', this.htmlDoc.description);
      param.append('templateGroupCode', this.templateGroupCode);

      if (!this.modifyFlag) {
        // modify
        SDLUtil.showLoadingBar(true);
        axios
          .post(`${SDLUtil.API_URL}/html-templates/${this.htmlDoc.id}`, param)
          .then(() => {
            this.$router.replace({
              path: `${this.$CONTEXT}/admin/htmlTemplate/${this.templateGroupCode}/edit/${this.htmlDoc.templateKey}`,
            });
            this.init();
            // Loading bar hidden
            SDLUtil.showLoadingBar(false);
          })
          .catch(error => {
            SDLUtil.showLoadingBar(false);
            console.log(error);
            SDLUtil.errorAlert(error);
          });
      } else {
        // add
        SDLUtil.showLoadingBar(true);
        axios
          .post(`${SDLUtil.API_URL}/html-templates/group/${this.templateGroupCode}`, param)
          .then(response => {
            console.log(response);
            this.$router.push({
              path: `${this.$CONTEXT}/admin/htmlTemplate/${this.templateGroupCode}/edit/${this.htmlDoc.templateKey}`,
            });
            // Loading bar hidden
            SDLUtil.showLoadingBar(false);
          })
          .catch(error => {
            SDLUtil.showLoadingBar(false);
            console.log(error);
            SDLUtil.errorAlert(error);
          });
      }
    },
    loadHtmlDoc() {
      // Loading bar execution
      SDLUtil.showLoadingBar(true);
      const { templateKey } = this.$route.params;
      axios
        .get(`${SDLUtil.API_URL}/html-templates/group/${this.templateGroupCode}/key/${templateKey}`)
        .then(response => {
          this.htmlDoc = response.data;
          this.modifyFlag = false;

          // Loading bar hidden
          SDLUtil.showLoadingBar(false);
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          console.log(error);
        });
    },
    onPreview(id) {
      SDLUtil.show(
        HtmlPreviewPopup,
        {
          id,
        },
        {
          width: '900px',
          height: 'auto',
        },
      );
    },
  },
  watch: {
    $route() {
      this.init();
    },
  },
  created() {
    this.init();
  },
};
</script>

<style scoped></style>
