<!--
  Program: Common code
  Author: SDL
  Brief: Generate and modify common code
-->
<template>
  <div class="modal-dialog modal-dialog-centered  modal-dialog-scrollable modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">{{ title }}</h5>
        <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close" @click="$emit('close')"></button>
      </div>
      <div class="modal-body">
        <form @submit.prevent name="commonCodePopupForm">
          <table class="table table-bordered ui--table-form ui--table-form-view">
            <colgroup>
              <col style="width:40%" />
              <col style="width:60%" />
            </colgroup>
            <tbody>
              <tr>
                <th class="text-nowrap" scope="row">
                  {{ $t('sdl.commonCode.label.code') }}<span class="ui--text-required">*</span>
                </th>
                <td>
                  <input
                    type="text"
                    class="form-control"
                    v-model.trim="code.code"
                    v-validation="{ groupId: 'popup' }"
                    errorMessage="sdl.samsung.validate.required"
                  />
                </td>
              </tr>
              <tr>
                <th class="text-nowrap" scope="row">
                  {{ $t('sdl.commonCode.label.codeNameDefault') }}<span class="ui--text-required">*</span>
                </th>
                <td>
                  <input
                    type="text"
                    class="form-control"
                    v-model.trim="code.label"
                    v-validation="{ groupId: 'popup' }"
                    errorMessage="sdl.samsung.validate.required"
                  />
                </td>
              </tr>
              <tr v-for="(locale, index) in $i18n.availableLocales" :key="'tr'+index">
                <th class="text-nowrap" scope="row">
                  {{ $t('sdl.commonCode.label.label') }}({{ locale }})
                </th>
                <td>
                  <input type="text" class="form-control" v-model="code.labelJson[locale]" />
                </td>
              </tr>
             <tr>
                <th class="text-nowrap" scope="row">{{ $t('sdl.common.label.description') }}</th>
                <td>
                  <textarea class="form-control" aria-label="textarea" rows="5" v-model="code.description"></textarea>
                </td>
              </tr>
              <tr v-show="false">
                <th class="text-nowrap" scope="row">
                  {{ $t('sdl.commonCode.label.order') }}<span class="ui--text-required">*</span>
                </th>
                <td>
                  <input
                    type="number"
                    min="0"
                    max="99999"
                    class="form-control"
                    v-model.number="code.ord"
                    v-validation="{ groupId: 'popup' }"
                  />
                </td>
              </tr>
            </tbody>
          </table>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal" @click="$emit('close')">
          {{ $t('sdl.common.label.cancel') }}
        </button>
        <button type="button" class="btn btn-primary" @click="saveCode()">{{ $t('sdl.common.label.save') }}</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { SDLUtil } from '@/utils';

export default {
  data() {
    return {
      flag: '',
      code: {
        codeId: '', // pk
        code: '',
        labelJson: {},
        description: '',
        ord: 0,
      },
    };
  },
  props: {
    groupCodeId: {
      required: true,
      type: String,
    },
    upperCodeId: {
      required: false,
      type: String,
    },
    hierarchyLevel: {
      required: false,
      type: Number,
    },
    codeId: {
      required: false,
      type: String,
    },
    title: {
      required: true,
      type: String,
    },
    ord: {
      required: false,
      type: Number,
    },
    refreshCodes: {
      type: Function,
    },
  },
  methods: {
    saveCode() {
      // validation
      if (SDLUtil.onSubmitValidation('popup')) return;

      if (
        this.code.code === ''
        || this.code.labelJson === ''
        || this.code.ord === ''
      ) {
        SDLUtil.alert('sdl.commonCode.message.valid.mandatory');
        return;
      }

      if (this.code.ord < 0) {
        // this.code.ord = this.code.ord * -1;
        SDLUtil.alert('sdl.commonCode.message.valid.negative');
        return;
      }
      if (this.code.ord > 99999) {
        // this.code.ord = 99999;
        SDLUtil.alert('sdl.commonCode.message.valid.maxInt');
        return;
      }

      SDLUtil.showLoadingBar(true);
      if (this.flag === 'NEW') {
        const code = {
          ...this.code,
          hierarchyLevel: this.hierarchyLevel,
        };
        delete code.codeId;
        if (this.upperCodeId) {
          code.upperCodeId = this.upperCodeId;
        }

        axios
          .post(`${SDLUtil.API_URL}/commcode/groupcodes/${this.groupCodeId}/commcodes`, code)
          .then(() => {
            SDLUtil.showLoadingBar(false);
            this.closeAndRefresh();
          })
          .catch(err => {
            console.error(err);
            SDLUtil.showLoadingBar(false);
            SDLUtil.errorAlert(err);
          });
      } else {
        axios
          .put(`${SDLUtil.API_URL}/commcode/groupcodes/${this.groupCodeId}/commcodes/${this.codeId}`, this.code)
          .then(() => {
            SDLUtil.showLoadingBar(false);
            this.closeAndRefresh();
          })
          .catch(err => {
            SDLUtil.showLoadingBar(false);
            SDLUtil.errorAlert(err);
          });
      }
    },
    closeAndRefresh() {
      this.$emit('close');
      this.refreshCodes();
    },
    getCode() {
      SDLUtil.showLoadingBar(true);
      axios
        .get(`${SDLUtil.API_URL}/commcode/groupcodes/${this.groupCodeId}/commcodes/${this.codeId}`)
        .then(({ data }) => {
          this.code = data;
          SDLUtil.showLoadingBar(false);
        })
        .catch(() => {
          SDLUtil.showLoadingBar(false);
        });
    },
  },
  created() {
    if (this.codeId) {
      this.flag = 'UPDATE';
      this.getCode();
    } else {
      this.flag = 'NEW';
      if (this.ord) {
        this.code.ord = this.ord;
      }
    }
  },
};
</script>
