<!--
  Program: MailGroupList.vue
  Author: SDL
  Description: Page to view, add and delete mail group
-->
<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">
            <div class="row">
              <label class="col-2 col-form-label text-end" style="min-width:100px;">
                {{ $t('sdl.mailGroup.label.mailGroup') }}
              </label>
              <div class="col-10 form-inline">
                <input type="text" class="form-control" v-model="searchParam.searchLabel" @keyup.esc="searchParam.searchLabel = ''" />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-2 float-end text-end">
        <button class="btn btn-primary btn-search" type="submit" @click="getMailGroupList()">
          {{ $t('sdl.common.label.search') }}
        </button>
      </div>
    </div>
    <!-- SEARCH Area -->
    <!-- Button Area -->
    <div class="ui--list-heading clearfix">
      <span class="ui--text-total"><strong>Total</strong> {{ $filters.numberFormat(total) }}</span>
      <div class="float-end">
        <button type="button" class="btn btn-secondary btn-sm" @click="deleteMailGroupBtn()" v-authorization="'update'">
          {{ $t('sdl.common.label.delete') }}
        </button>
        <button type="button" class="btn btn-secondary btn-sm" @click="updateMailGroupBtn()" v-authorization="'update'">
          {{ $t('sdl.common.label.edit') }}
        </button>
        <button type="button" class="btn btn-secondary btn-sm" @click="addMailGroupBtn()" v-authorization="'execute'">
          {{ $t('sdl.common.label.add') }}
        </button>
      </div>
    </div>
    <!-- Button Area -->
    <!-- List Area -->
    <table class="table table-bordered ui--table">
      <colgroup>
        <col style="width:3%" />
        <col style="width:15%" />
        <col style="width:20%" />
        <col v-for="locale in $i18n.availableLocales" :key="'col'+locale" style="" />
        <col style="width:7%" />
        <col style="width:10%" />
      </colgroup>
      <thead>
      <tr>
        <th scope="col">
          <input type="checkbox" @click.stop v-model="selectAll" @change="toggleSelectAll()" />
        </th>
        <th scope="col">{{ $t('sdl.mailGroup.label.mailGroupName') }}</th>
        <th scope="col">{{ $t('sdl.common.label.description') }}</th>
        <th scope="col" v-for="locale in $i18n.availableLocales" :key="'th'+locale">{{ $t('sdl.mailGroup.label.mailGroupNameLang', [locale]) }}</th>
        <th scope="col">{{ $t('sdl.common.label.used') }}</th>
        <th scope="col">{{ $t('sdl.common.label.createdBy') }}</th>
      </tr>
      </thead>
      <tr v-for="mailGroup in mailGroupList" :key="mailGroup.mailGroupId" @click="rowClick(mailGroup.mailGroupId)" class="cursor-pointer">
        <td class="text-center" @click.stop><input type="checkbox" v-model="mailGroup.selected" @change="checkBoxClick(mailGroup)" /></td>
        <td class="text-left">{{ mailGroup.label }}</td>
        <td class="text-left">{{ $filters.cutString(mailGroup.description, 100) }}</td>
        <td class="text-left" v-for="locale in $i18n.availableLocales" :key="'td'+locale">{{ mailGroup.labelJson[locale] }}</td>
        <td class="text-center">{{ mailGroup.used }}</td>
        <td class="text-center">{{ mailGroup.firstRegrName }}</td>
      </tr>
    </table>
    <!-- List Area -->
    <!-- Pagination Area-->
    <sdl-pagination
      :current-page="current_page"
      :total-rows="total"
      :per-page="per_page"
      @change="handleCurrentChange"
      align="center"
    />
    <!-- Pagination Area-->
  </div>
</template>

<script>
import axios from 'axios';
import { SDLUtil, StringUtil } from '@/utils';
import StoreParams from '@/mixin/StoreParams';
import MailGroupFormPopup from './popup/MailGroupFormPopup.vue';

