<template>
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <!-- SEARCH Area -->
    <div class="ui--search-container clearfix">
      <div class="col-9 float-start">
        <div class="row">
          <div class="col-6">
            <div class="row">
              <label class="col-3 col-form-label text-end">Measure</label>
              <div class="col-9">
                <div class="input-group">
                  <multiselect
                    v-model="measureItem.measure"
                    :reset-after="false"
                    @select="selectMeasure"
                    :custom-label="nameWithLang"
                    track-by="code"
                    label="label"
                    :show-labels="false"
                    placeholder="Select one"
                    :options="measureOptions"
                    :searchable="false"
                    :allow-empty="true"
                    class="mselect"
                  >
                  </multiselect>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-6">
            <div class="row">
              <label class="col-3 col-form-label text-end">SCOPE1</label>
              <div class="col-9">
                <div class="input-group">
                  <multiselect
                    id="scope1"
                    v-model="measureItem.scope1"
                    :reset-after="false"
                    @select="selectScope"
                    track-by="code"
                    label="label"
                    :show-labels="false"
                    placeholder="Select one"
                    :options="scope1Options"
                    :searchable="false"
                    :allow-empty="true"
                    class="scope_select"
                    :disabled="!isScope1Enabled"
                  >
                  </multiselect>
                </div>
              </div>
            </div>
          </div>
          <div class="col-6">
            <div class="row">
              <label class="col-3 col-form-label text-end">Target1</label>
              <div class="col-9">
                <div class="input-group"><component :is="currentComponent('target1')" v-model="measureItem.target1" class="period-component" /></div>
              </div>
            </div>
          </div>
        </div>

        <div class="row">
          <div class="col-6">
            <div class="row">
              <label class="col-3 col-form-label text-end">SCOPE2</label>
              <div class="col-9">
                <div class="input-group">
                  <multiselect
                    id="scope2"
                    v-model="measureItem.scope2"
                    :reset-after="false"
                    @select="selectScope"
                    track-by="code"
                    label="label"
                    :show-labels="false"
                    placeholder="Select one"
                    :options="scope2Options"
                    :searchable="false"
                    :allow-empty="true"
                    class="scope_select"
                    :disabled="!isScope2Enabled"
                  >
                  </multiselect>
                </div>
              </div>
            </div>
          </div>
          <div class="col-6">
            <div class="row">
              <label class="col-3 col-form-label text-end">Target2</label>
              <div class="col-9">
                <component :is="currentComponent('target2')" v-model="measureItem.target2" class="period-component" />
              </div>
            </div>
          </div>
        </div>

        <div class="row">
          <div class="col-6">
            <div class="row">
              <label class="col-3 col-form-label text-end">SCOPE3</label>
              <div class="col-9">
                <div class="input-group">
                  <multiselect
                    id="scope3"
                    v-model="measureItem.scope3"
                    :reset-after="false"
                    @select="selectScope"
                    track-by="code"
                    label="label"
                    :show-labels="false"
                    placeholder="Select one"
                    :options="scope3Options"
                    :searchable="false"
                    :allow-empty="true"
                    class="scope_select"
                    :disabled="!isScope3Enabled"
                  >
                  </multiselect>
                </div>
              </div>
            </div>
          </div>
          <div class="col-6">
            <div class="row">
              <label class="col-3 col-form-label text-end">Target3</label>
              <div class="col-9">
                <component :is="currentComponent('target3')" v-model="measureItem.target3" class="period-component" />
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- search button -->
      <div class="col-3 float-end text-end ">
        <!--<i class="bi bi-circle"></i><i class="bi bi-circle-half"></i><i class="bi bi-circle-fill"></i>-->
        <button class="btn btn-primary btn-search ml-1" type="button" @click="onInsert()">Insert Measure</button>
        <button class="btn btn-primary btn-search  ml-1" type="button" @click="onClear()">Clear</button>
      </div>
    </div>

    <div class="ui--list-heading clearfix">
      <div class="col-6 float-start">
        <h5 class="mb-2">Measure</h5>
      </div>
      <div class="col-6 float-end text-end">
        <button class="btn btn-primary btn-search" type="button">Excel Template Download</button>
        <button class="btn btn-primary btn-search" type="button">Delete</button>
      </div>
    </div>
    <div>
      <div class="grid-wrap" style="height:">
        <div class="realgrid" id="gridMeasure" style="width: 100%; height: 350px"></div>
      </div>
    </div>

    <div>add measure.</div>
    <div>measure list,</div>
    <pre>
