<template>
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <div class="ui--form-container">
      <h4 class="mb-3">Formula Edit [{{ mode }}]</h4>
      <form class="needs-validation" novalidate="">
        <div class="mb-2">
          <label>{{ $t('sdl.common.label.title') }} <span class="ui--text-required">&#42;</span></label>
          <input v-model="formula.fmName" type="text" class="form-control" />
        </div>
        <div class="row">
          <div class="col-6 mb-3">
            <label>{{ $t('sdl.board.label.groupWord') }}</label>
            <select v-model="formula.fmType" class="form-select d-block w-100">
              <option :value="fmType.code" v-for="fmType in fmTypeList" :key="fmType.codeId">
                {{ getLabel(fmType) }}
              </option>
            </select>

            <textarea style="width: 100%; overflow: scroll; height: 250px; max-height: 250px" class="form-control" v-model="formula.fmDesc"></textarea>
            <h4 class="mb-3">
              {{ $t('sdl.common.label.attachments') }}
              <h5>{{ $t('sdl.common.label.attachments') }}</h5>
              <!-- upload -->
              <sdl-fileuploader ref="fileUploader" :fileList="formula.attachments" @complete="uploadCompleted" :downloadType="downloadType" :maxTotalSize="1073741824" :modifyFlag="true" useExtList="xlsx"></sdl-fileuploader>
            </h4>
          </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']">
            {{ !fmId ? $t('sdl.common.label.register') : $t('sdl.common.label.save') }}
          </button>
        </div>
      </form>
    </div>
  </div>
  <pre>mode:{{mode}}
    <!--
fmId:{{ fmId }}

formula:{{ formula }}

urlPath:{{urlPath}}

this.$route:{{this.$route}}-->
  </pre>
</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 {
  mixins: [StoreParams, SDLLocale],

  data() {
    return {
      form: null,
      urlPath: _.replace(this.$route.path, `${this.$CONTEXT}/`, ''),
      fmTypeList: SDLUtil.getCommCodeList({ commCodeTypeId: 'FM_TYPE' }),
      fmId: this.$route.params.fmId,
      mode: '', //EDIT
      downloadType: 'FORMULA',
      formula: {
        fmId: this.$route.params.fmId,
        fmName: '',
        fmType: 'STANDARD',
        fmDesc: '',
        attachments: [],
      },
    };
  },
  methods: {
    init() {
      //this.fmId = this.urlPath.split('/')[3] || '';
      if (this.fmId) {
        this.mode = 'EDIT';
        this.getFormulaInfo();
      } else {
        this.mode = 'CREATE';
      }
    },
    async getFormulaInfo() {
      //console.log('getFormulaInfo');
      SDLUtil.showLoadingBar(true);
      let listApi = `${SDLUtil.API_URL}/embo/formula/item/main.do?method=getFormula`;
      let params = { fmId: this.fmId };
      axios
        .post(listApi, JSON.stringify(params), {
          headers: { 'Content-Type': `application/json` },
        })
        .then(response => {
          this.formula = response.data.result;
         
          this.formula.attachments = response.data.attachments;

          //console.log(item)

          // hide Loading bar
          SDLUtil.showLoadingBar(false);
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(error);
          console.log(error);
        });

      this.$refs.fileUploader.init();
    },
    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);
    },
    /**
     * param: downloadType -> String
     * param: fileList -> Array
     * return:
     * exception:
     * description : file upload callback
     */
    uploadCompleted(downloadType, fileList) {
      const attachType = 'attachments';
      // Setting uploaded file information
      this.formula[attachType] = fileList;
      this.savePost();
    },
    validatePost() {
      // Check the message post input
      if (SDLUtil.onSubmitValidation()) return false;

      if (_.isEmpty(this.formula.fmDesc.trim()) || _.eq(this.formula.fmDesc.trim(), '<p>&nbsp;</p>')) {
        SDLUtil.alert('sdl.board.alert.valid.boardDetail');
        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: () => {
            SDLUtil.showLoadingBar(true, { msg: 'sdl.common.message.uploading' });
            this.$refs.fileUploader.onUpload();
            //if (this.boardInfo.fileAttachUsed)
            //else            this.savePost();
          },
          onCancelEvt: () => console.log('cancel'),
        });
      }
    },
    savePost() {
      SDLUtil.showLoadingBar(true);
      if (!_.eq(this.mode, 'EDIT')) {
        // registration
        axios
          .post(`${SDLUtil.API_URL}/embo/formula/item/main.do?method=regist`, this.formula)
          .then(({ data }) => {
            this.fmId = data;
            SDLUtil.showLoadingBar(false);
            this.moveViewPage();
          })
          .catch(err => {
            SDLUtil.showLoadingBar(false);
            SDLUtil.errorAlert(err);
          });
      } else {
        // modification
        axios
          .post(`${SDLUtil.API_URL}/embo/formula/item/main.do?method=update`, this.formula)
          .then(() => {
            SDLUtil.showLoadingBar(false);
            this.moveViewPage();
          })
          .catch(err => {
            SDLUtil.showLoadingBar(false);
            SDLUtil.errorAlert(err);
          });
      }
    },
    moveViewPage() {
      this.$router.push(`${this.$CONTEXT}/embo/formula/view/`+this.fmId);
    },
    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 Formula Edit Page');

      this.init();
    });
  },
  
};
</script>

<style scoped></style>
