<template>
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <div class="ui--view-container">
      <h4 class="mb-3">Formula View</h4>
      <h4 class="mb-3">
        <span>[{{ formula.fmType }}] </span>{{ formula.fmName }}
      </h4>
      <div class="ui--view-heading d-flex">
        <div>
          {{ $t('sdl.common.label.createdBy') }} :<span class="ms-1">{{ formula.firstRegrId }}</span>
        </div>
        <div class="ms-auto">
          {{ $t('sdl.common.label.createdDate') }} : <span class="ms-1">{{ $filters.dateFormat(formula.lastModDatetime) }}</span>
        </div>
      </div>
      <article class="ui--viewer" v-html="$filters.nl2br(formula.fmDesc)"></article>
      <hr class="mb-4" />
      <div>
        <h5>{{ $t('sdl.common.label.attachments') }}</h5>
        <sdl-fileuploader ref="fileDownload" :fileList="attachments" :downloadType="downloadType" :maxTotalSize="1073741824" :modifyFlag="false" :multiFileNm="formula.fmName"></sdl-fileuploader>
      </div>

      <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="currentUser.systemAdminUser || formula.firstRegrId === currentUser.userId" @click="deleteFormula()" v-authorization="'execute'">
          {{ $t('sdl.common.label.delete') }}
        </button>
        
        <button v-if="currentUser.systemAdminUser || formula.firstRegrId === currentUser.userId" class="btn btn-secondary btn-lg" type="button" @click="moveEdit" v-authorization="'update'">
          {{ $t('sdl.common.label.edit') }}
        </button>
      </div>
      <div>
        <!--fm pre view-->
        <h4 class="mb-3">Formula PreView</h4>
        <div>
          <h5 class="mb-2">MBO</h5>
          <div class="grid-wrap" style="height:" id="grd_main_div">
            <div class="realgrid" id="grid" style="width: 100%; height: 350px"></div>
          </div>
        </div>
        <div class="text-center mt-5 mb-5">
          <button class="btn btn-secondary btn-lg" type="button" @click="calc">Calc <i class="bi bi-box-arrow-up"></i></button>
        </div>
        <div>
          <h5 class="mb-2">Measure</h5>
          <div class="grid-wrap" style="height:">
            <div class="realgrid" id="gridMeasure" style="width: 100%; height: 350px"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <pre>
<!--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';
import GridCommon from '@/mixin/GridCommon';
import RealGrid from 'realgrid';

