<template>
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <div class="ui--form-container">
      <h4 class="mb-3">Module Edit [{{ mode }}]</h4>
      <form class="needs-validation" novalidate="">
        <div class="mb-2">
          <label>Module Name <span class="ui--text-required">&#42;</span></label>
          <input v-model="item.kpiModuleName" type="text" class="form-control" />
        </div>
        <div class="row">
          <div class="col-6 mb-3">
            <label>Type</label>
            <select v-model="item.kpiModuleType" class="form-select d-block w-100">
              <option :value="itemType.code" v-for="itemType in itemTypeList" :key="itemType.codeId">
                {{ getLabel(itemType) }}
              </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.kpiModuleDesc"></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.kpiModuleProgram" 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']">
            {{ !kpiModuleId ? $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: "module/moduleEdit",
  mixins: [StoreParams, SDLLocale],

  data() {
    return {
      form: null,
      //urlPath: _.replace(this.$route.path, `${this.$CONTEXT}/`, ''),
      itemTypeList: SDLUtil.getCommCodeList({ commCodeTypeId: 'EMBO_KPI_MODULE_TYPE' }),
      kpiModuleId: this.$route.params.kpiModuleId,
      mode: '', //EDIT      
      item: {
        kpiModuleId: this.$route.params.kpiModuleId,
        kpiModuleName: '',
        kpiModuleType: 'FORMULA',
        kpiModuleDesc: '',
      },
    };
  },
  methods: {
    init() {
      
      if (this.kpiModuleId) {
        this.mode = 'EDIT';
        this.getItemInfo();
      } else {
        this.mode = 'CREATE';
      }
    },
    async getItemInfo() {
      SDLUtil.showLoadingBar(true);
      let listApi = `${SDLUtil.API_URL}/embo/module/main.do?method=getModule`;
      let params = { kpiModuleId: this.kpiModuleId };
      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.kpiModuleName.trim()) || _.eq(this.item.kpiModuleName.trim(), '<p>&nbsp;</p>')) {
        SDLUtil.alert('Please enter your Module Name.');
        return false;
      }

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

      if (_.isEmpty(this.item.kpiModuleProgram.trim()) || _.eq(this.item.kpiModuleProgram.trim(), '<p>&nbsp;</p>')) {
        SDLUtil.alert('Please enter your Module 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/module/main.do?method=regist`, this.item)
          .then(({ data }) => {
            this.kpiModuleId = data;
            SDLUtil.showLoadingBar(false);
            this.moveViewPage();
          })
          .catch(err => {
            SDLUtil.showLoadingBar(false);
            SDLUtil.errorAlert(err);
          });
      } else {
        // modification
        axios
          .post(`${SDLUtil.API_URL}/embo/module/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.kpiModuleId)
      this.$router.push(`${this.$CONTEXT}/embo/module/moduleView/` + this.kpiModuleId);
    },
    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 Module Edit Page');
      this.init();
    });
  },

};
</script>

<style scoped></style>
