<!--
 Program: IpMgmt.vue
 Author: SDL
 Description: IP management
-->
<template>
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>

    <div class="ui--list-heading clearfix">
      <span class="ui--text-total"><strong>Total</strong> {{ $filters.numberFormat(ipList.length) }}</span>
      <div class="float-end">
        <button type="button" class="btn btn-secondary btn-sm" @click="deleteIpBtn()">
          {{ $t('sdl.common.label.delete') }}
        </button>
        <button type="button" class="btn btn-secondary btn-sm" @click="addIpBtn()">
          {{ $t('sdl.common.label.add') }}
        </button>
        <button type="button" class="btn btn-primary btn-sm" @click="saveIpBtn()">
          {{ $t('sdl.common.label.save') }}
        </button>
      </div>
    </div>

    <table class="table table-bordered ui--table">
      <colgroup>
        <col style="width: 5%" />
        <col style="width: 25%" />
        <col style="width: 30%" />
        <col style="width: 20%" />
        <col style="width: 20%" />
      </colgroup>
      <thead>
        <tr>
          <th><input type="checkbox" @click.stop v-model="checkBoxAll" @change="toggleCheckBoxAll" /></th>
          <th>{{ $t('sdl.common.label.name') }}<span class="ui--text-required">*</span></th>
          <th>{{ $t('sdl.identity.log.label.useIp') }}<span class="ui--text-required">*</span></th>
          <th>{{ $t('sdl.privacyPolicy.createDate') }}</th>
          <th>{{ $t('sdl.privacyPolicy.createUser') }}</th>
        </tr>
      </thead>
      <tbody>
        <template v-for="(item, index) in ipList" :key="index">
          <tr v-if="`${item.id}`.startsWith('NEW_')">
            <td class="text-center">
              <input type="checkbox" v-model="item.checked" @change="toggleCheckbox()" />
            </td>
            <td><input type="text" class="form-control" v-model="item.name" /></td>
            <td><input type="text" class="form-control" v-model="item.address" /></td>
            <td class="text-center">-</td>
            <td>-</td>
          </tr>
          <tr v-else>
            <td class="text-center">
              <input type="checkbox" v-model="item.checked" @change="toggleCheckbox()" />
            </td>
            <td>{{ item.name }}</td>
            <td>{{ item.address }}</td>
            <td class="text-center">{{ $filters.dateFormat(item.firstRegDatetime) }}</td>
            <td>{{ item.firstRegrId }}</td>
          </tr>
        </template>
      </tbody>
    </table>
  </div>
</template>

<script>
import axios from 'axios';
import _ from 'lodash';
import { SDLUtil } from '@/utils';

export default {
  data() {
    return {
      checkBoxAll: false,
      ipList: [],
      regex: {
        ip: /^([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}$/,
      },
    };
  },
  created() {
    this.getIpList();
  },
  methods: {
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Select List CheckBox All
     */
    toggleCheckBoxAll() {
      this.ipList.forEach(ip => {
        ip.checked = this.checkBoxAll;
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Click on List CheckBox
     */
    toggleCheckbox() {
      const unChecked = this.ipList.find(ip => ip.checked === false);
      this.checkBoxAll = !unChecked;
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Check if it is a newly added item
     */
    checkNewItem(item) {
      return `${item.id}`.startsWith('NEW_');
    },
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Retrieving the Manager IP Information List
     */
    getIpList() {
      SDLUtil.showLoadingBar(true);

      /**
       * Called the API that retrieves the manager IP information list.
       */
      axios
        .get(`${SDLUtil.API_URL}/admin/admin-addresses`)
        .then(({ data }) => {
          this.ipList = data.map(ip => {
            ip.checked = false;
            return ip;
          });
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          console.error(err);
          SDLUtil.showLoadingBar(false);
        });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: invoke the Add Item method
     */
    addIpBtn() {
      this.addIp();
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: After checking whether there is a checked row in the checkbox and checking whether to execute it, call the delete method
     */
    deleteIpBtn() {
      const selectIpList = this.ipList.filter(ip => ip.checked);

      if (selectIpList.length === 0) {
        SDLUtil.alert('sdl.common.message.checkRowsToDelete');
        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.deleteIp(selectIpList),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: After checking the newly added items and whether to execute them, execute the save method.
     */
    saveIpBtn() {
      const newIpList = this.ipList
        .filter(ip => this.checkNewItem(ip))
        .map(newIp => ({
          name: newIp.name,
          address: newIp.address,
        }));

      if (newIpList.length === 0) {
        return;
      }
      // Validation
      this.validateCheck(newIpList);

      SDLUtil.confirm({
        title: 'sdl.common.label.save',
        msg: 'sdl.common.message.doSave',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.saveIp(newIpList),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Check validation
     */
    validateCheck(list) {
      list.some(obj => {
        if (_.isEmpty(obj.name) || _.isEmpty(obj.address)) {
          SDLUtil.alert('sdl.register.message.valid.mandatory');
          return true;
        }
        if (!this.regex.ip.test(obj.address)) {
          SDLUtil.alert('sdl.adminAddress.message.invalidIP');
          return true;
        }
        return false;
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Add row to ip list
     */
    addIp() {
      this.ipList.push({
        id: `NEW_${new Date().getTime()}`,
        checked: false,
        name: '',
        address: '',
        firstRegDatetime: this.$moment(),
        firstRegrId: '',
      });

      // refresh checkbox
      this.toggleCheckbox();
    },
    /**
     * param: array
     * return: nothing
     * exception: Call error alert
     * description: Delete a row checked in the checkbox among newly added and saved items
     */
    deleteIp(selectIpList) {
      // Delete the list and temporarily saved list if it is a newly created row
      const newIpList = selectIpList.filter(ip => this.checkNewItem(ip)).map(ip => ip.id);

      if (newIpList.length > 0) {
        newIpList.forEach(newIp => {
          setTimeout(() => {
            this.removeGrid(newIp);
          }, 10);
        });
      }

      // If it is a saved row, call delete api
      const deleteIdList = selectIpList.filter(ip => !this.checkNewItem(ip)).map(ip => ip.id);

      if (deleteIdList.length > 0) {
        deleteIdList.forEach(ip => {
          setTimeout(() => {
            this.removeGrid(ip);
          }, 10);
        });
      }

      if (deleteIdList.length > 0) {
        /**
         * Called the administrator IP deletion api
         */
        axios
          .delete(`${SDLUtil.API_URL}/admin/admin-addresses`, { data: deleteIdList })
          .then(response => {
            if (response.status === 200) {
              this.getIpList();
            }
          })
          .catch(err => {
            // Call error alert
            SDLUtil.errorAlert(err);
          });
      }
      // refresh checkbox
      this.checkBoxAll = false;
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Delete from the ip list
     */
    removeGrid(id) {
      this.$nextTick(() => {
        this.ipList.splice(
          this.ipList.findIndex(ip => ip.id === id),
          1,
        );
      });
    },

    /**
     * param: array
     * return: nothing
     * exception: Call error alert
     * description: Save the newly created row
     */
    saveIp(newIpList) {
      /**
       * Called the manager IP storage api
       */
      axios
        .post(`${SDLUtil.API_URL}/admin/admin-addresses`, newIpList, {
          headers: { 'Content-Type': 'application/json' },
        })
        .then(response => {
          if (response.status === 200) {
            this.getIpList();
          }
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
  },
};
</script>