measureItem:{{ measureItem }}

    </pre>
  </div>
</template>
<script>
import axios from 'axios';
import _ from 'lodash';
import { DateUtil, SDLUtil, StringUtil } from '@/utils';
import SDLLocale from '@/mixin/SDLLocale';
import Multiselect from 'vue-multiselect';
import YearSelector from '@/components/selectors/YearSelector.vue';
import MonthSelector from '@/components/selectors/MonthSelector.vue';
import QuarterSelector from '@/components/selectors/QuarterSelector.vue';
import WeekSelector from '@/components/selectors/WeekSelector.vue';
import RangeWeekSelector from '@/components/selectors/RangeWeekSelector.vue';
import SoldToCodeSelector from '@/components/selectors/SoldToCodeSelector.vue';
import ProductGroupSelector from '@/components/selectors/ProductGroupSelector.vue';
import SkuSelector from '@/components/selectors/SkuSelector.vue';

import GridCommon from '@/mixin/GridCommon';
import RealGrid from 'realgrid';

export default {
  name: "formula/formulaSim",
  components: {
    Multiselect,
  },
  mixins: [SDLLocale, GridCommon],
  data() {
    return {
      page: {
        title: 'fmSim',
      },
      termCodes: SDLUtil.getCommCodeList({ commCodeTypeId: 'PARAMETER_TERM' }),
      measureOptions: SDLUtil.getCommCodeList({ commCodeTypeId: 'PARAMETER_MEASURE' }),

      scope1Codes: [],
      scope2Codes: [],
      scope3Codes: [],

      scopeOptions: [], //term 전환전
      scope1Options: [],
      scope2Options: [],
      scope3Options: [],
      measureItem: {
        measure: null,
        scope1: null,
        scope2: null,
        scope3: null,
        target1: null,
        target2: null,
        target3: null,
        value: null,
      },
      //-- measure grid
      dataProviderMeasure: null,
      gridViewMeasure: null,
      gridListMeasure: [],
    };
  },
  computed: {
    isScope1Enabled: function () {
      return this.measureItem.measure !== null && (this.scopeOptions?.length ?? 0) >= 1;
    },
    isScope2Enabled: function () {
      return this.measureItem.scope1 !== null && (this.scopeOptions?.length ?? 0) >= 2;
    },
    isScope3Enabled: function () {
      return this.measureItem.scope2 !== null && (this.scopeOptions?.length ?? 0) >= 3;
    },
  },
  methods: {
    init() {
      this.setMeasure();
    },
    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);
    },
    currentComponent(target) {
      let code = null;
      switch (target) {
        case 'target1':
          code = this.measureItem.scope1?.code;
          break;
        case 'target2':
          code = this.measureItem.scope2?.code;
          break;
        case 'target3':
          code = this.measureItem.scope3?.code;
          break;
      }
      //console.log('   currentComponent  ', target, code);

      if (code) {
        this.measureItem[target] = this.initScopeValue[code];
        return this.initScopeValue[code].obj;
      } else {
        return null;
      }
    },
    onInsert() {
      console.log('onInsert');
      let item = {
        MEASURE: this.measureItem.measure.code,
        SCOPE1: this.measureItem.scope1?.code,
        SCOPE2: this.measureItem.scope2?.code,
        SCOPE3: this.measureItem.scope3?.code,
        TARGET1: this.measureItem.target1?.data,
        TARGET2: this.measureItem.target2?.data,
        TARGET3: this.measureItem.target3?.data,
        VALUE: null,
      };
      this.gridListMeasure.push(item);
      this.dataProviderMeasure.setRows(this.gridListMeasure);
    },
    onClear() {
      _.assign(this.measureItem, { measure: null, scope1: null, scope2: null, scope3: null, target1: null, target2: null, target3: null });
      this.scope1Options = [];
      this.scope2Options = [];
      this.scope3Options = [];
    },
    nameWithLang({ label, description }) {
      return `${label} — [${description}]`;
    },
    selectMeasure(obj) {
      this.scopeOptions = SDLUtil.getCommCodeList({ commCodeTypeId: `SCOPE_${this.measureItem.measure.code}` });
      console.log('selectMeasure scope1Options', this.scope1Options);

      this.scope1Options = _.clone(this.scopeOptions);
      if (_.includes(_.map(this.scope1Options, 'code'), 'TERM')) {
        _.remove(this.scope1Options, n => n.code == 'TERM');
        this.scope1Options = [...this.termCodes, ...this.scope1Options];
      }

      _.assign(this.measureItem, { scope1: null, scope2: null, scope3: null, target1: null, target2: null, target3: null });
      this.scope2Options = [];
      this.scope3Options = [];
    },
    selectScope(selectedOption, id) {
      console.log('selectScope', selectedOption, id);
      if (id == 'scope1') {
        this.scope2Options = _.cloneDeep(this.scope1Options);
        if (_.startsWith(this.measureItem.scope1.code, 'TERM')) {
          _.remove(this.scope2Options, n => _.startsWith(n.code, 'TERM'));
        }
        _.remove(this.scope2Options, n => n.code == this.measureItem.scope1.code);
        _.assign(this.measureItem, { scope2: null, scope3: null, target1: null, target2: null, target3: null }); //init
      }

      if (id == 'scope2') {
        this.scope3Options = _.cloneDeep(this.scope2Options);
        if (_.startsWith(this.measureItem.scope1.code, 'TERM') || _.startsWith(this.measureItem.scope2.code, 'TERM')) {
          _.remove(this.scope3Options, n => _.startsWith(n.code, 'TERM'));
        }
        _.remove(this.scope3Options, n => n.code == this.measureItem.scope1.code || n.code == this.measureItem.scope2.code);
        _.assign(this.measureItem, { scope3: null, target2: null, target3: null });
      }
    },
  }, //methods
  created() {
    this.initScopeValue = {
      TERM_YEAR: { obj: YearSelector, type: 'TERM_YEAR', data: 2024 },
      TERM_MONTH: { obj: MonthSelector, type: 'TERM_MONTH', data: '2024M06' },
      TERM_QUARTER: { obj: QuarterSelector, type: 'TERM_QUARTER', data: 'Q2' },
      TERM_WEEK: { obj: WeekSelector, type: 'TERM_WEEK', data: '2024-11-30' },
      TERM_RANGE_WEEK: { obj: RangeWeekSelector, type: 'TERM_RANGE_WEEK', data: '2024W51~2024W52' },
      SOLD_TO_CODE: { obj: SoldToCodeSelector, type: 'SOLD_TO_CODE', data: '' },
      PRODUCTGROUP: { obj: ProductGroupSelector, type: 'PRODUCTGROUP', data: 'VD' },
      SKU: { obj: SkuSelector, type: 'SKU', data: 'SM-928B/DS' },
    };
  },
  mounted() {
    this.$nextTick(() => {
      console.info('initialize Formula Sim Page');
      this.init();
    });
  },
  unmounted() {
    this.dataProviderMeasure.clearRows();
    this.gridViewMeasure.destroy();
    this.dataProviderMeasure.destroy();
    this.gridViewMeasure = null;
    this.dataProviderMeasure = null;
  },
};
</script>
<style src="vue-multiselect/dist/vue-multiselect.min.css"></style>
<style scoped>
.mselect {
  width: 350px;
}
.scope_select {
  width: 250px;
}
</style>
