<template>
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <!-- SEARCH Area -->
    <div class="ui--search-container clearfix">
      <div class="col-10 float-start">
        <div class="row">
          <div class="col-6">
            <!-- form -->
            <div class="row">
              <label class="col-3 col-form-label text-end">{{ $t('sdl.common.label.searchCondition') }}</label>
              <div class="col-9">
                <div class="input-group">
                  <select class="form-select" v-model="searchFmType">
                    <option value="">All</option>
                    <option :value="fmType.code" v-for="fmType in fmTypeList" :key="fmType.codeId">
                      {{ getLabel(fmType) }}
                    </option>
                  </select>
                </div>
              </div>
            </div>
          </div>
          <div class="col-6">
            <div class="row">
              <label class="col-2 col-form-label text-end">{{ $t('sdl.common.label.period') }}</label>
              <div class="col-10 form-inline">
                <sdl-datepicker v-model="searchPeriod" :period="searchPeriod"></sdl-datepicker>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- search button -->
      <div class="col-2 float-end text-end">
        <button class="btn btn-primary btn-search" type="button" @click="onSearch()">
          {{ $t('sdl.common.label.search') }}
        </button>
      </div>
    </div>
    <!-- LIST Header & buttons -->
    <div class="ui--list-heading clearfix">
      <span class="ui--text-total"><strong>Total</strong> {{ $filters.numberFormat_de(records) }} </span>
      <div class="float-end">
        <button type="button" class="btn btn-primary btn-sm" :disabled="!hasRow" @click="downloadExcel()" v-authorization="'execute'">
          {{ $t('sdl.common.label.excelDownload') }}
        </button>
        <button type="button" class="btn btn-primary btn-sm" :disabled="!hasChecked" @click="deleteFormula()" v-authorization="'execute'">
          {{ $t('sdl.common.label.delete') }}
        </button>
        <button type="button" class="btn btn-primary btn-sm" @click="moveRegistPage()" v-authorization="'execute'">
          {{ $t('sdl.common.label.register') }}
        </button>
        <button type="button" class="btn btn-primary btn-sm" @click="fmMerge()" v-authorization="'execute'">FM merge</button>
      </div>
    </div>
    <div class="grid-wrap" style="height:" id="grd_main_div">
      <div class="realgrid" id="grid" style="width: 100%; height: 400px"></div>
    </div>
  </div>
  <pre>
  </pre>
</template>
<script>
import axios from 'axios';
import _ from 'lodash';
import { DateUtil, SDLUtil, StringUtil } from '@/utils';
import StoreParams from '@/mixin/StoreParams';
import SDLLocale from '@/mixin/SDLLocale';
import GridCommon from '@/mixin/GridCommon';
import RealGrid from 'realgrid';