export default {
  mixins: [StoreParams, SDLLocale, GridCommon],

  data() {
    return {
      //form: null,
      currentUser: SDLUtil.getLoginedUserInfo(),
      urlPath: _.replace(this.$route.path, `${this.$CONTEXT}/`, ''),
      fmTypeList: [],
      fmId: this.$route.params.fmId,
      downloadType: 'FORMULA',
      formula: {},
      attachments: [],
      //-- mbo grid
      dataProvider: null,
      gridView: null,
      gridList: [],
      //-- measure grid
      dataProviderMeasure: null,
      gridViewMeasure: null,
      gridListMeasure: [],
    };
  },
  methods: {
    init() {
      this.getFormulaInfo();
    },
    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.attachments = response.data.attachments;
          this.setMbo(response.data.mboInfo);
          this.setMeasure(response.data.measureInfo);
          SDLUtil.showLoadingBar(false);
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(error);
          console.log(error);
        });

      this.$refs.fileDownload.init();
    },

    moveListPage() {
      this.$router.push(`${this.$CONTEXT}/embo/formula/list`);
    },
    moveEdit() {
      this.$router.push(`${this.$CONTEXT}/embo/formula/edit/` + this.fmId);
    },

    deleteFormula() {
      SDLUtil.confirm({
        title: 'sdl.common.label.delete',
        msg: 'sdl.common.message.doDelete',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => {
          SDLUtil.showLoadingBar(true);

          axios
            .post(`${SDLUtil.API_URL}/embo/formula/item/main.do?method=delete`, { items: [{ FM_ID: this.fmId }] })
            .then(({ data }) => {
              SDLUtil.showLoadingBar(false);
              this.goBackToList();
            })
            .catch(err => {
              SDLUtil.showLoadingBar(false);
              SDLUtil.errorAlert(err);
            });
        },
        onCancelEvt: () => console.log('cancel'),
      });
    },
    setMbo(mboInfo) {
      this.dataProvider = new RealGrid.LocalDataProvider(); // LocalDataProvider 사용
      this.gridView = new RealGrid.GridView('grid'); // GridView 사용
      this.gridView.setDataSource(this.dataProvider); // setDataSource 사용

      const options = {}; //remove sort
      this.grid_setGridOptions(this.gridView, options);
      this.gridView.setSortingOptions({ enabled: false });
      this.dataProvider.setFields([{ fieldName: 'MBO_ITEM' }, { fieldName: 'TYPE' }, { fieldName: 'TARGET' }, { fieldName: 'FORMULA' }, { fieldName: 'GRADE' }, { fieldName: 'FORMULA_VALUE' }, { fieldName: 'GRADE_VALUE' }]);

      this.gridView.setColumns([
        { fieldName: 'MBO_ITEM', header: 'MBO_ITEM', width: 200 },
        { fieldName: 'TYPE', header: 'TYPE', width: 100 },
        { fieldName: 'TARGET', header: 'D [TARGET]', width: 150 },
        { fieldName: 'FORMULA', header: 'E [FORMULA_TXT]', width: 150 },
        { fieldName: 'GRADE', header: 'GRADE_TXT', width: 150 },
        { fieldName: 'FORMULA_VALUE', header: 'FORMULA_VALUE', width: 150 },
        { fieldName: 'GRADE_VALUE', header: 'GRADE_VALUE', width: 150 },
      ]);

      this.gridList = _.map(mboInfo, r => {
        return r;
      });

      this.dataProvider.setRows(this.gridList);
    },
    setMeasure(measureInfo) {
      this.dataProviderMeasure = new RealGrid.LocalDataProvider(); // LocalDataProvider 사용
      this.gridViewMeasure = new RealGrid.GridView('gridMeasure'); // GridView 사용
      this.gridViewMeasure.setDataSource(this.dataProviderMeasure); // setDataSource 사용

      const options = {}; //remove sort
      this.grid_setGridOptions(this.gridViewMeasure, options);
      this.gridViewMeasure.setSortingOptions({ enabled: false });

      this.dataProviderMeasure.setFields([
        { fieldName: 'MEASURE' },
        { fieldName: 'SCOPE1' },
        { fieldName: 'SCOPE2' },
        { fieldName: 'SCOPE3' },
        { fieldName: 'TARGET1' },
        { fieldName: 'TARGET2' },
        { fieldName: 'TARGET3' },
        { fieldName: 'VALUE' },
      ]);

      this.gridViewMeasure.setColumns([
        { fieldName: 'MEASURE', header: 'MEASURE', width: 120 },
        { fieldName: 'SCOPE1', header: 'SCOPE1', width: 120 },
        { fieldName: 'SCOPE2', header: 'SCOPE2', width: 120 },
        { fieldName: 'SCOPE3', header: 'SCOPE3', width: 120 },
        { fieldName: 'TARGET1', header: 'TARGET1', width: 120 },
        { fieldName: 'TARGET2', header: 'TARGET2', width: 120 },
        { fieldName: 'TARGET3', header: 'TARGET3', width: 120 },
        { fieldName: 'VALUE', header: 'I [VALUE]', width: 120, editor: { maxLength: 10 }, editable: true },
      ]);

      this.gridListMeasure = _.map(measureInfo, r => {
        return r;
      });

      this.dataProviderMeasure.setRows(this.gridListMeasure);
    },
    calc() {
      let params = { fmId: this.fmId, rows: this.dataProviderMeasure.getJsonRows() };
      axios
        .post(`${SDLUtil.API_URL}/embo/formula/item/main.do?method=calc`, params)
        .then(({ data }) => {

          _.forEach(this.gridList, (r,idx) => {
            r.FORMULA_VALUE = data.mboInfo[idx].FORMULA;
            r.GRADE_VALUE = data.mboInfo[idx].GRADE;
            return r;
          });

          this.dataProvider.setRows(this.gridList);

          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
      //get measure value

      //call fm value
      //set mbo value
    },
  }, //--methods
  mounted() {
    this.$nextTick(() => {
      console.info('initialize Formula Edit Page');
      this.init();
    });
  },
  unmounted() {
    //alert('The component is removed (unmounted)!');
    this.dataProvider.clearRows();
    this.gridView.destroy();
    this.dataProvider.destroy();
    this.gridView = null;
    this.dataProvider = null;

    this.dataProviderMeasure.clearRows();
    this.gridViewMeasure.destroy();
    this.dataProviderMeasure.destroy();
    this.gridViewMeasure = null;
    this.dataProviderMeasure = null;
  },
};
</script>

<style scoped></style>