export default {
  data() {
    return {
      searchParam: {
        searchLabel: '',
      },
      selectAll: false,
      per_page: null,
      current_page: null,
      total: null,
      mailGroupList: [],
    };
  },
  mixins: [StoreParams],
  methods: {
    /**
         * param: number
         * return: nothing
         * exception: Call error alert
         * description: Mail Group lookup
         */
    getMailGroupList(pageIndex = 1) {
      // Set the page number sent to the current page number
      this.current_page = pageIndex;

      // Launch Loading bar
      SDLUtil.showLoadingBar(true);

      // Set Mail Group lookup API enforcement parameter
      const params = {
        label: this.searchParam.searchLabel,
        pageIndex: this.current_page,
        pageSize: this.per_page,
      };

      // Save parameter to store
      this.setStoreParameter(params);

      // Call Mail Group list lookup API
      axios
        .get(`${SDLUtil.API_URL}/mail-group-with-paging?${StringUtil.queryStringfy(params)}`)
        .then(({ data }) => {
          this.mailGroupList = data.rows;
          // Apply the page number that was retrieved to the current_page
          this.current_page = data.currentPage;
          // Full Row Count
          this.total = data.records;
          // Remove Loading bar
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          // Remove Loading bar
          SDLUtil.showLoadingBar(false);
          // Call error alert
          SDLUtil.errorAlert(err);
        });

      // Unselect All
      this.selectAll = false;
    },
    /**
         * param: nothing
         * return: nothing
         * exception: nothing
         * description: Call up a function that calls a popup register Mail Group
         */
    addMailGroupBtn() {
      this.openMailGroupFormPopUp();
    },
    /**
         * param: nothing
         * return: nothing
         * exception: nothing
         * description: Call up a function that calls a popup edit Mail Group
         */
    updateMailGroupBtn() {
      const selectedMailGroupList = this.mailGroupList.filter(mailGroup => mailGroup.selected);
      const selectCnt = selectedMailGroupList.length;

      if (selectCnt === 0) {
        SDLUtil.alert('sdl.common.message.selectRow');
        return;
      }
      if (selectCnt > 1) {
        SDLUtil.alert('sdl.common.message.selectOneRow');
        return;
      }

      this.openMailGroupFormPopUp(selectedMailGroupList[0].mailGroupId);
    },
    /**
         * param: nothing
         * return: nothing
         * exception: nothing
         * description: Call up a function to delete a role after verifying that it has been selected
         */
    deleteMailGroupBtn() {
      const selectedMailGroupList = this.mailGroupList.filter(mailGroup => mailGroup.selected);
      const selectCnt = selectedMailGroupList.length;

      if (selectCnt === 0) {
        SDLUtil.alert('sdl.common.message.selectRow');
        return;
      }

      SDLUtil.confirm({
        title: 'sdl.common.label.delete',
        msg: 'sdl.common.message.doDelete',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.deleteMailGroup(selectedMailGroupList),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
         * param: array
         * return: nothing
         * exception: nothing
         * description: Delete Mail Group
         */
    deleteMailGroup(mailGroupList) {
      const mailGroupIds = mailGroupList.map(mailGroup => mailGroup.mailGroupId);

      axios
        .delete(`${SDLUtil.API_URL}/mail-group`, { data: mailGroupIds })
        .then(response => {
          if (response.status === 200) {
            this.getMailGroupList();
          }
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
         * param: string
         * return: nothing
         * exception: nothing
         * description: Popup calls to register/modify Mail Group
         */
    openMailGroupFormPopUp(mailGroupId) {
      SDLUtil.show(
        MailGroupFormPopup,
        {
          mailGroupId,
          rtnFunc: args => {
            if (args) {
              this.getMailGroupList();
            }
          },
        },
        { width: '850px', height: 'auto' },
      );
    },
    /**
         * param: string
         * return: nothing
         * exception: nothing
         * description: Go to the MailGroup edit page
         */
    rowClick(mailGroupId) {
      this.$router.push(`${this.$CONTEXT}/admin/etc/mailGroupMappEdit/${mailGroupId}`);
    },
    /**
         * param: number
         * return: nothing
         * exception: Call error alert
         * description: paging
         */
    handleCurrentChange(currentPage) {
      // Invoke Mail Group list lookup method
      this.getMailGroupList(currentPage);
    },
    /**
         * param: object
         * return: nothing
         * exception: nothing
         * description: Select check box in the list of roles
         */
    checkBoxClick(item) {
      if (!item.selected) {
        if (this.selectAll) {
          this.selectAll = false;
        }
      }
    },
    /**
         * param: nothing
         * return: nothing
         * exception: nothing
         * description: Select All
         */
    toggleSelectAll() {
      this.mailGroupList.forEach(item => {
        item.selected = this.selectAll;
      });
    },
  },
  created() {
    const storeParams = this.getStoreParameter();

    // Restore if there are stored parameters
    if (storeParams) {
      this.searchParam.searchLabel = storeParams.label;
      this.per_page = storeParams.pageSize;
      this.current_page = storeParams.pageIndex;
      // Invoke Mail Group lookup method
      this.getMailGroupList(this.current_page);
    } else {
      // Page size - 10 settings
      this.per_page = 10;
      // Invoke Mail Group lookup method
      this.getMailGroupList();
    }
  },
};
</script>