export default {
  name: "formula/formulaList",
  mixins: [StoreParams, SDLLocale, GridCommon],
  data() {
    return {
      page: {
        title: 'fmpage',
      },
      searchFmType: '',
      fmTypeList: SDLUtil.getCommCodeList({ commCodeTypeId: 'FM_TYPE' }),
      userInfo: {},

      records: 10000,
      currentPage: 1,
      searchPeriod: {},
      //-- grid
      dataProvider: null,
      gridView: null,
      gridList: [],
      checkedItems: [],
    };
  },
  computed: {
    hasChecked: function () {
      return !_.isEmpty(this.checkedItems);
    },
    hasRow: function () {
      return !_.isEmpty(this.gridList);
    },
  },
  methods: {
    init() {
      const storeParams = this.getStoreParameter();
      //console.log('storeParams', storeParams);
      if (storeParams) {
        this.searchPeriod.startDate = storeParams.startDate;
        this.searchPeriod.endDate = storeParams.endDate;
        this.onSearch(storeParams.pageIndex);
      } else {
        this.searchPeriod.startDate = DateUtil.subDate(1, 'M');
        this.searchPeriod.endDate = DateUtil.now();
        this.onSearch();
      }
      // console.log(this.$route);
    },
    initGrid() {
      this.dataProvider = new RealGrid.LocalDataProvider(); // LocalDataProvider 사용
      this.gridView = new RealGrid.GridView('grid'); // GridView 사용
      this.gridView.setDataSource(this.dataProvider); // setDataSource 사용

      //set grid edit option
      const options = { options: { checkBar: { visible: true, showAll: true } }, displayOptions: { columnMovable: true, rowHeight: 25 } };
      this.grid_setGridOptions(this.gridView, options);
      //this.gridView.setCopyOptions({enabled: false});
      //this.gridView.setPasteOptions({enabled: false});
      /*this.gridView.setDisplayOptions({
        columnMovable: false,rowHeight: 20,
      });*/
      // 그리드 데이터 설정
      this.dataProvider.setFields([
        { fieldName: 'fmId' },
        { fieldName: 'fmType' },
        { fieldName: 'fmName' },
        { fieldName: 'fmDesc' },
        { fieldName: 'firstRegrId' },
        { fieldName: 'firstRegDatetime' },
        { fieldName: 'lastModrId' },
        { fieldName: 'lastModDatetime' },
      ]);

      this.gridView.setColumns([
        {
          fieldName: 'fmId',
          header: 'Formula ID',
          width: 150,
        },
        { fieldName: 'fmType', header: 'Category', width: 100 },
        { fieldName: 'fmName', header: 'Name', width: 200, styleName: 'rgsample-blue-column cursor' },
        { fieldName: 'fmDesc', header: 'Description', width: 300 },
        { fieldName: 'firstRegrId', header: 'Created By', width: 150 },
        { fieldName: 'firstRegDatetime', header: 'Created Date', width: 150 },
        { fieldName: 'lastModrId', header: 'Updated By', width: 150 },
        { fieldName: 'lastModDatetime', header: 'Updated Date', width: 150 },
      ]);

      // set grid event
      this.gridView.onCellClicked = (grid, clickData) => {
        //console.log('onCellClicked: ' + JSON.stringify(clickData));
        //전체 데이타 this.checkedItems = this.grid_getCheckedRowArray(grid);
        if (clickData.column == 'fmName') {
          let row = this.dataProvider.getJsonRow(clickData.dataRow);
          //console.log('row', row);
          this.moveRegistPage(row.fmId);
        }
      };

      this.gridView.onItemChecked = (grid, itemIndex, checked) => {
        //console.log('onItemChecked: ' + checked + ' at ' + itemIndex);
        this.checkedItems = checked ? this.grid_getCheckedRowArray(grid) : [];
      };

      this.gridView.onItemAllChecked = (grid, checked) => {
        //console.log('All checked as ' + checked);
        this.checkedItems = checked ? this.grid_getCheckedRowArray(grid) : [];
      };
    },
    onSearch(pageIndex = 1) {
      console.log('onSearch:pageIndex', pageIndex);
      this.currentPage = pageIndex;
      // eslint-disable-next-line no-underscore-dangle
      const _searchPeriod = DateUtil.stdFormat(this.searchPeriod);
      const params = {
        ..._searchPeriod,
        fmType: this.searchFmType,
      };
      this.setStoreParameter(params);

      let listApi = `${SDLUtil.API_URL}/embo/formula/list/main.do?method=search`;
      //console.log('listApi:', listApi);
      SDLUtil.showLoadingBar(true);

      axios
        .post(listApi, JSON.stringify(params), {
          headers: { 'Content-Type': `application/json` },
        })
        .then(response => {
          this.gridList = _.map(response.data.result, r => {
            r.firstRegDatetime = this.$filters.dateFormat(r.firstRegDatetime);
            r.lastModDatetime = this.$filters.dateFormat(r.lastModDatetime);
            return r;
          });

          this.dataProvider.setRows(this.gridList);
          // hide Loading bar
          SDLUtil.showLoadingBar(false);
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(error);
          console.log(error);
        });
    },
    fmMerge() {
      const _searchPeriod = DateUtil.stdFormat(this.searchPeriod);
      const params = {
        ..._searchPeriod,
        fmType: this.searchFmType,
      };
      let listApi = `${SDLUtil.API_URL}/embo/formula/list/main.do?method=merge`;
      axios
        .post(listApi, JSON.stringify(params), {
          headers: { 'Content-Type': `application/json` },
        })
        .then(response => {
          // hide Loading bar
          SDLUtil.showLoadingBar(false);
        })
        .catch(error => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(error);
          console.log(error);
        });
    },
    moveRegistPage(key = '') {
      if (key) {
        this.$router.push(`${this.$CONTEXT}/embo/formula/view/` + key);
      } else {
        this.$router.push(`${this.$CONTEXT}/embo/formula/edit/`);
      }
    },
    downloadExcel() {
      this.grid_getGridExcel(this.gridView, { fileName: 'testFmList' });
    },
    deleteFormula() {
      SDLUtil.confirm({
        msg: 'sdl.common.message.doDelete',
        // title: 'confirm title',
        // okLabel: 'ok label',
        // cancelLabel: 'Cancel',
        onOkEvt: () => this.doDeleteFormula(),
      });
    },
    doDeleteFormula() {
      var rows = this.grid_getCheckedRowArray(this.gridView);
      axios
        .post(`${SDLUtil.API_URL}/embo/formula/item/main.do?method=delete`, { items: rows })
        .then(({ data }) => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.alert('sdl.common.message.deleted');
          this.onSearch();
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
    },
  }, //--method
  created() {
    this.userInfo = SDLUtil.getLoginedUserInfo();
    this.init();
  },
  mounted() {
    this.initGrid();

    this.$nextTick(() => {
      console.info('initialize Page');

      // connection type
      /*axios.get(`${SDLUtil.API_URL}/commcode/groupcodes/fmType/commcodes`).then(({ data }) => {
        this.fmTypeList = data;
      });*/
    });
  },
  unmounted() {
    //alert('The component is removed (unmounted)!');
    this.dataProvider.clearRows();
    this.gridView.destroy();
    this.dataProvider.destroy();
    this.gridView = null;
    this.dataProvider = null;
  },
};
</script>
<style scoped>
button:disabled,
button[disabled] {
  border: 1px solid #999999;
  background-color: #cccccc;
  color: #666666;
}
</style>
