<template>
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <div class="ui--form-container">
      <h4 class="mb-3">Parameter Edit [{{ mode }}]</h4>
      <form class="needs-validation" novalidate="">
        <div class="mb-2">
          <label>Parameter Name <span class="ui--text-required">&#42;</span></label>
          <input v-model="item.parameterName" type="text" class="form-control" />
        </div>
        <div class="row">
          <div class="col-6 mb-3">
            <label>Multi</label>
            <select v-model="item.multi" class="form-select d-block w-100">
              <option value="Y" >Y</option>
              <option value="N" >N</option>
            </select>
          </div>
        </div>
        <div class="mb-2">
          <label>{{ $t('sdl.common.label.description') }} <span class="ui--text-required">&#42;</span></label>
          <textarea style="width: 100%; overflow: scroll; height: 150px; max-height: 250px" class="form-control"
            v-model="item.parameterDesc"></textarea>
        </div>
        <div class="row">
          <div class="col-6 mb-3">
            <label>Program <span class="ui--text-required">&#42;</span></label>
            <input v-model="item.parameterProgram" type="text" class="form-control" />
          </div>
        </div>
        <div class="ui--button-container">
          <button class="btn btn-secondary btn-lg" type="button" @click="cancelPost()">
            {{ $t('sdl.common.label.cancel') }}
          </button>
          <button class="btn btn-primary btn-lg" type="button" @click="saveConfirm()"
            v-authorization="['update', 'execute']">
            {{ !parameterType ? $t('sdl.common.label.register') : $t('sdl.common.label.save') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>
<script>
import axios from 'axios';
import _ from 'lodash';
import { SDLUtil, DateUtil } from '@/utils';
import StoreParams from '@/mixin/StoreParams';
import SDLLocale from '@/mixin/SDLLocale';

export default {
  //name: "parameter/parameterEdit",
  mixins: [StoreParams, SDLLocale],

  data() {
    return {            
      parameterType: this.$route.params.parameterType,
      mode: '', //EDIT      
      item: {
        parameterType: this.$route.params.parameterType,
        parameterName: '',
        multi: 'N',
        parameterDesc: '',
      },
    };
  },
  methods: {
    init() {
      
      if (this.parameterType) {
        this.mode = 'EDIT';
        this.getItemInfo();
      } else {
        this.mode = 'CREATE';
      }
    },
    async getItemInfo() {
      SDLUtil.showLoadingBar(true);
      let listApi = `${SDLUtil.API_URL}/embo/parameter/main.do?method=getParameter`;
      let params = { parameterType: this.parameterType };
      axios
        .post(listApi, JSON.stringify(params), {
          headers: { 'Content-Type': `application/json` },
        })
        .then(response => {
          this.item = _.head(response.data.result);
          this.item.createdAt = this.$filters.dateFormat(this.item.createdAt);
          this.item.updatedAt = this.$filters.dateFormat(this.item.updatedAt);
          SDLUtil.showLoadingBar(false);
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(error);
          console.log(error);
        });
    },
    checkTitleLength(str) {
      let len = 0;
      for (let i = 0; i < str.length; i += 1) {
        if (escape(str.charAt(i)).length === 6) {
          len += 1;
        }
        len += 1;
      }
      return !(len > 100);
    },


    validatePost() {
      // Check the message post input
      if (SDLUtil.onSubmitValidation()) return false;

      if (_.isEmpty(this.item.parameterName.trim()) || _.eq(this.item.parameterName.trim(), '<p>&nbsp;</p>')) {
        SDLUtil.alert('Please enter your Parameter Name.');
        return false;
      }

      if (_.isEmpty(this.item.parameterDesc.trim()) || _.eq(this.item.parameterDesc.trim(), '<p>&nbsp;</p>')) {
        SDLUtil.alert('Please enter your Parameter description.');
        return false;
      }

      if (_.isEmpty(this.item.parameterProgram.trim()) || _.eq(this.item.parameterProgram.trim(), '<p>&nbsp;</p>')) {
        SDLUtil.alert('Please enter your Parameter Program.');
        return false;
      }
      return true;
    },
    saveConfirm() {
      if (this.validatePost()) {
        SDLUtil.confirm({
          title: 'sdl.common.label.save',
          msg: 'sdl.common.message.doSave',
          okLabel: 'sdl.common.label.confirm',
          cancelLabel: 'sdl.common.label.cancel',
          onOkEvt: () => {
            this.savePost();
          },
          onCancelEvt: () => console.log('cancel'),
        });
      }
    },
    savePost() {
      SDLUtil.showLoadingBar(true);
      if (!_.eq(this.mode, 'EDIT')) {
        // registration
        axios
          .post(`${SDLUtil.API_URL}/embo/parameter/main.do?method=regist`, this.item)
          .then(({ data }) => {
            this.parameterType = data;
            SDLUtil.showLoadingBar(false);
            this.moveViewPage();
          })
          .catch(err => {
            SDLUtil.showLoadingBar(false);
            SDLUtil.errorAlert(err);
          });
      } else {
        // modification
        axios
          .post(`${SDLUtil.API_URL}/embo/parameter/main.do?method=update`, this.item)
          .then(() => {
            SDLUtil.showLoadingBar(false);
            this.moveViewPage();
          })
          .catch(err => {
            SDLUtil.showLoadingBar(false);
            SDLUtil.errorAlert(err);
          });
      }
    },
    moveViewPage() {
      console.log('moveViewPage:'+this.parameterType)
      this.$router.push(`${this.$CONTEXT}/embo/parameter/parameterView/` + this.parameterType);
    },
    cancelPost() {
      SDLUtil.confirm({
        msg: 'sdl.common.message.doCancel',
        title: 'sdl.common.label.save',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => (_.eq(this.mode, 'CREATE') ? this.goBackToList() : this.moveViewPage()),
        onCancelEvt: () => console.log('cancel'),
      });
    },
  }, //--methods
  mounted() {
    this.$nextTick(() => {
      console.info('initialize Parameter Edit Page');
      this.init();
    });
  },

};
</script>

<style scoped></style>
